@calmlens/sdk 0.9.1 → 0.10.1
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-DjYFaTyh.d.ts +8608 -0
- package/cjs/CalmLensWebhooks-DJnaLpRy.js +741 -0
- package/cjs/index.d.ts +276 -7525
- package/cjs/index.js +672 -1185
- package/cjs/testing.d.ts +83 -8
- package/cjs/testing.js +991 -596
- package/esm/CalmLensTypes-DjYFaTyh.d.ts +8608 -0
- package/esm/CalmLensWebhooks-DLUozliX.js +556 -0
- package/esm/index.d.ts +276 -7525
- package/esm/index.js +658 -1169
- 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-B6vwJijv.js +0 -657
- package/esm/CalmLensTypes-CZqyni4p.d.ts +0 -3633
- package/esm/CalmLensUtils-O1xk_Ts0.js +0 -492
package/cjs/index.js
CHANGED
|
@@ -1,403 +1,336 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
3
|
-
let zod = require("zod");
|
|
4
|
-
zod = require_CalmLensUtils.__toESM(zod);
|
|
5
|
-
require("zod/v4");
|
|
6
|
-
let api_def = require("api-def");
|
|
7
|
-
//#region ../shared/src/ModerationCategoryDefinitions.ts
|
|
8
|
-
const MODERATION_CATEGORY_DEFINITIONS = {
|
|
9
|
-
sexual: {
|
|
10
|
-
summary: "Sexual acts, explicit sexual anatomy, sexual services, sexual assault depictions and clearly erotic material.",
|
|
11
|
-
definition: "covers sexual acts, explicit sexual anatomy, sexual services and clearly erotic material. Descriptions of sexual assault can qualify without erotic intent. Fictional, illustrated and generated depictions can also qualify.",
|
|
12
|
-
exclusions: "Ordinary affection, swimwear, fitness, fashion, non-erotic medical diagrams and general sexual-health education do not qualify on their own. A person accepting money or wearing revealing clothing does not establish sexual content without a qualifying act, display or offer.",
|
|
13
|
-
docsHref: "/docs/guides/moderation-categories#sexual-content"
|
|
14
|
-
},
|
|
15
|
-
violence: {
|
|
16
|
-
summary: "Physical attacks, injury, death, threats against others, and planning or encouraging physical violence.",
|
|
17
|
-
definition: "covers physical attacks, bodily injury, death and threats against others. Accidental or medical injuries and natural death also count; an attacker or intent to harm is not required. It also includes planning, requesting, encouraging or praising physical violence. A depicted or described act can qualify in fiction or news reporting even when the author condemns it.",
|
|
18
|
-
exclusions: "Solely intentional self-injury or suicide belongs under self-harm. Property damage alone, figurative language, abstract discussion of violence, injury or death and merely possessing a weapon do not establish violence. Consensual sport or training without injury or abuse is excluded.",
|
|
19
|
-
docsHref: "/docs/guides/moderation-categories#violence"
|
|
20
|
-
},
|
|
21
|
-
"self-harm": {
|
|
22
|
-
summary: "Intentional self-injury, suicide, preparation, methods or encouragement; text also includes current or recurring self-harm thoughts.",
|
|
23
|
-
definition: "covers intentional self-injury, suicide, current self-harm risk, preparation, methods and encouragement. For text, it also includes current or recurring self-harm thoughts and an explicitly expressed desire to die. Asking for support does not cancel a separate disclosure of current risk or behavior.",
|
|
24
|
-
exclusions: "For images, require evidence of a self-directed act, preparation, harmful methods or encouragement. An injury or covered body does not establish that harm was self-inflicted. General sadness, neutral statistics, prevention, recovery and healed scars alone are excluded.",
|
|
25
|
-
docsHref: "/docs/guides/moderation-categories#self-harm"
|
|
26
|
-
},
|
|
27
|
-
harassment: {
|
|
28
|
-
summary: "Targeted personal abuse, humiliation, bullying or serious intimidation; ordinary criticism and neutral reporting are excluded.",
|
|
29
|
-
definition: "covers personal abuse, humiliation, bullying and serious intimidation directed at a person or identifiable group. The target can be named, implied or defined by an activity or affiliation. A protected identity is not required.",
|
|
30
|
-
exclusions: "Disagreement, ordinary criticism of conduct or competence, untargeted profanity and neutral reporting of abuse do not qualify without a separate personal attack. Criticism can still qualify when it also contains personal degradation.",
|
|
31
|
-
docsHref: "/docs/guides/moderation-categories#harassment-and-bullying"
|
|
32
|
-
},
|
|
33
|
-
hate: {
|
|
34
|
-
summary: "Identity-based abuse, dehumanization, discriminatory exclusion or threats against people because of protected characteristics.",
|
|
35
|
-
definition: "covers attacks on people because of race, ethnicity, nationality, religion, caste, sex, gender identity, sexual orientation or disability. It includes dehumanization, asserted inferiority, discriminatory exclusion, identity-based abuse and threats.",
|
|
36
|
-
exclusions: "Both the protected target and the identity-based attack must be supported. Identity mentions, cultural clothing, religious imagery, criticism of beliefs or an unrelated threat do not establish hate. Neutral reporting, condemnation and opposition to hate are excluded unless a separate attack is expressed or endorsed.",
|
|
37
|
-
docsHref: "/docs/guides/moderation-categories#hate-and-identity-abuse"
|
|
38
|
-
},
|
|
39
|
-
"criminal-activity": {
|
|
40
|
-
summary: "Planning, assistance, instructions, encouragement or facilitation of a concrete criminal or seriously dangerous act.",
|
|
41
|
-
definition: "covers planning, requests for assistance, instructions, encouragement or facilitation of a concrete criminal or seriously dangerous act. A request can qualify even when no act occurs and a later reply refuses it. Dangerous activity requires a concrete serious risk of physical harm.",
|
|
42
|
-
exclusions: "Neutral reporting, prevention, lawful safety advice, fiction without criminal assistance, and vague dangerous references do not qualify. Masks, computers, payment cards, detention or ordinary tools do not establish criminal facilitation by themselves. A clear visual demonstration of how to carry out a crime can qualify.",
|
|
43
|
-
docsHref: "/docs/guides/moderation-categories#criminal-and-dangerous-activity"
|
|
44
|
-
}
|
|
45
|
-
};
|
|
2
|
+
const require_CalmLensWebhooks = require("./CalmLensWebhooks-DJnaLpRy.js");
|
|
46
3
|
//#endregion
|
|
47
|
-
//#region
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"
|
|
55
|
-
|
|
56
|
-
"
|
|
57
|
-
"injury",
|
|
58
|
-
"death",
|
|
59
|
-
"graphic",
|
|
60
|
-
"self-harm-thoughts",
|
|
61
|
-
"self-harm-preparation",
|
|
62
|
-
"self-harm-act",
|
|
63
|
-
"self-harm-methods",
|
|
64
|
-
"self-harm-encouragement",
|
|
65
|
-
"personal-abuse",
|
|
66
|
-
"targeted-intimidation",
|
|
67
|
-
"harassment-threat",
|
|
68
|
-
"sexual-harassment",
|
|
69
|
-
"harassment-encouragement",
|
|
70
|
-
"identity-abuse",
|
|
71
|
-
"dehumanization",
|
|
72
|
-
"identity-inferiority",
|
|
73
|
-
"discriminatory-exclusion",
|
|
74
|
-
"hate-threat",
|
|
75
|
-
"criminal-demonstration",
|
|
76
|
-
"criminal-preparation",
|
|
77
|
-
"criminal-request",
|
|
78
|
-
"criminal-instructions",
|
|
79
|
-
"criminal-promotion",
|
|
80
|
-
"historical",
|
|
81
|
-
"documentary",
|
|
82
|
-
"fictional",
|
|
83
|
-
"support-prevention"
|
|
84
|
-
];
|
|
85
|
-
const SHARED_QUALIFIERS = [
|
|
86
|
-
"historical",
|
|
87
|
-
"documentary",
|
|
88
|
-
"fictional",
|
|
89
|
-
"support-prevention"
|
|
90
|
-
];
|
|
91
|
-
[...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS];
|
|
92
|
-
//#endregion
|
|
93
|
-
//#region ../../node_modules/zod-meta/esm/index.js
|
|
94
|
-
const createMetaType = (type) => {
|
|
95
|
-
return Object.assign((value) => {
|
|
96
|
-
return {
|
|
97
|
-
type,
|
|
98
|
-
data: value !== null && value !== void 0 ? value : {}
|
|
99
|
-
};
|
|
100
|
-
}, type);
|
|
4
|
+
//#region src/client/CalmLensVersion.ts
|
|
5
|
+
/** This SDK's version, from its package.json. */
|
|
6
|
+
const SDK_VERSION = "0.10.1";
|
|
7
|
+
const runtimeName = () => {
|
|
8
|
+
const runtime = globalThis;
|
|
9
|
+
if (runtime.Bun?.version) return `bun/${runtime.Bun.version}`;
|
|
10
|
+
if (runtime.Deno?.version?.deno) return `deno/${runtime.Deno.version.deno}`;
|
|
11
|
+
if (runtime.navigator?.userAgent === "Cloudflare-Workers") return "workerd";
|
|
12
|
+
if (runtime.process?.versions?.node) return `node/${runtime.process.versions.node}`;
|
|
13
|
+
return "unknown";
|
|
101
14
|
};
|
|
102
|
-
|
|
15
|
+
/** The `User-Agent` the SDK sends from server runtimes, e.g. `calmlens-js/0.10.0 (node/22.12.0)`. */
|
|
16
|
+
const getUserAgent = () => `calmlens-js/${SDK_VERSION} (${runtimeName()})`;
|
|
17
|
+
/** True in a web page, where API keys would be visible to every visitor. */
|
|
18
|
+
const isBrowserRuntime = () => typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined";
|
|
103
19
|
//#endregion
|
|
104
|
-
//#region
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
return true;
|
|
116
|
-
}, "Not long enough").refine((value) => {
|
|
117
|
-
var _options$maxLength, _options$type;
|
|
118
|
-
const sizeLimit = (_options$maxLength = options === null || options === void 0 ? void 0 : options.maxLength) !== null && _options$maxLength !== void 0 ? _options$maxLength : SIZE_LIMITS[(_options$type = options === null || options === void 0 ? void 0 : options.type) !== null && _options$type !== void 0 ? _options$type : "medium"];
|
|
119
|
-
return typeof value === "string" && value.length < sizeLimit;
|
|
120
|
-
}, "Too long");
|
|
121
|
-
};
|
|
122
|
-
const CLASSIFICATION_INPUT_TYPE_SCHEMA = zod.enum(["text", "image"]);
|
|
123
|
-
const CLASSIFICATION_CATEGORIES = [
|
|
124
|
-
"sexual",
|
|
125
|
-
"violence",
|
|
126
|
-
"self-harm",
|
|
127
|
-
"harassment",
|
|
128
|
-
"hate",
|
|
129
|
-
"criminal-activity"
|
|
130
|
-
];
|
|
131
|
-
const CLASSIFICATION_CATEGORY_SCHEMA = zod.enum(CLASSIFICATION_CATEGORIES);
|
|
132
|
-
zod.object({
|
|
133
|
-
category: CLASSIFICATION_CATEGORY_SCHEMA,
|
|
134
|
-
displayName: saneStringField(),
|
|
135
|
-
description: saneStringField(),
|
|
136
|
-
supportedInputTypes: zod.array(CLASSIFICATION_INPUT_TYPE_SCHEMA).min(1)
|
|
137
|
-
});
|
|
138
|
-
MODERATION_CATEGORY_DEFINITIONS.sexual.summary, MODERATION_CATEGORY_DEFINITIONS.violence.summary, MODERATION_CATEGORY_DEFINITIONS["self-harm"].summary, MODERATION_CATEGORY_DEFINITIONS.harassment.summary, MODERATION_CATEGORY_DEFINITIONS.hate.summary, MODERATION_CATEGORY_DEFINITIONS["criminal-activity"].summary;
|
|
139
|
-
const LIKELIHOOD_SCHEMA = zod.enum([
|
|
140
|
-
"very-unlikely",
|
|
141
|
-
"unlikely",
|
|
142
|
-
"possible",
|
|
143
|
-
"likely",
|
|
144
|
-
"very-likely"
|
|
20
|
+
//#region src/client/CalmLensTransport.ts
|
|
21
|
+
/** Retry delays grow from this base, doubling per attempt, with jitter. */
|
|
22
|
+
const RETRY_BASE_DELAY_MS = 500;
|
|
23
|
+
const RETRY_MAX_DELAY_MS = 8e3;
|
|
24
|
+
/** A `Retry-After` longer than this is returned to the caller instead of waited out. */
|
|
25
|
+
const RETRY_AFTER_MAX_MS = 6e4;
|
|
26
|
+
const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
|
|
27
|
+
429,
|
|
28
|
+
502,
|
|
29
|
+
503,
|
|
30
|
+
504
|
|
145
31
|
]);
|
|
146
|
-
const
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
likelihood: LIKELIHOOD_SCHEMA
|
|
152
|
-
}).strict().refine(({ score, scopeScore }) => scopeScore === void 0 || scopeScore <= score, {
|
|
153
|
-
message: "Only confidence cannot exceed Any confidence",
|
|
154
|
-
path: ["scopeScore"]
|
|
155
|
-
}), zod.object({
|
|
156
|
-
status: zod.literal("not-evaluated"),
|
|
157
|
-
reason: CLASSIFICATION_NOT_EVALUATED_REASON_SCHEMA
|
|
158
|
-
}).strict()]));
|
|
159
|
-
const CLASSIFICATION_CATEGORY_REPORT_SCHEMA = zod.discriminatedUnion("status", [
|
|
160
|
-
zod.object({
|
|
161
|
-
status: zod.literal("evaluated"),
|
|
162
|
-
likelihood: LIKELIHOOD_SCHEMA,
|
|
163
|
-
score: zod.number().min(0).max(1),
|
|
164
|
-
qualifiers: CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA.optional()
|
|
165
|
-
}).strict(),
|
|
166
|
-
zod.object({
|
|
167
|
-
status: zod.literal("partial"),
|
|
168
|
-
likelihood: LIKELIHOOD_SCHEMA,
|
|
169
|
-
score: zod.number().min(0).max(1),
|
|
170
|
-
qualifiers: CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA.optional()
|
|
171
|
-
}).strict(),
|
|
172
|
-
zod.object({
|
|
173
|
-
status: zod.literal("not-evaluated"),
|
|
174
|
-
reason: CLASSIFICATION_NOT_EVALUATED_REASON_SCHEMA,
|
|
175
|
-
qualifiers: CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA.optional()
|
|
176
|
-
}).strict()
|
|
177
|
-
]);
|
|
178
|
-
const CATEGORIES_SCHEMA = zod.object({
|
|
179
|
-
sexual: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
|
|
180
|
-
violence: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
|
|
181
|
-
"self-harm": CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
|
|
182
|
-
harassment: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
|
|
183
|
-
hate: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
|
|
184
|
-
"criminal-activity": CLASSIFICATION_CATEGORY_REPORT_SCHEMA
|
|
185
|
-
}).strict();
|
|
186
|
-
const CLASSIFICATION_LABEL_SCHEMA = zod.object({
|
|
187
|
-
description: saneStringField(),
|
|
188
|
-
score: zod.number(),
|
|
189
|
-
topicalityScore: zod.number().nullish(),
|
|
190
|
-
likelihood: LIKELIHOOD_SCHEMA,
|
|
191
|
-
knowledgeBaseId: saneStringField().nullish()
|
|
192
|
-
});
|
|
193
|
-
zod.object({
|
|
194
|
-
processedAt: zod.number(),
|
|
195
|
-
categories: CATEGORIES_SCHEMA,
|
|
196
|
-
flagged: zod.boolean(),
|
|
197
|
-
score: zod.number(),
|
|
198
|
-
notes: saneStringField().nullish(),
|
|
199
|
-
media: zod.object({
|
|
200
|
-
durationSeconds: zod.number().positive(),
|
|
201
|
-
frameIntervalSeconds: zod.number().positive().optional(),
|
|
202
|
-
sampledFrames: zod.number().int().nonnegative(),
|
|
203
|
-
audioTranscribed: zod.boolean(),
|
|
204
|
-
segments: zod.array(zod.object({
|
|
205
|
-
source: zod.enum([
|
|
206
|
-
"frame",
|
|
207
|
-
"speech",
|
|
208
|
-
"frame-text",
|
|
209
|
-
"clip"
|
|
210
|
-
]),
|
|
211
|
-
startSeconds: zod.number().nonnegative(),
|
|
212
|
-
endSeconds: zod.number().nonnegative(),
|
|
213
|
-
categories: CATEGORIES_SCHEMA
|
|
214
|
-
}).strict())
|
|
215
|
-
}).strict().optional(),
|
|
216
|
-
labels: zod.array(CLASSIFICATION_LABEL_SCHEMA).nullish()
|
|
217
|
-
}).strict();
|
|
218
|
-
//#endregion
|
|
219
|
-
//#region ../shared/src/MediaTestTriggers.ts
|
|
220
|
-
const MEDIA_TEST_SIGNALS = [...CLASSIFICATION_CATEGORIES, "violence.graphic"];
|
|
221
|
-
const HEX_WORDS = [
|
|
222
|
-
"zero",
|
|
223
|
-
"one",
|
|
224
|
-
"two",
|
|
225
|
-
"three",
|
|
226
|
-
"four",
|
|
227
|
-
"five",
|
|
228
|
-
"six",
|
|
229
|
-
"seven",
|
|
230
|
-
"eight",
|
|
231
|
-
"nine",
|
|
232
|
-
"alpha",
|
|
233
|
-
"bravo",
|
|
234
|
-
"charlie",
|
|
235
|
-
"delta",
|
|
236
|
-
"echo",
|
|
237
|
-
"foxtrot"
|
|
238
|
-
];
|
|
239
|
-
/** Read this aloud, or render it as large, high-contrast text in a video frame. */
|
|
240
|
-
function generateMediaTestCode(signal, projectId) {
|
|
241
|
-
if (!MEDIA_TEST_SIGNALS.includes(signal)) throw new Error("Unsupported media test signal");
|
|
242
|
-
const suffix = projectId.slice(-8).toLowerCase();
|
|
243
|
-
if (!/^[a-f0-9]{8}$/.test(suffix)) throw new Error("Expected a project ID with an eight-character hexadecimal suffix");
|
|
244
|
-
return `Calm Lens test ${[...suffix].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
|
|
245
|
-
}
|
|
246
|
-
//#endregion
|
|
247
|
-
//#region ../shared/src/CryptoUtils.ts
|
|
248
|
-
const encoder = new TextEncoder();
|
|
249
|
-
/** Lowercase hex of `bytes`, two characters per byte. */
|
|
250
|
-
const bytesToHex = (bytes) => Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
251
|
-
(function() {
|
|
252
|
-
var _ref = require_CalmLensUtils._asyncToGenerator(function* (value) {
|
|
253
|
-
return bytesToHex(yield crypto.subtle.digest("SHA-256", encoder.encode(value)));
|
|
254
|
-
});
|
|
255
|
-
return function sha256Hex(_x) {
|
|
256
|
-
return _ref.apply(this, arguments);
|
|
257
|
-
};
|
|
258
|
-
})();
|
|
259
|
-
/** HMAC-SHA256 of `message` keyed with `secret` (both UTF-8 encoded), as lowercase hex. */
|
|
260
|
-
const hmacSha256Hex = function() {
|
|
261
|
-
var _ref2 = require_CalmLensUtils._asyncToGenerator(function* (secret, message) {
|
|
262
|
-
const key = yield crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
263
|
-
name: "HMAC",
|
|
264
|
-
hash: "SHA-256"
|
|
265
|
-
}, false, ["sign"]);
|
|
266
|
-
return bytesToHex(yield crypto.subtle.sign("HMAC", key, encoder.encode(message)));
|
|
267
|
-
});
|
|
268
|
-
return function hmacSha256Hex(_x2, _x3) {
|
|
269
|
-
return _ref2.apply(this, arguments);
|
|
270
|
-
};
|
|
271
|
-
}();
|
|
32
|
+
const timeoutReason = () => {
|
|
33
|
+
const reason = /* @__PURE__ */ new Error("The operation timed out.");
|
|
34
|
+
reason.name = "TimeoutError";
|
|
35
|
+
return reason;
|
|
36
|
+
};
|
|
272
37
|
/**
|
|
273
|
-
*
|
|
274
|
-
*
|
|
38
|
+
* Links the callers' signals and a per-attempt deadline. `AbortSignal.any` holds its sources
|
|
39
|
+
* weakly, so a long-lived caller signal doesn't collect a listener per streamed response;
|
|
40
|
+
* runtimes without it get explicit listeners that `release` removes.
|
|
275
41
|
*/
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
42
|
+
const createAttemptSignal = (signals, timeoutMs) => {
|
|
43
|
+
const callers = signals.filter((signal) => signal !== void 0);
|
|
44
|
+
const deadline = new AbortController();
|
|
45
|
+
let timedOut = false;
|
|
46
|
+
let signal;
|
|
47
|
+
let onAbort;
|
|
48
|
+
if (typeof AbortSignal.any === "function") signal = AbortSignal.any([...callers, deadline.signal]);
|
|
49
|
+
else {
|
|
50
|
+
const controller = new AbortController();
|
|
51
|
+
signal = controller.signal;
|
|
52
|
+
onAbort = (event) => controller.abort(event.target.reason);
|
|
53
|
+
for (const source of [...callers, deadline.signal]) if (source.aborted) controller.abort(source.reason);
|
|
54
|
+
else source.addEventListener("abort", onAbort, { once: true });
|
|
55
|
+
}
|
|
56
|
+
let timer = timeoutMs === void 0 ? void 0 : setTimeout(() => {
|
|
57
|
+
timedOut = true;
|
|
58
|
+
deadline.abort(timeoutReason());
|
|
59
|
+
}, timeoutMs);
|
|
292
60
|
return {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
61
|
+
signal,
|
|
62
|
+
isTimedOut: () => timedOut,
|
|
63
|
+
isCancelled: () => callers.some((caller) => caller.aborted),
|
|
64
|
+
clearDeadline: () => {
|
|
65
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
66
|
+
timer = void 0;
|
|
67
|
+
},
|
|
68
|
+
release: () => {
|
|
69
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
70
|
+
timer = void 0;
|
|
71
|
+
if (onAbort) for (const caller of callers) caller.removeEventListener("abort", onAbort);
|
|
304
72
|
}
|
|
305
73
|
};
|
|
306
74
|
};
|
|
307
|
-
/** `v1=<hex HMAC-SHA256 of "<timestamp>.<body>">`, the `x-calmlens-signature` header value. */
|
|
308
|
-
const createWebhookSignatureHeader = function() {
|
|
309
|
-
var _ref = require_CalmLensUtils._asyncToGenerator(function* (secret, timestamp, body) {
|
|
310
|
-
return `v1=${yield hmacSha256Hex(secret, `${timestamp}.${body}`)}`;
|
|
311
|
-
});
|
|
312
|
-
return function createWebhookSignatureHeader(_x, _x2, _x3) {
|
|
313
|
-
return _ref.apply(this, arguments);
|
|
314
|
-
};
|
|
315
|
-
}();
|
|
316
|
-
/** Headers for one signed delivery of `body`. */
|
|
317
|
-
const createWebhookHeaders = function() {
|
|
318
|
-
var _ref2 = require_CalmLensUtils._asyncToGenerator(function* (options) {
|
|
319
|
-
var _options$timestampSec;
|
|
320
|
-
const timestamp = (_options$timestampSec = options.timestampSeconds) !== null && _options$timestampSec !== void 0 ? _options$timestampSec : Math.floor(Date.now() / 1e3);
|
|
321
|
-
return {
|
|
322
|
-
"content-type": "application/json",
|
|
323
|
-
[WEBHOOK_DELIVERY_HEADER]: options.deliveryId,
|
|
324
|
-
[WEBHOOK_TIMESTAMP_HEADER]: String(timestamp),
|
|
325
|
-
[WEBHOOK_SIGNATURE_HEADER]: yield createWebhookSignatureHeader(options.secret, timestamp, options.body)
|
|
326
|
-
};
|
|
327
|
-
});
|
|
328
|
-
return function createWebhookHeaders(_x4) {
|
|
329
|
-
return _ref2.apply(this, arguments);
|
|
330
|
-
};
|
|
331
|
-
}();
|
|
332
75
|
/**
|
|
333
|
-
*
|
|
334
|
-
*
|
|
335
|
-
* (default 300) of now. Returns `false` for anything missing or malformed.
|
|
76
|
+
* A redirect the SDK must not follow: it would send the API key to another origin. Browsers report
|
|
77
|
+
* a manual redirect as an opaque response; other runtimes return the 3xx with its Location.
|
|
336
78
|
*/
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
79
|
+
const isRedirect = (response) => response.type === "opaqueredirect" || response.status >= 300 && response.status < 400 && response.headers.has("location");
|
|
80
|
+
/** Turns anything thrown while sending or reading a request into a `CalmLensError`. */
|
|
81
|
+
const toFailure = (cause, attempt) => {
|
|
82
|
+
if (require_CalmLensWebhooks.CalmLensError.isCalmLensError(cause)) return cause;
|
|
83
|
+
if (attempt.isCancelled()) return new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.CANCELLED, {
|
|
84
|
+
message: "Request cancelled",
|
|
85
|
+
cause
|
|
86
|
+
});
|
|
87
|
+
if (attempt.isTimedOut()) return new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.TIMEOUT, {
|
|
88
|
+
message: "Request timed out",
|
|
89
|
+
cause
|
|
90
|
+
});
|
|
91
|
+
return new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.TRANSPORT_ERROR, {
|
|
92
|
+
message: "Request failed",
|
|
93
|
+
cause
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
97
|
+
if (signal?.aborted) {
|
|
98
|
+
reject(new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.CANCELLED, { message: "Request cancelled" }));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const onAbort = () => {
|
|
102
|
+
clearTimeout(timer);
|
|
103
|
+
reject(new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.CANCELLED, { message: "Request cancelled" }));
|
|
104
|
+
};
|
|
105
|
+
const timer = setTimeout(() => {
|
|
106
|
+
signal?.removeEventListener("abort", onAbort);
|
|
107
|
+
resolve();
|
|
108
|
+
}, ms);
|
|
109
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
110
|
+
});
|
|
111
|
+
/** Exponential backoff with jitter: half the delay is fixed, the other half random. */
|
|
112
|
+
const getRetryDelayMs = (attempt, random = Math.random) => {
|
|
113
|
+
const delay = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** attempt);
|
|
114
|
+
return Math.round(delay / 2 + random() * (delay / 2));
|
|
115
|
+
};
|
|
116
|
+
/** Parses `Retry-After` as seconds or an HTTP date, in seconds from `now`. */
|
|
117
|
+
const parseRetryAfter = (value, now = Date.now()) => {
|
|
118
|
+
if (!value) return void 0;
|
|
119
|
+
const trimmed = value.trim();
|
|
120
|
+
if (/^\d+$/.test(trimmed)) return Number(trimmed);
|
|
121
|
+
const date = Date.parse(trimmed);
|
|
122
|
+
if (Number.isNaN(date)) return void 0;
|
|
123
|
+
return Math.max(0, Math.ceil((date - now) / 1e3));
|
|
124
|
+
};
|
|
125
|
+
/** Bodies that can be sent again unchanged. Streams are consumed by the first attempt. */
|
|
126
|
+
const isReplayableBody = (body) => body === void 0 || body === null || typeof body === "string" || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof URLSearchParams;
|
|
127
|
+
const isApiErrorPayload = (value) => !!value && typeof value === "object" && typeof value.code === "string";
|
|
128
|
+
/** Reads at most `limit` bytes of a body, failing with `sdk/response-too-large` beyond that. */
|
|
129
|
+
const readBody = async (response, limit) => {
|
|
130
|
+
const declared = Number(response.headers.get("content-length"));
|
|
131
|
+
const tooLarge = () => new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.RESPONSE_TOO_LARGE, {
|
|
132
|
+
message: `Response body exceeds ${limit} bytes`,
|
|
133
|
+
status: response.status,
|
|
134
|
+
requestId: response.headers.get("x-request-id") ?? void 0,
|
|
135
|
+
headers: response.headers
|
|
136
|
+
});
|
|
137
|
+
if (Number.isFinite(declared) && declared > limit) {
|
|
138
|
+
await response.body?.cancel().catch(() => {});
|
|
139
|
+
throw tooLarge();
|
|
140
|
+
}
|
|
141
|
+
if (!response.body) return /* @__PURE__ */ new Uint8Array(0);
|
|
142
|
+
const reader = response.body.getReader();
|
|
143
|
+
const chunks = [];
|
|
144
|
+
let total = 0;
|
|
145
|
+
for (;;) {
|
|
146
|
+
const { done, value } = await reader.read();
|
|
147
|
+
if (done) break;
|
|
148
|
+
total += value.byteLength;
|
|
149
|
+
if (total > limit) {
|
|
150
|
+
await reader.cancel().catch(() => {});
|
|
151
|
+
throw tooLarge();
|
|
152
|
+
}
|
|
153
|
+
chunks.push(value);
|
|
154
|
+
}
|
|
155
|
+
const bytes = new Uint8Array(total);
|
|
156
|
+
let offset = 0;
|
|
157
|
+
for (const chunk of chunks) {
|
|
158
|
+
bytes.set(chunk, offset);
|
|
159
|
+
offset += chunk.byteLength;
|
|
160
|
+
}
|
|
161
|
+
return bytes;
|
|
162
|
+
};
|
|
163
|
+
const responseInfo = (response) => ({
|
|
164
|
+
status: response.status,
|
|
165
|
+
requestId: response.headers.get("x-request-id") ?? void 0,
|
|
166
|
+
headers: response.headers,
|
|
167
|
+
retryAfter: parseRetryAfter(response.headers.get("retry-after"))
|
|
168
|
+
});
|
|
169
|
+
/** The `CalmLensError` for a non-2xx response whose body has been read. */
|
|
170
|
+
const toHttpError = (response, bytes) => {
|
|
171
|
+
let data;
|
|
172
|
+
try {
|
|
173
|
+
data = JSON.parse(new TextDecoder().decode(bytes));
|
|
174
|
+
} catch {}
|
|
175
|
+
if (isApiErrorPayload(data)) {
|
|
176
|
+
const { code, message, details, traceId } = data;
|
|
177
|
+
return new require_CalmLensWebhooks.CalmLensError(code, {
|
|
178
|
+
message: message ?? code,
|
|
179
|
+
...responseInfo(response),
|
|
180
|
+
details: details || traceId ? {
|
|
181
|
+
...details,
|
|
182
|
+
...traceId ? { traceId } : {}
|
|
183
|
+
} : void 0
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
return new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.HTTP_ERROR, {
|
|
187
|
+
message: `HTTP ${response.status}`,
|
|
188
|
+
...responseInfo(response)
|
|
354
189
|
});
|
|
355
|
-
|
|
356
|
-
|
|
190
|
+
};
|
|
191
|
+
/** Sends requests with the client's credentials, deadlines, retries and response limits. */
|
|
192
|
+
var CalmLensTransport = class {
|
|
193
|
+
constructor(settings) {
|
|
194
|
+
this.settings = settings;
|
|
195
|
+
}
|
|
196
|
+
headersFor(request) {
|
|
197
|
+
const headers = new Headers(request.init?.headers);
|
|
198
|
+
for (const [name, value] of Object.entries(request.headers ?? {})) headers.set(name, value);
|
|
199
|
+
if (!headers.has("accept") && request.deadline === "body") headers.set("accept", "application/json");
|
|
200
|
+
headers.set("x-api-key", this.settings.apiKey);
|
|
201
|
+
if (!isBrowserRuntime()) headers.set("user-agent", getUserAgent());
|
|
202
|
+
if (request.idempotencyKey) headers.set("idempotency-key", request.idempotencyKey);
|
|
203
|
+
return Object.fromEntries(headers.entries());
|
|
204
|
+
}
|
|
205
|
+
canRetry(request) {
|
|
206
|
+
return this.settings.maxRetries > 0 && (request.method === "GET" || request.method === "HEAD" || !!request.idempotencyKey) && isReplayableBody(request.body);
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Sends a request and returns the response, retrying transport failures, 429, 502–504 and
|
|
210
|
+
* `idempotency/request-in-progress` when the request is safe to repeat. Non-2xx responses
|
|
211
|
+
* throw unless `allowHttpErrors` is set. Call `release` once the body has been read.
|
|
212
|
+
*/
|
|
213
|
+
async send(request, { allowHttpErrors = false } = {}) {
|
|
214
|
+
const fetchImpl = request.fetch ?? this.settings.fetch;
|
|
215
|
+
const retryable = this.canRetry(request);
|
|
216
|
+
const headers = this.headersFor(request);
|
|
217
|
+
for (let attemptNumber = 0;; attemptNumber++) {
|
|
218
|
+
const canRetryAgain = retryable && attemptNumber < this.settings.maxRetries;
|
|
219
|
+
const attempt = createAttemptSignal([this.settings.signal, request.init?.signal ?? void 0], request.timeoutMs);
|
|
220
|
+
let response;
|
|
221
|
+
try {
|
|
222
|
+
attempt.signal.throwIfAborted();
|
|
223
|
+
response = await fetchImpl(request.url, {
|
|
224
|
+
...request.init,
|
|
225
|
+
method: request.method,
|
|
226
|
+
headers,
|
|
227
|
+
body: request.body,
|
|
228
|
+
redirect: "manual",
|
|
229
|
+
signal: attempt.signal,
|
|
230
|
+
duplex: "half"
|
|
231
|
+
});
|
|
232
|
+
if (isRedirect(response)) {
|
|
233
|
+
await response.body?.cancel().catch(() => {});
|
|
234
|
+
throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.TRANSPORT_ERROR, { message: `Unexpected redirect (HTTP ${response.status})` });
|
|
235
|
+
}
|
|
236
|
+
} catch (cause) {
|
|
237
|
+
attempt.release();
|
|
238
|
+
const failure = toFailure(cause, attempt);
|
|
239
|
+
if (canRetryAgain && failure.code === require_CalmLensWebhooks.SDK_ERROR_CODES.TRANSPORT_ERROR) {
|
|
240
|
+
await sleep(getRetryDelayMs(attemptNumber), this.settings.signal);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
throw failure;
|
|
244
|
+
}
|
|
245
|
+
if (request.deadline === "headers") attempt.clearDeadline();
|
|
246
|
+
if (response.ok) return {
|
|
247
|
+
response,
|
|
248
|
+
attempt
|
|
249
|
+
};
|
|
250
|
+
if (allowHttpErrors) {
|
|
251
|
+
const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
|
|
252
|
+
const delayMs = retryAfter !== void 0 ? retryAfter * 1e3 : getRetryDelayMs(attemptNumber);
|
|
253
|
+
if (!canRetryAgain || !RETRYABLE_STATUSES.has(response.status) || delayMs > RETRY_AFTER_MAX_MS) return {
|
|
254
|
+
response,
|
|
255
|
+
attempt
|
|
256
|
+
};
|
|
257
|
+
attempt.release();
|
|
258
|
+
await response.body?.cancel().catch(() => {});
|
|
259
|
+
await sleep(delayMs, this.settings.signal);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
let error;
|
|
263
|
+
try {
|
|
264
|
+
error = toHttpError(response, await readBody(response, this.settings.maxResponseBytes));
|
|
265
|
+
} catch (cause) {
|
|
266
|
+
error = toFailure(cause, attempt);
|
|
267
|
+
} finally {
|
|
268
|
+
attempt.release();
|
|
269
|
+
}
|
|
270
|
+
const retryDelayMs = error.retryAfter !== void 0 ? error.retryAfter * 1e3 : getRetryDelayMs(attemptNumber);
|
|
271
|
+
if (canRetryAgain && retryDelayMs <= RETRY_AFTER_MAX_MS && (error.status !== void 0 && RETRYABLE_STATUSES.has(error.status) || error.code === require_CalmLensWebhooks.API_ERROR_CODES.IDEMPOTENT_REQUEST_IN_PROGRESS)) {
|
|
272
|
+
await sleep(retryDelayMs, this.settings.signal);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
throw error;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/** Sends a request and parses its JSON response body. */
|
|
279
|
+
async json(request) {
|
|
280
|
+
const { response, attempt } = await this.send(request);
|
|
281
|
+
try {
|
|
282
|
+
const bytes = await readBody(response, this.settings.maxResponseBytes);
|
|
283
|
+
if (bytes.byteLength === 0 && (response.status === 204 || request.method === "DELETE")) return;
|
|
284
|
+
try {
|
|
285
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
286
|
+
} catch (cause) {
|
|
287
|
+
throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.INVALID_RESPONSE, {
|
|
288
|
+
message: `Invalid JSON response (HTTP ${response.status})`,
|
|
289
|
+
...responseInfo(response),
|
|
290
|
+
cause
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
} catch (cause) {
|
|
294
|
+
throw toFailure(cause, attempt);
|
|
295
|
+
} finally {
|
|
296
|
+
attempt.release();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
};
|
|
357
300
|
//#endregion
|
|
358
301
|
//#region src/client/CalmLensClient.ts
|
|
359
|
-
const
|
|
360
|
-
const
|
|
361
|
-
const
|
|
362
|
-
const _excluded4 = ["assetIdentifier", "init"];
|
|
363
|
-
const _excluded5 = ["assetId"];
|
|
364
|
-
const _excluded6 = ["assetId"];
|
|
365
|
-
const _excluded7 = ["assetId"];
|
|
366
|
-
const _excluded8 = ["folderId"];
|
|
302
|
+
const DEFAULT_TIMEOUT_MS = 12e4;
|
|
303
|
+
const DEFAULT_MAX_RETRIES = 2;
|
|
304
|
+
const DEFAULT_MAX_RESPONSE_BYTES = 33554432;
|
|
367
305
|
const toBlobPartBytes = (value) => {
|
|
368
306
|
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
|
369
307
|
return Uint8Array.from(value);
|
|
370
308
|
};
|
|
371
309
|
const normalizePayloadForRequest = (payload) => {
|
|
372
|
-
if ("base64" in payload && payload.base64) return
|
|
310
|
+
if ("base64" in payload && payload.base64) return {
|
|
311
|
+
...payload,
|
|
312
|
+
base64: require_CalmLensWebhooks.getRawBase64(payload.base64)
|
|
313
|
+
};
|
|
373
314
|
if ("uint8Array" in payload && payload.uint8Array) {
|
|
374
|
-
const { uint8Array
|
|
375
|
-
return
|
|
315
|
+
const { uint8Array, ...rest } = payload;
|
|
316
|
+
return {
|
|
317
|
+
...rest,
|
|
318
|
+
data: new Blob([toBlobPartBytes(uint8Array)])
|
|
319
|
+
};
|
|
376
320
|
}
|
|
377
321
|
if ("buffer" in payload && payload.buffer) {
|
|
378
|
-
const { buffer
|
|
379
|
-
return
|
|
322
|
+
const { buffer, ...rest } = payload;
|
|
323
|
+
return {
|
|
324
|
+
...rest,
|
|
325
|
+
data: new Blob([toBlobPartBytes(buffer)])
|
|
326
|
+
};
|
|
380
327
|
}
|
|
381
328
|
return payload;
|
|
382
329
|
};
|
|
383
|
-
const normalizeMetadataForMultipart = (metadata) => {
|
|
384
|
-
if (!Array.isArray(metadata)) return metadata;
|
|
385
|
-
return Object.fromEntries(metadata.map((item, index) => [index, item]));
|
|
386
|
-
};
|
|
387
|
-
const normalizeMetadataOptionsForRequest = (options) => {
|
|
388
|
-
if (!("metadata" in options) || !Array.isArray(options.metadata)) return options;
|
|
389
|
-
return require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, options), {}, { metadata: normalizeMetadataForMultipart(options.metadata) });
|
|
390
|
-
};
|
|
391
|
-
const normalizeAssetOptionsForRequest = (options) => {
|
|
392
|
-
const normalizedOptions = normalizeMetadataOptionsForRequest(options);
|
|
393
|
-
if ("part" in normalizedOptions) return require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, normalizedOptions), {}, { part: normalizePayloadForRequest(normalizedOptions.part) });
|
|
394
|
-
if ("content" in normalizedOptions && !("plainText" in normalizedOptions.content)) return require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, normalizedOptions), {}, { content: normalizePayloadForRequest(normalizedOptions.content) });
|
|
395
|
-
return normalizedOptions;
|
|
396
|
-
};
|
|
397
330
|
const toRawUploadBody = (payload) => {
|
|
398
|
-
const data =
|
|
331
|
+
const data = require_CalmLensWebhooks.assetToData(normalizePayloadForRequest(payload));
|
|
399
332
|
if (data instanceof Response) {
|
|
400
|
-
if (!data.body) throw
|
|
333
|
+
if (!data.body) throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Response upload data must have a body" });
|
|
401
334
|
return data.body;
|
|
402
335
|
}
|
|
403
336
|
if (data instanceof ArrayBuffer || data instanceof Blob) return data;
|
|
@@ -408,923 +341,477 @@ const setOptionalQueryValue = (params, key, value) => {
|
|
|
408
341
|
if (value !== void 0 && value !== null) params.set(key, typeof value === "string" ? value : JSON.stringify(value));
|
|
409
342
|
};
|
|
410
343
|
const assertValidUploadMimeType = (mimeType) => {
|
|
411
|
-
if (
|
|
412
|
-
message:
|
|
344
|
+
if (require_CalmLensWebhooks.isRejectedUploadMimeType(mimeType)) throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.API_ERROR_CODES.INVALID_UPLOAD_MIME_TYPE, {
|
|
345
|
+
message: require_CalmLensWebhooks.getRejectedUploadMimeTypeError(mimeType),
|
|
413
346
|
details: { mimeType }
|
|
414
347
|
});
|
|
415
348
|
};
|
|
416
349
|
const isImageMimeType = (mimeType) => mimeType.toLowerCase().startsWith("image/");
|
|
350
|
+
const invalidPayload = (message) => new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message });
|
|
417
351
|
const prepareSubmitAssetOptions = (options) => {
|
|
418
|
-
if (!
|
|
419
|
-
if (!options
|
|
420
|
-
if (!
|
|
421
|
-
if ("part" in options &&
|
|
352
|
+
if (!options || typeof options !== "object") throw require_CalmLensWebhooks.invalidArgument("Asset options are required");
|
|
353
|
+
if (!("content" in options) && !("url" in options) && !("part" in options)) throw invalidPayload("Either file content, URL, or multipart part is required");
|
|
354
|
+
if (!options.name) throw invalidPayload("Asset name is required");
|
|
355
|
+
if (!("part" in options) && "isFinal" in options) throw invalidPayload("isFinal is only valid for multipart uploads");
|
|
356
|
+
if ("part" in options && options.part.partNumber && options.part.partNumber > 1) throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.API_ERROR_CODES.USE_UPLOAD_PART, { message: "Use uploadPart for multipart upload parts after the first part" });
|
|
422
357
|
if ("content" in options) {
|
|
423
358
|
assertValidUploadMimeType(options.content.type);
|
|
424
359
|
if (!("plainText" in options.content)) {
|
|
425
|
-
const validation =
|
|
426
|
-
if (!validation.ok) throw
|
|
360
|
+
const validation = require_CalmLensWebhooks.validateAssetPayload(options.content);
|
|
361
|
+
if (!validation.ok) throw invalidPayload(validation.error);
|
|
427
362
|
}
|
|
428
363
|
}
|
|
429
364
|
if ("part" in options) {
|
|
430
|
-
var _options$part$sizeInB;
|
|
431
365
|
assertValidUploadMimeType(options.part.type);
|
|
432
|
-
const partSizeInBytes =
|
|
366
|
+
const partSizeInBytes = options.part.sizeInBytes ?? require_CalmLensWebhooks.getAssetPayloadByteLength(options.part);
|
|
433
367
|
if (isImageMimeType(options.part.type) && partSizeInBytes !== void 0) {
|
|
434
|
-
if (partSizeInBytes >
|
|
435
|
-
if (options.part.isFinal && partSizeInBytes <
|
|
368
|
+
if (partSizeInBytes > require_CalmLensWebhooks.MAX_IMAGE_UPLOAD_BYTES) throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.API_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE, { message: "Multipart image uploads cannot exceed 20MB." });
|
|
369
|
+
if (options.part.isFinal && partSizeInBytes < require_CalmLensWebhooks.MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.API_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL, { message: "Multipart image uploads must total at least 10MB." });
|
|
436
370
|
}
|
|
437
|
-
const validation =
|
|
371
|
+
const validation = require_CalmLensWebhooks.validateAssetPayload(options.part, {
|
|
438
372
|
multipart: true,
|
|
439
373
|
isFinal: options.part.isFinal
|
|
440
374
|
});
|
|
441
|
-
if (!validation.ok) throw
|
|
375
|
+
if (!validation.ok) throw invalidPayload(validation.error);
|
|
442
376
|
}
|
|
443
377
|
return options;
|
|
444
378
|
};
|
|
445
|
-
const getEnsureLensCacheKey = (options) => {
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
const
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
return require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, init), {}, {
|
|
461
|
-
redirect: "error",
|
|
462
|
-
headers: Object.fromEntries(headers.entries())
|
|
463
|
-
});
|
|
464
|
-
};
|
|
465
|
-
const requestSignal = (options, signal) => {
|
|
466
|
-
var _options$timeoutMs;
|
|
467
|
-
const signals = [
|
|
468
|
-
options.signal,
|
|
469
|
-
signal,
|
|
470
|
-
AbortSignal.timeout((_options$timeoutMs = options.timeoutMs) !== null && _options$timeoutMs !== void 0 ? _options$timeoutMs : 12e4)
|
|
471
|
-
].filter((value) => value != null);
|
|
472
|
-
return AbortSignal.any(signals);
|
|
473
|
-
};
|
|
474
|
-
/** Copies a fully read body into a new Response, so later JSON parsing cannot hit the network. */
|
|
475
|
-
const toBufferedResponse = function() {
|
|
476
|
-
var _ref = require_CalmLensUtils._asyncToGenerator(function* (response) {
|
|
477
|
-
const body = response.status === 204 || response.status === 304 ? null : yield response.arrayBuffer();
|
|
478
|
-
const headers = new Headers(response.headers);
|
|
479
|
-
headers.delete("content-encoding");
|
|
480
|
-
headers.delete("content-length");
|
|
481
|
-
const buffered = new Response(body, {
|
|
482
|
-
status: response.status,
|
|
483
|
-
statusText: response.statusText,
|
|
484
|
-
headers
|
|
485
|
-
});
|
|
486
|
-
Object.defineProperty(buffered, "url", { value: response.url });
|
|
487
|
-
return buffered;
|
|
488
|
-
});
|
|
489
|
-
return function toBufferedResponse(_x) {
|
|
490
|
-
return _ref.apply(this, arguments);
|
|
491
|
-
};
|
|
492
|
-
}();
|
|
493
|
-
/**
|
|
494
|
-
* Wraps fetch with the client's deadline, cancellation and redirect policy. Every failure,
|
|
495
|
-
* including body reads, decompression and truncated bodies when `bufferBody` is set, becomes a
|
|
496
|
-
* `CalmLensError` (`sdk/transport-error`, `sdk/timeout` or `sdk/cancelled`) with the original
|
|
497
|
-
* error as its `cause`.
|
|
498
|
-
*/
|
|
499
|
-
const safeFetch = (fetchImpl, options, { bufferBody }) => function() {
|
|
500
|
-
var _ref2 = require_CalmLensUtils._asyncToGenerator(function* (input, init) {
|
|
501
|
-
var _init$signal;
|
|
502
|
-
const signal = requestSignal(options, (_init$signal = init === null || init === void 0 ? void 0 : init.signal) !== null && _init$signal !== void 0 ? _init$signal : input instanceof Request ? input.signal : void 0);
|
|
503
|
-
try {
|
|
504
|
-
signal.throwIfAborted();
|
|
505
|
-
const response = yield fetchImpl(input, require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, init), {}, {
|
|
506
|
-
redirect: "error",
|
|
507
|
-
signal
|
|
508
|
-
}));
|
|
509
|
-
return bufferBody ? yield toBufferedResponse(response) : response;
|
|
510
|
-
} catch (cause) {
|
|
511
|
-
var _signal$reason;
|
|
512
|
-
throw require_CalmLensUtils.calmLensError({ id: signal.aborted ? ((_signal$reason = signal.reason) === null || _signal$reason === void 0 ? void 0 : _signal$reason.name) === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" : "sdk/transport-error" }, {
|
|
513
|
-
message: signal.aborted ? "Request aborted" : "Request failed",
|
|
514
|
-
cause
|
|
515
|
-
});
|
|
516
|
-
}
|
|
517
|
-
});
|
|
518
|
-
return function(_x2, _x3) {
|
|
519
|
-
return _ref2.apply(this, arguments);
|
|
520
|
-
};
|
|
521
|
-
}();
|
|
522
|
-
const createApi = (options) => {
|
|
523
|
-
return new api_def.Api({
|
|
524
|
-
name: "Calm Lens",
|
|
525
|
-
baseUrl: options.baseUrl,
|
|
526
|
-
config: { queryHandling: { stringify: require_CalmLensUtils.stringifyQuery } },
|
|
527
|
-
middleware: [
|
|
528
|
-
(0, api_def.RequestCoalescingMiddleware)(),
|
|
529
|
-
{ beforeSend: (context) => {
|
|
530
|
-
context.updateHeaders({ "X-Api-Key": options.apiKey });
|
|
531
|
-
} },
|
|
532
|
-
{ [api_def.RequestEvent.ERROR]: (context) => {
|
|
533
|
-
if (context.error) throw normalizeApiError(context.error);
|
|
534
|
-
} }
|
|
535
|
-
],
|
|
536
|
-
requestBackend: options.requestBackend ? Object.assign(Object.create(options.requestBackend), "fetch" in options.requestBackend && typeof options.requestBackend.fetch === "function" ? { fetch: safeFetch(options.requestBackend.fetch, options, { bufferBody: true }) } : {}) : new api_def.FetchRequestBackend(safeFetch(globalThis.fetch, options, { bufferBody: true }))
|
|
537
|
-
});
|
|
538
|
-
};
|
|
539
|
-
const isApiErrorPayload = (value) => {
|
|
540
|
-
return !!value && typeof value === "object" && typeof value.code === "string";
|
|
541
|
-
};
|
|
542
|
-
const normalizeApiError = (error) => {
|
|
543
|
-
let cause = error;
|
|
544
|
-
const seen = /* @__PURE__ */ new Set();
|
|
545
|
-
while (cause instanceof Error && !seen.has(cause)) {
|
|
546
|
-
seen.add(cause);
|
|
547
|
-
if (cause instanceof require_CalmLensUtils.CalmLensError) return cause;
|
|
548
|
-
if (cause.name === "AbortError" || cause.name === "TimeoutError") return require_CalmLensUtils.calmLensError({ id: cause.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" }, {
|
|
549
|
-
message: "Request aborted",
|
|
550
|
-
cause
|
|
551
|
-
});
|
|
552
|
-
cause = cause.cause;
|
|
553
|
-
}
|
|
554
|
-
const response = error instanceof Error ? (0, api_def.getErrorResponse)(error) : void 0;
|
|
555
|
-
if (error instanceof Error && (0, api_def.isRequestError)(error) && isApiErrorPayload(response === null || response === void 0 ? void 0 : response.data)) {
|
|
556
|
-
const { code, message, details, traceId } = response.data;
|
|
557
|
-
return require_CalmLensUtils.calmLensError({
|
|
558
|
-
id: code,
|
|
559
|
-
defaultMessage: message
|
|
560
|
-
}, {
|
|
561
|
-
message,
|
|
562
|
-
status: response === null || response === void 0 ? void 0 : response.status,
|
|
563
|
-
cause: error,
|
|
564
|
-
details: require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, details), {}, {
|
|
565
|
-
traceId,
|
|
566
|
-
network: true
|
|
567
|
-
})
|
|
568
|
-
});
|
|
569
|
-
}
|
|
570
|
-
if (error instanceof require_CalmLensUtils.CalmLensError) return error;
|
|
571
|
-
return require_CalmLensUtils.calmLensError({ id: response ? response.ok ? "sdk/invalid-response" : "sdk/http-error" : "sdk/transport-error" }, {
|
|
572
|
-
message: response ? `HTTP ${response.status}` : error.message,
|
|
573
|
-
status: response === null || response === void 0 ? void 0 : response.status,
|
|
574
|
-
cause: error
|
|
575
|
-
});
|
|
576
|
-
};
|
|
577
|
-
const createEndpoints = (api) => {
|
|
578
|
-
const getFolders = api.endpoint().paramsOf().responseOf().build({
|
|
579
|
-
id: "getFolders",
|
|
580
|
-
method: "get",
|
|
581
|
-
path: "/projects/:projectId/folders"
|
|
582
|
-
});
|
|
583
|
-
const getFolder = api.endpoint().paramsOf().responseOf().build({
|
|
584
|
-
id: "getFolder",
|
|
585
|
-
method: "get",
|
|
586
|
-
path: "/folders/:folderId"
|
|
587
|
-
});
|
|
588
|
-
const postFolder = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
589
|
-
id: "postFolder",
|
|
590
|
-
method: "post",
|
|
591
|
-
path: "/projects/:projectId/folders"
|
|
592
|
-
});
|
|
593
|
-
const patchFolder = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
594
|
-
id: "patchFolder",
|
|
595
|
-
method: "patch",
|
|
596
|
-
path: "/folders/:folderId"
|
|
597
|
-
});
|
|
598
|
-
const deleteFolder = api.endpoint().paramsOf().responseOf().build({
|
|
599
|
-
id: "deleteFolder",
|
|
600
|
-
method: "delete",
|
|
601
|
-
path: "/folders/:folderId"
|
|
602
|
-
});
|
|
603
|
-
const moveFolder = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
604
|
-
id: "moveFolder",
|
|
605
|
-
method: "post",
|
|
606
|
-
path: "/folders/:folderId/move"
|
|
607
|
-
});
|
|
608
|
-
const getAssetsPage = api.endpoint().queryOf().paramsOf().responseOf().build({
|
|
609
|
-
id: "getAssetsPage",
|
|
610
|
-
method: "get",
|
|
611
|
-
path: "/projects/:projectId/assets/page"
|
|
612
|
-
});
|
|
613
|
-
const searchAssets = api.endpoint().paramsOf().queryOf().responseOf().build({
|
|
614
|
-
id: "searchAssets",
|
|
615
|
-
method: "get",
|
|
616
|
-
path: "/projects/:projectId/assets/search"
|
|
617
|
-
});
|
|
618
|
-
const getAsset = api.endpoint().paramsOf().responseOf().build({
|
|
619
|
-
id: "getAsset",
|
|
620
|
-
method: "get",
|
|
621
|
-
path: "/assets/:assetId"
|
|
622
|
-
});
|
|
623
|
-
const getAssetChildren = api.endpoint().paramsOf().queryOf().responseOf().build({
|
|
624
|
-
id: "getAssetChildren",
|
|
625
|
-
method: "get",
|
|
626
|
-
path: "/assets/:assetId/children"
|
|
627
|
-
});
|
|
628
|
-
const patchAsset = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
629
|
-
id: "patchAsset",
|
|
630
|
-
method: "patch",
|
|
631
|
-
path: "/assets/:assetId"
|
|
632
|
-
});
|
|
633
|
-
const postUploadAsset = api.endpoint().bodyOf({ encoding: "multipart/form-data" }).paramsOf().queryOf().responseOf().build({
|
|
634
|
-
id: "postUploadAsset",
|
|
635
|
-
method: "post",
|
|
636
|
-
path: "/projects/:projectId/assets"
|
|
637
|
-
});
|
|
638
|
-
const postAssetSignedUrl = api.endpoint().bodyOf().paramsOf().responseOf().build({
|
|
639
|
-
id: "postAssetSignedUrl",
|
|
640
|
-
method: "post",
|
|
641
|
-
path: "/assets/:assetId/signed-url"
|
|
642
|
-
});
|
|
643
|
-
const postAssetPart = api.endpoint().bodyOf({ encoding: "multipart/form-data" }).paramsOf().queryOf().responseOf().build({
|
|
644
|
-
id: "postAssetPart",
|
|
645
|
-
method: "post",
|
|
646
|
-
path: "/assets/:assetId/part"
|
|
647
|
-
});
|
|
648
|
-
const moveAsset = api.endpoint().paramsOf().bodyOf().responseOf().build({
|
|
649
|
-
id: "moveAsset",
|
|
650
|
-
method: "post",
|
|
651
|
-
path: "/assets/:assetId/move"
|
|
652
|
-
});
|
|
653
|
-
const retryAsset = api.endpoint().paramsOf().responseOf().build({
|
|
654
|
-
id: "retryAsset",
|
|
655
|
-
method: "post",
|
|
656
|
-
path: "/assets/:assetId/retry"
|
|
657
|
-
});
|
|
658
|
-
const deleteAsset = api.endpoint().paramsOf().responseOf().build({
|
|
659
|
-
id: "deleteAsset",
|
|
660
|
-
method: "delete",
|
|
661
|
-
path: "/assets/:assetId"
|
|
662
|
-
});
|
|
663
|
-
const deleteAssetContent = api.endpoint().paramsOf().responseOf().build({
|
|
664
|
-
id: "deleteAssetContent",
|
|
665
|
-
method: "delete",
|
|
666
|
-
path: "/assets/:assetId/content"
|
|
667
|
-
});
|
|
668
|
-
const getEvents = api.endpoint().paramsOf().queryOf().responseOf().build({
|
|
669
|
-
id: "getEvents",
|
|
670
|
-
method: "get",
|
|
671
|
-
path: "/projects/:projectId/events"
|
|
672
|
-
});
|
|
673
|
-
const ensureLens = api.endpoint().bodyOf().paramsOf().responseOf().build({
|
|
674
|
-
id: "ensureLens",
|
|
675
|
-
method: "put",
|
|
676
|
-
path: "/lenses/:lensIdentifier"
|
|
677
|
-
});
|
|
678
|
-
const ensureLenses = api.endpoint().bodyOf().paramsOf().responseOf().build({
|
|
679
|
-
id: "ensureLenses",
|
|
680
|
-
method: "put",
|
|
681
|
-
path: "/projects/:projectId/lenses"
|
|
682
|
-
});
|
|
683
|
-
return encodePathParams({
|
|
684
|
-
getFolders,
|
|
685
|
-
getFolder,
|
|
686
|
-
postFolder,
|
|
687
|
-
patchFolder,
|
|
688
|
-
deleteFolder,
|
|
689
|
-
moveFolder,
|
|
690
|
-
getAssetsPage,
|
|
691
|
-
searchAssets,
|
|
692
|
-
getAsset,
|
|
693
|
-
getAssetChildren,
|
|
694
|
-
patchAsset,
|
|
695
|
-
postUploadAsset,
|
|
696
|
-
postAssetSignedUrl,
|
|
697
|
-
postAssetPart,
|
|
698
|
-
moveAsset,
|
|
699
|
-
retryAsset,
|
|
700
|
-
deleteAsset,
|
|
701
|
-
deleteAssetContent,
|
|
702
|
-
ensureLens,
|
|
703
|
-
ensureLenses,
|
|
704
|
-
getEvents
|
|
705
|
-
});
|
|
706
|
-
};
|
|
379
|
+
const getEnsureLensCacheKey = (options) => require_CalmLensWebhooks.stringifyJsonCanonical({
|
|
380
|
+
identifier: options.identifier,
|
|
381
|
+
name: options.name,
|
|
382
|
+
description: options.description ?? null,
|
|
383
|
+
type: options.type,
|
|
384
|
+
active: options.active,
|
|
385
|
+
transforms: options.transforms ?? null,
|
|
386
|
+
version: options.version
|
|
387
|
+
});
|
|
388
|
+
const newIdempotencyKey = () => crypto.randomUUID();
|
|
389
|
+
/** Text content is small, so it keeps the API deadline; binary files may be arbitrarily large. */
|
|
390
|
+
const isTextPayload = (payload) => "plainText" in payload;
|
|
391
|
+
const requireId = (value, name) => require_CalmLensWebhooks.encodePathSegment(value, name);
|
|
392
|
+
const isAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && typeof data.status === "string";
|
|
393
|
+
const inspectSymbol = Symbol.for("nodejs.util.inspect.custom");
|
|
707
394
|
/**
|
|
708
|
-
*
|
|
709
|
-
*
|
|
395
|
+
* The CalmLens API client. Create one per project and reuse it; it holds no connections.
|
|
396
|
+
* Every method takes one options object and throws `CalmLensError` on failure.
|
|
710
397
|
*/
|
|
711
|
-
const encodePathParams = (endpoints) => {
|
|
712
|
-
for (const endpoint of Object.values(endpoints)) {
|
|
713
|
-
const submit = endpoint.submit.bind(endpoint);
|
|
714
|
-
endpoint.submit = (config) => submit(require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, config), {}, { params: config.params && Object.fromEntries(Object.entries(config.params).map(([key, value]) => [key, require_CalmLensUtils.encodePathSegment(value, key)])) }));
|
|
715
|
-
}
|
|
716
|
-
return endpoints;
|
|
717
|
-
};
|
|
718
398
|
var CalmLensClient = class CalmLensClient {
|
|
399
|
+
#apiKey;
|
|
400
|
+
#state;
|
|
401
|
+
#transport;
|
|
719
402
|
/**
|
|
720
403
|
* Verifies that a webhook delivery came from CalmLens: checks the `v1=` HMAC-SHA256 in
|
|
721
404
|
* `x-calmlens-signature` over `"<x-calmlens-timestamp>.<raw body>"` and rejects timestamps
|
|
722
405
|
* more than `toleranceSeconds` (default 300) from now, which stops replayed deliveries.
|
|
723
|
-
*
|
|
724
|
-
* @param options.payload - The raw request body, exactly as received (verify before parsing)
|
|
725
|
-
* @param options.signature - The 'x-calmlens-signature' header value
|
|
726
|
-
* @param options.timestamp - The 'x-calmlens-timestamp' header value
|
|
727
|
-
* @param options.secret - The connector's signing secret
|
|
728
|
-
* @param options.toleranceSeconds - Allowed clock distance in seconds (default 300)
|
|
729
|
-
* @param options.now - Override the current time (Date or epoch milliseconds), for tests
|
|
730
|
-
* @returns Promise<boolean> - True if the signature is valid and fresh, false otherwise
|
|
406
|
+
* Also exported as `verifyWebhookSignature`; `parseWebhookEvent` verifies and parses.
|
|
731
407
|
*
|
|
732
408
|
* @example
|
|
733
|
-
* ```
|
|
734
|
-
* // In your webhook handler (e.g. a Fetch API Request)
|
|
409
|
+
* ```ts
|
|
735
410
|
* const payload = await request.text();
|
|
736
411
|
* const isValid = await CalmLensClient.verifyWebhookSignature({
|
|
737
412
|
* payload,
|
|
738
|
-
*
|
|
739
|
-
*
|
|
740
|
-
* secret: WEBHOOK_SECRET,
|
|
413
|
+
* headers: request.headers,
|
|
414
|
+
* secret: process.env.CALMLENS_WEBHOOK_SECRET!,
|
|
741
415
|
* });
|
|
742
|
-
*
|
|
743
|
-
* if (!isValid) {
|
|
744
|
-
* return new Response('Unauthorized', { status: 401 });
|
|
745
|
-
* }
|
|
746
|
-
* const event = JSON.parse(payload); // { id, type, createdAt, projectId, data }
|
|
747
416
|
* ```
|
|
748
417
|
*/
|
|
749
|
-
static verifyWebhookSignature(options) {
|
|
750
|
-
return
|
|
751
|
-
return verifyWebhookSignature(options);
|
|
752
|
-
})();
|
|
418
|
+
static async verifyWebhookSignature(options) {
|
|
419
|
+
return require_CalmLensWebhooks.verifyWebhookSignature(options);
|
|
753
420
|
}
|
|
754
|
-
constructor(options) {
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
this
|
|
759
|
-
this
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
421
|
+
constructor(options, state) {
|
|
422
|
+
require_CalmLensWebhooks.validateClientOptions(options);
|
|
423
|
+
if (isBrowserRuntime() && !options.dangerouslyAllowBrowser) throw require_CalmLensWebhooks.invalidConfig("CalmLensClient is running in a browser, where every visitor could read the API key. Call CalmLens from your server, or set dangerouslyAllowBrowser: true for trusted internal tools.");
|
|
424
|
+
const { apiKey, ...rest } = options;
|
|
425
|
+
this.#apiKey = apiKey;
|
|
426
|
+
this.#state = {
|
|
427
|
+
options: {
|
|
428
|
+
...rest,
|
|
429
|
+
baseUrl: (rest.baseUrl ?? `https://api.calmlens.com/v1`).replace(/\/+$/, ""),
|
|
430
|
+
cdnBaseUrl: (rest.cdnBaseUrl ?? `https://cdn.calmlens.com/v1`).replace(/\/+$/, "")
|
|
431
|
+
},
|
|
432
|
+
ensuredLenses: state?.ensuredLenses ?? /* @__PURE__ */ new Map(),
|
|
433
|
+
pendingEnsureLenses: state?.pendingEnsureLenses ?? /* @__PURE__ */ new Map()
|
|
434
|
+
};
|
|
435
|
+
const resolveFetch = () => {
|
|
436
|
+
const fetchImpl = this.#state.options.fetch ?? globalThis.fetch;
|
|
437
|
+
if (typeof fetchImpl !== "function") throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.NO_FETCH, { message: "No fetch implementation is available; pass one as the fetch option" });
|
|
438
|
+
return fetchImpl;
|
|
439
|
+
};
|
|
440
|
+
this.#transport = new CalmLensTransport({
|
|
441
|
+
apiKey,
|
|
442
|
+
fetch: ((input, init) => resolveFetch()(input, init)),
|
|
443
|
+
signal: rest.signal,
|
|
444
|
+
maxRetries: rest.maxRetries ?? DEFAULT_MAX_RETRIES,
|
|
445
|
+
maxResponseBytes: rest.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES
|
|
446
|
+
});
|
|
767
447
|
}
|
|
768
|
-
/**
|
|
448
|
+
/**
|
|
449
|
+
* A client with different cancellation, deadlines or retries for the calls made through it,
|
|
450
|
+
* sharing this client's credentials and lens cache. This client is unchanged.
|
|
451
|
+
*/
|
|
769
452
|
withRequestOptions(options) {
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
453
|
+
require_CalmLensWebhooks.validateRequestOptions(options);
|
|
454
|
+
return new CalmLensClient({
|
|
455
|
+
...this.#state.options,
|
|
456
|
+
...options,
|
|
457
|
+
apiKey: this.#apiKey
|
|
458
|
+
}, this.#state);
|
|
774
459
|
}
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
const
|
|
778
|
-
|
|
779
|
-
if (!fetchImpl) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.SDK_ERRORS.NO_CDN_FETCH);
|
|
780
|
-
return safeFetch(fetchImpl, this.options, { bufferBody: true });
|
|
460
|
+
/** Keeps the API key out of `console.log`, `util.inspect` and `JSON.stringify`. */
|
|
461
|
+
[inspectSymbol]() {
|
|
462
|
+
const { projectId, baseUrl } = this.#state.options;
|
|
463
|
+
return `CalmLensClient { projectId: ${JSON.stringify(projectId)}, baseUrl: ${JSON.stringify(baseUrl)} }`;
|
|
781
464
|
}
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
return
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
setOptionalQueryValue(query, "description", options.description);
|
|
790
|
-
setOptionalQueryValue(query, "processingOptions", options.processingOptions);
|
|
791
|
-
setOptionalQueryValue(query, "visibility", options.visibility);
|
|
792
|
-
setOptionalQueryValue(query, "metadata", options.metadata);
|
|
793
|
-
setOptionalQueryValue(query, "externalId", options.externalId);
|
|
794
|
-
setOptionalQueryValue(query, "externalUrl", options.externalUrl);
|
|
795
|
-
setOptionalQueryValue(query, "folderId", options.folderId);
|
|
796
|
-
const isMultipart = "part" in options;
|
|
797
|
-
const payload = isMultipart ? options.part : options.content;
|
|
798
|
-
query.set("contentType", payload.type);
|
|
799
|
-
setOptionalQueryValue(query, "sizeInBytes", (_payload$sizeInBytes = payload.sizeInBytes) !== null && _payload$sizeInBytes !== void 0 ? _payload$sizeInBytes : require_CalmLensUtils.getAssetPayloadByteLength(payload));
|
|
800
|
-
if (isMultipart) {
|
|
801
|
-
var _part$partNumber, _part$isFinal, _part$sizeInBytes;
|
|
802
|
-
const part = payload;
|
|
803
|
-
const multipartOptions = options;
|
|
804
|
-
query.set("partNumber", String((_part$partNumber = part.partNumber) !== null && _part$partNumber !== void 0 ? _part$partNumber : 1));
|
|
805
|
-
query.set("isFinal", String((_part$isFinal = part.isFinal) !== null && _part$isFinal !== void 0 ? _part$isFinal : false));
|
|
806
|
-
setOptionalQueryValue(query, "sizeInBytes", (_part$sizeInBytes = part.sizeInBytes) !== null && _part$sizeInBytes !== void 0 ? _part$sizeInBytes : multipartOptions.sizeInBytes);
|
|
807
|
-
}
|
|
808
|
-
const baseUrl = _this.options.baseUrl.replace(/\/$/, "");
|
|
809
|
-
const path = isMultipart ? "assets/multipart-upload" : "assets/upload";
|
|
810
|
-
const url = `${baseUrl}/projects/${encodeURIComponent(_this.options.projectId)}/${path}?${query}`;
|
|
811
|
-
const response = yield _this.getUploadFetch()(url, {
|
|
812
|
-
method: "POST",
|
|
813
|
-
headers: {
|
|
814
|
-
"Content-Type": payload.type,
|
|
815
|
-
"X-Api-Key": _this.options.apiKey,
|
|
816
|
-
"X-CalmLens-Upload": isMultipart ? "part" : "content"
|
|
817
|
-
},
|
|
818
|
-
body: toRawUploadBody(payload),
|
|
819
|
-
duplex: "half"
|
|
820
|
-
});
|
|
821
|
-
const asset = yield _this.parseRawUploadResponse(response);
|
|
822
|
-
if (isMultipart && asset.status === "uploading") {
|
|
823
|
-
_this.multipartUploadQueues.set(asset.id, queue);
|
|
824
|
-
if (isImageMimeType(payload.type)) {
|
|
825
|
-
var _asset$sizeInBytes;
|
|
826
|
-
_this.multipartImageUploadSizes.set(asset.id, (_asset$sizeInBytes = asset.sizeInBytes) !== null && _asset$sizeInBytes !== void 0 ? _asset$sizeInBytes : 0);
|
|
827
|
-
}
|
|
828
|
-
}
|
|
829
|
-
return asset;
|
|
830
|
-
})();
|
|
465
|
+
toJSON() {
|
|
466
|
+
const { projectId, baseUrl, cdnBaseUrl } = this.#state.options;
|
|
467
|
+
return {
|
|
468
|
+
projectId,
|
|
469
|
+
baseUrl,
|
|
470
|
+
cdnBaseUrl
|
|
471
|
+
};
|
|
831
472
|
}
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
return require_CalmLensUtils._asyncToGenerator(function* () {
|
|
835
|
-
var _part$isFinal2, _part$sizeInBytes2;
|
|
836
|
-
const query = new URLSearchParams({
|
|
837
|
-
queue: String(queue),
|
|
838
|
-
partNumber: String(part.partNumber),
|
|
839
|
-
isFinal: String((_part$isFinal2 = part.isFinal) !== null && _part$isFinal2 !== void 0 ? _part$isFinal2 : false)
|
|
840
|
-
});
|
|
841
|
-
setOptionalQueryValue(query, "sizeInBytes", (_part$sizeInBytes2 = part.sizeInBytes) !== null && _part$sizeInBytes2 !== void 0 ? _part$sizeInBytes2 : require_CalmLensUtils.getAssetPayloadByteLength(part));
|
|
842
|
-
const url = `${_this2.options.baseUrl.replace(/\/$/, "")}/assets/${require_CalmLensUtils.encodePathSegment(assetId, "Asset ID")}/part?${query}`;
|
|
843
|
-
const response = yield _this2.getUploadFetch()(url, {
|
|
844
|
-
method: "POST",
|
|
845
|
-
headers: {
|
|
846
|
-
"X-Api-Key": _this2.options.apiKey,
|
|
847
|
-
"X-CalmLens-Upload": "part"
|
|
848
|
-
},
|
|
849
|
-
body: toRawUploadBody(part),
|
|
850
|
-
duplex: "half"
|
|
851
|
-
});
|
|
852
|
-
const asset = yield _this2.parseRawUploadResponse(response);
|
|
853
|
-
if (asset.status === "uploading") {
|
|
854
|
-
var _asset$sizeInBytes2;
|
|
855
|
-
_this2.multipartImageUploadSizes.set(asset.id, (_asset$sizeInBytes2 = asset.sizeInBytes) !== null && _asset$sizeInBytes2 !== void 0 ? _asset$sizeInBytes2 : 0);
|
|
856
|
-
} else {
|
|
857
|
-
_this2.multipartImageUploadSizes.delete(assetId);
|
|
858
|
-
_this2.multipartUploadQueues.delete(assetId);
|
|
859
|
-
}
|
|
860
|
-
return asset;
|
|
861
|
-
})();
|
|
473
|
+
get timeoutMs() {
|
|
474
|
+
return this.#state.options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
862
475
|
}
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
476
|
+
apiUrl(path, query) {
|
|
477
|
+
const search = query ? require_CalmLensWebhooks.stringifyQuery(query) : "";
|
|
478
|
+
return `${this.#state.options.baseUrl}${path}${search ? `?${search}` : ""}`;
|
|
479
|
+
}
|
|
480
|
+
get projectPath() {
|
|
481
|
+
return `/projects/${encodeURIComponent(this.#state.options.projectId)}`;
|
|
482
|
+
}
|
|
483
|
+
request(method, path, { query, body } = {}) {
|
|
484
|
+
return this.#transport.json({
|
|
485
|
+
method,
|
|
486
|
+
url: this.apiUrl(path, query),
|
|
487
|
+
headers: body === void 0 ? void 0 : { "Content-Type": "application/json" },
|
|
488
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
489
|
+
timeoutMs: this.timeoutMs,
|
|
490
|
+
deadline: "body"
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
uploadRequest(url, payload, headers, idempotencyKey) {
|
|
494
|
+
const options = this.#state.options;
|
|
495
|
+
return this.#transport.json({
|
|
496
|
+
method: "POST",
|
|
497
|
+
url,
|
|
498
|
+
headers,
|
|
499
|
+
body: toRawUploadBody(payload),
|
|
500
|
+
idempotencyKey,
|
|
501
|
+
timeoutMs: isTextPayload(payload) ? this.timeoutMs : options.uploadTimeoutMs,
|
|
502
|
+
deadline: "body",
|
|
503
|
+
fetch: options.uploadFetch
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
async submitRawAssetUpload(options, queue) {
|
|
507
|
+
const query = new URLSearchParams();
|
|
508
|
+
query.set("name", options.name);
|
|
509
|
+
query.set("queue", String(queue));
|
|
510
|
+
setOptionalQueryValue(query, "description", options.description);
|
|
511
|
+
setOptionalQueryValue(query, "processingOptions", options.processingOptions);
|
|
512
|
+
setOptionalQueryValue(query, "visibility", options.visibility);
|
|
513
|
+
setOptionalQueryValue(query, "metadata", options.metadata);
|
|
514
|
+
setOptionalQueryValue(query, "externalId", options.externalId);
|
|
515
|
+
setOptionalQueryValue(query, "externalUrl", options.externalUrl);
|
|
516
|
+
setOptionalQueryValue(query, "folderId", options.folderId);
|
|
517
|
+
const isMultipart = "part" in options;
|
|
518
|
+
const payload = isMultipart ? options.part : options.content;
|
|
519
|
+
query.set("contentType", payload.type);
|
|
520
|
+
setOptionalQueryValue(query, "sizeInBytes", payload.sizeInBytes ?? require_CalmLensWebhooks.getAssetPayloadByteLength(payload));
|
|
521
|
+
if (isMultipart) {
|
|
522
|
+
const part = payload;
|
|
523
|
+
const multipartOptions = options;
|
|
524
|
+
query.set("partNumber", String(part.partNumber ?? 1));
|
|
525
|
+
query.set("isFinal", String(part.isFinal ?? false));
|
|
526
|
+
setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? multipartOptions.sizeInBytes);
|
|
527
|
+
setOptionalQueryValue(query, "totalSizeInBytes", multipartOptions.totalSizeInBytes);
|
|
528
|
+
}
|
|
529
|
+
const path = isMultipart ? "assets/multipart-upload" : "assets/upload";
|
|
530
|
+
const data = await this.uploadRequest(this.apiUrl(`${this.projectPath}/${path}?${query}`), payload, {
|
|
531
|
+
"Content-Type": payload.type,
|
|
532
|
+
"X-CalmLens-Upload": isMultipart ? "part" : "content"
|
|
533
|
+
}, options.idempotencyKey ?? newIdempotencyKey());
|
|
534
|
+
return this.expectAsset(data);
|
|
535
|
+
}
|
|
536
|
+
expectAsset(data) {
|
|
537
|
+
if (!isAsset(data)) throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.INVALID_RESPONSE, {
|
|
538
|
+
message: "Expected an asset response",
|
|
539
|
+
status: 200
|
|
540
|
+
});
|
|
541
|
+
return data;
|
|
542
|
+
}
|
|
543
|
+
async submitAsset(options, queue) {
|
|
544
|
+
const body = prepareSubmitAssetOptions(options);
|
|
545
|
+
if ("content" in body || "part" in body) return this.submitRawAssetUpload(body, queue);
|
|
546
|
+
const { idempotencyKey, ...fields } = body;
|
|
547
|
+
const data = await this.#transport.json({
|
|
548
|
+
method: "POST",
|
|
549
|
+
url: this.apiUrl(`${this.projectPath}/assets`, { queue }),
|
|
550
|
+
headers: { "Content-Type": "application/json" },
|
|
551
|
+
body: JSON.stringify(fields),
|
|
552
|
+
idempotencyKey: idempotencyKey ?? newIdempotencyKey(),
|
|
553
|
+
timeoutMs: this.timeoutMs,
|
|
554
|
+
deadline: "body"
|
|
555
|
+
});
|
|
556
|
+
return this.expectAsset(data);
|
|
904
557
|
}
|
|
905
558
|
get cdn() {
|
|
906
|
-
var _this3 = this;
|
|
907
559
|
return {
|
|
908
560
|
/**
|
|
909
|
-
*
|
|
910
|
-
*
|
|
561
|
+
* Builds a CDN URL for asset content or a preview, without a request. Private assets
|
|
562
|
+
* need a signed URL (`assets.createSignedUrl`) or an authenticated request.
|
|
911
563
|
*/
|
|
912
|
-
getAssetUrl: (
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
const resource = (_options$resource = options.resource) !== null && _options$resource !== void 0 ? _options$resource : "content";
|
|
917
|
-
const url = `${this.options.cdnBaseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(this.options.projectId)}/${require_CalmLensUtils.encodePathSegment(assetIdentifier, "Asset identifier")}/${resource}`;
|
|
918
|
-
return require_CalmLensUtils.appendCdnSelector(url, options);
|
|
564
|
+
getAssetUrl: ({ assetIdentifier, ...options }) => {
|
|
565
|
+
const resource = options.resource ?? "content";
|
|
566
|
+
const url = `${this.#state.options.cdnBaseUrl}/assets/${encodeURIComponent(this.#state.options.projectId)}/${requireId(assetIdentifier, "Asset identifier")}/${resource}`;
|
|
567
|
+
return require_CalmLensWebhooks.appendCdnSelector(url, options);
|
|
919
568
|
},
|
|
920
569
|
/**
|
|
921
|
-
*
|
|
922
|
-
*
|
|
570
|
+
* Fetches asset content or a preview from the CDN with the client's API key, and returns
|
|
571
|
+
* the `Response` as soon as headers arrive, so the body streams. Non-2xx responses are
|
|
572
|
+
* returned, not thrown; `timeoutMs` covers only the wait for headers.
|
|
923
573
|
*/
|
|
924
|
-
serve:
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
const fetchImpl = (_this$options$cdnFetc = _this3.options.cdnFetch) !== null && _this$options$cdnFetc !== void 0 ? _this$options$cdnFetc : globalThis.fetch;
|
|
929
|
-
if (!fetchImpl) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.SDK_ERRORS.NO_CDN_FETCH);
|
|
930
|
-
return safeFetch(fetchImpl, _this3.options, { bufferBody: false })(_this3.cdn.getAssetUrl(require_CalmLensUtils._objectSpread2({ assetIdentifier }, urlOptions)), withApiKeyHeader(init, _this3.options.apiKey));
|
|
574
|
+
serve: async ({ assetIdentifier, init, ...urlOptions }) => {
|
|
575
|
+
const url = this.cdn.getAssetUrl({
|
|
576
|
+
assetIdentifier,
|
|
577
|
+
...urlOptions
|
|
931
578
|
});
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
579
|
+
const method = init?.method?.toUpperCase() ?? "GET";
|
|
580
|
+
const { response } = await this.#transport.send({
|
|
581
|
+
method,
|
|
582
|
+
url,
|
|
583
|
+
init,
|
|
584
|
+
timeoutMs: this.timeoutMs,
|
|
585
|
+
deadline: "headers",
|
|
586
|
+
fetch: this.#state.options.cdnFetch
|
|
587
|
+
}, { allowHttpErrors: true });
|
|
588
|
+
return response;
|
|
589
|
+
}
|
|
936
590
|
};
|
|
937
591
|
}
|
|
938
592
|
get text() {
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
return _ref7.apply(this, arguments);
|
|
946
|
-
};
|
|
947
|
-
}() };
|
|
593
|
+
return {
|
|
594
|
+
/**
|
|
595
|
+
* Moderates text and waits for the decision. Sends `text` as `text/plain` content named
|
|
596
|
+
* `text` unless you pass `name`.
|
|
597
|
+
*/
|
|
598
|
+
moderate: async (options) => this.assets.moderate(require_CalmLensWebhooks.toTextAssetOptions(options)) };
|
|
948
599
|
}
|
|
949
600
|
get assets() {
|
|
950
|
-
var _this5 = this;
|
|
951
601
|
return {
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
return function search(_x6) {
|
|
960
|
-
return _ref8.apply(this, arguments);
|
|
961
|
-
};
|
|
962
|
-
}(),
|
|
602
|
+
/** Searches accessible assets by keyword or a natural-language description. */
|
|
603
|
+
search: async (options) => this.request("GET", `${this.projectPath}/assets/search`, { query: options }),
|
|
604
|
+
/** Lists one page of the project's assets, with optional filter and ordering. */
|
|
605
|
+
list: async (options = {}) => this.request("GET", `${this.projectPath}/assets/page`, { query: {
|
|
606
|
+
...options,
|
|
607
|
+
pageIndex: options.pageIndex ?? 0
|
|
608
|
+
} }),
|
|
963
609
|
/**
|
|
964
|
-
*
|
|
965
|
-
*
|
|
966
|
-
* @returns Promise with paginated assets
|
|
610
|
+
* Yields every asset matching `options`, fetching pages as needed. Assets created or
|
|
611
|
+
* deleted while iterating can shift pages, so an asset may be skipped or repeated.
|
|
967
612
|
*/
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
});
|
|
990
|
-
return function retrieve(_x7) {
|
|
991
|
-
return _ref10.apply(this, arguments);
|
|
992
|
-
};
|
|
993
|
-
}(),
|
|
994
|
-
update: function() {
|
|
995
|
-
var _ref12 = require_CalmLensUtils._asyncToGenerator(function* (_ref11) {
|
|
996
|
-
let { assetId } = _ref11, body = require_CalmLensUtils._objectWithoutProperties(_ref11, _excluded5);
|
|
997
|
-
if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
998
|
-
return (yield _this5.endpoints.patchAsset.submit({
|
|
999
|
-
params: { assetId },
|
|
1000
|
-
body
|
|
1001
|
-
})).data;
|
|
1002
|
-
});
|
|
1003
|
-
return function update(_x8) {
|
|
1004
|
-
return _ref12.apply(this, arguments);
|
|
1005
|
-
};
|
|
1006
|
-
}(),
|
|
613
|
+
iterate: (options = {}) => this.iteratePages((pageIndex) => this.assets.list({
|
|
614
|
+
...options,
|
|
615
|
+
pageIndex
|
|
616
|
+
})),
|
|
617
|
+
/** Retrieves an asset with its status and moderation report. */
|
|
618
|
+
retrieve: async ({ assetId }) => this.request("GET", `/assets/${requireId(assetId, "Asset ID")}`),
|
|
619
|
+
/** Updates an asset's editable fields. */
|
|
620
|
+
update: async ({ assetId, ...body }) => this.request("PATCH", `/assets/${requireId(assetId, "Asset ID")}`, { body }),
|
|
621
|
+
/** Lists one page of the assets extracted from a website or multimedia document. */
|
|
622
|
+
listChildren: async ({ assetId, ...options } = {}) => this.request("GET", `/assets/${requireId(assetId, "Asset ID")}/children`, { query: {
|
|
623
|
+
...options,
|
|
624
|
+
pageIndex: options.pageIndex ?? 0
|
|
625
|
+
} }),
|
|
626
|
+
/** Yields every child of an asset, fetching pages as needed. */
|
|
627
|
+
iterateChildren: (options) => {
|
|
628
|
+
requireId(options?.assetId, "Asset ID");
|
|
629
|
+
return this.iteratePages((pageIndex) => this.assets.listChildren({
|
|
630
|
+
...options,
|
|
631
|
+
pageIndex
|
|
632
|
+
}));
|
|
633
|
+
},
|
|
1007
634
|
/**
|
|
1008
|
-
*
|
|
1009
|
-
*
|
|
1010
|
-
*
|
|
1011
|
-
* @returns Promise with paginated child assets
|
|
635
|
+
* Uploads an asset and queues it for moderation, returning immediately with status
|
|
636
|
+
* `pending` (or `uploading` for the first multipart part). Retried safely with an
|
|
637
|
+
* `Idempotency-Key`.
|
|
1012
638
|
*/
|
|
1013
|
-
|
|
1014
|
-
var _ref14 = require_CalmLensUtils._asyncToGenerator(function* (_ref13 = {}) {
|
|
1015
|
-
var _options$pageIndex2;
|
|
1016
|
-
let { assetId } = _ref13, options = require_CalmLensUtils._objectWithoutProperties(_ref13, _excluded6);
|
|
1017
|
-
if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1018
|
-
return (yield _this5.endpoints.getAssetChildren.submit({
|
|
1019
|
-
params: { assetId },
|
|
1020
|
-
query: require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, options), {}, { pageIndex: (_options$pageIndex2 = options.pageIndex) !== null && _options$pageIndex2 !== void 0 ? _options$pageIndex2 : 0 })
|
|
1021
|
-
})).data;
|
|
1022
|
-
});
|
|
1023
|
-
return function listChildren() {
|
|
1024
|
-
return _ref14.apply(this, arguments);
|
|
1025
|
-
};
|
|
1026
|
-
}(),
|
|
639
|
+
create: async (options) => this.submitAsset(options, true),
|
|
1027
640
|
/**
|
|
1028
|
-
*
|
|
1029
|
-
*
|
|
1030
|
-
* @param options - Asset submission options
|
|
1031
|
-
* @returns Promise with created asset
|
|
641
|
+
* Uploads an asset and waits for its moderation decision. Audio and video still finish
|
|
642
|
+
* in the background. Retried safely with an `Idempotency-Key`.
|
|
1032
643
|
*/
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
return (yield _this5.endpoints.postUploadAsset.submit({
|
|
1038
|
-
body: normalizeAssetOptionsForRequest(body),
|
|
1039
|
-
params: { projectId: _this5.options.projectId },
|
|
1040
|
-
query: { queue: true }
|
|
1041
|
-
})).data;
|
|
1042
|
-
});
|
|
1043
|
-
return function create(_x9) {
|
|
1044
|
-
return _ref15.apply(this, arguments);
|
|
1045
|
-
};
|
|
1046
|
-
}(),
|
|
644
|
+
moderate: async (options) => {
|
|
645
|
+
if (options && "content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) throw invalidPayload("Text to moderate must be a non-empty string");
|
|
646
|
+
return this.submitAsset(options, false);
|
|
647
|
+
},
|
|
1047
648
|
/**
|
|
1048
|
-
*
|
|
1049
|
-
*
|
|
1050
|
-
* This may take longer but ensures the asset is fully processed.
|
|
1051
|
-
* @param options - Asset submission options
|
|
1052
|
-
* @returns Promise with created and analyzed asset
|
|
649
|
+
* Uploads the next part of a multipart upload. The upload's queue mode, chosen when it
|
|
650
|
+
* started, applies when the final part arrives; pass `queue` to override it.
|
|
1053
651
|
*/
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
body: normalizeAssetOptionsForRequest(body),
|
|
1061
|
-
params: { projectId: _this5.options.projectId },
|
|
1062
|
-
query: { queue: false }
|
|
1063
|
-
})).data;
|
|
652
|
+
uploadPart: async ({ assetId, part, queue, idempotencyKey }) => {
|
|
653
|
+
const encodedAssetId = requireId(assetId, "Asset ID");
|
|
654
|
+
if (!part) throw require_CalmLensWebhooks.invalidArgument("Part options are required");
|
|
655
|
+
const validation = require_CalmLensWebhooks.validateAssetPayload(part, {
|
|
656
|
+
multipart: true,
|
|
657
|
+
isFinal: part.isFinal
|
|
1064
658
|
});
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
/**
|
|
1070
|
-
* Upload a part for a multipart upload
|
|
1071
|
-
* @param assetId - The asset ID
|
|
1072
|
-
* @param part - The part to upload
|
|
1073
|
-
* @returns Promise with asset data
|
|
1074
|
-
*/
|
|
1075
|
-
uploadPart: function() {
|
|
1076
|
-
var _ref17 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId, part }) {
|
|
1077
|
-
var _part$sizeInBytes3, _this$multipartUpload;
|
|
1078
|
-
if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1079
|
-
if (!part) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Part options are required" });
|
|
1080
|
-
const validation = require_CalmLensUtils.validateAssetPayload(part, {
|
|
1081
|
-
multipart: true,
|
|
1082
|
-
isFinal: part.isFinal
|
|
1083
|
-
});
|
|
1084
|
-
if (!validation.ok) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: validation.error });
|
|
1085
|
-
const existingImageSizeInBytes = _this5.multipartImageUploadSizes.get(assetId);
|
|
1086
|
-
const partSizeInBytes = (_part$sizeInBytes3 = part.sizeInBytes) !== null && _part$sizeInBytes3 !== void 0 ? _part$sizeInBytes3 : require_CalmLensUtils.getAssetPayloadByteLength(part);
|
|
1087
|
-
if (existingImageSizeInBytes !== void 0 && partSizeInBytes !== void 0) {
|
|
1088
|
-
const totalSizeInBytes = existingImageSizeInBytes + partSizeInBytes;
|
|
1089
|
-
if (totalSizeInBytes > require_CalmLensUtils.MAX_IMAGE_UPLOAD_BYTES) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
|
|
1090
|
-
if (part.isFinal && totalSizeInBytes < require_CalmLensUtils.MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
|
|
1091
|
-
}
|
|
1092
|
-
return yield _this5.submitRawAssetPart(assetId, part, (_this$multipartUpload = _this5.multipartUploadQueues.get(assetId)) !== null && _this$multipartUpload !== void 0 ? _this$multipartUpload : false);
|
|
659
|
+
if (!validation.ok) throw invalidPayload(validation.error);
|
|
660
|
+
const query = new URLSearchParams({
|
|
661
|
+
partNumber: String(part.partNumber),
|
|
662
|
+
isFinal: String(part.isFinal ?? false)
|
|
1093
663
|
});
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
};
|
|
1097
|
-
|
|
664
|
+
if (queue !== void 0) query.set("queue", String(queue));
|
|
665
|
+
setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? require_CalmLensWebhooks.getAssetPayloadByteLength(part));
|
|
666
|
+
const data = await this.uploadRequest(this.apiUrl(`/assets/${encodedAssetId}/part?${query}`), part, { "X-CalmLens-Upload": "part" }, idempotencyKey ?? newIdempotencyKey());
|
|
667
|
+
return this.expectAsset(data);
|
|
668
|
+
},
|
|
1098
669
|
/**
|
|
1099
|
-
*
|
|
1100
|
-
*
|
|
1101
|
-
* auth cookies or API keys to the CDN on every media request.
|
|
670
|
+
* Creates a short-lived signed CDN URL, so browsers can load private content without
|
|
671
|
+
* an API key.
|
|
1102
672
|
*/
|
|
1103
|
-
createSignedUrl:
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
},
|
|
1116
|
-
params: { assetId }
|
|
1117
|
-
})).data;
|
|
1118
|
-
});
|
|
1119
|
-
return function createSignedUrl(_x12) {
|
|
1120
|
-
return _ref19.apply(this, arguments);
|
|
1121
|
-
};
|
|
1122
|
-
}(),
|
|
1123
|
-
move: function() {
|
|
1124
|
-
var _ref20 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId, folderId }) {
|
|
1125
|
-
if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1126
|
-
return (yield _this5.endpoints.moveAsset.submit({
|
|
1127
|
-
params: { assetId },
|
|
1128
|
-
body: { folderId }
|
|
1129
|
-
})).data;
|
|
1130
|
-
});
|
|
1131
|
-
return function move(_x13) {
|
|
1132
|
-
return _ref20.apply(this, arguments);
|
|
1133
|
-
};
|
|
1134
|
-
}(),
|
|
673
|
+
createSignedUrl: async ({ assetId, ...options }) => {
|
|
674
|
+
const encodedAssetId = requireId(assetId, "Asset ID");
|
|
675
|
+
if (options.lens && options.transform) throw require_CalmLensWebhooks.invalidArgument("Specify either a lens or a transform, not both");
|
|
676
|
+
return this.request("POST", `/assets/${encodedAssetId}/signed-url`, { body: {
|
|
677
|
+
resource: options.resource ?? "content",
|
|
678
|
+
expiresInSeconds: options.expiresInSeconds ?? 900,
|
|
679
|
+
lens: options.lens,
|
|
680
|
+
transform: options.transform
|
|
681
|
+
} });
|
|
682
|
+
},
|
|
683
|
+
/** Moves an asset into a folder, or to the project root with `folderId: null`. */
|
|
684
|
+
move: async ({ assetId, folderId }) => this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/move`, { body: { folderId } }),
|
|
1135
685
|
/**
|
|
1136
686
|
* Processes an asset that failed (status `error`) again. It returns to `pending` and is
|
|
1137
687
|
* moderated like a new upload; its content must still be stored.
|
|
1138
688
|
*/
|
|
1139
|
-
retry:
|
|
1140
|
-
var _ref21 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId }) {
|
|
1141
|
-
if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1142
|
-
return (yield _this5.endpoints.retryAsset.submit({ params: { assetId } })).data;
|
|
1143
|
-
});
|
|
1144
|
-
return function retry(_x14) {
|
|
1145
|
-
return _ref21.apply(this, arguments);
|
|
1146
|
-
};
|
|
1147
|
-
}(),
|
|
689
|
+
retry: async ({ assetId }) => this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/retry`),
|
|
1148
690
|
/**
|
|
1149
691
|
* Removes an asset's stored content (source, preview and retained extracted text) while
|
|
1150
692
|
* keeping the asset record, metadata and moderation report. The returned asset has
|
|
1151
693
|
* `storageDeletedAt` set; the CDN no longer serves it.
|
|
1152
694
|
*/
|
|
1153
|
-
deleteContent:
|
|
1154
|
-
var _ref22 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId }) {
|
|
1155
|
-
if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1156
|
-
return (yield _this5.endpoints.deleteAssetContent.submit({ params: { assetId } })).data;
|
|
1157
|
-
});
|
|
1158
|
-
return function deleteContent(_x15) {
|
|
1159
|
-
return _ref22.apply(this, arguments);
|
|
1160
|
-
};
|
|
1161
|
-
}(),
|
|
695
|
+
deleteContent: async ({ assetId }) => this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}/content`),
|
|
1162
696
|
/** Deletes an asset record together with its stored content. */
|
|
1163
|
-
delete:
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
yield _this5.endpoints.deleteAsset.submit({ params: { assetId } });
|
|
1167
|
-
});
|
|
1168
|
-
return function _delete(_x16) {
|
|
1169
|
-
return _ref23.apply(this, arguments);
|
|
1170
|
-
};
|
|
1171
|
-
}()
|
|
697
|
+
delete: async ({ assetId }) => {
|
|
698
|
+
await this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}`);
|
|
699
|
+
}
|
|
1172
700
|
};
|
|
1173
701
|
}
|
|
1174
702
|
get events() {
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
703
|
+
return {
|
|
704
|
+
/**
|
|
705
|
+
* Lists project events after a cursor, oldest first. Call without `after` to get a cursor
|
|
706
|
+
* for "now", then poll with the returned `cursor`. Webhook deliveries carry the same events
|
|
707
|
+
* reshaped as `{ id, type, createdAt, projectId, data }`.
|
|
708
|
+
*/
|
|
709
|
+
list: async (options = {}) => this.request("GET", `${this.projectPath}/events`, { query: { ...options } }),
|
|
710
|
+
/**
|
|
711
|
+
* Yields pages of events after `after` until no more are waiting. Save each page's
|
|
712
|
+
* `cursor` to resume later. Without `after`, yields one empty page whose cursor is "now".
|
|
713
|
+
*/
|
|
714
|
+
pages: (options = {}) => this.iterateEventPages(options)
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
async *iterateEventPages(options) {
|
|
718
|
+
let after = options.after;
|
|
719
|
+
for (;;) {
|
|
720
|
+
const page = await this.events.list({
|
|
721
|
+
...options,
|
|
722
|
+
after
|
|
1188
723
|
});
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
}
|
|
724
|
+
yield page;
|
|
725
|
+
if (!page.hasMore || page.cursor === after) return;
|
|
726
|
+
after = page.cursor;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
async *iteratePages(listPage) {
|
|
730
|
+
for (let pageIndex = 0;; pageIndex++) {
|
|
731
|
+
const page = await listPage(pageIndex);
|
|
732
|
+
yield* page.items;
|
|
733
|
+
if (!page.hasMore || page.items.length === 0) return;
|
|
734
|
+
}
|
|
1193
735
|
}
|
|
1194
736
|
get folders() {
|
|
1195
|
-
var _this7 = this;
|
|
1196
737
|
return {
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
}
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
});
|
|
1210
|
-
return function retrieve(_x17) {
|
|
1211
|
-
return _ref26.apply(this, arguments);
|
|
1212
|
-
};
|
|
1213
|
-
}(),
|
|
1214
|
-
create: function() {
|
|
1215
|
-
var _ref27 = require_CalmLensUtils._asyncToGenerator(function* (options) {
|
|
1216
|
-
return (yield _this7.endpoints.postFolder.submit({
|
|
1217
|
-
params: { projectId: _this7.options.projectId },
|
|
1218
|
-
body: options
|
|
1219
|
-
})).data;
|
|
1220
|
-
});
|
|
1221
|
-
return function create(_x18) {
|
|
1222
|
-
return _ref27.apply(this, arguments);
|
|
1223
|
-
};
|
|
1224
|
-
}(),
|
|
1225
|
-
update: function() {
|
|
1226
|
-
var _ref29 = require_CalmLensUtils._asyncToGenerator(function* (_ref28) {
|
|
1227
|
-
let { folderId } = _ref28, body = require_CalmLensUtils._objectWithoutProperties(_ref28, _excluded8);
|
|
1228
|
-
if (!folderId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
1229
|
-
return (yield _this7.endpoints.patchFolder.submit({
|
|
1230
|
-
params: { folderId },
|
|
1231
|
-
body
|
|
1232
|
-
})).data;
|
|
1233
|
-
});
|
|
1234
|
-
return function update(_x19) {
|
|
1235
|
-
return _ref29.apply(this, arguments);
|
|
1236
|
-
};
|
|
1237
|
-
}(),
|
|
1238
|
-
delete: function() {
|
|
1239
|
-
var _ref30 = require_CalmLensUtils._asyncToGenerator(function* ({ folderId }) {
|
|
1240
|
-
if (!folderId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
1241
|
-
yield _this7.endpoints.deleteFolder.submit({ params: { folderId } });
|
|
1242
|
-
});
|
|
1243
|
-
return function _delete(_x20) {
|
|
1244
|
-
return _ref30.apply(this, arguments);
|
|
1245
|
-
};
|
|
1246
|
-
}(),
|
|
1247
|
-
move: function() {
|
|
1248
|
-
var _ref31 = require_CalmLensUtils._asyncToGenerator(function* ({ folderId, parentId }) {
|
|
1249
|
-
if (!folderId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
1250
|
-
return (yield _this7.endpoints.moveFolder.submit({
|
|
1251
|
-
params: { folderId },
|
|
1252
|
-
body: { parentId }
|
|
1253
|
-
})).data;
|
|
1254
|
-
});
|
|
1255
|
-
return function move(_x21) {
|
|
1256
|
-
return _ref31.apply(this, arguments);
|
|
1257
|
-
};
|
|
1258
|
-
}()
|
|
738
|
+
/** Lists every folder in the project. */
|
|
739
|
+
list: async () => (await this.request("GET", `${this.projectPath}/folders`)).folders,
|
|
740
|
+
retrieve: async ({ folderId }) => this.request("GET", `/folders/${requireId(folderId, "Folder ID")}`),
|
|
741
|
+
/** Creates a folder at the project root or inside `parentId`. */
|
|
742
|
+
create: async (options) => this.request("POST", `${this.projectPath}/folders`, { body: options }),
|
|
743
|
+
update: async ({ folderId, ...body }) => this.request("PATCH", `/folders/${requireId(folderId, "Folder ID")}`, { body }),
|
|
744
|
+
/** Deletes an empty folder; throws `folder/not-empty` otherwise. */
|
|
745
|
+
delete: async ({ folderId }) => {
|
|
746
|
+
await this.request("DELETE", `/folders/${requireId(folderId, "Folder ID")}`);
|
|
747
|
+
},
|
|
748
|
+
/** Moves a folder under `parentId`, or to the project root with `parentId: null`. */
|
|
749
|
+
move: async ({ folderId, parentId }) => this.request("POST", `/folders/${requireId(folderId, "Folder ID")}/move`, { body: { parentId } })
|
|
1259
750
|
};
|
|
1260
751
|
}
|
|
1261
752
|
/**
|
|
1262
753
|
* Create a named lens at any positive version, or update it with a greater version.
|
|
1263
754
|
* Supplying the same definition and version is idempotent.
|
|
1264
755
|
*/
|
|
1265
|
-
ensureLens(options) {
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
const [lens] = yield _this8.ensureLenses({ lenses: [options] });
|
|
1270
|
-
return lens;
|
|
1271
|
-
})();
|
|
756
|
+
async ensureLens(options) {
|
|
757
|
+
if (!options?.identifier) throw require_CalmLensWebhooks.invalidArgument("Lens identifier is required");
|
|
758
|
+
const [lens] = await this.ensureLenses({ lenses: [options] });
|
|
759
|
+
return lens;
|
|
1272
760
|
}
|
|
1273
761
|
/**
|
|
1274
762
|
* Create or update several named lenses in one API request.
|
|
1275
763
|
* Each lens follows the same versioning and idempotency rules as ensureLens().
|
|
1276
764
|
*/
|
|
1277
|
-
ensureLenses({ lenses }) {
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
missingOptions.push(option);
|
|
1289
|
-
}
|
|
765
|
+
async ensureLenses({ lenses }) {
|
|
766
|
+
if (!Array.isArray(lenses) || lenses.length === 0) throw require_CalmLensWebhooks.invalidArgument("At least one lens is required");
|
|
767
|
+
if (lenses.some((option) => !option?.identifier)) throw require_CalmLensWebhooks.invalidArgument("Lens identifier is required");
|
|
768
|
+
const { ensuredLenses, pendingEnsureLenses } = this.#state;
|
|
769
|
+
const missingOptions = [];
|
|
770
|
+
const missingKeys = /* @__PURE__ */ new Set();
|
|
771
|
+
for (const option of lenses) {
|
|
772
|
+
const cacheKey = getEnsureLensCacheKey(option);
|
|
773
|
+
if (!ensuredLenses.has(cacheKey) && !missingKeys.has(cacheKey)) {
|
|
774
|
+
missingKeys.add(cacheKey);
|
|
775
|
+
missingOptions.push(option);
|
|
1290
776
|
}
|
|
1291
|
-
|
|
777
|
+
}
|
|
778
|
+
if (missingOptions.length > 0) {
|
|
1292
779
|
const batchCacheKey = JSON.stringify([...missingKeys].sort());
|
|
1293
|
-
let pending =
|
|
780
|
+
let pending = pendingEnsureLenses.get(batchCacheKey);
|
|
1294
781
|
if (!pending) {
|
|
1295
|
-
pending =
|
|
1296
|
-
|
|
1297
|
-
pending.then(() =>
|
|
782
|
+
pending = this.submitEnsureLenses(missingOptions);
|
|
783
|
+
pendingEnsureLenses.set(batchCacheKey, pending);
|
|
784
|
+
pending.then(() => pendingEnsureLenses.delete(batchCacheKey), () => pendingEnsureLenses.delete(batchCacheKey));
|
|
1298
785
|
}
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
786
|
+
await pending;
|
|
787
|
+
}
|
|
788
|
+
return lenses.map((option) => {
|
|
789
|
+
const lens = ensuredLenses.get(getEnsureLensCacheKey(option));
|
|
790
|
+
if (!lens) throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.INVALID_RESPONSE, { message: `CalmLens did not return lens "${option.identifier}"` });
|
|
791
|
+
return lens;
|
|
792
|
+
});
|
|
1302
793
|
}
|
|
1303
|
-
submitEnsureLenses(options) {
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
_this10.ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
|
|
1315
|
-
}
|
|
1316
|
-
})();
|
|
794
|
+
async submitEnsureLenses(options) {
|
|
795
|
+
const result = await this.request("PUT", `${this.projectPath}/lenses`, { body: { lenses: options } });
|
|
796
|
+
const returned = Array.isArray(result?.lenses) ? result.lenses : [];
|
|
797
|
+
if (returned.length !== options.length) throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.INVALID_RESPONSE, { message: `Expected ${options.length} lenses but CalmLens returned ${returned.length}` });
|
|
798
|
+
const { ensuredLenses } = this.#state;
|
|
799
|
+
for (const [index, lens] of returned.entries()) {
|
|
800
|
+
const optionsForLens = options[index];
|
|
801
|
+
if (lens?.identifier !== optionsForLens.identifier) throw new require_CalmLensWebhooks.CalmLensError(require_CalmLensWebhooks.SDK_ERROR_CODES.INVALID_RESPONSE, { message: `Expected lens "${optionsForLens.identifier}" at position ${index}` });
|
|
802
|
+
for (const [cacheKey, cachedLens] of ensuredLenses) if (cachedLens.identifier === optionsForLens.identifier) ensuredLenses.delete(cacheKey);
|
|
803
|
+
ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
|
|
804
|
+
}
|
|
1317
805
|
}
|
|
1318
806
|
};
|
|
1319
807
|
//#endregion
|
|
808
|
+
exports.CALMLENS_ERROR_CODES = require_CalmLensWebhooks.CALMLENS_ERROR_CODES;
|
|
1320
809
|
exports.CalmLensClient = CalmLensClient;
|
|
1321
|
-
exports.CalmLensError =
|
|
1322
|
-
exports.
|
|
1323
|
-
exports.WEBHOOK_DELIVERY_HEADER = WEBHOOK_DELIVERY_HEADER;
|
|
1324
|
-
exports.WEBHOOK_SIGNATURE_HEADER = WEBHOOK_SIGNATURE_HEADER;
|
|
1325
|
-
exports.WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = WEBHOOK_SIGNATURE_TOLERANCE_SECONDS;
|
|
1326
|
-
exports.WEBHOOK_TIMESTAMP_HEADER = WEBHOOK_TIMESTAMP_HEADER;
|
|
1327
|
-
exports.
|
|
1328
|
-
exports.
|
|
1329
|
-
exports.toWebhookEventPayload = toWebhookEventPayload;
|
|
1330
|
-
exports.verifyWebhookSignature = verifyWebhookSignature;
|
|
810
|
+
exports.CalmLensError = require_CalmLensWebhooks.CalmLensError;
|
|
811
|
+
exports.SDK_VERSION = SDK_VERSION;
|
|
812
|
+
exports.WEBHOOK_DELIVERY_HEADER = require_CalmLensWebhooks.WEBHOOK_DELIVERY_HEADER;
|
|
813
|
+
exports.WEBHOOK_SIGNATURE_HEADER = require_CalmLensWebhooks.WEBHOOK_SIGNATURE_HEADER;
|
|
814
|
+
exports.WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = require_CalmLensWebhooks.WEBHOOK_SIGNATURE_TOLERANCE_SECONDS;
|
|
815
|
+
exports.WEBHOOK_TIMESTAMP_HEADER = require_CalmLensWebhooks.WEBHOOK_TIMESTAMP_HEADER;
|
|
816
|
+
exports.parseWebhookEvent = require_CalmLensWebhooks.parseWebhookEvent;
|
|
817
|
+
exports.verifyWebhookSignature = require_CalmLensWebhooks.verifyWebhookSignature;
|