calmlens 0.28.2 → 0.29.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/bin/calmlens.js +151 -123
- package/cjs/{BrowserUpload-DmKNP0Vy.js → BrowserUpload-CcSQI7Kf.js} +1 -1
- package/cjs/{BrowserUpload-CRbCsX7a.d.ts → BrowserUpload-CeGsM9h1.d.ts} +2 -2
- package/cjs/{CalmLensAppClient-Bl9VU7S2.js → CalmLensAppClient-BPILD5mg.js} +11 -17
- package/cjs/{CalmLensAppClient-B3u6BlP5.d.ts → CalmLensAppClient-D-BD_Ny1.d.ts} +7 -1
- package/cjs/{CalmLensOptionKeys-DolSy6qV.js → CalmLensConnection-Wfxn25LT.js} +660 -643
- package/cjs/{CalmLensServerClient-B8ntjNL3.d.ts → CalmLensServerClient-BYN_N0lt.d.ts} +33 -2
- package/cjs/{CalmLensServerClient-DA-sB9ru.js → CalmLensServerClient-C_42j_i4.js} +72 -41
- package/cjs/{CalmLensTypes-CtO4Dieu.d.ts → CalmLensTypes-C2blKgTu.d.ts} +51 -75
- package/{esm/Core-BJaLU71Q.d.ts → cjs/Core-CNmoxDCW.d.ts} +2 -2
- package/cjs/{Core-RSm9Xcse.js → Core-CfdovxKJ.js} +2 -2
- package/cjs/{ModerationContextLimits-51OdOFof.js → ModerationContextLimits-DXlPrt4K.js} +24 -13
- package/cjs/{ReactUpload-DQYHaJSZ.js → ReactUpload-CzsQwVKM.js} +1 -1
- package/cjs/{ReactUpload-BGUkcMpg.d.ts → ReactUpload-kqEe6gcN.d.ts} +1 -1
- package/cjs/{UploadController-C6Gt-YQA.js → UploadController-D_Y5wktq.js} +2 -2
- package/cjs/{WebhookPayload-DZadhbAJ.d.ts → WebhookPayload-DZWlnvcY.d.ts} +3 -2
- package/cjs/app.d.ts +5 -5
- package/cjs/app.js +2 -2
- package/cjs/elements.d.ts +4 -4
- package/cjs/elements.js +4 -4
- package/cjs/{index-DQUZYLVY.d.ts → index-Dl2qwS8L.d.ts} +2 -2
- package/cjs/index.d.ts +4 -4
- package/cjs/index.js +1 -1
- package/cjs/react-native.d.ts +2 -2
- package/cjs/react-native.js +4 -4
- package/cjs/react.d.ts +4 -4
- package/cjs/react.js +5 -5
- package/cjs/server.d.ts +5 -5
- package/cjs/server.js +2 -2
- package/cjs/testing.d.ts +46 -12
- package/cjs/testing.js +405 -88
- package/cjs/{ui-BGywTQ2M.d.ts → ui-BtmJC-f9.d.ts} +2 -2
- package/cjs/{ui-Ntkv4inL.js → ui-CkOexkAO.js} +2 -2
- package/cjs/ui.d.ts +2 -2
- package/cjs/ui.js +3 -3
- package/cjs/vue.d.ts +5 -5
- package/cjs/vue.js +4 -4
- package/esm/{BrowserUpload-CRbCsX7a.d.ts → BrowserUpload-CeGsM9h1.d.ts} +2 -2
- package/esm/{BrowserUpload-CvUgnS8I.js → BrowserUpload-DJ2euKyv.js} +1 -1
- package/esm/{CalmLensAppClient-ktB4Vfbk.js → CalmLensAppClient-CCT5Em2S.js} +3 -9
- package/esm/{CalmLensAppClient-B3u6BlP5.d.ts → CalmLensAppClient-D-BD_Ny1.d.ts} +7 -1
- package/esm/{CalmLensOptionKeys-DCO58tKr.js → CalmLensConnection-CfBXkam-.js} +661 -644
- package/esm/{CalmLensServerClient-B8ntjNL3.d.ts → CalmLensServerClient-BYN_N0lt.d.ts} +33 -2
- package/esm/{CalmLensServerClient-D02L8AUH.js → CalmLensServerClient-e6gVcMxy.js} +58 -27
- package/esm/{CalmLensTypes-CtO4Dieu.d.ts → CalmLensTypes-C2blKgTu.d.ts} +51 -75
- package/{cjs/Core-BJaLU71Q.d.ts → esm/Core-CNmoxDCW.d.ts} +2 -2
- package/esm/{Core-22KeL-HD.js → Core-CojlqrKH.js} +2 -2
- package/esm/{ModerationContextLimits-BFfngsVu.js → ModerationContextLimits-Abu_L1Df.js} +24 -13
- package/esm/{ReactUpload-CFGawuk6.js → ReactUpload-CDrA7hRn.js} +1 -1
- package/esm/{ReactUpload-BGUkcMpg.d.ts → ReactUpload-kqEe6gcN.d.ts} +1 -1
- package/esm/{UploadController-CLEvEwzd.js → UploadController-BubUXclM.js} +2 -2
- package/esm/{WebhookPayload-DZadhbAJ.d.ts → WebhookPayload-DZWlnvcY.d.ts} +3 -2
- package/esm/app.d.ts +5 -5
- package/esm/app.js +2 -2
- package/esm/elements.d.ts +4 -4
- package/esm/elements.js +4 -4
- package/esm/{index-DQUZYLVY.d.ts → index-Dl2qwS8L.d.ts} +2 -2
- package/esm/index.d.ts +4 -4
- package/esm/index.js +1 -1
- package/esm/react-native.d.ts +2 -2
- package/esm/react-native.js +4 -4
- package/esm/react.d.ts +4 -4
- package/esm/react.js +5 -5
- package/esm/server.d.ts +5 -5
- package/esm/server.js +2 -2
- package/esm/testing.d.ts +46 -12
- package/esm/testing.js +398 -82
- package/esm/{ui-C9u03xc3.js → ui--AzgLLVf.js} +2 -2
- package/esm/{ui-BGywTQ2M.d.ts → ui-BtmJC-f9.d.ts} +2 -2
- package/esm/ui.d.ts +2 -2
- package/esm/ui.js +3 -3
- package/esm/vue.d.ts +5 -5
- package/esm/vue.js +4 -4
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as MAX_IMAGE_UPLOAD_BYTES, F as sleep, M as getRejectedUploadMimeTypeError, P as CalmLensTransport, Q as CalmLensError, S as stringifyQuery, U as resolveLogLevel, _ as isAcceptedUploadMimeType, b as randomUuid, ft as API_ERROR_CODES, j as MAX_NON_IMAGE_UPLOAD_BYTES, k as MAX_DIRECT_IMAGE_UPLOAD_BYTES, lt as SDK_ERROR_CODES, r as selectModerationContextItems, ut as invalidArgument } from "./ModerationContextLimits-
|
|
1
|
+
import { A as MAX_IMAGE_UPLOAD_BYTES, F as sleep, M as getRejectedUploadMimeTypeError, P as CalmLensTransport, Q as CalmLensError, S as stringifyQuery, U as resolveLogLevel, _ as isAcceptedUploadMimeType, b as randomUuid, ft as API_ERROR_CODES, j as MAX_NON_IMAGE_UPLOAD_BYTES, k as MAX_DIRECT_IMAGE_UPLOAD_BYTES, lt as SDK_ERROR_CODES, r as selectModerationContextItems, ut as invalidArgument } from "./ModerationContextLimits-Abu_L1Df.js";
|
|
2
2
|
// src/contract/AssetPayload.js
|
|
3
3
|
const bufferInputToBytes = (value) => {
|
|
4
4
|
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
|
@@ -89,566 +89,6 @@ const validateAssetPayload = (payload, options) => {
|
|
|
89
89
|
*/
|
|
90
90
|
const MAX_MEDIA_UPLOAD_BYTES = 52428800;
|
|
91
91
|
const MAX_LONG_MEDIA_UPLOAD_BYTES = 2147483648;
|
|
92
|
-
/**
|
|
93
|
-
* Where `calmlens/testing` puts its hooks in client options. Not part of the public API:
|
|
94
|
-
* the mock clients run the real clients against their in-memory API with these.
|
|
95
|
-
*/
|
|
96
|
-
const MOCK_HOOKS = Symbol.for("@calmlens/sdk.mockHooks");
|
|
97
|
-
/** The mock hooks in client options, if a mock client set them. */
|
|
98
|
-
const getMockHooks = (options) => options[MOCK_HOOKS];
|
|
99
|
-
/** Content larger than this is uploaded in parts of this size (`partSizeBytes`). */
|
|
100
|
-
const DEFAULT_PART_SIZE_BYTES = 8388608;
|
|
101
|
-
/**
|
|
102
|
-
* The size of content the client can split, read again and resend: bytes, base64 and Blobs.
|
|
103
|
-
* Streams and Responses can be read only once, and text stays one request.
|
|
104
|
-
*/
|
|
105
|
-
const getSplittableContent = (content) => {
|
|
106
|
-
if ("plainText" in content && content.plainText !== void 0) return void 0;
|
|
107
|
-
if ("data" in content && content.data !== void 0) {
|
|
108
|
-
const { data } = content;
|
|
109
|
-
if (!(data instanceof Blob)) return void 0;
|
|
110
|
-
return {
|
|
111
|
-
size: data.size,
|
|
112
|
-
slice: (start, end) => ({ data: data.slice(start, end) })
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
const size = getAssetPayloadByteLength(content);
|
|
116
|
-
if (size === void 0) return void 0;
|
|
117
|
-
let bytes;
|
|
118
|
-
return {
|
|
119
|
-
size,
|
|
120
|
-
slice: (start, end) => {
|
|
121
|
-
if (!bytes) {
|
|
122
|
-
const data = assetToData(content);
|
|
123
|
-
bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
|
124
|
-
}
|
|
125
|
-
return { uint8Array: bytes.subarray(start, end) };
|
|
126
|
-
}
|
|
127
|
-
};
|
|
128
|
-
};
|
|
129
|
-
/** Whether `content` goes in parts: its size is known, it can be resent, and it's over a part. */
|
|
130
|
-
const splitsIntoParts = (content, partSizeBytes) => {
|
|
131
|
-
const splittable = getSplittableContent(content);
|
|
132
|
-
return splittable !== void 0 && splittable.size > partSizeBytes;
|
|
133
|
-
};
|
|
134
|
-
/**
|
|
135
|
-
* Bytes as a fetch body. They're sent as they are rather than in a Blob: React Native can't
|
|
136
|
-
* build a Blob from bytes, and every fetch accepts a Uint8Array.
|
|
137
|
-
*/
|
|
138
|
-
const toBodyBytes = (value) => value.buffer instanceof ArrayBuffer ? value : Uint8Array.from(value);
|
|
139
|
-
/** The bytes of an upload's content or part, as a Blob, bytes or a one-shot stream. */
|
|
140
|
-
const toUploadData = (payload) => {
|
|
141
|
-
const data = assetToData(payload);
|
|
142
|
-
if (data instanceof Response) {
|
|
143
|
-
if (!data.body) throw new CalmLensError(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Response upload data must have a body" });
|
|
144
|
-
return data.body;
|
|
145
|
-
}
|
|
146
|
-
if (data instanceof Blob) return data;
|
|
147
|
-
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
148
|
-
if ("getReader" in data) return data;
|
|
149
|
-
return toBodyBytes(data);
|
|
150
|
-
};
|
|
151
|
-
/** An upload's bytes as a raw part body (parts after the first carry no options). */
|
|
152
|
-
const toRawUploadBody = (payload) => toUploadData(payload);
|
|
153
|
-
const textEncoder = new TextEncoder();
|
|
154
|
-
/**
|
|
155
|
-
* An upload form: `multipart/form-data` with the asset's fields as the JSON `options` part, then
|
|
156
|
-
* the bytes as the `file` part. Asset fields never go in the URL, which proxies and servers log.
|
|
157
|
-
* Bytes stay bytes (React Native can't build a Blob from them). Read Blob bytes before composing
|
|
158
|
-
* the form: Bun's Blob constructor drops disk-backed BunFile parts. Automatic multipart uploads
|
|
159
|
-
* read only the current part. Streams remain streamed, and buffered bodies remain retryable.
|
|
160
|
-
*/
|
|
161
|
-
const toUploadForm = async (options, payload) => {
|
|
162
|
-
const boundary = `calmlens-${randomUuid()}`;
|
|
163
|
-
const head = `--${boundary}\r\nContent-Disposition: form-data; name="options"\r\nContent-Type: application/json\r\n\r\n${JSON.stringify(options)}\r\n--${boundary}\r\nContent-Disposition: form-data; name="file"\r\nContent-Type: ${payload.type.replace(/[\r\n]/g, "")}\r\n\r\n`;
|
|
164
|
-
const tail = `\r\n--${boundary}--\r\n`;
|
|
165
|
-
const contentType = `multipart/form-data; boundary=${boundary}`;
|
|
166
|
-
const input = toUploadData(payload);
|
|
167
|
-
const data = input instanceof Blob ? new Uint8Array(await input.arrayBuffer()) : input;
|
|
168
|
-
const headBytes = textEncoder.encode(head);
|
|
169
|
-
const tailBytes = textEncoder.encode(tail);
|
|
170
|
-
if (data instanceof Uint8Array) {
|
|
171
|
-
const body = new Uint8Array(headBytes.length + data.length + tailBytes.length);
|
|
172
|
-
body.set(headBytes);
|
|
173
|
-
body.set(data, headBytes.length);
|
|
174
|
-
body.set(tailBytes, headBytes.length + data.length);
|
|
175
|
-
return {
|
|
176
|
-
body,
|
|
177
|
-
contentType
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
const reader = data.getReader();
|
|
181
|
-
let stage = "head";
|
|
182
|
-
return {
|
|
183
|
-
body: new ReadableStream({
|
|
184
|
-
async pull(controller) {
|
|
185
|
-
if (stage === "head") {
|
|
186
|
-
stage = "file";
|
|
187
|
-
controller.enqueue(headBytes);
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
if (stage === "done") return;
|
|
191
|
-
const { done, value } = await reader.read();
|
|
192
|
-
if (!done) {
|
|
193
|
-
if (value.byteLength) controller.enqueue(value);
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
stage = "done";
|
|
197
|
-
controller.enqueue(tailBytes);
|
|
198
|
-
controller.close();
|
|
199
|
-
},
|
|
200
|
-
cancel: (reason) => reader.cancel(reason)
|
|
201
|
-
}),
|
|
202
|
-
contentType
|
|
203
|
-
};
|
|
204
|
-
};
|
|
205
|
-
/** The options an upload sends, without the transport ones and without empty values. */
|
|
206
|
-
const uploadFields = (options) => Object.fromEntries(UPLOAD_OPTION_KEYS.flatMap((key) => options[key] === void 0 || options[key] === null ? [] : [[key, options[key]]]));
|
|
207
|
-
/** The asset fields an upload carries in its body: the API refuses them in the query string. */
|
|
208
|
-
const UPLOAD_OPTION_KEYS = [
|
|
209
|
-
"name",
|
|
210
|
-
"description",
|
|
211
|
-
"processingOptions",
|
|
212
|
-
"visibility",
|
|
213
|
-
"metadata",
|
|
214
|
-
"tags",
|
|
215
|
-
"authorId",
|
|
216
|
-
"context",
|
|
217
|
-
"externalId",
|
|
218
|
-
"externalUrl",
|
|
219
|
-
"folderId",
|
|
220
|
-
"uploadPresetId"
|
|
221
|
-
];
|
|
222
|
-
const setOptionalQueryValue = (params, key, value) => {
|
|
223
|
-
if (value !== void 0 && value !== null) params.set(key, String(value));
|
|
224
|
-
};
|
|
225
|
-
const assertValidUploadMimeType = (mimeType) => {
|
|
226
|
-
if (!isAcceptedUploadMimeType(mimeType)) throw new CalmLensError(API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, {
|
|
227
|
-
message: getRejectedUploadMimeTypeError(mimeType),
|
|
228
|
-
details: {
|
|
229
|
-
mimeType,
|
|
230
|
-
source: "calmlens"
|
|
231
|
-
}
|
|
232
|
-
});
|
|
233
|
-
};
|
|
234
|
-
const isImageMimeType = (mimeType) => mimeType.toLowerCase().startsWith("image/");
|
|
235
|
-
const invalidPayload = (message) => new CalmLensError(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message });
|
|
236
|
-
const assertDeclaredPayloadSize = (payload, declared = payload.sizeInBytes) => {
|
|
237
|
-
if (declared === void 0) return;
|
|
238
|
-
const data = "data" in payload ? payload.data : void 0;
|
|
239
|
-
const measured = data instanceof ArrayBuffer || ArrayBuffer.isView(data) ? data.byteLength : getAssetPayloadByteLength(payload);
|
|
240
|
-
if (!Number.isSafeInteger(declared) || declared < 0 || measured !== void 0 && measured !== declared) throw invalidPayload("sizeInBytes must match the payload byte length");
|
|
241
|
-
};
|
|
242
|
-
/**
|
|
243
|
-
* Refuses content whose known size is over the API's limit for its type, so nothing is sent and
|
|
244
|
-
* an oversized file fails at once instead of after its upload. In one request, images can be up
|
|
245
|
-
* to 10 MiB (larger ones are uploaded in parts), audio and video up to 50 MiB and other files up
|
|
246
|
-
* to 5,000 MiB. Sent in parts (`inParts`), audio and video can be up to 2 GiB; the API holds free
|
|
247
|
-
* uploads, made before billing is set up, to 50 MiB itself. Images in parts are checked apart.
|
|
248
|
-
*/
|
|
249
|
-
const assertUploadSize = (type, size, inParts) => {
|
|
250
|
-
if (size === void 0) return;
|
|
251
|
-
const mime = type.toLowerCase();
|
|
252
|
-
const [limit, message] = mime.startsWith("image/") ? [MAX_DIRECT_IMAGE_UPLOAD_BYTES, "Images uploaded in one request can be at most 10 MiB; upload larger images in parts"] : mime.startsWith("audio/") || mime.startsWith("video/") ? [inParts ? MAX_LONG_MEDIA_UPLOAD_BYTES : MAX_MEDIA_UPLOAD_BYTES, "Audio and video files can be at most 50 MiB in one request, or 2 GiB in parts"] : [MAX_NON_IMAGE_UPLOAD_BYTES, "Files can be at most 5,000 MiB"];
|
|
253
|
-
if (size > limit) throw new CalmLensError(API_ERROR_CODES.UPLOAD_TOO_LARGE, {
|
|
254
|
-
message,
|
|
255
|
-
details: {
|
|
256
|
-
limitBytes: limit,
|
|
257
|
-
source: "plan"
|
|
258
|
-
}
|
|
259
|
-
});
|
|
260
|
-
};
|
|
261
|
-
/** Checks upload options before anything is sent. */
|
|
262
|
-
const isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
|
|
263
|
-
/**
|
|
264
|
-
* `content` given as a `Blob` or `File`, as the `{ data, type }` the rest of the client reads: the
|
|
265
|
-
* content type is the Blob's own, and a File's name is the asset's when the options give none.
|
|
266
|
-
*/
|
|
267
|
-
const withContentObject = (options) => {
|
|
268
|
-
if (!options || typeof options !== "object" || !("content" in options)) return options;
|
|
269
|
-
const content = options.content;
|
|
270
|
-
if (!isBlob(content)) return options;
|
|
271
|
-
if (!content.type) throw invalidPayload("The Blob has no type: create it with one, such as new Blob([bytes], { type: \"image/png\" }), or pass { data, type }");
|
|
272
|
-
const fileName = typeof File !== "undefined" && content instanceof File ? content.name : void 0;
|
|
273
|
-
const named = options;
|
|
274
|
-
return {
|
|
275
|
-
...options,
|
|
276
|
-
...named.name || !fileName ? {} : { name: fileName },
|
|
277
|
-
content: {
|
|
278
|
-
data: content,
|
|
279
|
-
type: content.type
|
|
280
|
-
}
|
|
281
|
-
};
|
|
282
|
-
};
|
|
283
|
-
const prepareSubmitAssetOptions = (input, { deferUploadChecks = false, partSizeBytes = DEFAULT_PART_SIZE_BYTES } = {}) => {
|
|
284
|
-
const options = withContentObject(input);
|
|
285
|
-
if (!options || typeof options !== "object") throw invalidArgument("Asset options are required");
|
|
286
|
-
if (!("content" in options) && !("url" in options) && !("part" in options)) throw invalidPayload("Either file content, URL, or multipart part is required");
|
|
287
|
-
if (!options.name) throw invalidPayload("Asset name is required");
|
|
288
|
-
if (!("part" in options) && "isFinal" in options) throw invalidPayload("isFinal is only valid for multipart uploads");
|
|
289
|
-
if ("part" in options && options.part.partNumber && options.part.partNumber > 1) throw new CalmLensError(API_ERROR_CODES.USE_UPLOAD_PART, { message: "Use uploadPart for multipart upload parts after the first part" });
|
|
290
|
-
if ("content" in options) {
|
|
291
|
-
assertDeclaredPayloadSize(options.content);
|
|
292
|
-
assertValidUploadMimeType(options.content.type);
|
|
293
|
-
const inParts = splitsIntoParts(options.content, partSizeBytes);
|
|
294
|
-
if (inParts && (options.idempotencyKey?.length ?? 0) > 240) throw invalidArgument(`idempotencyKey can be at most 240 characters for an upload sent in parts`);
|
|
295
|
-
if (!deferUploadChecks && inParts && isImageMimeType(options.content.type)) {
|
|
296
|
-
if ((getAssetPayloadByteLength(options.content) ?? 0) > MAX_IMAGE_UPLOAD_BYTES) throw new CalmLensError(API_ERROR_CODES.UPLOAD_TOO_LARGE, {
|
|
297
|
-
message: "Multipart image uploads cannot exceed 20 MiB.",
|
|
298
|
-
details: {
|
|
299
|
-
limitBytes: MAX_IMAGE_UPLOAD_BYTES,
|
|
300
|
-
source: "plan"
|
|
301
|
-
}
|
|
302
|
-
});
|
|
303
|
-
} else if (!deferUploadChecks) assertUploadSize(options.content.type, options.content.sizeInBytes ?? getAssetPayloadByteLength(options.content), inParts);
|
|
304
|
-
if (!("plainText" in options.content)) {
|
|
305
|
-
const validation = validateAssetPayload(options.content);
|
|
306
|
-
if (!validation.ok) throw invalidPayload(validation.error);
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
if ("part" in options) {
|
|
310
|
-
assertDeclaredPayloadSize(options.part, options.part.sizeInBytes ?? options.sizeInBytes);
|
|
311
|
-
assertValidUploadMimeType(options.part.type);
|
|
312
|
-
const partSizeInBytes = options.part.sizeInBytes ?? getAssetPayloadByteLength(options.part);
|
|
313
|
-
if (!deferUploadChecks && isImageMimeType(options.part.type) && partSizeInBytes !== void 0) {
|
|
314
|
-
if (partSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw new CalmLensError(API_ERROR_CODES.UPLOAD_TOO_LARGE, {
|
|
315
|
-
message: "Multipart image uploads cannot exceed 20 MiB.",
|
|
316
|
-
details: {
|
|
317
|
-
limitBytes: MAX_IMAGE_UPLOAD_BYTES,
|
|
318
|
-
source: "plan"
|
|
319
|
-
}
|
|
320
|
-
});
|
|
321
|
-
}
|
|
322
|
-
if (!deferUploadChecks && !isImageMimeType(options.part.type)) assertUploadSize(options.part.type, options.totalSizeInBytes, true);
|
|
323
|
-
const validation = validateAssetPayload(options.part, {
|
|
324
|
-
multipart: true,
|
|
325
|
-
isFinal: deferUploadChecks || options.part.isFinal
|
|
326
|
-
});
|
|
327
|
-
if (!validation.ok) throw invalidPayload(validation.error);
|
|
328
|
-
}
|
|
329
|
-
if (options.context !== void 0) {
|
|
330
|
-
if (!options.context || !Array.isArray(options.context.items)) throw invalidArgument("context.items must be an array of earlier posts");
|
|
331
|
-
return {
|
|
332
|
-
...options,
|
|
333
|
-
context: { items: selectModerationContextItems(options.context.items) }
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
return options;
|
|
337
|
-
};
|
|
338
|
-
const newIdempotencyKey = () => randomUuid();
|
|
339
|
-
/** Text content is small, so it keeps the API deadline; binary files may be arbitrarily large. */
|
|
340
|
-
const isTextPayload = (payload) => "plainText" in payload;
|
|
341
|
-
const hasStringStatus = (value) => !!value && typeof value === "object" && typeof value.status === "string";
|
|
342
|
-
const hasDecision = (data) => {
|
|
343
|
-
const decision = data.classification?.moderation?.decision;
|
|
344
|
-
return decision === null || typeof decision === "string";
|
|
345
|
-
};
|
|
346
|
-
const isAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload) && hasDecision(data);
|
|
347
|
-
const isUploadedAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload);
|
|
348
|
-
const expectUploadedAsset = (data) => {
|
|
349
|
-
if (!isUploadedAsset(data)) throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
|
|
350
|
-
message: "Expected an uploaded asset response",
|
|
351
|
-
status: 200
|
|
352
|
-
});
|
|
353
|
-
return data;
|
|
354
|
-
};
|
|
355
|
-
const expectAsset = (data) => {
|
|
356
|
-
if (!isAsset(data)) throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
|
|
357
|
-
message: "Expected an asset response",
|
|
358
|
-
status: 200
|
|
359
|
-
});
|
|
360
|
-
return data;
|
|
361
|
-
};
|
|
362
|
-
/** Checks one call's request options. */
|
|
363
|
-
const validateCallOptions = (options) => {
|
|
364
|
-
if (options === void 0) return;
|
|
365
|
-
if (!options || typeof options !== "object" || Array.isArray(options)) throw invalidArgument("Request options must be an object");
|
|
366
|
-
const known = [
|
|
367
|
-
"signal",
|
|
368
|
-
"timeoutMs",
|
|
369
|
-
"maxRetries",
|
|
370
|
-
"idempotencyKey",
|
|
371
|
-
"headers",
|
|
372
|
-
"extraQuery",
|
|
373
|
-
"extraBody"
|
|
374
|
-
];
|
|
375
|
-
const unknown = Object.keys(options).filter((key) => !known.includes(key));
|
|
376
|
-
if (unknown.length) throw invalidArgument(`Unknown request options: ${unknown.join(", ")}`, { options: unknown });
|
|
377
|
-
const { timeoutMs, maxRetries, idempotencyKey, headers, extraQuery, extraBody } = options;
|
|
378
|
-
if (timeoutMs !== void 0 && (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1)) throw invalidArgument("timeoutMs must be a positive integer");
|
|
379
|
-
if (maxRetries !== void 0 && (!Number.isSafeInteger(maxRetries) || maxRetries < 0)) throw invalidArgument("maxRetries must be a non-negative integer");
|
|
380
|
-
if (idempotencyKey !== void 0 && (typeof idempotencyKey !== "string" || !idempotencyKey)) throw invalidArgument("idempotencyKey must be a non-empty string");
|
|
381
|
-
for (const [name, value] of Object.entries({
|
|
382
|
-
headers,
|
|
383
|
-
extraQuery,
|
|
384
|
-
extraBody
|
|
385
|
-
})) if (value !== void 0 && (!value || typeof value !== "object" || Array.isArray(value))) throw invalidArgument(`${name} must be an object`);
|
|
386
|
-
if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) throw invalidArgument("signal must be an AbortSignal");
|
|
387
|
-
};
|
|
388
|
-
const isPlainObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
389
|
-
/** Fills in the default API base URL and drops trailing slashes. */
|
|
390
|
-
const resolveConnectionOptions = (options) => ({
|
|
391
|
-
...options,
|
|
392
|
-
baseUrl: (options.baseUrl ?? `https://api.calmlens.com/v1`).replace(/\/+$/, "")
|
|
393
|
-
});
|
|
394
|
-
/** One client's transport, base URL and deadlines, and the requests both clients make. */
|
|
395
|
-
var CalmLensConnection = class CalmLensConnection {
|
|
396
|
-
constructor(options, apiKey, { readEnvironment = false, shared } = {}) {
|
|
397
|
-
this.options = options;
|
|
398
|
-
if (shared) {
|
|
399
|
-
this.transport = shared.transport;
|
|
400
|
-
this.hooks = shared.hooks;
|
|
401
|
-
this.call = shared.call;
|
|
402
|
-
return;
|
|
403
|
-
}
|
|
404
|
-
this.call = {};
|
|
405
|
-
const resolveFetch = () => {
|
|
406
|
-
const fetchImpl = this.options.fetch ?? globalThis.fetch;
|
|
407
|
-
if (typeof fetchImpl !== "function") throw new CalmLensError(SDK_ERROR_CODES.NO_FETCH, { message: "No fetch implementation is available; pass one as the fetch option" });
|
|
408
|
-
return fetchImpl;
|
|
409
|
-
};
|
|
410
|
-
this.hooks = getMockHooks(options);
|
|
411
|
-
const logLevel = resolveLogLevel(options.logLevel, readEnvironment);
|
|
412
|
-
this.transport = new CalmLensTransport({
|
|
413
|
-
apiKey,
|
|
414
|
-
sleep: this.hooks?.sleep,
|
|
415
|
-
fetch: ((input, init) => resolveFetch()(input, init)),
|
|
416
|
-
signal: options.signal,
|
|
417
|
-
maxRetries: options.maxRetries ?? 2,
|
|
418
|
-
maxResponseBytes: options.maxResponseBytes ?? 33554432,
|
|
419
|
-
appInfo: options.appInfo,
|
|
420
|
-
logLevel,
|
|
421
|
-
logger: logLevel === "off" ? void 0 : options.logger ?? console,
|
|
422
|
-
onAttempt: options.onAttempt,
|
|
423
|
-
now: this.hooks?.now
|
|
424
|
-
});
|
|
425
|
-
}
|
|
426
|
-
/**
|
|
427
|
-
* This connection for one call: its requests carry `operation` to the attempt hook and logs, and
|
|
428
|
-
* follow `requestOptions` (checked here) over the client's.
|
|
429
|
-
*/
|
|
430
|
-
forCall(operation, requestOptions) {
|
|
431
|
-
validateCallOptions(requestOptions);
|
|
432
|
-
return new CalmLensConnection(this.options, void 0, { shared: {
|
|
433
|
-
transport: this.transport,
|
|
434
|
-
hooks: this.hooks,
|
|
435
|
-
call: {
|
|
436
|
-
...this.call,
|
|
437
|
-
...requestOptions,
|
|
438
|
-
operation
|
|
439
|
-
}
|
|
440
|
-
} });
|
|
441
|
-
}
|
|
442
|
-
/** The call's transport settings, for a request built here or by the client. */
|
|
443
|
-
callRequest() {
|
|
444
|
-
const { operation, signal, maxRetries } = this.call;
|
|
445
|
-
return {
|
|
446
|
-
operation,
|
|
447
|
-
signal,
|
|
448
|
-
maxRetries
|
|
449
|
-
};
|
|
450
|
-
}
|
|
451
|
-
/** The call's extra headers under the SDK's own, which win. */
|
|
452
|
-
callHeaders(headers) {
|
|
453
|
-
return this.call.headers ? {
|
|
454
|
-
...this.call.headers,
|
|
455
|
-
...headers
|
|
456
|
-
} : headers;
|
|
457
|
-
}
|
|
458
|
-
/** The call's `extraBody` merged into a JSON body. */
|
|
459
|
-
callBody(method, body) {
|
|
460
|
-
const { extraBody } = this.call;
|
|
461
|
-
if (!extraBody) return body;
|
|
462
|
-
if (method === "GET" || method === "HEAD") throw invalidArgument("extraBody needs a request with a body");
|
|
463
|
-
if (body === void 0) return extraBody;
|
|
464
|
-
if (!isPlainObject(body)) throw invalidArgument("extraBody needs a JSON object body");
|
|
465
|
-
return {
|
|
466
|
-
...body,
|
|
467
|
-
...extraBody
|
|
468
|
-
};
|
|
469
|
-
}
|
|
470
|
-
/** How the client waits between polls and retries. */
|
|
471
|
-
get sleep() {
|
|
472
|
-
return this.hooks?.sleep ?? sleep;
|
|
473
|
-
}
|
|
474
|
-
/** Whether multipart size checks are left to the API (mock clients only). */
|
|
475
|
-
get deferUploadChecks() {
|
|
476
|
-
return this.hooks?.deferUploadChecks ?? false;
|
|
477
|
-
}
|
|
478
|
-
get timeoutMs() {
|
|
479
|
-
return this.call.timeoutMs ?? this.options.timeoutMs ?? 12e4;
|
|
480
|
-
}
|
|
481
|
-
/** The URL of `path` (which may carry a query already) with `query` and the call's `extraQuery`. */
|
|
482
|
-
url(path, query) {
|
|
483
|
-
const search = [query, this.call.extraQuery].map((values) => values ? stringifyQuery(values) : "").filter(Boolean).join("&");
|
|
484
|
-
const separator = path.includes("?") ? "&" : "?";
|
|
485
|
-
return `${this.options.baseUrl}${path}${search ? `${separator}${search}` : ""}`;
|
|
486
|
-
}
|
|
487
|
-
/** A JSON request whose deadline covers reading the response. */
|
|
488
|
-
json(method, path, { query, body, headers, idempotencyKey } = {}) {
|
|
489
|
-
const sent = this.callBody(method, body);
|
|
490
|
-
return this.transport.json({
|
|
491
|
-
...this.callRequest(),
|
|
492
|
-
method,
|
|
493
|
-
url: this.url(path, query),
|
|
494
|
-
headers: this.callHeaders(sent === void 0 ? headers : {
|
|
495
|
-
...headers,
|
|
496
|
-
"Content-Type": "application/json"
|
|
497
|
-
}),
|
|
498
|
-
body: sent === void 0 ? void 0 : JSON.stringify(sent),
|
|
499
|
-
idempotencyKey: idempotencyKey ?? this.call.idempotencyKey,
|
|
500
|
-
timeoutMs: this.timeoutMs,
|
|
501
|
-
deadline: "body"
|
|
502
|
-
});
|
|
503
|
-
}
|
|
504
|
-
upload(url, body, headers, idempotencyKey, text) {
|
|
505
|
-
return this.transport.json({
|
|
506
|
-
...this.callRequest(),
|
|
507
|
-
method: "POST",
|
|
508
|
-
url,
|
|
509
|
-
headers: this.callHeaders(headers),
|
|
510
|
-
body,
|
|
511
|
-
idempotencyKey,
|
|
512
|
-
timeoutMs: text ? this.timeoutMs : this.call.timeoutMs ?? this.options.uploadTimeoutMs,
|
|
513
|
-
deadline: "body",
|
|
514
|
-
fetch: this.options.uploadFetch
|
|
515
|
-
});
|
|
516
|
-
}
|
|
517
|
-
/**
|
|
518
|
-
* Uploads file content or a first multipart part to `uploadsPath` (`.../assets`). Plain text
|
|
519
|
-
* goes as a JSON body; other content as an upload form, the asset's fields in its options part
|
|
520
|
-
* and the bytes in its file part. Either way the query holds only transport values.
|
|
521
|
-
*/
|
|
522
|
-
async submitUpload(uploadsPath, options, wait, authHeaders = {}) {
|
|
523
|
-
const isMultipart = "part" in options;
|
|
524
|
-
const payload = isMultipart ? options.part : options.content;
|
|
525
|
-
const multipartOptions = options;
|
|
526
|
-
const idempotencyKey = options.idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey();
|
|
527
|
-
const fields = {
|
|
528
|
-
...uploadFields(options),
|
|
529
|
-
...this.call.extraBody
|
|
530
|
-
};
|
|
531
|
-
if (isTextPayload(payload)) {
|
|
532
|
-
const { sizeInBytes: _size, ...text } = payload;
|
|
533
|
-
const body = isMultipart ? {
|
|
534
|
-
...fields,
|
|
535
|
-
part: text,
|
|
536
|
-
...multipartOptions.sizeInBytes === void 0 ? {} : { sizeInBytes: multipartOptions.sizeInBytes },
|
|
537
|
-
...multipartOptions.totalSizeInBytes === void 0 ? {} : { totalSizeInBytes: multipartOptions.totalSizeInBytes }
|
|
538
|
-
} : {
|
|
539
|
-
...fields,
|
|
540
|
-
content: text
|
|
541
|
-
};
|
|
542
|
-
return this.upload(this.url(uploadsPath, { wait }), JSON.stringify(body), {
|
|
543
|
-
...authHeaders,
|
|
544
|
-
"Content-Type": "application/json"
|
|
545
|
-
}, idempotencyKey, true);
|
|
546
|
-
}
|
|
547
|
-
const query = new URLSearchParams();
|
|
548
|
-
query.set("wait", String(wait));
|
|
549
|
-
query.set("contentType", payload.type);
|
|
550
|
-
setOptionalQueryValue(query, "sizeInBytes", payload.sizeInBytes ?? getAssetPayloadByteLength(payload));
|
|
551
|
-
if (isMultipart) {
|
|
552
|
-
const part = payload;
|
|
553
|
-
query.set("partNumber", String(part.partNumber ?? 1));
|
|
554
|
-
query.set("isFinal", String(part.isFinal ?? false));
|
|
555
|
-
setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? multipartOptions.sizeInBytes);
|
|
556
|
-
setOptionalQueryValue(query, "totalSizeInBytes", multipartOptions.totalSizeInBytes);
|
|
557
|
-
}
|
|
558
|
-
const form = await toUploadForm(fields, payload);
|
|
559
|
-
return this.upload(this.url(`${uploadsPath}?${query}`), form.body, {
|
|
560
|
-
...authHeaders,
|
|
561
|
-
"Content-Type": form.contentType,
|
|
562
|
-
"X-CalmLens-Upload": isMultipart ? "part" : "content"
|
|
563
|
-
}, idempotencyKey, false);
|
|
564
|
-
}
|
|
565
|
-
/** Content larger than this is uploaded in parts. */
|
|
566
|
-
get partSizeBytes() {
|
|
567
|
-
return this.options.partSizeBytes ?? 8388608;
|
|
568
|
-
}
|
|
569
|
-
/**
|
|
570
|
-
* Uploads content larger than `partSizeBytes` in parts: the first to `uploadsPath` with the
|
|
571
|
-
* upload's fields, the rest to `partPath(assetId)`. Each part carries its own Idempotency-Key
|
|
572
|
-
* (`<key>:part-<n>`), so it is retried safely and a repeated call with the same key resumes the
|
|
573
|
-
* upload. A part the API already has is skipped, and a final part that finds the upload already
|
|
574
|
-
* completed reads it back with `retrieve`.
|
|
575
|
-
*/
|
|
576
|
-
async submitInParts(uploadsPath, options, wait, { authHeaders = {}, partPath, onStarted, retrieve }) {
|
|
577
|
-
const { content, idempotencyKey, ...fields } = options;
|
|
578
|
-
const source = getSplittableContent(content);
|
|
579
|
-
const partSize = this.partSizeBytes;
|
|
580
|
-
const count = Math.ceil(source.size / partSize);
|
|
581
|
-
const key = idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey();
|
|
582
|
-
const part = (partNumber) => source.slice((partNumber - 1) * partSize, Math.min(partNumber * partSize, source.size));
|
|
583
|
-
const first = await this.submitUpload(uploadsPath, {
|
|
584
|
-
...fields,
|
|
585
|
-
part: {
|
|
586
|
-
...part(1),
|
|
587
|
-
type: content.type,
|
|
588
|
-
partNumber: 1,
|
|
589
|
-
isFinal: false
|
|
590
|
-
},
|
|
591
|
-
totalSizeInBytes: source.size,
|
|
592
|
-
idempotencyKey: key
|
|
593
|
-
}, wait, authHeaders);
|
|
594
|
-
const assetId = expectUploadedAsset(first).id;
|
|
595
|
-
onStarted?.(assetId);
|
|
596
|
-
const laterParts = new CalmLensConnection(this.options, void 0, { shared: {
|
|
597
|
-
transport: this.transport,
|
|
598
|
-
hooks: this.hooks,
|
|
599
|
-
call: {
|
|
600
|
-
...this.call,
|
|
601
|
-
extraBody: void 0
|
|
602
|
-
}
|
|
603
|
-
} });
|
|
604
|
-
let result = first;
|
|
605
|
-
for (let partNumber = 2; partNumber <= count;) {
|
|
606
|
-
const isFinal = partNumber === count;
|
|
607
|
-
try {
|
|
608
|
-
result = await laterParts.uploadPart(partPath(assetId), {
|
|
609
|
-
part: {
|
|
610
|
-
...part(partNumber),
|
|
611
|
-
partNumber,
|
|
612
|
-
isFinal
|
|
613
|
-
},
|
|
614
|
-
idempotencyKey: `${key}:part-${partNumber}`
|
|
615
|
-
}, authHeaders);
|
|
616
|
-
partNumber++;
|
|
617
|
-
} catch (error) {
|
|
618
|
-
if (!(error instanceof CalmLensError)) throw error;
|
|
619
|
-
const expected = error.details?.expectedPartNumber;
|
|
620
|
-
if (error.code === API_ERROR_CODES.INVALID_UPLOAD_PART_NUMBER && typeof expected === "number" && expected > partNumber && expected <= count) {
|
|
621
|
-
partNumber = expected;
|
|
622
|
-
continue;
|
|
623
|
-
}
|
|
624
|
-
if (isFinal && error.code === API_ERROR_CODES.UPLOAD_NOT_OPEN) return retrieve(assetId);
|
|
625
|
-
throw error;
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
return result;
|
|
629
|
-
}
|
|
630
|
-
/** Uploads the next part of a multipart upload to `partPath` (`.../assets/{id}/part`). */
|
|
631
|
-
uploadPart(partPath, { part, wait, idempotencyKey }, authHeaders = {}) {
|
|
632
|
-
if (!part) throw invalidArgument("Part options are required");
|
|
633
|
-
if (this.call.extraBody) throw invalidArgument("A part's body is its bytes: extraBody can't apply");
|
|
634
|
-
assertDeclaredPayloadSize(part);
|
|
635
|
-
const validation = validateAssetPayload(part, {
|
|
636
|
-
multipart: true,
|
|
637
|
-
isFinal: this.deferUploadChecks || part.isFinal
|
|
638
|
-
});
|
|
639
|
-
if (!validation.ok) throw invalidPayload(validation.error);
|
|
640
|
-
const query = new URLSearchParams({
|
|
641
|
-
partNumber: String(part.partNumber),
|
|
642
|
-
isFinal: String(part.isFinal ?? false)
|
|
643
|
-
});
|
|
644
|
-
if (wait !== void 0) query.set("wait", String(wait));
|
|
645
|
-
setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? getAssetPayloadByteLength(part));
|
|
646
|
-
return this.upload(this.url(`${partPath}?${query}`), toRawUploadBody(part), {
|
|
647
|
-
...authHeaders,
|
|
648
|
-
"X-CalmLens-Upload": "part"
|
|
649
|
-
}, idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey(), isTextPayload(part));
|
|
650
|
-
}
|
|
651
|
-
};
|
|
652
92
|
// src/client/CalmLensOptionKeys.ts
|
|
653
93
|
/** The option keys each `CalmLensServerClient` method sends to the API. */
|
|
654
94
|
const SERVER_OPTION_KEYS = {
|
|
@@ -719,7 +159,9 @@ const SERVER_OPTION_KEYS = {
|
|
|
719
159
|
],
|
|
720
160
|
"assets.move": ["assetId", "folderId"],
|
|
721
161
|
"assets.removeContent": ["assetId"],
|
|
162
|
+
"assets.requestReview": ["assetId", "note"],
|
|
722
163
|
"assets.retrieve": ["assetId"],
|
|
164
|
+
"assets.retrieveByExternalId": ["externalId"],
|
|
723
165
|
"assets.retry": ["assetId"],
|
|
724
166
|
"assets.search": [
|
|
725
167
|
"mode",
|
|
@@ -904,90 +346,665 @@ const SERVER_OPTION_KEYS = {
|
|
|
904
346
|
"sort"
|
|
905
347
|
]
|
|
906
348
|
};
|
|
907
|
-
/** The option keys each `CalmLensAppClient` method sends to the API. */
|
|
908
|
-
const APP_OPTION_KEYS = {
|
|
909
|
-
"assets.classify": [
|
|
910
|
-
"content",
|
|
911
|
-
"description",
|
|
912
|
-
"externalUrl",
|
|
913
|
-
"name",
|
|
914
|
-
"part",
|
|
915
|
-
"sizeInBytes",
|
|
916
|
-
"totalSizeInBytes"
|
|
917
|
-
],
|
|
918
|
-
"assets.create": [
|
|
919
|
-
"content",
|
|
920
|
-
"description",
|
|
921
|
-
"externalUrl",
|
|
922
|
-
"name",
|
|
923
|
-
"part",
|
|
924
|
-
"sizeInBytes",
|
|
925
|
-
"totalSizeInBytes"
|
|
926
|
-
],
|
|
927
|
-
"assets.retrieve": ["assetId"],
|
|
928
|
-
"assets.uploadPart": [
|
|
929
|
-
"assetId",
|
|
930
|
-
"part",
|
|
931
|
-
"wait"
|
|
932
|
-
]
|
|
349
|
+
/** The option keys each `CalmLensAppClient` method sends to the API. */
|
|
350
|
+
const APP_OPTION_KEYS = {
|
|
351
|
+
"assets.classify": [
|
|
352
|
+
"content",
|
|
353
|
+
"description",
|
|
354
|
+
"externalUrl",
|
|
355
|
+
"name",
|
|
356
|
+
"part",
|
|
357
|
+
"sizeInBytes",
|
|
358
|
+
"totalSizeInBytes"
|
|
359
|
+
],
|
|
360
|
+
"assets.create": [
|
|
361
|
+
"content",
|
|
362
|
+
"description",
|
|
363
|
+
"externalUrl",
|
|
364
|
+
"name",
|
|
365
|
+
"part",
|
|
366
|
+
"sizeInBytes",
|
|
367
|
+
"totalSizeInBytes"
|
|
368
|
+
],
|
|
369
|
+
"assets.retrieve": ["assetId"],
|
|
370
|
+
"assets.uploadPart": [
|
|
371
|
+
"assetId",
|
|
372
|
+
"part",
|
|
373
|
+
"wait"
|
|
374
|
+
]
|
|
375
|
+
};
|
|
376
|
+
/**
|
|
377
|
+
* The option keys each `CalmLensServerClient` method sends as `null` when given `null`; any
|
|
378
|
+
* other option given as `null` is left out, as the API refuses `null` for it.
|
|
379
|
+
*/
|
|
380
|
+
const NULLABLE_OPTION_KEYS = {
|
|
381
|
+
"assets.classify": [
|
|
382
|
+
"authorId",
|
|
383
|
+
"context",
|
|
384
|
+
"description",
|
|
385
|
+
"externalId",
|
|
386
|
+
"folderId",
|
|
387
|
+
"metadata",
|
|
388
|
+
"processingOptions",
|
|
389
|
+
"tags",
|
|
390
|
+
"uploadPresetId",
|
|
391
|
+
"visibility"
|
|
392
|
+
],
|
|
393
|
+
"assets.create": [
|
|
394
|
+
"authorId",
|
|
395
|
+
"context",
|
|
396
|
+
"description",
|
|
397
|
+
"externalId",
|
|
398
|
+
"folderId",
|
|
399
|
+
"metadata",
|
|
400
|
+
"processingOptions",
|
|
401
|
+
"tags",
|
|
402
|
+
"uploadPresetId",
|
|
403
|
+
"visibility"
|
|
404
|
+
],
|
|
405
|
+
"assets.list": ["filter"],
|
|
406
|
+
"assets.move": ["folderId"],
|
|
407
|
+
"assets.update": [
|
|
408
|
+
"description",
|
|
409
|
+
"externalId",
|
|
410
|
+
"externalUrl",
|
|
411
|
+
"metadata",
|
|
412
|
+
"tags",
|
|
413
|
+
"visibility"
|
|
414
|
+
],
|
|
415
|
+
"folders.create": ["parentId"],
|
|
416
|
+
"folders.move": ["parentId"],
|
|
417
|
+
"hashLists.addEntry": ["label", "quality"],
|
|
418
|
+
"hashLists.create": ["description"],
|
|
419
|
+
"hashLists.update": ["description"],
|
|
420
|
+
"lenses.create": ["description", "transform"],
|
|
421
|
+
"lenses.update": ["description", "transform"],
|
|
422
|
+
"text.classify": [
|
|
423
|
+
"authorId",
|
|
424
|
+
"context",
|
|
425
|
+
"description",
|
|
426
|
+
"externalId",
|
|
427
|
+
"folderId",
|
|
428
|
+
"metadata",
|
|
429
|
+
"processingOptions",
|
|
430
|
+
"tags",
|
|
431
|
+
"uploadPresetId",
|
|
432
|
+
"visibility"
|
|
433
|
+
]
|
|
434
|
+
};
|
|
435
|
+
/** The request options every method takes as its last argument (`RequestOptions`). */
|
|
436
|
+
const REQUEST_OPTION_KEYS = [
|
|
437
|
+
"deadlineMs",
|
|
438
|
+
"extraBody",
|
|
439
|
+
"extraQuery",
|
|
440
|
+
"headers",
|
|
441
|
+
"idempotencyKey",
|
|
442
|
+
"maxRetries",
|
|
443
|
+
"signal",
|
|
444
|
+
"timeoutMs"
|
|
445
|
+
];
|
|
446
|
+
/**
|
|
447
|
+
* Where `calmlens/testing` puts its hooks in client options. Not part of the public API:
|
|
448
|
+
* the mock clients run the real clients against their in-memory API with these.
|
|
449
|
+
*/
|
|
450
|
+
const MOCK_HOOKS = Symbol.for("@calmlens/sdk.mockHooks");
|
|
451
|
+
/** The mock hooks in client options, if a mock client set them. */
|
|
452
|
+
const getMockHooks = (options) => options[MOCK_HOOKS];
|
|
453
|
+
/** Content larger than this is uploaded in parts of this size (`partSizeBytes`). */
|
|
454
|
+
const DEFAULT_PART_SIZE_BYTES = 8388608;
|
|
455
|
+
/**
|
|
456
|
+
* The size of content the client can split, read again and resend: bytes, base64 and Blobs.
|
|
457
|
+
* Streams and Responses can be read only once, and text stays one request.
|
|
458
|
+
*/
|
|
459
|
+
const getSplittableContent = (content) => {
|
|
460
|
+
if ("plainText" in content && content.plainText !== void 0) return void 0;
|
|
461
|
+
if ("data" in content && content.data !== void 0) {
|
|
462
|
+
const { data } = content;
|
|
463
|
+
if (!(data instanceof Blob)) return void 0;
|
|
464
|
+
return {
|
|
465
|
+
size: data.size,
|
|
466
|
+
slice: (start, end) => ({ data: data.slice(start, end) })
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
const size = getAssetPayloadByteLength(content);
|
|
470
|
+
if (size === void 0) return void 0;
|
|
471
|
+
let bytes;
|
|
472
|
+
return {
|
|
473
|
+
size,
|
|
474
|
+
slice: (start, end) => {
|
|
475
|
+
if (!bytes) {
|
|
476
|
+
const data = assetToData(content);
|
|
477
|
+
bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
|
478
|
+
}
|
|
479
|
+
return { uint8Array: bytes.subarray(start, end) };
|
|
480
|
+
}
|
|
481
|
+
};
|
|
482
|
+
};
|
|
483
|
+
/** Whether `content` goes in parts: its size is known, it can be resent, and it's over a part. */
|
|
484
|
+
const splitsIntoParts = (content, partSizeBytes) => {
|
|
485
|
+
const splittable = getSplittableContent(content);
|
|
486
|
+
return splittable !== void 0 && splittable.size > partSizeBytes;
|
|
487
|
+
};
|
|
488
|
+
/**
|
|
489
|
+
* Bytes as a fetch body. They're sent as they are rather than in a Blob: React Native can't
|
|
490
|
+
* build a Blob from bytes, and every fetch accepts a Uint8Array.
|
|
491
|
+
*/
|
|
492
|
+
const toBodyBytes = (value) => value.buffer instanceof ArrayBuffer ? value : Uint8Array.from(value);
|
|
493
|
+
/** The bytes of an upload's content or part, as a Blob, bytes or a one-shot stream. */
|
|
494
|
+
const toUploadData = (payload) => {
|
|
495
|
+
const data = assetToData(payload);
|
|
496
|
+
if (data instanceof Response) {
|
|
497
|
+
if (!data.body) throw new CalmLensError(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Response upload data must have a body" });
|
|
498
|
+
return data.body;
|
|
499
|
+
}
|
|
500
|
+
if (data instanceof Blob) return data;
|
|
501
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
502
|
+
if ("getReader" in data) return data;
|
|
503
|
+
return toBodyBytes(data);
|
|
504
|
+
};
|
|
505
|
+
/** An upload's bytes as a raw part body (parts after the first carry no options). */
|
|
506
|
+
const toRawUploadBody = (payload) => toUploadData(payload);
|
|
507
|
+
const textEncoder = new TextEncoder();
|
|
508
|
+
/**
|
|
509
|
+
* An upload form: `multipart/form-data` with the asset's fields as the JSON `options` part, then
|
|
510
|
+
* the bytes as the `file` part. Asset fields never go in the URL, which proxies and servers log.
|
|
511
|
+
* Bytes stay bytes (React Native can't build a Blob from them). Read Blob bytes before composing
|
|
512
|
+
* the form: Bun's Blob constructor drops disk-backed BunFile parts. Automatic multipart uploads
|
|
513
|
+
* read only the current part. Streams remain streamed, and buffered bodies remain retryable.
|
|
514
|
+
*/
|
|
515
|
+
const toUploadForm = async (options, payload) => {
|
|
516
|
+
const boundary = `calmlens-${randomUuid()}`;
|
|
517
|
+
const head = `--${boundary}\r\nContent-Disposition: form-data; name="options"\r\nContent-Type: application/json\r\n\r\n${JSON.stringify(options)}\r\n--${boundary}\r\nContent-Disposition: form-data; name="file"\r\nContent-Type: ${payload.type.replace(/[\r\n]/g, "")}\r\n\r\n`;
|
|
518
|
+
const tail = `\r\n--${boundary}--\r\n`;
|
|
519
|
+
const contentType = `multipart/form-data; boundary=${boundary}`;
|
|
520
|
+
const input = toUploadData(payload);
|
|
521
|
+
const data = input instanceof Blob ? new Uint8Array(await input.arrayBuffer()) : input;
|
|
522
|
+
const headBytes = textEncoder.encode(head);
|
|
523
|
+
const tailBytes = textEncoder.encode(tail);
|
|
524
|
+
if (data instanceof Uint8Array) {
|
|
525
|
+
const body = new Uint8Array(headBytes.length + data.length + tailBytes.length);
|
|
526
|
+
body.set(headBytes);
|
|
527
|
+
body.set(data, headBytes.length);
|
|
528
|
+
body.set(tailBytes, headBytes.length + data.length);
|
|
529
|
+
return {
|
|
530
|
+
body,
|
|
531
|
+
contentType
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
const reader = data.getReader();
|
|
535
|
+
let stage = "head";
|
|
536
|
+
return {
|
|
537
|
+
body: new ReadableStream({
|
|
538
|
+
async pull(controller) {
|
|
539
|
+
if (stage === "head") {
|
|
540
|
+
stage = "file";
|
|
541
|
+
controller.enqueue(headBytes);
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
if (stage === "done") return;
|
|
545
|
+
const { done, value } = await reader.read();
|
|
546
|
+
if (!done) {
|
|
547
|
+
if (value.byteLength) controller.enqueue(value);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
stage = "done";
|
|
551
|
+
controller.enqueue(tailBytes);
|
|
552
|
+
controller.close();
|
|
553
|
+
},
|
|
554
|
+
cancel: (reason) => reader.cancel(reason)
|
|
555
|
+
}),
|
|
556
|
+
contentType
|
|
557
|
+
};
|
|
558
|
+
};
|
|
559
|
+
/** The options an upload sends, without the transport ones and without empty values. */
|
|
560
|
+
const uploadFields = (options) => Object.fromEntries(UPLOAD_OPTION_KEYS.flatMap((key) => options[key] === void 0 || options[key] === null ? [] : [[key, options[key]]]));
|
|
561
|
+
/** The asset fields an upload carries in its body: the API refuses them in the query string. */
|
|
562
|
+
const UPLOAD_OPTION_KEYS = [
|
|
563
|
+
"name",
|
|
564
|
+
"description",
|
|
565
|
+
"processingOptions",
|
|
566
|
+
"visibility",
|
|
567
|
+
"metadata",
|
|
568
|
+
"tags",
|
|
569
|
+
"authorId",
|
|
570
|
+
"context",
|
|
571
|
+
"externalId",
|
|
572
|
+
"externalUrl",
|
|
573
|
+
"folderId",
|
|
574
|
+
"uploadPresetId"
|
|
575
|
+
];
|
|
576
|
+
const setOptionalQueryValue = (params, key, value) => {
|
|
577
|
+
if (value !== void 0 && value !== null) params.set(key, String(value));
|
|
578
|
+
};
|
|
579
|
+
const assertValidUploadMimeType = (mimeType) => {
|
|
580
|
+
if (!isAcceptedUploadMimeType(mimeType)) throw new CalmLensError(API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, {
|
|
581
|
+
message: getRejectedUploadMimeTypeError(mimeType),
|
|
582
|
+
details: {
|
|
583
|
+
mimeType,
|
|
584
|
+
source: "calmlens"
|
|
585
|
+
}
|
|
586
|
+
});
|
|
587
|
+
};
|
|
588
|
+
const isImageMimeType = (mimeType) => mimeType.toLowerCase().startsWith("image/");
|
|
589
|
+
const invalidPayload = (message) => new CalmLensError(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message });
|
|
590
|
+
const assertDeclaredPayloadSize = (payload, declared = payload.sizeInBytes) => {
|
|
591
|
+
if (declared === void 0) return;
|
|
592
|
+
const data = "data" in payload ? payload.data : void 0;
|
|
593
|
+
const measured = data instanceof ArrayBuffer || ArrayBuffer.isView(data) ? data.byteLength : getAssetPayloadByteLength(payload);
|
|
594
|
+
if (!Number.isSafeInteger(declared) || declared < 0 || measured !== void 0 && measured !== declared) throw invalidPayload("sizeInBytes must match the payload byte length");
|
|
933
595
|
};
|
|
934
596
|
/**
|
|
935
|
-
*
|
|
936
|
-
*
|
|
597
|
+
* Refuses content whose known size is over the API's limit for its type, so nothing is sent and
|
|
598
|
+
* an oversized file fails at once instead of after its upload. In one request, images can be up
|
|
599
|
+
* to 10 MiB (larger ones are uploaded in parts), audio and video up to 50 MiB and other files up
|
|
600
|
+
* to 5,000 MiB. Sent in parts (`inParts`), audio and video can be up to 2 GiB; the API holds free
|
|
601
|
+
* uploads, made before billing is set up, to 50 MiB itself. Images in parts are checked apart.
|
|
937
602
|
*/
|
|
938
|
-
const
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
"
|
|
975
|
-
"
|
|
976
|
-
|
|
977
|
-
"
|
|
978
|
-
"
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
603
|
+
const assertUploadSize = (type, size, inParts) => {
|
|
604
|
+
if (size === void 0) return;
|
|
605
|
+
const mime = type.toLowerCase();
|
|
606
|
+
const [limit, message] = mime.startsWith("image/") ? [MAX_DIRECT_IMAGE_UPLOAD_BYTES, "Images uploaded in one request can be at most 10 MiB; upload larger images in parts"] : mime.startsWith("audio/") || mime.startsWith("video/") ? [inParts ? MAX_LONG_MEDIA_UPLOAD_BYTES : MAX_MEDIA_UPLOAD_BYTES, "Audio and video files can be at most 50 MiB in one request, or 2 GiB in parts"] : [MAX_NON_IMAGE_UPLOAD_BYTES, "Files can be at most 5,000 MiB"];
|
|
607
|
+
if (size > limit) throw new CalmLensError(API_ERROR_CODES.UPLOAD_TOO_LARGE, {
|
|
608
|
+
message,
|
|
609
|
+
details: {
|
|
610
|
+
limitBytes: limit,
|
|
611
|
+
source: "plan"
|
|
612
|
+
}
|
|
613
|
+
});
|
|
614
|
+
};
|
|
615
|
+
/** Checks upload options before anything is sent. */
|
|
616
|
+
const isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
|
|
617
|
+
/**
|
|
618
|
+
* `content` given as a `Blob` or `File`, as the `{ data, type }` the rest of the client reads: the
|
|
619
|
+
* content type is the Blob's own, and a File's name is the asset's when the options give none.
|
|
620
|
+
*/
|
|
621
|
+
const withContentObject = (options) => {
|
|
622
|
+
if (!options || typeof options !== "object" || !("content" in options)) return options;
|
|
623
|
+
const content = options.content;
|
|
624
|
+
if (!isBlob(content)) return options;
|
|
625
|
+
if (!content.type) throw invalidPayload("The Blob has no type: create it with one, such as new Blob([bytes], { type: \"image/png\" }), or pass { data, type }");
|
|
626
|
+
const fileName = typeof File !== "undefined" && content instanceof File ? content.name : void 0;
|
|
627
|
+
const named = options;
|
|
628
|
+
return {
|
|
629
|
+
...options,
|
|
630
|
+
...named.name || !fileName ? {} : { name: fileName },
|
|
631
|
+
content: {
|
|
632
|
+
data: content,
|
|
633
|
+
type: content.type
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
};
|
|
637
|
+
const prepareSubmitAssetOptions = (input, { deferUploadChecks = false, partSizeBytes = DEFAULT_PART_SIZE_BYTES } = {}) => {
|
|
638
|
+
const options = withContentObject(input);
|
|
639
|
+
if (!options || typeof options !== "object") throw invalidArgument("Asset options are required");
|
|
640
|
+
if (!("content" in options) && !("url" in options) && !("part" in options)) throw invalidPayload("Either file content, URL, or multipart part is required");
|
|
641
|
+
if (!options.name) throw invalidPayload("Asset name is required");
|
|
642
|
+
if (!("part" in options) && "isFinal" in options) throw invalidPayload("isFinal is only valid for multipart uploads");
|
|
643
|
+
if ("part" in options && options.part.partNumber && options.part.partNumber > 1) throw new CalmLensError(API_ERROR_CODES.USE_UPLOAD_PART, { message: "Use uploadPart for multipart upload parts after the first part" });
|
|
644
|
+
if ("content" in options) {
|
|
645
|
+
assertDeclaredPayloadSize(options.content);
|
|
646
|
+
assertValidUploadMimeType(options.content.type);
|
|
647
|
+
const inParts = splitsIntoParts(options.content, partSizeBytes);
|
|
648
|
+
if (inParts && (options.idempotencyKey?.length ?? 0) > 240) throw invalidArgument(`idempotencyKey can be at most 240 characters for an upload sent in parts`);
|
|
649
|
+
if (!deferUploadChecks && inParts && isImageMimeType(options.content.type)) {
|
|
650
|
+
if ((getAssetPayloadByteLength(options.content) ?? 0) > MAX_IMAGE_UPLOAD_BYTES) throw new CalmLensError(API_ERROR_CODES.UPLOAD_TOO_LARGE, {
|
|
651
|
+
message: "Multipart image uploads cannot exceed 20 MiB.",
|
|
652
|
+
details: {
|
|
653
|
+
limitBytes: MAX_IMAGE_UPLOAD_BYTES,
|
|
654
|
+
source: "plan"
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
} else if (!deferUploadChecks) assertUploadSize(options.content.type, options.content.sizeInBytes ?? getAssetPayloadByteLength(options.content), inParts);
|
|
658
|
+
if (!("plainText" in options.content)) {
|
|
659
|
+
const validation = validateAssetPayload(options.content);
|
|
660
|
+
if (!validation.ok) throw invalidPayload(validation.error);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if ("part" in options) {
|
|
664
|
+
assertDeclaredPayloadSize(options.part, options.part.sizeInBytes ?? options.sizeInBytes);
|
|
665
|
+
assertValidUploadMimeType(options.part.type);
|
|
666
|
+
const partSizeInBytes = options.part.sizeInBytes ?? getAssetPayloadByteLength(options.part);
|
|
667
|
+
if (!deferUploadChecks && isImageMimeType(options.part.type) && partSizeInBytes !== void 0) {
|
|
668
|
+
if (partSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw new CalmLensError(API_ERROR_CODES.UPLOAD_TOO_LARGE, {
|
|
669
|
+
message: "Multipart image uploads cannot exceed 20 MiB.",
|
|
670
|
+
details: {
|
|
671
|
+
limitBytes: MAX_IMAGE_UPLOAD_BYTES,
|
|
672
|
+
source: "plan"
|
|
673
|
+
}
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
if (!deferUploadChecks && !isImageMimeType(options.part.type)) assertUploadSize(options.part.type, options.totalSizeInBytes, true);
|
|
677
|
+
const validation = validateAssetPayload(options.part, {
|
|
678
|
+
multipart: true,
|
|
679
|
+
isFinal: deferUploadChecks || options.part.isFinal
|
|
680
|
+
});
|
|
681
|
+
if (!validation.ok) throw invalidPayload(validation.error);
|
|
682
|
+
}
|
|
683
|
+
if (options.context !== void 0) {
|
|
684
|
+
if (!options.context || !Array.isArray(options.context.items)) throw invalidArgument("context.items must be an array of earlier posts");
|
|
685
|
+
return {
|
|
686
|
+
...options,
|
|
687
|
+
context: { items: selectModerationContextItems(options.context.items) }
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
return options;
|
|
691
|
+
};
|
|
692
|
+
const newIdempotencyKey = () => randomUuid();
|
|
693
|
+
/** Text content is small, so it keeps the API deadline; binary files may be arbitrarily large. */
|
|
694
|
+
const isTextPayload = (payload) => "plainText" in payload;
|
|
695
|
+
const hasStringStatus = (value) => !!value && typeof value === "object" && typeof value.status === "string";
|
|
696
|
+
const hasDecision = (data) => {
|
|
697
|
+
const decision = data.classification?.moderation?.decision;
|
|
698
|
+
return decision === null || typeof decision === "string";
|
|
699
|
+
};
|
|
700
|
+
const isAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload) && hasDecision(data);
|
|
701
|
+
const isUploadedAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload);
|
|
702
|
+
const expectUploadedAsset = (data) => {
|
|
703
|
+
if (!isUploadedAsset(data)) throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
|
|
704
|
+
message: "Expected an uploaded asset response",
|
|
705
|
+
status: 200
|
|
706
|
+
});
|
|
707
|
+
return data;
|
|
708
|
+
};
|
|
709
|
+
const expectAsset = (data) => {
|
|
710
|
+
if (!isAsset(data)) throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
|
|
711
|
+
message: "Expected an asset response",
|
|
712
|
+
status: 200
|
|
713
|
+
});
|
|
714
|
+
return data;
|
|
715
|
+
};
|
|
716
|
+
/** Checks one call's request options. */
|
|
717
|
+
const validateCallOptions = (options) => {
|
|
718
|
+
if (options === void 0) return;
|
|
719
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw invalidArgument("Request options must be an object");
|
|
720
|
+
const unknown = Object.keys(options).filter((key) => !REQUEST_OPTION_KEYS.includes(key));
|
|
721
|
+
if (unknown.length) throw invalidArgument(`Unknown request options: ${unknown.join(", ")}`, { options: unknown });
|
|
722
|
+
const { timeoutMs, deadlineMs, maxRetries, idempotencyKey, headers, extraQuery, extraBody } = options;
|
|
723
|
+
for (const [name, value] of Object.entries({
|
|
724
|
+
timeoutMs,
|
|
725
|
+
deadlineMs
|
|
726
|
+
})) if (value !== void 0 && (!Number.isSafeInteger(value) || value < 1)) throw invalidArgument(`${name} must be a positive integer`);
|
|
727
|
+
if (maxRetries !== void 0 && (!Number.isSafeInteger(maxRetries) || maxRetries < 0)) throw invalidArgument("maxRetries must be a non-negative integer");
|
|
728
|
+
if (idempotencyKey !== void 0 && (typeof idempotencyKey !== "string" || !idempotencyKey)) throw invalidArgument("idempotencyKey must be a non-empty string");
|
|
729
|
+
for (const [name, value] of Object.entries({
|
|
730
|
+
headers,
|
|
731
|
+
extraQuery,
|
|
732
|
+
extraBody
|
|
733
|
+
})) if (value !== void 0 && (!value || typeof value !== "object" || Array.isArray(value))) throw invalidArgument(`${name} must be an object`);
|
|
734
|
+
if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) throw invalidArgument("signal must be an AbortSignal");
|
|
735
|
+
};
|
|
736
|
+
const isPlainObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
737
|
+
/** Fills in the default API base URL and drops trailing slashes. */
|
|
738
|
+
const resolveConnectionOptions = (options) => ({
|
|
739
|
+
...options,
|
|
740
|
+
baseUrl: (options.baseUrl ?? `https://api.calmlens.com/v1`).replace(/\/+$/, "")
|
|
741
|
+
});
|
|
742
|
+
/** One client's transport, base URL and deadlines, and the requests both clients make. */
|
|
743
|
+
var CalmLensConnection = class CalmLensConnection {
|
|
744
|
+
constructor(options, apiKey, { readEnvironment = false, shared } = {}) {
|
|
745
|
+
this.options = options;
|
|
746
|
+
if (shared) {
|
|
747
|
+
this.transport = shared.transport;
|
|
748
|
+
this.hooks = shared.hooks;
|
|
749
|
+
this.call = shared.call;
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
this.call = {};
|
|
753
|
+
const resolveFetch = () => {
|
|
754
|
+
const fetchImpl = this.options.fetch ?? globalThis.fetch;
|
|
755
|
+
if (typeof fetchImpl !== "function") throw new CalmLensError(SDK_ERROR_CODES.NO_FETCH, { message: "No fetch implementation is available; pass one as the fetch option" });
|
|
756
|
+
return fetchImpl;
|
|
757
|
+
};
|
|
758
|
+
this.hooks = getMockHooks(options);
|
|
759
|
+
const logLevel = resolveLogLevel(options.logLevel, readEnvironment);
|
|
760
|
+
this.transport = new CalmLensTransport({
|
|
761
|
+
apiKey,
|
|
762
|
+
sleep: this.hooks?.sleep,
|
|
763
|
+
fetch: ((input, init) => resolveFetch()(input, init)),
|
|
764
|
+
signal: options.signal,
|
|
765
|
+
maxRetries: options.maxRetries ?? 2,
|
|
766
|
+
maxResponseBytes: options.maxResponseBytes ?? 33554432,
|
|
767
|
+
appInfo: options.appInfo,
|
|
768
|
+
logLevel,
|
|
769
|
+
logger: logLevel === "off" ? void 0 : options.logger ?? console,
|
|
770
|
+
onAttempt: options.onAttempt,
|
|
771
|
+
now: this.hooks?.now
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* This connection for one call: its requests carry `operation` to the attempt hook and logs, and
|
|
776
|
+
* follow `requestOptions` (checked here) over the client's.
|
|
777
|
+
*/
|
|
778
|
+
forCall(operation, requestOptions) {
|
|
779
|
+
validateCallOptions(requestOptions);
|
|
780
|
+
const deadlines = [this.call.deadlineAt, requestOptions?.deadlineMs === void 0 ? void 0 : this.now() + requestOptions.deadlineMs].filter((deadline) => deadline !== void 0);
|
|
781
|
+
return this.withCall({
|
|
782
|
+
...requestOptions,
|
|
783
|
+
operation,
|
|
784
|
+
deadlineAt: deadlines.length ? Math.min(...deadlines) : void 0
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
/** This connection with `call` over its call's settings, sharing its transport. */
|
|
788
|
+
withCall(call) {
|
|
789
|
+
return new CalmLensConnection(this.options, void 0, { shared: {
|
|
790
|
+
transport: this.transport,
|
|
791
|
+
hooks: this.hooks,
|
|
792
|
+
call: {
|
|
793
|
+
...this.call,
|
|
794
|
+
...call
|
|
795
|
+
}
|
|
796
|
+
} });
|
|
797
|
+
}
|
|
798
|
+
/** The clock retries, deadlines and `waitForDecision` read; mock clients pass their own. */
|
|
799
|
+
get now() {
|
|
800
|
+
return this.hooks?.now ?? Date.now;
|
|
801
|
+
}
|
|
802
|
+
/** The call's transport settings, for a request built here or by the client. */
|
|
803
|
+
callRequest() {
|
|
804
|
+
const { operation, signal, maxRetries, deadlineAt } = this.call;
|
|
805
|
+
return {
|
|
806
|
+
operation,
|
|
807
|
+
signal,
|
|
808
|
+
maxRetries,
|
|
809
|
+
deadlineAt
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
/** The call's extra headers under the SDK's own, which win. */
|
|
813
|
+
callHeaders(headers) {
|
|
814
|
+
return this.call.headers ? {
|
|
815
|
+
...this.call.headers,
|
|
816
|
+
...headers
|
|
817
|
+
} : headers;
|
|
818
|
+
}
|
|
819
|
+
/** The call's `extraBody` merged into a JSON body. */
|
|
820
|
+
callBody(method, body) {
|
|
821
|
+
const { extraBody } = this.call;
|
|
822
|
+
if (!extraBody) return body;
|
|
823
|
+
if (method === "GET" || method === "HEAD") throw invalidArgument("extraBody needs a request with a body");
|
|
824
|
+
if (body === void 0) return extraBody;
|
|
825
|
+
if (!isPlainObject(body)) throw invalidArgument("extraBody needs a JSON object body");
|
|
826
|
+
return {
|
|
827
|
+
...body,
|
|
828
|
+
...extraBody
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
/** How the client waits between polls and retries. */
|
|
832
|
+
get sleep() {
|
|
833
|
+
return this.hooks?.sleep ?? sleep;
|
|
834
|
+
}
|
|
835
|
+
/** Whether multipart size checks are left to the API (mock clients only). */
|
|
836
|
+
get deferUploadChecks() {
|
|
837
|
+
return this.hooks?.deferUploadChecks ?? false;
|
|
838
|
+
}
|
|
839
|
+
get timeoutMs() {
|
|
840
|
+
return this.call.timeoutMs ?? this.options.timeoutMs ?? 12e4;
|
|
841
|
+
}
|
|
842
|
+
/** The URL of `path` (which may carry a query already) with `query` and the call's `extraQuery`. */
|
|
843
|
+
url(path, query) {
|
|
844
|
+
const search = [query, this.call.extraQuery].map((values) => values ? stringifyQuery(values) : "").filter(Boolean).join("&");
|
|
845
|
+
const separator = path.includes("?") ? "&" : "?";
|
|
846
|
+
return `${this.options.baseUrl}${path}${search ? `${separator}${search}` : ""}`;
|
|
847
|
+
}
|
|
848
|
+
/** A JSON request whose deadline covers reading the response. */
|
|
849
|
+
json(method, path, { query, body, headers, idempotencyKey } = {}) {
|
|
850
|
+
const sent = this.callBody(method, body);
|
|
851
|
+
return this.transport.json({
|
|
852
|
+
...this.callRequest(),
|
|
853
|
+
method,
|
|
854
|
+
url: this.url(path, query),
|
|
855
|
+
headers: this.callHeaders(sent === void 0 ? headers : {
|
|
856
|
+
...headers,
|
|
857
|
+
"Content-Type": "application/json"
|
|
858
|
+
}),
|
|
859
|
+
body: sent === void 0 ? void 0 : JSON.stringify(sent),
|
|
860
|
+
idempotencyKey: idempotencyKey ?? this.call.idempotencyKey,
|
|
861
|
+
timeoutMs: this.timeoutMs,
|
|
862
|
+
deadline: "body"
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
upload(url, body, headers, idempotencyKey, text) {
|
|
866
|
+
return this.transport.json({
|
|
867
|
+
...this.callRequest(),
|
|
868
|
+
method: "POST",
|
|
869
|
+
url,
|
|
870
|
+
headers: this.callHeaders(headers),
|
|
871
|
+
body,
|
|
872
|
+
idempotencyKey,
|
|
873
|
+
timeoutMs: text ? this.timeoutMs : this.call.timeoutMs ?? this.options.uploadTimeoutMs,
|
|
874
|
+
deadline: "body",
|
|
875
|
+
fetch: this.options.uploadFetch
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* Uploads file content or a first multipart part to `uploadsPath` (`.../assets`). Plain text
|
|
880
|
+
* goes as a JSON body; other content as an upload form, the asset's fields in its options part
|
|
881
|
+
* and the bytes in its file part. Either way the query holds only transport values.
|
|
882
|
+
*/
|
|
883
|
+
async submitUpload(uploadsPath, options, wait, authHeaders = {}) {
|
|
884
|
+
const isMultipart = "part" in options;
|
|
885
|
+
const payload = isMultipart ? options.part : options.content;
|
|
886
|
+
const multipartOptions = options;
|
|
887
|
+
const idempotencyKey = options.idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey();
|
|
888
|
+
const fields = {
|
|
889
|
+
...uploadFields(options),
|
|
890
|
+
...this.call.extraBody
|
|
891
|
+
};
|
|
892
|
+
if (isTextPayload(payload)) {
|
|
893
|
+
const { sizeInBytes: _size, ...text } = payload;
|
|
894
|
+
const body = isMultipart ? {
|
|
895
|
+
...fields,
|
|
896
|
+
part: text,
|
|
897
|
+
...multipartOptions.sizeInBytes === void 0 ? {} : { sizeInBytes: multipartOptions.sizeInBytes },
|
|
898
|
+
...multipartOptions.totalSizeInBytes === void 0 ? {} : { totalSizeInBytes: multipartOptions.totalSizeInBytes }
|
|
899
|
+
} : {
|
|
900
|
+
...fields,
|
|
901
|
+
content: text
|
|
902
|
+
};
|
|
903
|
+
return this.upload(this.url(uploadsPath, { wait }), JSON.stringify(body), {
|
|
904
|
+
...authHeaders,
|
|
905
|
+
"Content-Type": "application/json"
|
|
906
|
+
}, idempotencyKey, true);
|
|
907
|
+
}
|
|
908
|
+
const query = new URLSearchParams();
|
|
909
|
+
query.set("wait", String(wait));
|
|
910
|
+
query.set("contentType", payload.type);
|
|
911
|
+
setOptionalQueryValue(query, "sizeInBytes", payload.sizeInBytes ?? getAssetPayloadByteLength(payload));
|
|
912
|
+
if (isMultipart) {
|
|
913
|
+
const part = payload;
|
|
914
|
+
query.set("partNumber", String(part.partNumber ?? 1));
|
|
915
|
+
query.set("isFinal", String(part.isFinal ?? false));
|
|
916
|
+
setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? multipartOptions.sizeInBytes);
|
|
917
|
+
setOptionalQueryValue(query, "totalSizeInBytes", multipartOptions.totalSizeInBytes);
|
|
918
|
+
}
|
|
919
|
+
const form = await toUploadForm(fields, payload);
|
|
920
|
+
return this.upload(this.url(`${uploadsPath}?${query}`), form.body, {
|
|
921
|
+
...authHeaders,
|
|
922
|
+
"Content-Type": form.contentType,
|
|
923
|
+
"X-CalmLens-Upload": isMultipart ? "part" : "content"
|
|
924
|
+
}, idempotencyKey, false);
|
|
925
|
+
}
|
|
926
|
+
/** Content larger than this is uploaded in parts. */
|
|
927
|
+
get partSizeBytes() {
|
|
928
|
+
return this.options.partSizeBytes ?? 8388608;
|
|
929
|
+
}
|
|
930
|
+
/**
|
|
931
|
+
* Uploads content larger than `partSizeBytes` in parts: the first to `uploadsPath` with the
|
|
932
|
+
* upload's fields, the rest to `partPath(assetId)`. Each part carries its own Idempotency-Key
|
|
933
|
+
* (`<key>:part-<n>`), so it is retried safely and a repeated call with the same key resumes the
|
|
934
|
+
* upload. A part the API already has is skipped, and a final part that finds the upload already
|
|
935
|
+
* completed reads it back with `retrieve`.
|
|
936
|
+
*/
|
|
937
|
+
async submitInParts(uploadsPath, options, wait, { authHeaders = {}, partPath, onStarted, retrieve }) {
|
|
938
|
+
const { content, idempotencyKey, ...fields } = options;
|
|
939
|
+
const source = getSplittableContent(content);
|
|
940
|
+
const partSize = this.partSizeBytes;
|
|
941
|
+
const count = Math.ceil(source.size / partSize);
|
|
942
|
+
const key = idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey();
|
|
943
|
+
const part = (partNumber) => source.slice((partNumber - 1) * partSize, Math.min(partNumber * partSize, source.size));
|
|
944
|
+
const first = await this.submitUpload(uploadsPath, {
|
|
945
|
+
...fields,
|
|
946
|
+
part: {
|
|
947
|
+
...part(1),
|
|
948
|
+
type: content.type,
|
|
949
|
+
partNumber: 1,
|
|
950
|
+
isFinal: false
|
|
951
|
+
},
|
|
952
|
+
totalSizeInBytes: source.size,
|
|
953
|
+
idempotencyKey: key
|
|
954
|
+
}, wait, authHeaders);
|
|
955
|
+
const assetId = expectUploadedAsset(first).id;
|
|
956
|
+
onStarted?.(assetId);
|
|
957
|
+
const laterParts = this.withCall({ extraBody: void 0 });
|
|
958
|
+
let result = first;
|
|
959
|
+
for (let partNumber = 2; partNumber <= count;) {
|
|
960
|
+
const isFinal = partNumber === count;
|
|
961
|
+
try {
|
|
962
|
+
result = await laterParts.uploadPart(partPath(assetId), {
|
|
963
|
+
part: {
|
|
964
|
+
...part(partNumber),
|
|
965
|
+
partNumber,
|
|
966
|
+
isFinal
|
|
967
|
+
},
|
|
968
|
+
idempotencyKey: `${key}:part-${partNumber}`
|
|
969
|
+
}, authHeaders);
|
|
970
|
+
partNumber++;
|
|
971
|
+
} catch (error) {
|
|
972
|
+
if (!(error instanceof CalmLensError)) throw error;
|
|
973
|
+
const expected = error.details?.expectedPartNumber;
|
|
974
|
+
if (error.code === API_ERROR_CODES.INVALID_UPLOAD_PART_NUMBER && typeof expected === "number" && expected > partNumber && expected <= count) {
|
|
975
|
+
partNumber = expected;
|
|
976
|
+
continue;
|
|
977
|
+
}
|
|
978
|
+
if (isFinal && error.code === API_ERROR_CODES.UPLOAD_NOT_OPEN) return retrieve(assetId, this.withCall({
|
|
979
|
+
operation: "assets.retrieve",
|
|
980
|
+
idempotencyKey: void 0,
|
|
981
|
+
extraBody: void 0
|
|
982
|
+
}));
|
|
983
|
+
throw error;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
return result;
|
|
987
|
+
}
|
|
988
|
+
/** Uploads the next part of a multipart upload to `partPath` (`.../assets/{id}/part`). */
|
|
989
|
+
uploadPart(partPath, { part, wait, idempotencyKey }, authHeaders = {}) {
|
|
990
|
+
if (!part) throw invalidArgument("Part options are required");
|
|
991
|
+
if (this.call.extraBody) throw invalidArgument("A part's body is its bytes: extraBody can't apply");
|
|
992
|
+
assertDeclaredPayloadSize(part);
|
|
993
|
+
const validation = validateAssetPayload(part, {
|
|
994
|
+
multipart: true,
|
|
995
|
+
isFinal: this.deferUploadChecks || part.isFinal
|
|
996
|
+
});
|
|
997
|
+
if (!validation.ok) throw invalidPayload(validation.error);
|
|
998
|
+
const query = new URLSearchParams({
|
|
999
|
+
partNumber: String(part.partNumber),
|
|
1000
|
+
isFinal: String(part.isFinal ?? false)
|
|
1001
|
+
});
|
|
1002
|
+
if (wait !== void 0) query.set("wait", String(wait));
|
|
1003
|
+
setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? getAssetPayloadByteLength(part));
|
|
1004
|
+
return this.upload(this.url(`${partPath}?${query}`), toRawUploadBody(part), {
|
|
1005
|
+
...authHeaders,
|
|
1006
|
+
"X-CalmLens-Upload": "part"
|
|
1007
|
+
}, idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey(), isTextPayload(part));
|
|
1008
|
+
}
|
|
992
1009
|
};
|
|
993
|
-
export { validateAssetPayload as _,
|
|
1010
|
+
export { validateAssetPayload as _, getMockHooks as a, prepareSubmitAssetOptions as c, validateCallOptions as d, APP_OPTION_KEYS as f, assetToData as g, assetDataToUint8Array as h, expectUploadedAsset as i, resolveConnectionOptions as l, SERVER_OPTION_KEYS as m, MOCK_HOOKS as n, invalidPayload as o, NULLABLE_OPTION_KEYS as p, expectAsset as r, newIdempotencyKey as s, CalmLensConnection as t, splitsIntoParts as u };
|