@calmlens/sdk 0.9.0 → 0.10.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/LICENSE +21 -0
- package/README.md +156 -60
- package/cjs/CalmLensTypes-BfweJTMS.d.ts +8584 -0
- package/cjs/CalmLensWebhooks-DJnaLpRy.js +741 -0
- package/cjs/index.d.ts +276 -7525
- package/cjs/index.js +662 -1184
- package/cjs/testing.d.ts +83 -8
- package/cjs/testing.js +991 -596
- package/esm/CalmLensTypes-BfweJTMS.d.ts +8584 -0
- package/esm/CalmLensWebhooks-DLUozliX.js +556 -0
- package/esm/index.d.ts +276 -7525
- package/esm/index.js +648 -1168
- package/esm/testing.d.ts +83 -8
- package/esm/testing.js +960 -592
- package/package.json +24 -18
- package/cjs/CalmLensTypes-CZqyni4p.d.ts +0 -3633
- package/cjs/CalmLensUtils-CArkVfj0.js +0 -637
- package/esm/CalmLensTypes-CZqyni4p.d.ts +0 -3633
- package/esm/CalmLensUtils-Bnikzonc.js +0 -472
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
//#region ../shared/src/AssetPayload.ts
|
|
2
|
+
const uint8ArrayInputToNumbers = (value) => {
|
|
3
|
+
if (Array.isArray(value)) return value;
|
|
4
|
+
return Array.from(value);
|
|
5
|
+
};
|
|
6
|
+
const bufferInputToBytes = (value) => {
|
|
7
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
|
8
|
+
return Uint8Array.from(value);
|
|
9
|
+
};
|
|
10
|
+
const BASE64_PART_BOUNDARY_ERROR = "Invalid base64 part. For multipart uploads, split the original bytes first, then base64-encode each part. Do not split one full base64 string into substrings.";
|
|
11
|
+
const MULTIPART_PART_TOO_SMALL_ERROR = `Multipart upload parts must be at least 5MiB except the final part.`;
|
|
12
|
+
const getRawBase64 = (value) => {
|
|
13
|
+
const markerIndex = value.indexOf(";base64,");
|
|
14
|
+
if (markerIndex === -1) return value;
|
|
15
|
+
return value.slice(markerIndex + 8);
|
|
16
|
+
};
|
|
17
|
+
const validateBase64PayloadString = (payload, options) => {
|
|
18
|
+
const raw = getRawBase64(payload.base64).replace(/\s/g, "");
|
|
19
|
+
if (options?.multipart && raw.length % 4 !== 0) return {
|
|
20
|
+
ok: false,
|
|
21
|
+
error: BASE64_PART_BOUNDARY_ERROR
|
|
22
|
+
};
|
|
23
|
+
return { ok: true };
|
|
24
|
+
};
|
|
25
|
+
const isReadableStream = (value) => typeof value === "object" && value !== null && "getReader" in value && typeof value.getReader === "function";
|
|
26
|
+
const assetToData = (payload) => {
|
|
27
|
+
if ("plainText" in payload && payload.plainText !== void 0) return new TextEncoder().encode(payload.plainText);
|
|
28
|
+
if ("data" in payload && payload.data) return payload.data;
|
|
29
|
+
if ("buffer" in payload) {
|
|
30
|
+
if (payload.buffer instanceof ArrayBuffer) return payload.buffer;
|
|
31
|
+
return bufferInputToBytes(payload.buffer);
|
|
32
|
+
}
|
|
33
|
+
if (payload.uint8Array !== void 0) return Uint8Array.from(uint8ArrayInputToNumbers(payload.uint8Array));
|
|
34
|
+
if (payload.base64 === void 0) throw new Error("Invalid asset payload");
|
|
35
|
+
const raw = getRawBase64(payload.base64);
|
|
36
|
+
if (typeof Buffer !== "undefined") return Uint8Array.from(Buffer.from(raw, "base64"));
|
|
37
|
+
const binary = atob(raw);
|
|
38
|
+
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
39
|
+
};
|
|
40
|
+
const assetDataToUint8Array = async (data) => {
|
|
41
|
+
if (data instanceof Response) return new Uint8Array(await data.arrayBuffer());
|
|
42
|
+
if (isReadableStream(data)) return new Uint8Array(await new Response(data).arrayBuffer());
|
|
43
|
+
if (data instanceof Blob) return new Uint8Array(await data.arrayBuffer());
|
|
44
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
45
|
+
return data;
|
|
46
|
+
};
|
|
47
|
+
const getAssetPayloadByteLength = (payload) => {
|
|
48
|
+
if ("plainText" in payload && payload.plainText !== void 0) return new TextEncoder().encode(payload.plainText).byteLength;
|
|
49
|
+
if ("data" in payload && payload.data) {
|
|
50
|
+
if (payload.data instanceof Blob) return payload.data.size;
|
|
51
|
+
if (payload.data instanceof Response) {
|
|
52
|
+
const contentLength = payload.data.headers.get("content-length");
|
|
53
|
+
return contentLength ? Number(contentLength) : void 0;
|
|
54
|
+
}
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if ("buffer" in payload && payload.buffer) return payload.buffer.byteLength;
|
|
58
|
+
if (payload.uint8Array !== void 0) {
|
|
59
|
+
if (Array.isArray(payload.uint8Array)) return payload.uint8Array.length;
|
|
60
|
+
return payload.uint8Array.byteLength;
|
|
61
|
+
}
|
|
62
|
+
if (payload.base64 === void 0) return;
|
|
63
|
+
const raw = getRawBase64(payload.base64).replace(/\s/g, "");
|
|
64
|
+
const padding = raw.endsWith("==") ? 2 : raw.endsWith("=") ? 1 : 0;
|
|
65
|
+
return Math.max(0, Math.floor(raw.length * 3 / 4) - padding);
|
|
66
|
+
};
|
|
67
|
+
const validateAssetPayload = (payload, options) => {
|
|
68
|
+
if ("base64" in payload && payload.base64 !== void 0) {
|
|
69
|
+
const validation = validateBase64PayloadString(payload, options);
|
|
70
|
+
if (!validation.ok) return {
|
|
71
|
+
ok: false,
|
|
72
|
+
error: validation.error
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const byteLength = getAssetPayloadByteLength(payload);
|
|
76
|
+
if (options?.multipart && !options.isFinal && byteLength !== void 0 && byteLength < 5242880) return {
|
|
77
|
+
ok: false,
|
|
78
|
+
error: MULTIPART_PART_TOO_SMALL_ERROR
|
|
79
|
+
};
|
|
80
|
+
return { ok: true };
|
|
81
|
+
};
|
|
82
|
+
//#endregion
|
|
83
|
+
//#region ../shared/src/JsonUtils.ts
|
|
84
|
+
const stringifyJsonCanonical = (value) => JSON.stringify(value, (_key, nestedValue) => {
|
|
85
|
+
if (!nestedValue || typeof nestedValue !== "object" || Array.isArray(nestedValue)) return nestedValue;
|
|
86
|
+
return Object.fromEntries(Object.keys(nestedValue).sort().map((key) => [key, nestedValue[key]]));
|
|
87
|
+
});
|
|
88
|
+
const MAX_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 20971520)();
|
|
89
|
+
const MIN_MULTIPART_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 10485760)();
|
|
90
|
+
const REJECTED_UPLOAD_MIME_TYPE_SET = /* @__PURE__ */ new Set([
|
|
91
|
+
"application/octet-stream",
|
|
92
|
+
"multipart/form-data",
|
|
93
|
+
"multipart/mixed",
|
|
94
|
+
"multipart/alternative",
|
|
95
|
+
"multipart/related",
|
|
96
|
+
"multipart/signed",
|
|
97
|
+
"multipart/encrypted"
|
|
98
|
+
]);
|
|
99
|
+
const normalizeUploadMimeType = (mimeType) => mimeType.toLowerCase().split(";")[0]?.trim() || mimeType.toLowerCase().trim();
|
|
100
|
+
const isRejectedUploadMimeType = (mimeType) => REJECTED_UPLOAD_MIME_TYPE_SET.has(normalizeUploadMimeType(mimeType));
|
|
101
|
+
const getRejectedUploadMimeTypeError = (mimeType) => `${normalizeUploadMimeType(mimeType)} is not a valid upload file type. Uploads must use a concrete file MIME type that CalmLens can store and process, such as image/png, image/jpeg, application/pdf, or text/plain.`;
|
|
102
|
+
const DOMAIN = "calmlens.com";
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/client/CalmLensErrorCodes.ts
|
|
105
|
+
/** Error codes the CalmLens API documents, by name. */
|
|
106
|
+
const API_ERROR_CODES = {
|
|
107
|
+
MISSING_TOKEN: "auth/missing-token",
|
|
108
|
+
INVALID_API_KEY: "auth/invalid-api-key",
|
|
109
|
+
API_KEY_PROJECT_MISMATCH: "auth/project-mismatch",
|
|
110
|
+
API_KEY_NOT_ACCEPTED: "auth/api-key-not-accepted",
|
|
111
|
+
FILE_TOO_LARGE: "upload/file-too-large",
|
|
112
|
+
IMAGE_REQUIRES_MULTIPART_UPLOAD: "upload/image-requires-multipart-upload",
|
|
113
|
+
MULTIPART_IMAGE_TOO_SMALL: "upload/multipart-image-too-small",
|
|
114
|
+
MULTIPART_IMAGE_TOO_LARGE: "upload/multipart-image-too-large",
|
|
115
|
+
IMAGE_EXCEEDED_MAX_DIMENSIONS: "upload/image-exceeded-max-dimensions",
|
|
116
|
+
UPLOAD_LIMIT_EXCEEDED: "upload/limit-exceeded",
|
|
117
|
+
INVALID_UPLOAD_MIME_TYPE: "upload/invalid-mime-type",
|
|
118
|
+
INVALID_EVENT_CURSOR: "events/invalid-cursor",
|
|
119
|
+
INVALID_UPLOAD_PAYLOAD: "upload/invalid-payload",
|
|
120
|
+
USE_UPLOAD_PART: "upload/use-upload-part",
|
|
121
|
+
UPLOAD_NOT_OPEN: "upload/not-open",
|
|
122
|
+
INVALID_UPLOAD_PART_NUMBER: "upload/invalid-part-number",
|
|
123
|
+
UPLOAD_MISSING: "upload/missing",
|
|
124
|
+
UPLOAD_SIZE_MISMATCH: "upload/size-mismatch",
|
|
125
|
+
INVALID_IDEMPOTENCY_KEY: "idempotency/invalid-key",
|
|
126
|
+
IDEMPOTENCY_KEY_REUSED: "idempotency/key-reused",
|
|
127
|
+
IDEMPOTENT_REQUEST_IN_PROGRESS: "idempotency/request-in-progress",
|
|
128
|
+
ASSET_NOT_FOUND: "asset/not-found",
|
|
129
|
+
PROJECT_NOT_FOUND: "project/not-found",
|
|
130
|
+
ASSET_UPDATE_FAILED: "asset/update-failed",
|
|
131
|
+
ASSET_SAFETY_HELD: "asset/safety-held",
|
|
132
|
+
ASSET_NOT_RETRYABLE: "asset/not-retryable",
|
|
133
|
+
ASSET_CONTENT_UNAVAILABLE: "asset/content-unavailable",
|
|
134
|
+
SUPPORT_TICKET_NOT_FOUND: "support/ticket-not-found",
|
|
135
|
+
DUPLICATE_EXTERNAL_ID: "asset/duplicate-external-id",
|
|
136
|
+
FOLDER_NOT_FOUND: "folder/not-found",
|
|
137
|
+
DUPLICATE_FOLDER_NAME: "folder/duplicate-name",
|
|
138
|
+
FOLDER_NOT_EMPTY: "folder/not-empty",
|
|
139
|
+
FOLDER_PARENT_CYCLE: "folder/parent-cycle",
|
|
140
|
+
LENS_VERSION_CONFLICT: "lens/version-conflict"
|
|
141
|
+
};
|
|
142
|
+
/** The HTTP status and default message the API returns with each documented error code. */
|
|
143
|
+
const API_ERROR_DEFINITIONS = {
|
|
144
|
+
"auth/missing-token": {
|
|
145
|
+
status: 401,
|
|
146
|
+
message: "Authentication required. Send your project API key in the X-Api-Key header."
|
|
147
|
+
},
|
|
148
|
+
"auth/invalid-api-key": {
|
|
149
|
+
status: 401,
|
|
150
|
+
message: "The API key is invalid, revoked or expired. Create a key under Developer → API Keys."
|
|
151
|
+
},
|
|
152
|
+
"auth/project-mismatch": {
|
|
153
|
+
status: 403,
|
|
154
|
+
message: "This API key belongs to a different project. Use a key created for the project that owns this resource."
|
|
155
|
+
},
|
|
156
|
+
"auth/api-key-not-accepted": {
|
|
157
|
+
status: 403,
|
|
158
|
+
message: "API keys are only accepted by the public API at /v1."
|
|
159
|
+
},
|
|
160
|
+
"upload/file-too-large": {
|
|
161
|
+
status: 400,
|
|
162
|
+
message: "File size exceeds limit. Maximum direct image size is 10MB, audio/video size is 50MiB, and other files is 5GB."
|
|
163
|
+
},
|
|
164
|
+
"upload/image-requires-multipart-upload": {
|
|
165
|
+
status: 400,
|
|
166
|
+
message: "Images of 10MB or more must use a multipart upload."
|
|
167
|
+
},
|
|
168
|
+
"upload/multipart-image-too-small": {
|
|
169
|
+
status: 400,
|
|
170
|
+
message: "Multipart image uploads must total at least 10MB."
|
|
171
|
+
},
|
|
172
|
+
"upload/multipart-image-too-large": {
|
|
173
|
+
status: 400,
|
|
174
|
+
message: "Multipart image uploads cannot exceed 20MB."
|
|
175
|
+
},
|
|
176
|
+
"upload/image-exceeded-max-dimensions": {
|
|
177
|
+
status: 400,
|
|
178
|
+
message: "Image exceeds maximum dimensions. Maximum dimensions are 12,000px."
|
|
179
|
+
},
|
|
180
|
+
"upload/limit-exceeded": {
|
|
181
|
+
status: 403,
|
|
182
|
+
message: "Upload limit exceeded. You have used all your free uploads. Please upgrade to Plus or Pro for unlimited uploads."
|
|
183
|
+
},
|
|
184
|
+
"upload/invalid-mime-type": {
|
|
185
|
+
status: 400,
|
|
186
|
+
message: "Upload file type is not supported. Uploads must use a concrete file MIME type that CalmLens can store and process, such as image/png, image/jpeg, application/pdf, or text/plain."
|
|
187
|
+
},
|
|
188
|
+
"events/invalid-cursor": {
|
|
189
|
+
status: 400,
|
|
190
|
+
message: "The events cursor is invalid. Use the cursor from a previous response, or omit it to start from now."
|
|
191
|
+
},
|
|
192
|
+
"upload/invalid-payload": {
|
|
193
|
+
status: 400,
|
|
194
|
+
message: "Upload payload is invalid."
|
|
195
|
+
},
|
|
196
|
+
"upload/use-upload-part": {
|
|
197
|
+
status: 409,
|
|
198
|
+
message: "Use uploadPart for multipart upload parts after the first part"
|
|
199
|
+
},
|
|
200
|
+
"upload/not-open": {
|
|
201
|
+
status: 409,
|
|
202
|
+
message: "Asset is not accepting additional parts"
|
|
203
|
+
},
|
|
204
|
+
"upload/invalid-part-number": {
|
|
205
|
+
status: 409,
|
|
206
|
+
message: "Multipart upload part number is invalid."
|
|
207
|
+
},
|
|
208
|
+
"upload/missing": {
|
|
209
|
+
status: 409,
|
|
210
|
+
message: "Multipart upload state is missing"
|
|
211
|
+
},
|
|
212
|
+
"upload/size-mismatch": {
|
|
213
|
+
status: 400,
|
|
214
|
+
message: "The uploaded parts do not add up to the totalSizeInBytes declared when the multipart upload started."
|
|
215
|
+
},
|
|
216
|
+
"idempotency/invalid-key": {
|
|
217
|
+
status: 400,
|
|
218
|
+
message: "The Idempotency-Key header must be 1 to 255 printable ASCII characters, such as a UUID."
|
|
219
|
+
},
|
|
220
|
+
"idempotency/key-reused": {
|
|
221
|
+
status: 409,
|
|
222
|
+
message: "This Idempotency-Key was already used for a different request. Use a new key for each distinct request."
|
|
223
|
+
},
|
|
224
|
+
"idempotency/request-in-progress": {
|
|
225
|
+
status: 409,
|
|
226
|
+
message: "A request with this Idempotency-Key is still being processed. Retry after the Retry-After delay to receive its result."
|
|
227
|
+
},
|
|
228
|
+
"asset/not-found": {
|
|
229
|
+
status: 404,
|
|
230
|
+
message: "Asset not found"
|
|
231
|
+
},
|
|
232
|
+
"project/not-found": {
|
|
233
|
+
status: 404,
|
|
234
|
+
message: "Project not found"
|
|
235
|
+
},
|
|
236
|
+
"asset/update-failed": {
|
|
237
|
+
status: 500,
|
|
238
|
+
message: "Failed to update asset"
|
|
239
|
+
},
|
|
240
|
+
"asset/safety-held": {
|
|
241
|
+
status: 423,
|
|
242
|
+
message: "Asset access is restricted by a safety hold."
|
|
243
|
+
},
|
|
244
|
+
"asset/not-retryable": {
|
|
245
|
+
status: 409,
|
|
246
|
+
message: "Only assets that failed to process (status error) can be retried."
|
|
247
|
+
},
|
|
248
|
+
"asset/content-unavailable": {
|
|
249
|
+
status: 409,
|
|
250
|
+
message: "This asset's content is no longer stored, so it can't be processed again. Upload it again instead."
|
|
251
|
+
},
|
|
252
|
+
"support/ticket-not-found": {
|
|
253
|
+
status: 404,
|
|
254
|
+
message: "Support ticket not found."
|
|
255
|
+
},
|
|
256
|
+
"asset/duplicate-external-id": {
|
|
257
|
+
status: 409,
|
|
258
|
+
message: "An asset with this externalId already exists in the project."
|
|
259
|
+
},
|
|
260
|
+
"folder/not-found": {
|
|
261
|
+
status: 404,
|
|
262
|
+
message: "Folder not found"
|
|
263
|
+
},
|
|
264
|
+
"folder/duplicate-name": {
|
|
265
|
+
status: 409,
|
|
266
|
+
message: "A folder with this name already exists in this location."
|
|
267
|
+
},
|
|
268
|
+
"folder/not-empty": {
|
|
269
|
+
status: 409,
|
|
270
|
+
message: "Folder must be empty before it can be deleted."
|
|
271
|
+
},
|
|
272
|
+
"folder/parent-cycle": {
|
|
273
|
+
status: 409,
|
|
274
|
+
message: "A folder cannot be moved inside itself or one of its descendants."
|
|
275
|
+
},
|
|
276
|
+
"lens/version-conflict": {
|
|
277
|
+
status: 409,
|
|
278
|
+
message: "Lens updates require a version greater than the current version."
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
//#endregion
|
|
282
|
+
//#region src/client/CalmLensError.ts
|
|
283
|
+
/** Codes for failures the SDK detects itself, before or instead of an API error response. */
|
|
284
|
+
const SDK_ERROR_CODES = {
|
|
285
|
+
/** The request could not be completed: DNS, TLS, a refused or reset connection, a truncated body. */
|
|
286
|
+
TRANSPORT_ERROR: "sdk/transport-error",
|
|
287
|
+
/** The request did not finish within `timeoutMs`. */
|
|
288
|
+
TIMEOUT: "sdk/timeout",
|
|
289
|
+
/** The caller's `AbortSignal` cancelled the request. */
|
|
290
|
+
CANCELLED: "sdk/cancelled",
|
|
291
|
+
/** A successful response whose body is not the JSON the operation returns. */
|
|
292
|
+
INVALID_RESPONSE: "sdk/invalid-response",
|
|
293
|
+
/** An HTTP failure without a CalmLens error body, for example from a proxy. */
|
|
294
|
+
HTTP_ERROR: "sdk/http-error",
|
|
295
|
+
/** A response body larger than `maxResponseBytes`. */
|
|
296
|
+
RESPONSE_TOO_LARGE: "sdk/response-too-large",
|
|
297
|
+
/** A method argument is missing or invalid, for example an empty asset ID. */
|
|
298
|
+
INVALID_ARGUMENT: "sdk/invalid-argument",
|
|
299
|
+
/** The client options are invalid, for example a missing API key. */
|
|
300
|
+
INVALID_CONFIG: "sdk/invalid-config",
|
|
301
|
+
/** No `fetch` implementation is available in this runtime. */
|
|
302
|
+
NO_FETCH: "sdk/no-fetch",
|
|
303
|
+
/** A webhook delivery whose signature or timestamp did not verify. */
|
|
304
|
+
INVALID_WEBHOOK_SIGNATURE: "sdk/invalid-webhook-signature",
|
|
305
|
+
/** A verified webhook delivery whose body is not a webhook event. */
|
|
306
|
+
INVALID_WEBHOOK_PAYLOAD: "sdk/invalid-webhook-payload"
|
|
307
|
+
};
|
|
308
|
+
/** Every error code the SDK can throw: the documented API codes and the SDK's own `sdk/*` codes. */
|
|
309
|
+
const CALMLENS_ERROR_CODES = {
|
|
310
|
+
...API_ERROR_CODES,
|
|
311
|
+
...SDK_ERROR_CODES
|
|
312
|
+
};
|
|
313
|
+
const BRAND = Symbol.for("calmlens.sdk.CalmLensError");
|
|
314
|
+
const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
|
|
315
|
+
429,
|
|
316
|
+
502,
|
|
317
|
+
503,
|
|
318
|
+
504
|
|
319
|
+
]);
|
|
320
|
+
const RETRYABLE_CODES = /* @__PURE__ */ new Set([SDK_ERROR_CODES.TRANSPORT_ERROR, API_ERROR_CODES.IDEMPOTENT_REQUEST_IN_PROGRESS]);
|
|
321
|
+
/**
|
|
322
|
+
* Every failure the SDK reports, whether the API returned an error or the request never
|
|
323
|
+
* completed. Branch on `code`; `status`, `requestId`, `headers` and `retryAfter` describe the
|
|
324
|
+
* HTTP response when there was one, and `cause` holds the underlying error.
|
|
325
|
+
*
|
|
326
|
+
* `instanceof CalmLensError` and `CalmLensError.isCalmLensError(value)` both recognise errors
|
|
327
|
+
* from any copy of the SDK, so they work when ESM and CommonJS builds are loaded side by side.
|
|
328
|
+
*/
|
|
329
|
+
var CalmLensError = class CalmLensError extends Error {
|
|
330
|
+
constructor(code, options = {}) {
|
|
331
|
+
const id = typeof code === "string" ? code : code.id;
|
|
332
|
+
const defaultMessage = typeof code === "string" ? void 0 : code.defaultMessage;
|
|
333
|
+
super(`[calmlens] ${options.message ?? defaultMessage ?? id}`, { cause: options.cause });
|
|
334
|
+
this.name = "CalmLensError";
|
|
335
|
+
this.code = id;
|
|
336
|
+
this.status = options.status;
|
|
337
|
+
this.details = options.details;
|
|
338
|
+
this.requestId = options.requestId;
|
|
339
|
+
this.headers = options.headers;
|
|
340
|
+
this.retryAfter = options.retryAfter;
|
|
341
|
+
Object.defineProperty(this, BRAND, { value: true });
|
|
342
|
+
}
|
|
343
|
+
/** True for any `CalmLensError`, including one created by another copy or build of the SDK. */
|
|
344
|
+
static isCalmLensError(value) {
|
|
345
|
+
return typeof value === "object" && value !== null && value[BRAND] === true;
|
|
346
|
+
}
|
|
347
|
+
static [Symbol.hasInstance](value) {
|
|
348
|
+
return CalmLensError.isCalmLensError(value);
|
|
349
|
+
}
|
|
350
|
+
/** The resource does not exist or is not visible to this API key. */
|
|
351
|
+
isNotFound() {
|
|
352
|
+
return this.status === 404;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Whether repeating the same request may succeed: transport failures, throttling (429),
|
|
356
|
+
* gateway errors (502, 503, 504) and idempotent requests still in progress. Only repeat a
|
|
357
|
+
* create or upload with the same `idempotencyKey`.
|
|
358
|
+
*/
|
|
359
|
+
isRetryable() {
|
|
360
|
+
return RETRYABLE_CODES.has(this.code) || this.status !== void 0 && RETRYABLE_STATUSES.has(this.status);
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
const invalidArgument = (message, details) => new CalmLensError(SDK_ERROR_CODES.INVALID_ARGUMENT, {
|
|
364
|
+
message,
|
|
365
|
+
details
|
|
366
|
+
});
|
|
367
|
+
const invalidConfig = (message) => new CalmLensError(SDK_ERROR_CODES.INVALID_CONFIG, { message });
|
|
368
|
+
//#endregion
|
|
369
|
+
//#region src/client/CalmLensUtils.ts
|
|
370
|
+
const assertHttpUrl = (name, value) => {
|
|
371
|
+
if (value === void 0) return;
|
|
372
|
+
let url;
|
|
373
|
+
try {
|
|
374
|
+
url = new URL(value);
|
|
375
|
+
} catch {}
|
|
376
|
+
if (!url || url.protocol !== "https:" && url.protocol !== "http:") throw invalidConfig(`${name} must be an absolute http(s) URL`);
|
|
377
|
+
};
|
|
378
|
+
const assertInteger = (name, value, minimum) => {
|
|
379
|
+
if (value !== void 0 && (!Number.isSafeInteger(value) || value < minimum)) throw invalidConfig(minimum === 0 ? `${name} must be a non-negative integer` : `${name} must be a positive integer`);
|
|
380
|
+
};
|
|
381
|
+
/**
|
|
382
|
+
* Checks client options before the client sets anything up. `CalmLensClient` and
|
|
383
|
+
* `MockCalmLensClient` share it so both reject the same configuration.
|
|
384
|
+
*/
|
|
385
|
+
const validateClientOptions = (options) => {
|
|
386
|
+
if (!options || typeof options !== "object") throw invalidConfig("Client options are required");
|
|
387
|
+
if (!options.apiKey || typeof options.apiKey !== "string") throw invalidConfig("API key is required");
|
|
388
|
+
if (!options.projectId) throw invalidConfig("Project ID is required");
|
|
389
|
+
try {
|
|
390
|
+
encodePathSegment(options.projectId, "Project ID");
|
|
391
|
+
} catch (error) {
|
|
392
|
+
throw invalidConfig(error.message.replace(/^\[calmlens\] /, ""));
|
|
393
|
+
}
|
|
394
|
+
if ("requestBackend" in options) throw invalidConfig("requestBackend is no longer supported; pass a fetch implementation as fetch");
|
|
395
|
+
validateRequestOptions(options);
|
|
396
|
+
assertInteger("maxResponseBytes", options.maxResponseBytes, 1);
|
|
397
|
+
for (const name of [
|
|
398
|
+
"fetch",
|
|
399
|
+
"uploadFetch",
|
|
400
|
+
"cdnFetch"
|
|
401
|
+
]) if (options[name] !== void 0 && typeof options[name] !== "function") throw invalidConfig(`${name} must be a function`);
|
|
402
|
+
assertHttpUrl("baseUrl", options.baseUrl);
|
|
403
|
+
assertHttpUrl("cdnBaseUrl", options.cdnBaseUrl);
|
|
404
|
+
};
|
|
405
|
+
/** Checks the options `withRequestOptions` accepts. */
|
|
406
|
+
const validateRequestOptions = (options) => {
|
|
407
|
+
assertInteger("timeoutMs", options.timeoutMs, 1);
|
|
408
|
+
assertInteger("uploadTimeoutMs", options.uploadTimeoutMs, 1);
|
|
409
|
+
assertInteger("maxRetries", options.maxRetries, 0);
|
|
410
|
+
};
|
|
411
|
+
const toTextAssetOptions = ({ text, name, ...options }) => {
|
|
412
|
+
if (typeof text !== "string" || !text.trim()) throw new CalmLensError(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Text to moderate must be a non-empty string" });
|
|
413
|
+
return {
|
|
414
|
+
...options,
|
|
415
|
+
name: name ?? "text",
|
|
416
|
+
content: {
|
|
417
|
+
plainText: text,
|
|
418
|
+
type: "text/plain"
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
};
|
|
422
|
+
/**
|
|
423
|
+
* Encodes an identifier as one URL path segment. `.` and `..` are rejected because URL
|
|
424
|
+
* resolution would treat them as relative segments and send the request to another route.
|
|
425
|
+
*/
|
|
426
|
+
const encodePathSegment = (value, name) => {
|
|
427
|
+
if (typeof value !== "string" || !value) throw invalidArgument(`${name} is required`);
|
|
428
|
+
if (value === "." || value === "..") throw invalidArgument(`${name} cannot be "." or ".."`);
|
|
429
|
+
return encodeURIComponent(value);
|
|
430
|
+
};
|
|
431
|
+
/** Appends a CDN lens (`/@name`) or direct transform selector to an asset URL. */
|
|
432
|
+
const appendCdnSelector = (url, options) => {
|
|
433
|
+
if (options.lens && options.transform) throw invalidArgument("Specify either a lens or a transform, not both");
|
|
434
|
+
if (options.lens) return `${url}/@${encodePathSegment(options.lens, "Lens")}`;
|
|
435
|
+
if (!options.transform) return url;
|
|
436
|
+
const transform = options.transform.replace(/^\/+/, "");
|
|
437
|
+
if (transform.includes("..") || transform.includes("?") || transform.includes("#")) throw invalidArgument("Transform cannot contain \"..\", \"?\" or \"#\"");
|
|
438
|
+
return `${url}/${encodeURI(transform)}`;
|
|
439
|
+
};
|
|
440
|
+
const appendQueryValue = (parts, key, value) => {
|
|
441
|
+
if (value === void 0 || value === null) return;
|
|
442
|
+
if (Array.isArray(value)) {
|
|
443
|
+
for (const [index, item] of value.entries()) appendQueryValue(parts, `${key}[${index}]`, item);
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (typeof value === "object") {
|
|
447
|
+
for (const [field, item] of Object.entries(value)) appendQueryValue(parts, `${key}[${field}]`, item);
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
|
|
451
|
+
};
|
|
452
|
+
/**
|
|
453
|
+
* Serialises a query object the way the API parses it (qs bracket notation), for example
|
|
454
|
+
* `ordering[0][field]=createdAt&ordering[0][direction]=DESC`. Every key and value is
|
|
455
|
+
* percent-encoded and missing values are omitted.
|
|
456
|
+
*/
|
|
457
|
+
const stringifyQuery = (query) => {
|
|
458
|
+
const parts = [];
|
|
459
|
+
for (const [key, value] of Object.entries(query)) appendQueryValue(parts, key, value);
|
|
460
|
+
return parts.join("&");
|
|
461
|
+
};
|
|
462
|
+
//#endregion
|
|
463
|
+
//#region ../shared/src/CryptoUtils.ts
|
|
464
|
+
const encoder = new TextEncoder();
|
|
465
|
+
/** Lowercase hex of `bytes`, two characters per byte. */
|
|
466
|
+
const bytesToHex = (bytes) => Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
467
|
+
/** HMAC-SHA256 of `message` keyed with `secret` (both UTF-8 encoded), as lowercase hex. */
|
|
468
|
+
const hmacSha256Hex = async (secret, message) => {
|
|
469
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
470
|
+
name: "HMAC",
|
|
471
|
+
hash: "SHA-256"
|
|
472
|
+
}, false, ["sign"]);
|
|
473
|
+
return bytesToHex(await crypto.subtle.sign("HMAC", key, encoder.encode(message)));
|
|
474
|
+
};
|
|
475
|
+
/**
|
|
476
|
+
* Compares two strings without leaking, through timing, where they first differ. Strings of
|
|
477
|
+
* different lengths are unequal immediately (the length itself is not secret here).
|
|
478
|
+
*/
|
|
479
|
+
const timingSafeEqual = (a, b) => {
|
|
480
|
+
if (a.length !== b.length) return false;
|
|
481
|
+
let difference = 0;
|
|
482
|
+
for (let index = 0; index < a.length; index++) difference |= a.charCodeAt(index) ^ b.charCodeAt(index);
|
|
483
|
+
return difference === 0;
|
|
484
|
+
};
|
|
485
|
+
//#endregion
|
|
486
|
+
//#region src/client/CalmLensWebhooks.ts
|
|
487
|
+
const WEBHOOK_DELIVERY_HEADER = "x-calmlens-delivery";
|
|
488
|
+
const WEBHOOK_TIMESTAMP_HEADER = "x-calmlens-timestamp";
|
|
489
|
+
const WEBHOOK_SIGNATURE_HEADER = "x-calmlens-signature";
|
|
490
|
+
/** Deliveries whose timestamp is further than this from the receiver's clock are rejected. */
|
|
491
|
+
const WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = 300;
|
|
492
|
+
const readHeader = (headers, name) => {
|
|
493
|
+
if (!headers) return void 0;
|
|
494
|
+
if (typeof headers.get === "function") return headers.get(name) ?? void 0;
|
|
495
|
+
const record = headers;
|
|
496
|
+
const key = Object.keys(record).find((candidate) => candidate.toLowerCase() === name);
|
|
497
|
+
const value = key === void 0 ? void 0 : record[key];
|
|
498
|
+
return Array.isArray(value) ? value.join(",") : value ?? void 0;
|
|
499
|
+
};
|
|
500
|
+
/** The raw body as text. Parsed objects are refused: re-serializing JSON changes the signed bytes. */
|
|
501
|
+
const payloadToText = (payload) => {
|
|
502
|
+
if (typeof payload === "string") return payload;
|
|
503
|
+
if (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload)) {
|
|
504
|
+
const view = ArrayBuffer.isView(payload) ? new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength) : new Uint8Array(payload);
|
|
505
|
+
return new TextDecoder("utf-8", { fatal: false }).decode(view);
|
|
506
|
+
}
|
|
507
|
+
throw invalidArgument("Webhook payload must be the raw request body as a string, Uint8Array/Buffer or ArrayBuffer, not parsed JSON");
|
|
508
|
+
};
|
|
509
|
+
/**
|
|
510
|
+
* Verifies a webhook delivery: `x-calmlens-signature` must contain a `v1=` HMAC-SHA256 of
|
|
511
|
+
* `"<x-calmlens-timestamp>.<raw body>"`, and the timestamp must be within `toleranceSeconds`
|
|
512
|
+
* (default 300) of now. Returns `false` for anything missing, malformed or stale, and throws
|
|
513
|
+
* `sdk/invalid-argument` when `payload` is not a raw body (for example, parsed JSON).
|
|
514
|
+
*/
|
|
515
|
+
async function verifyWebhookSignature(options) {
|
|
516
|
+
const { payload, secret, toleranceSeconds = 300, now, headers } = options;
|
|
517
|
+
const body = payloadToText(payload);
|
|
518
|
+
const signature = options.signature ?? readHeader(headers, "x-calmlens-signature");
|
|
519
|
+
const timestamp = options.timestamp ?? readHeader(headers, "x-calmlens-timestamp");
|
|
520
|
+
if (!secret || !signature || timestamp === null || timestamp === void 0) return false;
|
|
521
|
+
const timestampText = String(timestamp).trim();
|
|
522
|
+
if (!/^\d+$/.test(timestampText)) return false;
|
|
523
|
+
const nowMs = now === void 0 ? Date.now() : now instanceof Date ? now.getTime() : now;
|
|
524
|
+
if (Math.abs(Math.floor(nowMs / 1e3) - Number(timestampText)) > toleranceSeconds) return false;
|
|
525
|
+
const candidates = signature.split(",").map((part) => part.trim()).filter((part) => part.startsWith("v1=")).map((part) => part.slice(3).toLowerCase());
|
|
526
|
+
if (candidates.length === 0) return false;
|
|
527
|
+
const expected = await hmacSha256Hex(secret, `${timestampText}.${body}`);
|
|
528
|
+
let matched = false;
|
|
529
|
+
for (const candidate of candidates) if (timingSafeEqual(expected, candidate)) matched = true;
|
|
530
|
+
return matched;
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Verifies a webhook delivery and parses its body. Throws `sdk/invalid-webhook-signature`
|
|
534
|
+
* when the signature or timestamp does not verify, and `sdk/invalid-webhook-payload` when a
|
|
535
|
+
* verified body is not a webhook event. Narrow the result on `type` for typed `data.facts`.
|
|
536
|
+
*
|
|
537
|
+
* Event types and fact keys added to CalmLens after this SDK version are returned as they are,
|
|
538
|
+
* so keep a default branch when you switch on `type`.
|
|
539
|
+
*/
|
|
540
|
+
async function parseWebhookEvent(options) {
|
|
541
|
+
if (!await verifyWebhookSignature(options)) throw new CalmLensError(SDK_ERROR_CODES.INVALID_WEBHOOK_SIGNATURE, { message: "Webhook signature or timestamp did not verify" });
|
|
542
|
+
let event;
|
|
543
|
+
try {
|
|
544
|
+
event = JSON.parse(payloadToText(options.payload));
|
|
545
|
+
} catch (cause) {
|
|
546
|
+
throw new CalmLensError(SDK_ERROR_CODES.INVALID_WEBHOOK_PAYLOAD, {
|
|
547
|
+
message: "Webhook body is not JSON",
|
|
548
|
+
cause
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
const candidate = event;
|
|
552
|
+
if (!candidate || typeof candidate !== "object" || typeof candidate.id !== "string" || typeof candidate.type !== "string" || typeof candidate.projectId !== "string" || !candidate.data || typeof candidate.data !== "object") throw new CalmLensError(SDK_ERROR_CODES.INVALID_WEBHOOK_PAYLOAD, { message: "Webhook body is not a CalmLens event" });
|
|
553
|
+
return event;
|
|
554
|
+
}
|
|
555
|
+
//#endregion
|
|
556
|
+
Object.defineProperty(exports, "API_ERROR_CODES", {
|
|
557
|
+
enumerable: true,
|
|
558
|
+
get: function() {
|
|
559
|
+
return API_ERROR_CODES;
|
|
560
|
+
}
|
|
561
|
+
});
|
|
562
|
+
Object.defineProperty(exports, "API_ERROR_DEFINITIONS", {
|
|
563
|
+
enumerable: true,
|
|
564
|
+
get: function() {
|
|
565
|
+
return API_ERROR_DEFINITIONS;
|
|
566
|
+
}
|
|
567
|
+
});
|
|
568
|
+
Object.defineProperty(exports, "CALMLENS_ERROR_CODES", {
|
|
569
|
+
enumerable: true,
|
|
570
|
+
get: function() {
|
|
571
|
+
return CALMLENS_ERROR_CODES;
|
|
572
|
+
}
|
|
573
|
+
});
|
|
574
|
+
Object.defineProperty(exports, "CalmLensError", {
|
|
575
|
+
enumerable: true,
|
|
576
|
+
get: function() {
|
|
577
|
+
return CalmLensError;
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
Object.defineProperty(exports, "DOMAIN", {
|
|
581
|
+
enumerable: true,
|
|
582
|
+
get: function() {
|
|
583
|
+
return DOMAIN;
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
Object.defineProperty(exports, "MAX_IMAGE_UPLOAD_BYTES", {
|
|
587
|
+
enumerable: true,
|
|
588
|
+
get: function() {
|
|
589
|
+
return MAX_IMAGE_UPLOAD_BYTES;
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
Object.defineProperty(exports, "MIN_MULTIPART_IMAGE_UPLOAD_BYTES", {
|
|
593
|
+
enumerable: true,
|
|
594
|
+
get: function() {
|
|
595
|
+
return MIN_MULTIPART_IMAGE_UPLOAD_BYTES;
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
Object.defineProperty(exports, "SDK_ERROR_CODES", {
|
|
599
|
+
enumerable: true,
|
|
600
|
+
get: function() {
|
|
601
|
+
return SDK_ERROR_CODES;
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
Object.defineProperty(exports, "WEBHOOK_DELIVERY_HEADER", {
|
|
605
|
+
enumerable: true,
|
|
606
|
+
get: function() {
|
|
607
|
+
return WEBHOOK_DELIVERY_HEADER;
|
|
608
|
+
}
|
|
609
|
+
});
|
|
610
|
+
Object.defineProperty(exports, "WEBHOOK_SIGNATURE_HEADER", {
|
|
611
|
+
enumerable: true,
|
|
612
|
+
get: function() {
|
|
613
|
+
return WEBHOOK_SIGNATURE_HEADER;
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
Object.defineProperty(exports, "WEBHOOK_SIGNATURE_TOLERANCE_SECONDS", {
|
|
617
|
+
enumerable: true,
|
|
618
|
+
get: function() {
|
|
619
|
+
return WEBHOOK_SIGNATURE_TOLERANCE_SECONDS;
|
|
620
|
+
}
|
|
621
|
+
});
|
|
622
|
+
Object.defineProperty(exports, "WEBHOOK_TIMESTAMP_HEADER", {
|
|
623
|
+
enumerable: true,
|
|
624
|
+
get: function() {
|
|
625
|
+
return WEBHOOK_TIMESTAMP_HEADER;
|
|
626
|
+
}
|
|
627
|
+
});
|
|
628
|
+
Object.defineProperty(exports, "appendCdnSelector", {
|
|
629
|
+
enumerable: true,
|
|
630
|
+
get: function() {
|
|
631
|
+
return appendCdnSelector;
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
Object.defineProperty(exports, "assetDataToUint8Array", {
|
|
635
|
+
enumerable: true,
|
|
636
|
+
get: function() {
|
|
637
|
+
return assetDataToUint8Array;
|
|
638
|
+
}
|
|
639
|
+
});
|
|
640
|
+
Object.defineProperty(exports, "assetToData", {
|
|
641
|
+
enumerable: true,
|
|
642
|
+
get: function() {
|
|
643
|
+
return assetToData;
|
|
644
|
+
}
|
|
645
|
+
});
|
|
646
|
+
Object.defineProperty(exports, "encodePathSegment", {
|
|
647
|
+
enumerable: true,
|
|
648
|
+
get: function() {
|
|
649
|
+
return encodePathSegment;
|
|
650
|
+
}
|
|
651
|
+
});
|
|
652
|
+
Object.defineProperty(exports, "getAssetPayloadByteLength", {
|
|
653
|
+
enumerable: true,
|
|
654
|
+
get: function() {
|
|
655
|
+
return getAssetPayloadByteLength;
|
|
656
|
+
}
|
|
657
|
+
});
|
|
658
|
+
Object.defineProperty(exports, "getRawBase64", {
|
|
659
|
+
enumerable: true,
|
|
660
|
+
get: function() {
|
|
661
|
+
return getRawBase64;
|
|
662
|
+
}
|
|
663
|
+
});
|
|
664
|
+
Object.defineProperty(exports, "getRejectedUploadMimeTypeError", {
|
|
665
|
+
enumerable: true,
|
|
666
|
+
get: function() {
|
|
667
|
+
return getRejectedUploadMimeTypeError;
|
|
668
|
+
}
|
|
669
|
+
});
|
|
670
|
+
Object.defineProperty(exports, "hmacSha256Hex", {
|
|
671
|
+
enumerable: true,
|
|
672
|
+
get: function() {
|
|
673
|
+
return hmacSha256Hex;
|
|
674
|
+
}
|
|
675
|
+
});
|
|
676
|
+
Object.defineProperty(exports, "invalidArgument", {
|
|
677
|
+
enumerable: true,
|
|
678
|
+
get: function() {
|
|
679
|
+
return invalidArgument;
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
Object.defineProperty(exports, "invalidConfig", {
|
|
683
|
+
enumerable: true,
|
|
684
|
+
get: function() {
|
|
685
|
+
return invalidConfig;
|
|
686
|
+
}
|
|
687
|
+
});
|
|
688
|
+
Object.defineProperty(exports, "isRejectedUploadMimeType", {
|
|
689
|
+
enumerable: true,
|
|
690
|
+
get: function() {
|
|
691
|
+
return isRejectedUploadMimeType;
|
|
692
|
+
}
|
|
693
|
+
});
|
|
694
|
+
Object.defineProperty(exports, "parseWebhookEvent", {
|
|
695
|
+
enumerable: true,
|
|
696
|
+
get: function() {
|
|
697
|
+
return parseWebhookEvent;
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
Object.defineProperty(exports, "stringifyJsonCanonical", {
|
|
701
|
+
enumerable: true,
|
|
702
|
+
get: function() {
|
|
703
|
+
return stringifyJsonCanonical;
|
|
704
|
+
}
|
|
705
|
+
});
|
|
706
|
+
Object.defineProperty(exports, "stringifyQuery", {
|
|
707
|
+
enumerable: true,
|
|
708
|
+
get: function() {
|
|
709
|
+
return stringifyQuery;
|
|
710
|
+
}
|
|
711
|
+
});
|
|
712
|
+
Object.defineProperty(exports, "toTextAssetOptions", {
|
|
713
|
+
enumerable: true,
|
|
714
|
+
get: function() {
|
|
715
|
+
return toTextAssetOptions;
|
|
716
|
+
}
|
|
717
|
+
});
|
|
718
|
+
Object.defineProperty(exports, "validateAssetPayload", {
|
|
719
|
+
enumerable: true,
|
|
720
|
+
get: function() {
|
|
721
|
+
return validateAssetPayload;
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
Object.defineProperty(exports, "validateClientOptions", {
|
|
725
|
+
enumerable: true,
|
|
726
|
+
get: function() {
|
|
727
|
+
return validateClientOptions;
|
|
728
|
+
}
|
|
729
|
+
});
|
|
730
|
+
Object.defineProperty(exports, "validateRequestOptions", {
|
|
731
|
+
enumerable: true,
|
|
732
|
+
get: function() {
|
|
733
|
+
return validateRequestOptions;
|
|
734
|
+
}
|
|
735
|
+
});
|
|
736
|
+
Object.defineProperty(exports, "verifyWebhookSignature", {
|
|
737
|
+
enumerable: true,
|
|
738
|
+
get: function() {
|
|
739
|
+
return verifyWebhookSignature;
|
|
740
|
+
}
|
|
741
|
+
});
|