@calmlens/sdk 0.0.0-stage → 0.6.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 +654 -2
- package/cjs/CalmLensTypes-BpmT60j-.d.ts +3522 -0
- package/cjs/CalmLensUtils-DA1_j5-P.js +578 -0
- package/cjs/index.d.ts +2751 -0
- package/cjs/index.js +1252 -0
- package/cjs/package.json +3 -0
- package/cjs/testing.d.ts +190 -0
- package/cjs/testing.js +814 -0
- package/esm/CalmLensTypes-BpmT60j-.d.ts +3522 -0
- package/esm/CalmLensUtils-UthMaLx_.js +431 -0
- package/esm/index.d.ts +2751 -0
- package/esm/index.js +1240 -0
- package/esm/package.json +3 -0
- package/esm/testing.d.ts +190 -0
- package/esm/testing.js +808 -0
- package/package.json +87 -4
package/esm/index.js
ADDED
|
@@ -0,0 +1,1240 @@
|
|
|
1
|
+
import { _ as getRawBase64, a as SDK_ERRORS, b as _objectSpread2, c as MAX_IMAGE_UPLOAD_BYTES, d as isRejectedUploadMimeType, f as PUBLIC_ERROR_CODES, g as getAssetPayloadByteLength, h as assetToData, i as CalmLensError, l as MIN_MULTIPART_IMAGE_UPLOAD_BYTES, n as validateClientOptions, o as calmLensError, p as stringifyJsonCanonical, r as _objectWithoutProperties, s as DOMAIN, t as toTextAssetOptions, u as getRejectedUploadMimeTypeError, v as validateAssetPayload, y as _asyncToGenerator } from "./CalmLensUtils-UthMaLx_.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
|
+
"clip"
|
|
206
|
+
]),
|
|
207
|
+
startSeconds: zod.number().nonnegative(),
|
|
208
|
+
endSeconds: zod.number().nonnegative(),
|
|
209
|
+
categories: CATEGORIES_SCHEMA
|
|
210
|
+
}).strict())
|
|
211
|
+
}).strict().optional(),
|
|
212
|
+
labels: zod.array(CLASSIFICATION_LABEL_SCHEMA).nullish()
|
|
213
|
+
}).strict();
|
|
214
|
+
//#endregion
|
|
215
|
+
//#region ../shared/src/MediaTestTriggers.ts
|
|
216
|
+
const MEDIA_TEST_SIGNALS = [...CLASSIFICATION_CATEGORIES, "violence.graphic"];
|
|
217
|
+
const HEX_WORDS = [
|
|
218
|
+
"zero",
|
|
219
|
+
"one",
|
|
220
|
+
"two",
|
|
221
|
+
"three",
|
|
222
|
+
"four",
|
|
223
|
+
"five",
|
|
224
|
+
"six",
|
|
225
|
+
"seven",
|
|
226
|
+
"eight",
|
|
227
|
+
"nine",
|
|
228
|
+
"alpha",
|
|
229
|
+
"bravo",
|
|
230
|
+
"charlie",
|
|
231
|
+
"delta",
|
|
232
|
+
"echo",
|
|
233
|
+
"foxtrot"
|
|
234
|
+
];
|
|
235
|
+
/** Read this aloud, or render it as large, high-contrast text in a video frame. */
|
|
236
|
+
function generateMediaTestCode(signal, projectId) {
|
|
237
|
+
if (!MEDIA_TEST_SIGNALS.includes(signal)) throw new Error("Unsupported media test signal");
|
|
238
|
+
const suffix = projectId.slice(-8).toLowerCase();
|
|
239
|
+
if (!/^[a-f0-9]{8}$/.test(suffix)) throw new Error("Expected a project ID with an eight-character hexadecimal suffix");
|
|
240
|
+
return `Calm Lens test ${[...suffix].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
|
|
241
|
+
}
|
|
242
|
+
//#endregion
|
|
243
|
+
//#region src/client/CalmLensWebhooks.ts
|
|
244
|
+
const WEBHOOK_DELIVERY_HEADER = "x-calmlens-delivery";
|
|
245
|
+
const WEBHOOK_TIMESTAMP_HEADER = "x-calmlens-timestamp";
|
|
246
|
+
const WEBHOOK_SIGNATURE_HEADER = "x-calmlens-signature";
|
|
247
|
+
/** Deliveries whose timestamp is further than this from the receiver's clock are rejected. */
|
|
248
|
+
const WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = 300;
|
|
249
|
+
/** The JSON body of a webhook delivery for a stored event. */
|
|
250
|
+
const toWebhookEventPayload = (event) => {
|
|
251
|
+
var _event$description, _event$assetId, _event$asset;
|
|
252
|
+
return {
|
|
253
|
+
id: event.id,
|
|
254
|
+
type: event.type,
|
|
255
|
+
createdAt: event.createdAt,
|
|
256
|
+
projectId: event.projectId,
|
|
257
|
+
data: {
|
|
258
|
+
severity: event.severity,
|
|
259
|
+
title: event.title,
|
|
260
|
+
description: (_event$description = event.description) !== null && _event$description !== void 0 ? _event$description : null,
|
|
261
|
+
assetId: (_event$assetId = event.assetId) !== null && _event$assetId !== void 0 ? _event$assetId : null,
|
|
262
|
+
asset: (_event$asset = event.asset) !== null && _event$asset !== void 0 ? _event$asset : null,
|
|
263
|
+
facts: event.facts
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
const encoder = new TextEncoder();
|
|
268
|
+
const hmacSha256Hex = function() {
|
|
269
|
+
var _ref = _asyncToGenerator(function* (secret, message) {
|
|
270
|
+
const key = yield crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
271
|
+
name: "HMAC",
|
|
272
|
+
hash: "SHA-256"
|
|
273
|
+
}, false, ["sign"]);
|
|
274
|
+
const signature = yield crypto.subtle.sign("HMAC", key, encoder.encode(message));
|
|
275
|
+
return Array.from(new Uint8Array(signature), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
276
|
+
});
|
|
277
|
+
return function hmacSha256Hex(_x, _x2) {
|
|
278
|
+
return _ref.apply(this, arguments);
|
|
279
|
+
};
|
|
280
|
+
}();
|
|
281
|
+
/** Constant-time comparison of two strings of the same length. */
|
|
282
|
+
const timingSafeEqual = (a, b) => {
|
|
283
|
+
if (a.length !== b.length) return false;
|
|
284
|
+
let diff = 0;
|
|
285
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
286
|
+
return diff === 0;
|
|
287
|
+
};
|
|
288
|
+
/** `v1=<hex HMAC-SHA256 of "<timestamp>.<body>">`, the `x-calmlens-signature` header value. */
|
|
289
|
+
const createWebhookSignatureHeader = function() {
|
|
290
|
+
var _ref2 = _asyncToGenerator(function* (secret, timestamp, body) {
|
|
291
|
+
return `v1=${yield hmacSha256Hex(secret, `${timestamp}.${body}`)}`;
|
|
292
|
+
});
|
|
293
|
+
return function createWebhookSignatureHeader(_x3, _x4, _x5) {
|
|
294
|
+
return _ref2.apply(this, arguments);
|
|
295
|
+
};
|
|
296
|
+
}();
|
|
297
|
+
/** Headers for one signed delivery of `body`. */
|
|
298
|
+
const createWebhookHeaders = function() {
|
|
299
|
+
var _ref3 = _asyncToGenerator(function* (options) {
|
|
300
|
+
var _options$timestampSec;
|
|
301
|
+
const timestamp = (_options$timestampSec = options.timestampSeconds) !== null && _options$timestampSec !== void 0 ? _options$timestampSec : Math.floor(Date.now() / 1e3);
|
|
302
|
+
return {
|
|
303
|
+
"content-type": "application/json",
|
|
304
|
+
[WEBHOOK_DELIVERY_HEADER]: options.deliveryId,
|
|
305
|
+
[WEBHOOK_TIMESTAMP_HEADER]: String(timestamp),
|
|
306
|
+
[WEBHOOK_SIGNATURE_HEADER]: yield createWebhookSignatureHeader(options.secret, timestamp, options.body)
|
|
307
|
+
};
|
|
308
|
+
});
|
|
309
|
+
return function createWebhookHeaders(_x6) {
|
|
310
|
+
return _ref3.apply(this, arguments);
|
|
311
|
+
};
|
|
312
|
+
}();
|
|
313
|
+
/**
|
|
314
|
+
* Verifies a webhook delivery: `x-calmlens-signature` must contain a `v1=` HMAC-SHA256 of
|
|
315
|
+
* `"<x-calmlens-timestamp>.<raw body>"`, and the timestamp must be within `toleranceSeconds`
|
|
316
|
+
* (default 300) of now. Returns `false` for anything missing or malformed.
|
|
317
|
+
*/
|
|
318
|
+
function verifyWebhookSignature(_x7) {
|
|
319
|
+
return _verifyWebhookSignature.apply(this, arguments);
|
|
320
|
+
}
|
|
321
|
+
function _verifyWebhookSignature() {
|
|
322
|
+
_verifyWebhookSignature = _asyncToGenerator(function* ({ payload, signature, timestamp, secret, toleranceSeconds = 300, now }) {
|
|
323
|
+
if (!secret || !signature || timestamp === null || timestamp === void 0) return false;
|
|
324
|
+
const timestampText = String(timestamp).trim();
|
|
325
|
+
if (!/^\d+$/.test(timestampText)) return false;
|
|
326
|
+
const nowMs = now === void 0 ? Date.now() : now instanceof Date ? now.getTime() : now;
|
|
327
|
+
if (Math.abs(Math.floor(nowMs / 1e3) - Number(timestampText)) > toleranceSeconds) return false;
|
|
328
|
+
const candidates = signature.split(",").map((part) => part.trim()).filter((part) => part.startsWith("v1=")).map((part) => part.slice(3).toLowerCase());
|
|
329
|
+
if (candidates.length === 0) return false;
|
|
330
|
+
const body = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
331
|
+
const expected = yield hmacSha256Hex(secret, `${timestampText}.${body}`);
|
|
332
|
+
let matched = false;
|
|
333
|
+
for (const candidate of candidates) if (timingSafeEqual(expected, candidate)) matched = true;
|
|
334
|
+
return matched;
|
|
335
|
+
});
|
|
336
|
+
return _verifyWebhookSignature.apply(this, arguments);
|
|
337
|
+
}
|
|
338
|
+
//#endregion
|
|
339
|
+
//#region src/client/CalmLensClient.ts
|
|
340
|
+
const _excluded = ["uint8Array"];
|
|
341
|
+
const _excluded2 = ["buffer"];
|
|
342
|
+
const _excluded3 = ["assetIdentifier"];
|
|
343
|
+
const _excluded4 = ["assetIdentifier", "init"];
|
|
344
|
+
const _excluded5 = ["assetId"];
|
|
345
|
+
const _excluded6 = ["assetId"];
|
|
346
|
+
const _excluded7 = ["assetId"];
|
|
347
|
+
const _excluded8 = ["folderId"];
|
|
348
|
+
const toBlobPartBytes = (value) => {
|
|
349
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
|
350
|
+
return Uint8Array.from(value);
|
|
351
|
+
};
|
|
352
|
+
const normalizePayloadForRequest = (payload) => {
|
|
353
|
+
if ("base64" in payload && payload.base64) return _objectSpread2(_objectSpread2({}, payload), {}, { base64: getRawBase64(payload.base64) });
|
|
354
|
+
if ("uint8Array" in payload && payload.uint8Array) {
|
|
355
|
+
const { uint8Array } = payload, rest = _objectWithoutProperties(payload, _excluded);
|
|
356
|
+
return _objectSpread2(_objectSpread2({}, rest), {}, { data: new Blob([toBlobPartBytes(uint8Array)]) });
|
|
357
|
+
}
|
|
358
|
+
if ("buffer" in payload && payload.buffer) {
|
|
359
|
+
const { buffer } = payload, rest = _objectWithoutProperties(payload, _excluded2);
|
|
360
|
+
return _objectSpread2(_objectSpread2({}, rest), {}, { data: new Blob([toBlobPartBytes(buffer)]) });
|
|
361
|
+
}
|
|
362
|
+
return payload;
|
|
363
|
+
};
|
|
364
|
+
const normalizeMetadataForMultipart = (metadata) => {
|
|
365
|
+
if (!Array.isArray(metadata)) return metadata;
|
|
366
|
+
return Object.fromEntries(metadata.map((item, index) => [index, item]));
|
|
367
|
+
};
|
|
368
|
+
const normalizeMetadataOptionsForRequest = (options) => {
|
|
369
|
+
if (!("metadata" in options) || !Array.isArray(options.metadata)) return options;
|
|
370
|
+
return _objectSpread2(_objectSpread2({}, options), {}, { metadata: normalizeMetadataForMultipart(options.metadata) });
|
|
371
|
+
};
|
|
372
|
+
const normalizeAssetOptionsForRequest = (options) => {
|
|
373
|
+
const normalizedOptions = normalizeMetadataOptionsForRequest(options);
|
|
374
|
+
if ("part" in normalizedOptions) return _objectSpread2(_objectSpread2({}, normalizedOptions), {}, { part: normalizePayloadForRequest(normalizedOptions.part) });
|
|
375
|
+
if ("content" in normalizedOptions && !("plainText" in normalizedOptions.content)) return _objectSpread2(_objectSpread2({}, normalizedOptions), {}, { content: normalizePayloadForRequest(normalizedOptions.content) });
|
|
376
|
+
return normalizedOptions;
|
|
377
|
+
};
|
|
378
|
+
const toRawUploadBody = (payload) => {
|
|
379
|
+
const data = assetToData(normalizePayloadForRequest(payload));
|
|
380
|
+
if (data instanceof Response) {
|
|
381
|
+
if (!data.body) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Response upload data must have a body" });
|
|
382
|
+
return data.body;
|
|
383
|
+
}
|
|
384
|
+
if (data instanceof ArrayBuffer || data instanceof Blob) return data;
|
|
385
|
+
if ("getReader" in data) return data;
|
|
386
|
+
return new Blob([toBlobPartBytes(data)]);
|
|
387
|
+
};
|
|
388
|
+
const setOptionalQueryValue = (params, key, value) => {
|
|
389
|
+
if (value !== void 0 && value !== null) params.set(key, typeof value === "string" ? value : JSON.stringify(value));
|
|
390
|
+
};
|
|
391
|
+
const assertValidUploadMimeType = (mimeType) => {
|
|
392
|
+
if (isRejectedUploadMimeType(mimeType)) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_MIME_TYPE, {
|
|
393
|
+
message: getRejectedUploadMimeTypeError(mimeType),
|
|
394
|
+
details: { mimeType }
|
|
395
|
+
});
|
|
396
|
+
};
|
|
397
|
+
const isImageMimeType = (mimeType) => mimeType.toLowerCase().startsWith("image/");
|
|
398
|
+
const prepareSubmitAssetOptions = (options) => {
|
|
399
|
+
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" });
|
|
400
|
+
if (!options.name) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset name is required" });
|
|
401
|
+
if (!("part" in options) && "isFinal" in options) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "isFinal is only valid for multipart uploads" });
|
|
402
|
+
if ("part" in options && options.part.partNumber && options.part.partNumber > 1) throw calmLensError(PUBLIC_ERROR_CODES.USE_UPLOAD_PART);
|
|
403
|
+
if ("content" in options) {
|
|
404
|
+
assertValidUploadMimeType(options.content.type);
|
|
405
|
+
if (!("plainText" in options.content)) {
|
|
406
|
+
const validation = validateAssetPayload(options.content);
|
|
407
|
+
if (!validation.ok) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: validation.error });
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
if ("part" in options) {
|
|
411
|
+
var _options$part$sizeInB;
|
|
412
|
+
assertValidUploadMimeType(options.part.type);
|
|
413
|
+
const partSizeInBytes = (_options$part$sizeInB = options.part.sizeInBytes) !== null && _options$part$sizeInB !== void 0 ? _options$part$sizeInB : getAssetPayloadByteLength(options.part);
|
|
414
|
+
if (isImageMimeType(options.part.type) && partSizeInBytes !== void 0) {
|
|
415
|
+
if (partSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
|
|
416
|
+
if (options.part.isFinal && partSizeInBytes < MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
|
|
417
|
+
}
|
|
418
|
+
const validation = validateAssetPayload(options.part, {
|
|
419
|
+
multipart: true,
|
|
420
|
+
isFinal: options.part.isFinal
|
|
421
|
+
});
|
|
422
|
+
if (!validation.ok) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: validation.error });
|
|
423
|
+
}
|
|
424
|
+
return options;
|
|
425
|
+
};
|
|
426
|
+
const appendCdnSelector = (url, options) => {
|
|
427
|
+
if (options.lens && options.transform) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
|
|
428
|
+
if (options.lens) return `${url}/@${encodeURIComponent(options.lens)}`;
|
|
429
|
+
if (!options.transform) return url;
|
|
430
|
+
return `${url}/${encodeURI(options.transform.replace(/^\/+/, ""))}`;
|
|
431
|
+
};
|
|
432
|
+
const getEnsureLensCacheKey = (options) => {
|
|
433
|
+
var _options$description, _options$transforms;
|
|
434
|
+
return stringifyJsonCanonical({
|
|
435
|
+
identifier: options.identifier,
|
|
436
|
+
name: options.name,
|
|
437
|
+
description: (_options$description = options.description) !== null && _options$description !== void 0 ? _options$description : null,
|
|
438
|
+
type: options.type,
|
|
439
|
+
active: options.active,
|
|
440
|
+
transforms: (_options$transforms = options.transforms) !== null && _options$transforms !== void 0 ? _options$transforms : null,
|
|
441
|
+
version: options.version
|
|
442
|
+
});
|
|
443
|
+
};
|
|
444
|
+
const withApiKeyHeader = (init, apiKey) => {
|
|
445
|
+
const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);
|
|
446
|
+
headers.set("X-Api-Key", apiKey);
|
|
447
|
+
return _objectSpread2(_objectSpread2({}, init), {}, {
|
|
448
|
+
redirect: "error",
|
|
449
|
+
headers: Object.fromEntries(headers.entries())
|
|
450
|
+
});
|
|
451
|
+
};
|
|
452
|
+
const requestSignal = (options, signal) => {
|
|
453
|
+
var _options$timeoutMs;
|
|
454
|
+
const signals = [
|
|
455
|
+
options.signal,
|
|
456
|
+
signal,
|
|
457
|
+
AbortSignal.timeout((_options$timeoutMs = options.timeoutMs) !== null && _options$timeoutMs !== void 0 ? _options$timeoutMs : 12e4)
|
|
458
|
+
].filter((value) => value != null);
|
|
459
|
+
return AbortSignal.any(signals);
|
|
460
|
+
};
|
|
461
|
+
/** Copies a fully read body into a new Response, so later JSON parsing cannot hit the network. */
|
|
462
|
+
const toBufferedResponse = function() {
|
|
463
|
+
var _ref = _asyncToGenerator(function* (response) {
|
|
464
|
+
const body = response.status === 204 || response.status === 304 ? null : yield response.arrayBuffer();
|
|
465
|
+
const headers = new Headers(response.headers);
|
|
466
|
+
headers.delete("content-encoding");
|
|
467
|
+
headers.delete("content-length");
|
|
468
|
+
const buffered = new Response(body, {
|
|
469
|
+
status: response.status,
|
|
470
|
+
statusText: response.statusText,
|
|
471
|
+
headers
|
|
472
|
+
});
|
|
473
|
+
Object.defineProperty(buffered, "url", { value: response.url });
|
|
474
|
+
return buffered;
|
|
475
|
+
});
|
|
476
|
+
return function toBufferedResponse(_x) {
|
|
477
|
+
return _ref.apply(this, arguments);
|
|
478
|
+
};
|
|
479
|
+
}();
|
|
480
|
+
/**
|
|
481
|
+
* Wraps fetch with the client's deadline, cancellation and redirect policy. Every failure,
|
|
482
|
+
* including body reads, decompression and truncated bodies when `bufferBody` is set, becomes a
|
|
483
|
+
* `CalmLensError` (`sdk/transport-error`, `sdk/timeout` or `sdk/cancelled`) with the original
|
|
484
|
+
* error as its `cause`.
|
|
485
|
+
*/
|
|
486
|
+
const safeFetch = (fetchImpl, options, { bufferBody }) => function() {
|
|
487
|
+
var _ref2 = _asyncToGenerator(function* (input, init) {
|
|
488
|
+
var _init$signal;
|
|
489
|
+
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);
|
|
490
|
+
try {
|
|
491
|
+
signal.throwIfAborted();
|
|
492
|
+
const response = yield fetchImpl(input, _objectSpread2(_objectSpread2({}, init), {}, {
|
|
493
|
+
redirect: "error",
|
|
494
|
+
signal
|
|
495
|
+
}));
|
|
496
|
+
return bufferBody ? yield toBufferedResponse(response) : response;
|
|
497
|
+
} catch (cause) {
|
|
498
|
+
var _signal$reason;
|
|
499
|
+
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" }, {
|
|
500
|
+
message: signal.aborted ? "Request aborted" : "Request failed",
|
|
501
|
+
cause
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
});
|
|
505
|
+
return function(_x2, _x3) {
|
|
506
|
+
return _ref2.apply(this, arguments);
|
|
507
|
+
};
|
|
508
|
+
}();
|
|
509
|
+
const createApi = (options) => {
|
|
510
|
+
return new Api({
|
|
511
|
+
name: "Calm Lens",
|
|
512
|
+
baseUrl: options.baseUrl,
|
|
513
|
+
middleware: [
|
|
514
|
+
RequestCoalescingMiddleware(),
|
|
515
|
+
{ beforeSend: (context) => {
|
|
516
|
+
context.updateHeaders({ "X-Api-Key": options.apiKey });
|
|
517
|
+
} },
|
|
518
|
+
{ [RequestEvent.ERROR]: (context) => {
|
|
519
|
+
if (context.error) throw normalizeApiError(context.error);
|
|
520
|
+
} }
|
|
521
|
+
],
|
|
522
|
+
requestBackend: options.requestBackend ? Object.assign(Object.create(options.requestBackend), "fetch" in options.requestBackend && typeof options.requestBackend.fetch === "function" ? { fetch: safeFetch(options.requestBackend.fetch, options, { bufferBody: true }) } : {}) : new FetchRequestBackend(safeFetch(globalThis.fetch, options, { bufferBody: true }))
|
|
523
|
+
});
|
|
524
|
+
};
|
|
525
|
+
const isApiErrorPayload = (value) => {
|
|
526
|
+
return !!value && typeof value === "object" && typeof value.code === "string";
|
|
527
|
+
};
|
|
528
|
+
const normalizeApiError = (error) => {
|
|
529
|
+
let cause = error;
|
|
530
|
+
const seen = /* @__PURE__ */ new Set();
|
|
531
|
+
while (cause instanceof Error && !seen.has(cause)) {
|
|
532
|
+
seen.add(cause);
|
|
533
|
+
if (cause instanceof CalmLensError) return cause;
|
|
534
|
+
if (cause.name === "AbortError" || cause.name === "TimeoutError") return calmLensError({ id: cause.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" }, {
|
|
535
|
+
message: "Request aborted",
|
|
536
|
+
cause
|
|
537
|
+
});
|
|
538
|
+
cause = cause.cause;
|
|
539
|
+
}
|
|
540
|
+
const response = error instanceof Error ? getErrorResponse(error) : void 0;
|
|
541
|
+
if (error instanceof Error && isRequestError(error) && isApiErrorPayload(response === null || response === void 0 ? void 0 : response.data)) {
|
|
542
|
+
const { code, message, details, traceId } = response.data;
|
|
543
|
+
return calmLensError({
|
|
544
|
+
id: code,
|
|
545
|
+
defaultMessage: message
|
|
546
|
+
}, {
|
|
547
|
+
message,
|
|
548
|
+
status: response === null || response === void 0 ? void 0 : response.status,
|
|
549
|
+
cause: error,
|
|
550
|
+
details: _objectSpread2(_objectSpread2({}, details), {}, {
|
|
551
|
+
traceId,
|
|
552
|
+
network: true
|
|
553
|
+
})
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
if (error instanceof CalmLensError) return error;
|
|
557
|
+
return calmLensError({ id: response ? response.ok ? "sdk/invalid-response" : "sdk/http-error" : "sdk/transport-error" }, {
|
|
558
|
+
message: response ? `HTTP ${response.status}` : error.message,
|
|
559
|
+
status: response === null || response === void 0 ? void 0 : response.status,
|
|
560
|
+
cause: error
|
|
561
|
+
});
|
|
562
|
+
};
|
|
563
|
+
const createEndpoints = (api) => {
|
|
564
|
+
const getFolders = api.endpoint().paramsOf().responseOf().build({
|
|
565
|
+
id: "getFolders",
|
|
566
|
+
method: "get",
|
|
567
|
+
path: "/projects/:projectId/folders"
|
|
568
|
+
});
|
|
569
|
+
const getFolder = api.endpoint().paramsOf().responseOf().build({
|
|
570
|
+
id: "getFolder",
|
|
571
|
+
method: "get",
|
|
572
|
+
path: "/folders/:folderId"
|
|
573
|
+
});
|
|
574
|
+
const postFolder = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
575
|
+
id: "postFolder",
|
|
576
|
+
method: "post",
|
|
577
|
+
path: "/projects/:projectId/folders"
|
|
578
|
+
});
|
|
579
|
+
const patchFolder = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
580
|
+
id: "patchFolder",
|
|
581
|
+
method: "patch",
|
|
582
|
+
path: "/folders/:folderId"
|
|
583
|
+
});
|
|
584
|
+
const deleteFolder = api.endpoint().paramsOf().responseOf().build({
|
|
585
|
+
id: "deleteFolder",
|
|
586
|
+
method: "delete",
|
|
587
|
+
path: "/folders/:folderId"
|
|
588
|
+
});
|
|
589
|
+
const moveFolder = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
590
|
+
id: "moveFolder",
|
|
591
|
+
method: "post",
|
|
592
|
+
path: "/folders/:folderId/move"
|
|
593
|
+
});
|
|
594
|
+
const getAssetsPage = api.endpoint().queryOf().paramsOf().responseOf().build({
|
|
595
|
+
id: "getAssetsPage",
|
|
596
|
+
method: "get",
|
|
597
|
+
path: "/projects/:projectId/assets/page"
|
|
598
|
+
});
|
|
599
|
+
const getAsset = api.endpoint().paramsOf().responseOf().build({
|
|
600
|
+
id: "getAsset",
|
|
601
|
+
method: "get",
|
|
602
|
+
path: "/assets/:assetId"
|
|
603
|
+
});
|
|
604
|
+
const getAssetChildren = api.endpoint().paramsOf().queryOf().responseOf().build({
|
|
605
|
+
id: "getAssetChildren",
|
|
606
|
+
method: "get",
|
|
607
|
+
path: "/assets/:assetId/children"
|
|
608
|
+
});
|
|
609
|
+
const patchAsset = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
610
|
+
id: "patchAsset",
|
|
611
|
+
method: "patch",
|
|
612
|
+
path: "/assets/:assetId"
|
|
613
|
+
});
|
|
614
|
+
const postUploadAsset = api.endpoint().bodyOf({ encoding: "multipart/form-data" }).paramsOf().queryOf().responseOf().build({
|
|
615
|
+
id: "postUploadAsset",
|
|
616
|
+
method: "post",
|
|
617
|
+
path: "/projects/:projectId/assets"
|
|
618
|
+
});
|
|
619
|
+
const postAssetSignedUrl = api.endpoint().bodyOf().paramsOf().responseOf().build({
|
|
620
|
+
id: "postAssetSignedUrl",
|
|
621
|
+
method: "post",
|
|
622
|
+
path: "/assets/:assetId/signed-url"
|
|
623
|
+
});
|
|
624
|
+
const postAssetPart = api.endpoint().bodyOf({ encoding: "multipart/form-data" }).paramsOf().queryOf().responseOf().build({
|
|
625
|
+
id: "postAssetPart",
|
|
626
|
+
method: "post",
|
|
627
|
+
path: "/assets/:assetId/part"
|
|
628
|
+
});
|
|
629
|
+
const moveAsset = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
630
|
+
id: "moveAsset",
|
|
631
|
+
method: "post",
|
|
632
|
+
path: "/assets/:assetId/move"
|
|
633
|
+
});
|
|
634
|
+
const retryAsset = api.endpoint().paramsOf().responseOf().build({
|
|
635
|
+
id: "retryAsset",
|
|
636
|
+
method: "post",
|
|
637
|
+
path: "/assets/:assetId/retry"
|
|
638
|
+
});
|
|
639
|
+
const getEvents = api.endpoint().paramsOf().queryOf().responseOf().build({
|
|
640
|
+
id: "getEvents",
|
|
641
|
+
method: "get",
|
|
642
|
+
path: "/projects/:projectId/events"
|
|
643
|
+
});
|
|
644
|
+
return {
|
|
645
|
+
getFolders,
|
|
646
|
+
getFolder,
|
|
647
|
+
postFolder,
|
|
648
|
+
patchFolder,
|
|
649
|
+
deleteFolder,
|
|
650
|
+
moveFolder,
|
|
651
|
+
getAssetsPage,
|
|
652
|
+
getAsset,
|
|
653
|
+
getAssetChildren,
|
|
654
|
+
patchAsset,
|
|
655
|
+
postUploadAsset,
|
|
656
|
+
postAssetSignedUrl,
|
|
657
|
+
postAssetPart,
|
|
658
|
+
moveAsset,
|
|
659
|
+
retryAsset,
|
|
660
|
+
ensureLens: api.endpoint().bodyOf().paramsOf().responseOf().build({
|
|
661
|
+
id: "ensureLens",
|
|
662
|
+
method: "put",
|
|
663
|
+
path: "/lenses/:lensIdentifier"
|
|
664
|
+
}),
|
|
665
|
+
ensureLenses: api.endpoint().bodyOf().paramsOf().responseOf().build({
|
|
666
|
+
id: "ensureLenses",
|
|
667
|
+
method: "put",
|
|
668
|
+
path: "/projects/:projectId/lenses"
|
|
669
|
+
}),
|
|
670
|
+
getEvents
|
|
671
|
+
};
|
|
672
|
+
};
|
|
673
|
+
var CalmLensClient = class CalmLensClient {
|
|
674
|
+
/**
|
|
675
|
+
* Verifies that a webhook delivery came from CalmLens: checks the `v1=` HMAC-SHA256 in
|
|
676
|
+
* `x-calmlens-signature` over `"<x-calmlens-timestamp>.<raw body>"` and rejects timestamps
|
|
677
|
+
* more than `toleranceSeconds` (default 300) from now, which stops replayed deliveries.
|
|
678
|
+
*
|
|
679
|
+
* @param options.payload - The raw request body, exactly as received (verify before parsing)
|
|
680
|
+
* @param options.signature - The 'x-calmlens-signature' header value
|
|
681
|
+
* @param options.timestamp - The 'x-calmlens-timestamp' header value
|
|
682
|
+
* @param options.secret - The connector's signing secret
|
|
683
|
+
* @param options.toleranceSeconds - Allowed clock distance in seconds (default 300)
|
|
684
|
+
* @param options.now - Override the current time (Date or epoch milliseconds), for tests
|
|
685
|
+
* @returns Promise<boolean> - True if the signature is valid and fresh, false otherwise
|
|
686
|
+
*
|
|
687
|
+
* @example
|
|
688
|
+
* ```javascript
|
|
689
|
+
* // In your webhook handler (e.g. a Fetch API Request)
|
|
690
|
+
* const payload = await request.text();
|
|
691
|
+
* const isValid = await CalmLensClient.verifyWebhookSignature({
|
|
692
|
+
* payload,
|
|
693
|
+
* signature: request.headers.get('x-calmlens-signature'),
|
|
694
|
+
* timestamp: request.headers.get('x-calmlens-timestamp'),
|
|
695
|
+
* secret: WEBHOOK_SECRET,
|
|
696
|
+
* });
|
|
697
|
+
*
|
|
698
|
+
* if (!isValid) {
|
|
699
|
+
* return new Response('Unauthorized', { status: 401 });
|
|
700
|
+
* }
|
|
701
|
+
* const event = JSON.parse(payload); // { id, type, createdAt, projectId, data }
|
|
702
|
+
* ```
|
|
703
|
+
*/
|
|
704
|
+
static verifyWebhookSignature(options) {
|
|
705
|
+
return _asyncToGenerator(function* () {
|
|
706
|
+
return verifyWebhookSignature(options);
|
|
707
|
+
})();
|
|
708
|
+
}
|
|
709
|
+
constructor(options) {
|
|
710
|
+
var _this$options$baseUrl, _this$options$cdnBase;
|
|
711
|
+
this.options = options;
|
|
712
|
+
this.ensuredLenses = /* @__PURE__ */ new Map();
|
|
713
|
+
this.pendingEnsureLenses = /* @__PURE__ */ new Map();
|
|
714
|
+
this.multipartImageUploadSizes = /* @__PURE__ */ new Map();
|
|
715
|
+
this.multipartUploadQueues = /* @__PURE__ */ new Map();
|
|
716
|
+
validateClientOptions(options);
|
|
717
|
+
this.options = _objectSpread2({}, options);
|
|
718
|
+
this.options.baseUrl = (_this$options$baseUrl = this.options.baseUrl) !== null && _this$options$baseUrl !== void 0 ? _this$options$baseUrl : `https://api.${DOMAIN}/v1`;
|
|
719
|
+
this.options.cdnBaseUrl = (_this$options$cdnBase = this.options.cdnBaseUrl) !== null && _this$options$cdnBase !== void 0 ? _this$options$cdnBase : `https://cdn.${DOMAIN}/v1`;
|
|
720
|
+
this.api = createApi(this.options);
|
|
721
|
+
this.endpoints = createEndpoints(this.api);
|
|
722
|
+
}
|
|
723
|
+
/** Scope cancellation/timeout to an operation without changing this client's defaults. */
|
|
724
|
+
withRequestOptions(options) {
|
|
725
|
+
const client = new CalmLensClient(_objectSpread2(_objectSpread2({}, this.options), options));
|
|
726
|
+
client.multipartUploadQueues = this.multipartUploadQueues;
|
|
727
|
+
client.multipartImageUploadSizes = this.multipartImageUploadSizes;
|
|
728
|
+
return client;
|
|
729
|
+
}
|
|
730
|
+
getUploadFetch() {
|
|
731
|
+
var _this$options$request, _ref3, _this$options$uploadF;
|
|
732
|
+
const requestBackendFetch = (_this$options$request = this.options.requestBackend) === null || _this$options$request === void 0 ? void 0 : _this$options$request.fetch;
|
|
733
|
+
const fetchImpl = (_ref3 = (_this$options$uploadF = this.options.uploadFetch) !== null && _this$options$uploadF !== void 0 ? _this$options$uploadF : requestBackendFetch) !== null && _ref3 !== void 0 ? _ref3 : globalThis.fetch;
|
|
734
|
+
if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
|
|
735
|
+
return safeFetch(fetchImpl, this.options, { bufferBody: true });
|
|
736
|
+
}
|
|
737
|
+
submitRawAssetUpload(options, queue) {
|
|
738
|
+
var _this = this;
|
|
739
|
+
return _asyncToGenerator(function* () {
|
|
740
|
+
var _payload$sizeInBytes;
|
|
741
|
+
const query = new URLSearchParams();
|
|
742
|
+
query.set("name", options.name);
|
|
743
|
+
query.set("queue", String(queue));
|
|
744
|
+
setOptionalQueryValue(query, "description", options.description);
|
|
745
|
+
setOptionalQueryValue(query, "processingOptions", options.processingOptions);
|
|
746
|
+
setOptionalQueryValue(query, "visibility", options.visibility);
|
|
747
|
+
setOptionalQueryValue(query, "metadata", options.metadata);
|
|
748
|
+
setOptionalQueryValue(query, "externalId", options.externalId);
|
|
749
|
+
setOptionalQueryValue(query, "externalUrl", options.externalUrl);
|
|
750
|
+
setOptionalQueryValue(query, "folderId", options.folderId);
|
|
751
|
+
const isMultipart = "part" in options;
|
|
752
|
+
const payload = isMultipart ? options.part : options.content;
|
|
753
|
+
query.set("contentType", payload.type);
|
|
754
|
+
setOptionalQueryValue(query, "sizeInBytes", (_payload$sizeInBytes = payload.sizeInBytes) !== null && _payload$sizeInBytes !== void 0 ? _payload$sizeInBytes : getAssetPayloadByteLength(payload));
|
|
755
|
+
if (isMultipart) {
|
|
756
|
+
var _part$partNumber, _part$isFinal, _part$sizeInBytes;
|
|
757
|
+
const part = payload;
|
|
758
|
+
const multipartOptions = options;
|
|
759
|
+
query.set("partNumber", String((_part$partNumber = part.partNumber) !== null && _part$partNumber !== void 0 ? _part$partNumber : 1));
|
|
760
|
+
query.set("isFinal", String((_part$isFinal = part.isFinal) !== null && _part$isFinal !== void 0 ? _part$isFinal : false));
|
|
761
|
+
setOptionalQueryValue(query, "sizeInBytes", (_part$sizeInBytes = part.sizeInBytes) !== null && _part$sizeInBytes !== void 0 ? _part$sizeInBytes : multipartOptions.sizeInBytes);
|
|
762
|
+
}
|
|
763
|
+
const baseUrl = _this.options.baseUrl.replace(/\/$/, "");
|
|
764
|
+
const path = isMultipart ? "assets/multipart-upload" : "assets/upload";
|
|
765
|
+
const url = `${baseUrl}/projects/${encodeURIComponent(_this.options.projectId)}/${path}?${query}`;
|
|
766
|
+
const response = yield _this.getUploadFetch()(url, {
|
|
767
|
+
method: "POST",
|
|
768
|
+
headers: {
|
|
769
|
+
"Content-Type": payload.type,
|
|
770
|
+
"X-Api-Key": _this.options.apiKey,
|
|
771
|
+
"X-CalmLens-Upload": isMultipart ? "part" : "content"
|
|
772
|
+
},
|
|
773
|
+
body: toRawUploadBody(payload),
|
|
774
|
+
duplex: "half"
|
|
775
|
+
});
|
|
776
|
+
const asset = yield _this.parseRawUploadResponse(response);
|
|
777
|
+
if (isMultipart && asset.status === "uploading") {
|
|
778
|
+
_this.multipartUploadQueues.set(asset.id, queue);
|
|
779
|
+
if (isImageMimeType(payload.type)) {
|
|
780
|
+
var _asset$sizeInBytes;
|
|
781
|
+
_this.multipartImageUploadSizes.set(asset.id, (_asset$sizeInBytes = asset.sizeInBytes) !== null && _asset$sizeInBytes !== void 0 ? _asset$sizeInBytes : 0);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return asset;
|
|
785
|
+
})();
|
|
786
|
+
}
|
|
787
|
+
submitRawAssetPart(assetId, part, queue) {
|
|
788
|
+
var _this2 = this;
|
|
789
|
+
return _asyncToGenerator(function* () {
|
|
790
|
+
var _part$isFinal2, _part$sizeInBytes2;
|
|
791
|
+
const query = new URLSearchParams({
|
|
792
|
+
queue: String(queue),
|
|
793
|
+
partNumber: String(part.partNumber),
|
|
794
|
+
isFinal: String((_part$isFinal2 = part.isFinal) !== null && _part$isFinal2 !== void 0 ? _part$isFinal2 : false)
|
|
795
|
+
});
|
|
796
|
+
setOptionalQueryValue(query, "sizeInBytes", (_part$sizeInBytes2 = part.sizeInBytes) !== null && _part$sizeInBytes2 !== void 0 ? _part$sizeInBytes2 : getAssetPayloadByteLength(part));
|
|
797
|
+
const url = `${_this2.options.baseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(assetId)}/part?${query}`;
|
|
798
|
+
const response = yield _this2.getUploadFetch()(url, {
|
|
799
|
+
method: "POST",
|
|
800
|
+
headers: {
|
|
801
|
+
"X-Api-Key": _this2.options.apiKey,
|
|
802
|
+
"X-CalmLens-Upload": "part"
|
|
803
|
+
},
|
|
804
|
+
body: toRawUploadBody(part),
|
|
805
|
+
duplex: "half"
|
|
806
|
+
});
|
|
807
|
+
const asset = yield _this2.parseRawUploadResponse(response);
|
|
808
|
+
if (asset.status === "uploading") {
|
|
809
|
+
var _asset$sizeInBytes2;
|
|
810
|
+
_this2.multipartImageUploadSizes.set(asset.id, (_asset$sizeInBytes2 = asset.sizeInBytes) !== null && _asset$sizeInBytes2 !== void 0 ? _asset$sizeInBytes2 : 0);
|
|
811
|
+
} else {
|
|
812
|
+
_this2.multipartImageUploadSizes.delete(assetId);
|
|
813
|
+
_this2.multipartUploadQueues.delete(assetId);
|
|
814
|
+
}
|
|
815
|
+
return asset;
|
|
816
|
+
})();
|
|
817
|
+
}
|
|
818
|
+
parseRawUploadResponse(response) {
|
|
819
|
+
return _asyncToGenerator(function* () {
|
|
820
|
+
let data;
|
|
821
|
+
try {
|
|
822
|
+
data = yield response.json();
|
|
823
|
+
} catch (cause) {
|
|
824
|
+
throw calmLensError({ id: response.ok ? "sdk/invalid-response" : "sdk/http-error" }, {
|
|
825
|
+
message: `Invalid JSON response (HTTP ${response.status})`,
|
|
826
|
+
status: response.status,
|
|
827
|
+
cause
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
if (!response.ok) {
|
|
831
|
+
if (isApiErrorPayload(data)) throw calmLensError({
|
|
832
|
+
id: data.code,
|
|
833
|
+
defaultMessage: data.message
|
|
834
|
+
}, {
|
|
835
|
+
message: data.message,
|
|
836
|
+
status: response.status,
|
|
837
|
+
details: _objectSpread2(_objectSpread2({}, data.details), {}, {
|
|
838
|
+
traceId: data.traceId,
|
|
839
|
+
network: true
|
|
840
|
+
})
|
|
841
|
+
});
|
|
842
|
+
throw calmLensError({ id: "sdk/http-error" }, {
|
|
843
|
+
message: `HTTP ${response.status}`,
|
|
844
|
+
status: response.status
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
if (!data || typeof data !== "object" || !("id" in data) || typeof data.id !== "string" || !data.id || !("status" in data) || ![
|
|
848
|
+
"uploading",
|
|
849
|
+
"pending",
|
|
850
|
+
"approved",
|
|
851
|
+
"rejected",
|
|
852
|
+
"error"
|
|
853
|
+
].includes(String(data.status))) throw calmLensError({ id: "sdk/invalid-response" }, {
|
|
854
|
+
message: "Expected an asset response",
|
|
855
|
+
status: response.status
|
|
856
|
+
});
|
|
857
|
+
return data;
|
|
858
|
+
})();
|
|
859
|
+
}
|
|
860
|
+
get cdn() {
|
|
861
|
+
var _this3 = this;
|
|
862
|
+
return {
|
|
863
|
+
/**
|
|
864
|
+
* Create a CDN URL for asset content or previews.
|
|
865
|
+
* Private assets require an authenticated request or signed URL.
|
|
866
|
+
*/
|
|
867
|
+
getAssetUrl: (_ref4) => {
|
|
868
|
+
var _options$resource;
|
|
869
|
+
let { assetIdentifier } = _ref4, options = _objectWithoutProperties(_ref4, _excluded3);
|
|
870
|
+
if (!assetIdentifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset identifier is required" });
|
|
871
|
+
const resource = (_options$resource = options.resource) !== null && _options$resource !== void 0 ? _options$resource : "content";
|
|
872
|
+
const url = `${this.options.cdnBaseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(this.options.projectId)}/${encodeURIComponent(assetIdentifier)}/${resource}`;
|
|
873
|
+
return appendCdnSelector(url, options);
|
|
874
|
+
},
|
|
875
|
+
/**
|
|
876
|
+
* Fetch asset content or previews from the CDN.
|
|
877
|
+
* Private assets are authenticated with the client's API key.
|
|
878
|
+
*/
|
|
879
|
+
serve: function() {
|
|
880
|
+
var _ref6 = _asyncToGenerator(function* (_ref5) {
|
|
881
|
+
var _this$options$cdnFetc;
|
|
882
|
+
let { assetIdentifier, init } = _ref5, urlOptions = _objectWithoutProperties(_ref5, _excluded4);
|
|
883
|
+
const fetchImpl = (_this$options$cdnFetc = _this3.options.cdnFetch) !== null && _this$options$cdnFetc !== void 0 ? _this$options$cdnFetc : globalThis.fetch;
|
|
884
|
+
if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
|
|
885
|
+
return safeFetch(fetchImpl, _this3.options, { bufferBody: false })(_this3.cdn.getAssetUrl(_objectSpread2({ assetIdentifier }, urlOptions)), withApiKeyHeader(init, _this3.options.apiKey));
|
|
886
|
+
});
|
|
887
|
+
return function serve(_x4) {
|
|
888
|
+
return _ref6.apply(this, arguments);
|
|
889
|
+
};
|
|
890
|
+
}()
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
get text() {
|
|
894
|
+
var _this4 = this;
|
|
895
|
+
return { moderate: function() {
|
|
896
|
+
var _ref7 = _asyncToGenerator(function* (options) {
|
|
897
|
+
return _this4.assets.moderate(toTextAssetOptions(options));
|
|
898
|
+
});
|
|
899
|
+
return function moderate(_x5) {
|
|
900
|
+
return _ref7.apply(this, arguments);
|
|
901
|
+
};
|
|
902
|
+
}() };
|
|
903
|
+
}
|
|
904
|
+
get assets() {
|
|
905
|
+
var _this5 = this;
|
|
906
|
+
return {
|
|
907
|
+
/**
|
|
908
|
+
* List all assets for a project
|
|
909
|
+
* @param options - Pagination and filtering options
|
|
910
|
+
* @returns Promise with paginated assets
|
|
911
|
+
*/
|
|
912
|
+
list: function() {
|
|
913
|
+
var _ref8 = _asyncToGenerator(function* (options) {
|
|
914
|
+
var _options$pageIndex;
|
|
915
|
+
return (yield _this5.endpoints.getAssetsPage.submit({
|
|
916
|
+
params: { projectId: _this5.options.projectId },
|
|
917
|
+
query: _objectSpread2(_objectSpread2({}, options), {}, { pageIndex: (_options$pageIndex = options.pageIndex) !== null && _options$pageIndex !== void 0 ? _options$pageIndex : 0 })
|
|
918
|
+
})).data;
|
|
919
|
+
});
|
|
920
|
+
return function list(_x6) {
|
|
921
|
+
return _ref8.apply(this, arguments);
|
|
922
|
+
};
|
|
923
|
+
}(),
|
|
924
|
+
/**
|
|
925
|
+
* Retrieve a specific asset by ID
|
|
926
|
+
* @param assetId - The asset ID
|
|
927
|
+
* @returns Promise with asset data
|
|
928
|
+
*/
|
|
929
|
+
retrieve: function() {
|
|
930
|
+
var _ref9 = _asyncToGenerator(function* ({ assetId }) {
|
|
931
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
932
|
+
return (yield _this5.endpoints.getAsset.submit({ params: { assetId } })).data;
|
|
933
|
+
});
|
|
934
|
+
return function retrieve(_x7) {
|
|
935
|
+
return _ref9.apply(this, arguments);
|
|
936
|
+
};
|
|
937
|
+
}(),
|
|
938
|
+
update: function() {
|
|
939
|
+
var _ref11 = _asyncToGenerator(function* (_ref10) {
|
|
940
|
+
let { assetId } = _ref10, body = _objectWithoutProperties(_ref10, _excluded5);
|
|
941
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
942
|
+
return (yield _this5.endpoints.patchAsset.submit({
|
|
943
|
+
params: { assetId },
|
|
944
|
+
body
|
|
945
|
+
})).data;
|
|
946
|
+
});
|
|
947
|
+
return function update(_x8) {
|
|
948
|
+
return _ref11.apply(this, arguments);
|
|
949
|
+
};
|
|
950
|
+
}(),
|
|
951
|
+
/**
|
|
952
|
+
* Get child assets of a parent asset
|
|
953
|
+
* @param assetId - The parent asset ID
|
|
954
|
+
* @param options - Pagination options
|
|
955
|
+
* @returns Promise with paginated child assets
|
|
956
|
+
*/
|
|
957
|
+
listChildren: function() {
|
|
958
|
+
var _ref13 = _asyncToGenerator(function* (_ref12) {
|
|
959
|
+
var _options$pageIndex2;
|
|
960
|
+
let { assetId } = _ref12, options = _objectWithoutProperties(_ref12, _excluded6);
|
|
961
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
962
|
+
return (yield _this5.endpoints.getAssetChildren.submit({
|
|
963
|
+
params: { assetId },
|
|
964
|
+
query: _objectSpread2(_objectSpread2({}, options), {}, { pageIndex: (_options$pageIndex2 = options.pageIndex) !== null && _options$pageIndex2 !== void 0 ? _options$pageIndex2 : 0 })
|
|
965
|
+
})).data;
|
|
966
|
+
});
|
|
967
|
+
return function listChildren(_x9) {
|
|
968
|
+
return _ref13.apply(this, arguments);
|
|
969
|
+
};
|
|
970
|
+
}(),
|
|
971
|
+
/**
|
|
972
|
+
* Submit a new asset for processing (queued asynchronously)
|
|
973
|
+
* The asset will be queued for classification and returned immediately.
|
|
974
|
+
* @param options - Asset submission options
|
|
975
|
+
* @returns Promise with created asset
|
|
976
|
+
*/
|
|
977
|
+
create: function() {
|
|
978
|
+
var _ref14 = _asyncToGenerator(function* (options) {
|
|
979
|
+
const body = prepareSubmitAssetOptions(options);
|
|
980
|
+
if ("content" in body || "part" in body) return yield _this5.submitRawAssetUpload(body, true);
|
|
981
|
+
return (yield _this5.endpoints.postUploadAsset.submit({
|
|
982
|
+
body: normalizeAssetOptionsForRequest(body),
|
|
983
|
+
params: { projectId: _this5.options.projectId },
|
|
984
|
+
query: { queue: true }
|
|
985
|
+
})).data;
|
|
986
|
+
});
|
|
987
|
+
return function create(_x10) {
|
|
988
|
+
return _ref14.apply(this, arguments);
|
|
989
|
+
};
|
|
990
|
+
}(),
|
|
991
|
+
/**
|
|
992
|
+
* Submit a new asset and moderate it synchronously
|
|
993
|
+
* The asset will be classified immediately before the response is returned.
|
|
994
|
+
* This may take longer but ensures the asset is fully processed.
|
|
995
|
+
* @param options - Asset submission options
|
|
996
|
+
* @returns Promise with created and analyzed asset
|
|
997
|
+
*/
|
|
998
|
+
moderate: function() {
|
|
999
|
+
var _ref15 = _asyncToGenerator(function* (options) {
|
|
1000
|
+
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" });
|
|
1001
|
+
const body = prepareSubmitAssetOptions(options);
|
|
1002
|
+
if ("content" in body || "part" in body) return yield _this5.submitRawAssetUpload(body, false);
|
|
1003
|
+
return (yield _this5.endpoints.postUploadAsset.submit({
|
|
1004
|
+
body: normalizeAssetOptionsForRequest(body),
|
|
1005
|
+
params: { projectId: _this5.options.projectId },
|
|
1006
|
+
query: { queue: false }
|
|
1007
|
+
})).data;
|
|
1008
|
+
});
|
|
1009
|
+
return function moderate(_x11) {
|
|
1010
|
+
return _ref15.apply(this, arguments);
|
|
1011
|
+
};
|
|
1012
|
+
}(),
|
|
1013
|
+
/**
|
|
1014
|
+
* Upload a part for a multipart upload
|
|
1015
|
+
* @param assetId - The asset ID
|
|
1016
|
+
* @param part - The part to upload
|
|
1017
|
+
* @returns Promise with asset data
|
|
1018
|
+
*/
|
|
1019
|
+
uploadPart: function() {
|
|
1020
|
+
var _ref16 = _asyncToGenerator(function* ({ assetId, part }) {
|
|
1021
|
+
var _part$sizeInBytes3, _this$multipartUpload;
|
|
1022
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1023
|
+
if (!part) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Part options are required" });
|
|
1024
|
+
const validation = validateAssetPayload(part, {
|
|
1025
|
+
multipart: true,
|
|
1026
|
+
isFinal: part.isFinal
|
|
1027
|
+
});
|
|
1028
|
+
if (!validation.ok) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: validation.error });
|
|
1029
|
+
const existingImageSizeInBytes = _this5.multipartImageUploadSizes.get(assetId);
|
|
1030
|
+
const partSizeInBytes = (_part$sizeInBytes3 = part.sizeInBytes) !== null && _part$sizeInBytes3 !== void 0 ? _part$sizeInBytes3 : getAssetPayloadByteLength(part);
|
|
1031
|
+
if (existingImageSizeInBytes !== void 0 && partSizeInBytes !== void 0) {
|
|
1032
|
+
const totalSizeInBytes = existingImageSizeInBytes + partSizeInBytes;
|
|
1033
|
+
if (totalSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
|
|
1034
|
+
if (part.isFinal && totalSizeInBytes < MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
|
|
1035
|
+
}
|
|
1036
|
+
return yield _this5.submitRawAssetPart(assetId, part, (_this$multipartUpload = _this5.multipartUploadQueues.get(assetId)) !== null && _this$multipartUpload !== void 0 ? _this$multipartUpload : false);
|
|
1037
|
+
});
|
|
1038
|
+
return function uploadPart(_x12) {
|
|
1039
|
+
return _ref16.apply(this, arguments);
|
|
1040
|
+
};
|
|
1041
|
+
}(),
|
|
1042
|
+
/**
|
|
1043
|
+
* Create a short-lived signed CDN URL for an asset.
|
|
1044
|
+
* This is useful for private assets where clients should not send app
|
|
1045
|
+
* auth cookies or API keys to the CDN on every media request.
|
|
1046
|
+
*/
|
|
1047
|
+
createSignedUrl: function() {
|
|
1048
|
+
var _ref18 = _asyncToGenerator(function* (_ref17) {
|
|
1049
|
+
var _options$resource2, _options$expiresInSec;
|
|
1050
|
+
let { assetId } = _ref17, options = _objectWithoutProperties(_ref17, _excluded7);
|
|
1051
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1052
|
+
if (options.lens && options.transform) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
|
|
1053
|
+
return (yield _this5.endpoints.postAssetSignedUrl.submit({
|
|
1054
|
+
body: {
|
|
1055
|
+
resource: (_options$resource2 = options.resource) !== null && _options$resource2 !== void 0 ? _options$resource2 : "content",
|
|
1056
|
+
expiresInSeconds: (_options$expiresInSec = options.expiresInSeconds) !== null && _options$expiresInSec !== void 0 ? _options$expiresInSec : 900,
|
|
1057
|
+
lens: options.lens,
|
|
1058
|
+
transform: options.transform
|
|
1059
|
+
},
|
|
1060
|
+
params: { assetId }
|
|
1061
|
+
})).data;
|
|
1062
|
+
});
|
|
1063
|
+
return function createSignedUrl(_x13) {
|
|
1064
|
+
return _ref18.apply(this, arguments);
|
|
1065
|
+
};
|
|
1066
|
+
}(),
|
|
1067
|
+
move: function() {
|
|
1068
|
+
var _ref19 = _asyncToGenerator(function* ({ assetId, folderId }) {
|
|
1069
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1070
|
+
return (yield _this5.endpoints.moveAsset.submit({
|
|
1071
|
+
params: { assetId },
|
|
1072
|
+
body: { folderId }
|
|
1073
|
+
})).data;
|
|
1074
|
+
});
|
|
1075
|
+
return function move(_x14) {
|
|
1076
|
+
return _ref19.apply(this, arguments);
|
|
1077
|
+
};
|
|
1078
|
+
}(),
|
|
1079
|
+
/**
|
|
1080
|
+
* Processes an asset that failed (status `error`) again. It returns to `pending` and is
|
|
1081
|
+
* moderated like a new upload; its content must still be stored.
|
|
1082
|
+
*/
|
|
1083
|
+
retry: function() {
|
|
1084
|
+
var _ref20 = _asyncToGenerator(function* ({ assetId }) {
|
|
1085
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1086
|
+
return (yield _this5.endpoints.retryAsset.submit({ params: { assetId } })).data;
|
|
1087
|
+
});
|
|
1088
|
+
return function retry(_x15) {
|
|
1089
|
+
return _ref20.apply(this, arguments);
|
|
1090
|
+
};
|
|
1091
|
+
}()
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
get events() {
|
|
1095
|
+
var _this6 = this;
|
|
1096
|
+
return {
|
|
1097
|
+
/**
|
|
1098
|
+
* List project events after a cursor, oldest first. Call without `after` to get a cursor
|
|
1099
|
+
* for "now", then poll with the returned `cursor`. Webhook deliveries carry the same events
|
|
1100
|
+
* reshaped as `{ id, type, createdAt, projectId, data }`.
|
|
1101
|
+
*/
|
|
1102
|
+
list: function() {
|
|
1103
|
+
var _ref21 = _asyncToGenerator(function* (options = {}) {
|
|
1104
|
+
return (yield _this6.endpoints.getEvents.submit({
|
|
1105
|
+
params: { projectId: _this6.options.projectId },
|
|
1106
|
+
query: options
|
|
1107
|
+
})).data;
|
|
1108
|
+
});
|
|
1109
|
+
return function list() {
|
|
1110
|
+
return _ref21.apply(this, arguments);
|
|
1111
|
+
};
|
|
1112
|
+
}() };
|
|
1113
|
+
}
|
|
1114
|
+
get folders() {
|
|
1115
|
+
var _this7 = this;
|
|
1116
|
+
return {
|
|
1117
|
+
list: function() {
|
|
1118
|
+
var _ref22 = _asyncToGenerator(function* () {
|
|
1119
|
+
return (yield _this7.endpoints.getFolders.submit({ params: { projectId: _this7.options.projectId } })).data.folders;
|
|
1120
|
+
});
|
|
1121
|
+
return function list() {
|
|
1122
|
+
return _ref22.apply(this, arguments);
|
|
1123
|
+
};
|
|
1124
|
+
}(),
|
|
1125
|
+
retrieve: function() {
|
|
1126
|
+
var _ref23 = _asyncToGenerator(function* ({ folderId }) {
|
|
1127
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
1128
|
+
return (yield _this7.endpoints.getFolder.submit({ params: { folderId } })).data;
|
|
1129
|
+
});
|
|
1130
|
+
return function retrieve(_x16) {
|
|
1131
|
+
return _ref23.apply(this, arguments);
|
|
1132
|
+
};
|
|
1133
|
+
}(),
|
|
1134
|
+
create: function() {
|
|
1135
|
+
var _ref24 = _asyncToGenerator(function* (options) {
|
|
1136
|
+
return (yield _this7.endpoints.postFolder.submit({
|
|
1137
|
+
params: { projectId: _this7.options.projectId },
|
|
1138
|
+
body: options
|
|
1139
|
+
})).data;
|
|
1140
|
+
});
|
|
1141
|
+
return function create(_x17) {
|
|
1142
|
+
return _ref24.apply(this, arguments);
|
|
1143
|
+
};
|
|
1144
|
+
}(),
|
|
1145
|
+
update: function() {
|
|
1146
|
+
var _ref26 = _asyncToGenerator(function* (_ref25) {
|
|
1147
|
+
let { folderId } = _ref25, body = _objectWithoutProperties(_ref25, _excluded8);
|
|
1148
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
1149
|
+
return (yield _this7.endpoints.patchFolder.submit({
|
|
1150
|
+
params: { folderId },
|
|
1151
|
+
body
|
|
1152
|
+
})).data;
|
|
1153
|
+
});
|
|
1154
|
+
return function update(_x18) {
|
|
1155
|
+
return _ref26.apply(this, arguments);
|
|
1156
|
+
};
|
|
1157
|
+
}(),
|
|
1158
|
+
delete: function() {
|
|
1159
|
+
var _ref27 = _asyncToGenerator(function* ({ folderId }) {
|
|
1160
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
1161
|
+
yield _this7.endpoints.deleteFolder.submit({ params: { folderId } });
|
|
1162
|
+
});
|
|
1163
|
+
return function _delete(_x19) {
|
|
1164
|
+
return _ref27.apply(this, arguments);
|
|
1165
|
+
};
|
|
1166
|
+
}(),
|
|
1167
|
+
move: function() {
|
|
1168
|
+
var _ref28 = _asyncToGenerator(function* ({ folderId, parentId }) {
|
|
1169
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
1170
|
+
return (yield _this7.endpoints.moveFolder.submit({
|
|
1171
|
+
params: { folderId },
|
|
1172
|
+
body: { parentId }
|
|
1173
|
+
})).data;
|
|
1174
|
+
});
|
|
1175
|
+
return function move(_x20) {
|
|
1176
|
+
return _ref28.apply(this, arguments);
|
|
1177
|
+
};
|
|
1178
|
+
}()
|
|
1179
|
+
};
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Create a named lens at any positive version, or update it with a greater version.
|
|
1183
|
+
* Supplying the same definition and version is idempotent.
|
|
1184
|
+
*/
|
|
1185
|
+
ensureLens(options) {
|
|
1186
|
+
var _this8 = this;
|
|
1187
|
+
return _asyncToGenerator(function* () {
|
|
1188
|
+
if (!options.identifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
|
|
1189
|
+
const [lens] = yield _this8.ensureLenses({ lenses: [options] });
|
|
1190
|
+
return lens;
|
|
1191
|
+
})();
|
|
1192
|
+
}
|
|
1193
|
+
/**
|
|
1194
|
+
* Create or update several named lenses in one API request.
|
|
1195
|
+
* Each lens follows the same versioning and idempotency rules as ensureLens().
|
|
1196
|
+
*/
|
|
1197
|
+
ensureLenses({ lenses }) {
|
|
1198
|
+
var _this9 = this;
|
|
1199
|
+
return _asyncToGenerator(function* () {
|
|
1200
|
+
if (lenses.length === 0) throw calmLensError({ id: "upload/invalid-payload" }, { message: "At least one lens is required" });
|
|
1201
|
+
if (lenses.some((option) => !option.identifier)) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
|
|
1202
|
+
const missingOptions = [];
|
|
1203
|
+
const missingKeys = /* @__PURE__ */ new Set();
|
|
1204
|
+
for (const option of lenses) {
|
|
1205
|
+
const cacheKey = getEnsureLensCacheKey(option);
|
|
1206
|
+
if (!_this9.ensuredLenses.has(cacheKey) && !missingKeys.has(cacheKey)) {
|
|
1207
|
+
missingKeys.add(cacheKey);
|
|
1208
|
+
missingOptions.push(option);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
if (missingOptions.length === 0) return lenses.map((option) => _this9.ensuredLenses.get(getEnsureLensCacheKey(option)));
|
|
1212
|
+
const batchCacheKey = JSON.stringify([...missingKeys].sort());
|
|
1213
|
+
let pending = _this9.pendingEnsureLenses.get(batchCacheKey);
|
|
1214
|
+
if (!pending) {
|
|
1215
|
+
pending = _this9.submitEnsureLenses(missingOptions);
|
|
1216
|
+
_this9.pendingEnsureLenses.set(batchCacheKey, pending);
|
|
1217
|
+
pending.then(() => _this9.pendingEnsureLenses.delete(batchCacheKey), () => _this9.pendingEnsureLenses.delete(batchCacheKey));
|
|
1218
|
+
}
|
|
1219
|
+
yield pending;
|
|
1220
|
+
return lenses.map((option) => _this9.ensuredLenses.get(getEnsureLensCacheKey(option)));
|
|
1221
|
+
})();
|
|
1222
|
+
}
|
|
1223
|
+
submitEnsureLenses(options) {
|
|
1224
|
+
var _this10 = this;
|
|
1225
|
+
return _asyncToGenerator(function* () {
|
|
1226
|
+
const result = yield _this10.endpoints.ensureLenses.submit({
|
|
1227
|
+
body: { lenses: options },
|
|
1228
|
+
params: { projectId: _this10.options.projectId }
|
|
1229
|
+
});
|
|
1230
|
+
for (const [index, lens] of result.data.lenses.entries()) {
|
|
1231
|
+
const optionsForLens = options[index];
|
|
1232
|
+
if (!optionsForLens) throw calmLensError({ id: "sdk/invalid-response" }, { message: "CalmLens returned an unexpected lens response" });
|
|
1233
|
+
for (const [cacheKey, cachedLens] of _this10.ensuredLenses) if (cachedLens.identifier === optionsForLens.identifier) _this10.ensuredLenses.delete(cacheKey);
|
|
1234
|
+
_this10.ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
|
|
1235
|
+
}
|
|
1236
|
+
})();
|
|
1237
|
+
}
|
|
1238
|
+
};
|
|
1239
|
+
//#endregion
|
|
1240
|
+
export { CalmLensClient, CalmLensError, MEDIA_TEST_SIGNALS, WEBHOOK_DELIVERY_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, WEBHOOK_TIMESTAMP_HEADER, createWebhookHeaders, generateMediaTestCode, toWebhookEventPayload, verifyWebhookSignature };
|