calmlens 0.24.0 → 0.26.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.
Files changed (84) hide show
  1. package/README.md +14 -14
  2. package/bin/calmlens.js +2202 -521
  3. package/cjs/{BrowserUpload-DB-G4tjH.js → BrowserUpload-DdkcoZLH.js} +1 -1
  4. package/{esm/BrowserUpload-nyagMGlJ.d.ts → cjs/BrowserUpload-zYWKtFSs.d.ts} +2 -2
  5. package/cjs/{CalmLensAppClient-CmikPp9x.js → CalmLensAppClient-Gu9mU_66.js} +22 -15
  6. package/{esm/CalmLensAppClient-8qOu4bIX.d.ts → cjs/CalmLensAppClient-mTTjqpRc.d.ts} +5 -11
  7. package/cjs/{CalmLensOptionKeys-BbMF4k44.js → CalmLensOptionKeys-BCITGsr9.js} +138 -90
  8. package/cjs/CalmLensServerClient-D5-njsNk.d.ts +357 -0
  9. package/cjs/{CalmLensServerClient-DJyULgDN.js → CalmLensServerClient-DHmAPT1u.js} +283 -303
  10. package/cjs/{CalmLensTypes-D3eKASff.d.ts → CalmLensTypes-Df8eBgWB.d.ts} +228 -59
  11. package/cjs/{Core-dsHfSHt3.d.ts → Core-CREGGR0L.d.ts} +10 -3
  12. package/cjs/{Core-DnXZJjWN.js → Core-DAf9lqe2.js} +30 -12
  13. package/{esm/ModerationContextLimits-BFILRYw_.js → cjs/ModerationContextLimits-D4iwqoN_.js} +858 -28
  14. package/cjs/{ReactUpload-DWnJElAd.js → ReactUpload-BNIbpxIH.js} +38 -2
  15. package/cjs/ReactUpload-D4htIz8X.d.ts +27 -0
  16. package/cjs/{UploadController-CEHCQar2.js → UploadController-B_lKxvpM.js} +16 -3
  17. package/cjs/{WebhookPayload-DiBh-W7_.d.ts → WebhookPayload-DMa6ihHr.d.ts} +152 -3
  18. package/cjs/app.d.ts +5 -5
  19. package/cjs/app.js +20 -2
  20. package/cjs/elements.d.ts +5 -5
  21. package/cjs/elements.js +102 -67
  22. package/{esm/index-L7S6-AX8.d.ts → cjs/index-CtpQldn_.d.ts} +2 -2
  23. package/cjs/index.d.ts +4 -4
  24. package/cjs/index.js +19 -1
  25. package/cjs/react-native.d.ts +3 -3
  26. package/cjs/react-native.js +6 -4
  27. package/cjs/react.d.ts +5 -4
  28. package/cjs/react.js +10 -14
  29. package/cjs/server.d.ts +5 -5
  30. package/cjs/server.js +20 -2
  31. package/cjs/testing.d.ts +11 -9
  32. package/cjs/testing.js +73 -41
  33. package/cjs/{ui-DJPSG8nD.d.ts → ui-BwFPFrno.d.ts} +2 -2
  34. package/cjs/{ui-DjX32iuB.js → ui-CvlJmRYM.js} +6 -4
  35. package/cjs/ui.d.ts +3 -3
  36. package/cjs/ui.js +4 -3
  37. package/cjs/vue.d.ts +15 -8
  38. package/cjs/vue.js +29 -16
  39. package/esm/{BrowserUpload-B9IJOAOn.js → BrowserUpload-BAWYEBd7.js} +1 -1
  40. package/{cjs/BrowserUpload-nyagMGlJ.d.ts → esm/BrowserUpload-zYWKtFSs.d.ts} +2 -2
  41. package/esm/{CalmLensAppClient-DKDX61Ip.js → CalmLensAppClient-DNkIZb6x.js} +22 -15
  42. package/{cjs/CalmLensAppClient-8qOu4bIX.d.ts → esm/CalmLensAppClient-mTTjqpRc.d.ts} +5 -11
  43. package/esm/{CalmLensOptionKeys-CEX6GvWi.js → CalmLensOptionKeys-CYHJo3nV.js} +133 -91
  44. package/esm/{CalmLensServerClient-DM147w2r.js → CalmLensServerClient-B1AiR4nv.js} +283 -303
  45. package/esm/CalmLensServerClient-D5-njsNk.d.ts +357 -0
  46. package/esm/{CalmLensTypes-D3eKASff.d.ts → CalmLensTypes-Df8eBgWB.d.ts} +228 -59
  47. package/esm/{Core-dsHfSHt3.d.ts → Core-CREGGR0L.d.ts} +10 -3
  48. package/esm/{Core-ix7mc07M.js → Core-xNBQxZWH.js} +30 -12
  49. package/{cjs/ModerationContextLimits-CPNFkp0P.js → esm/ModerationContextLimits-DxuPP4uM.js} +475 -285
  50. package/esm/{ReactUpload-CW1v2fmH.js → ReactUpload-BWifQdLv.js} +34 -4
  51. package/esm/ReactUpload-D4htIz8X.d.ts +27 -0
  52. package/esm/{UploadController-4wdF7tKa.js → UploadController-jlJdddyI.js} +11 -4
  53. package/esm/{WebhookPayload-DiBh-W7_.d.ts → WebhookPayload-DMa6ihHr.d.ts} +152 -3
  54. package/esm/app.d.ts +5 -5
  55. package/esm/app.js +3 -3
  56. package/esm/elements.d.ts +5 -5
  57. package/esm/elements.js +102 -68
  58. package/{cjs/index-L7S6-AX8.d.ts → esm/index-CtpQldn_.d.ts} +2 -2
  59. package/esm/index.d.ts +4 -4
  60. package/esm/index.js +1 -1
  61. package/esm/react-native.d.ts +3 -3
  62. package/esm/react-native.js +5 -5
  63. package/esm/react.d.ts +5 -4
  64. package/esm/react.js +9 -15
  65. package/esm/server.d.ts +5 -5
  66. package/esm/server.js +3 -3
  67. package/esm/styles.css +28 -10
  68. package/esm/svelte/CalmLensUploader.svelte +17 -17
  69. package/esm/svelte/context.js +21 -0
  70. package/esm/svelte/index.d.ts +12 -0
  71. package/esm/svelte/index.js +1 -0
  72. package/esm/testing.d.ts +11 -9
  73. package/esm/testing.js +73 -41
  74. package/esm/{ui-eVZ1gGuL.js → ui-BXzzqh7M.js} +6 -4
  75. package/esm/{ui-DJPSG8nD.d.ts → ui-BwFPFrno.d.ts} +2 -2
  76. package/esm/ui.d.ts +3 -3
  77. package/esm/ui.js +4 -4
  78. package/esm/vue.d.ts +15 -8
  79. package/esm/vue.js +29 -18
  80. package/package.json +16 -6
  81. package/cjs/CalmLensServerClient-CDhey01B.d.ts +0 -353
  82. package/cjs/ReactUpload-B_zmKB9X.d.ts +0 -17
  83. package/esm/CalmLensServerClient-CDhey01B.d.ts +0 -353
  84. package/esm/ReactUpload-B_zmKB9X.d.ts +0 -17
package/bin/calmlens.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import { readFile as readFile2 } from "node:fs/promises";
4
4
  import { parseArgs } from "node:util";
5
5
  // package.json
6
- var version = "0.24.0";
6
+ var version = "0.26.1";
7
7
 
8
8
  // src/contract/ModerationCategories-CHFRoeWV.js
9
9
  var CLASSIFICATION_CATEGORIES = [
@@ -162,6 +162,66 @@ var SDK_ERROR_CODES = {
162
162
  INVALID_WEBHOOK_PAYLOAD: "sdk/invalid-webhook-payload"
163
163
  };
164
164
  var CALMLENS_ERROR_CODES = { ...API_ERROR_CODES, ...SDK_ERROR_CODES };
165
+ var KIND_PARENTS = {
166
+ error: null,
167
+ api: "error",
168
+ "bad-request": "api",
169
+ authentication: "api",
170
+ "permission-denied": "api",
171
+ "not-found": "api",
172
+ conflict: "api",
173
+ "payload-too-large": "api",
174
+ "unprocessable-entity": "api",
175
+ "rate-limit": "api",
176
+ server: "api",
177
+ connection: "error",
178
+ timeout: "error",
179
+ cancelled: "error",
180
+ "invalid-argument": "error",
181
+ configuration: "invalid-argument",
182
+ "invalid-response": "error",
183
+ "webhook-verification": "error"
184
+ };
185
+ var STATUS_KINDS = {
186
+ 400: "bad-request",
187
+ 401: "authentication",
188
+ 403: "permission-denied",
189
+ 404: "not-found",
190
+ 409: "conflict",
191
+ 413: "payload-too-large",
192
+ 422: "unprocessable-entity",
193
+ 429: "rate-limit"
194
+ };
195
+ var CODE_KINDS = {
196
+ "sdk/transport-error": "connection",
197
+ "sdk/timeout": "timeout",
198
+ "sdk/cancelled": "cancelled",
199
+ "sdk/invalid-response": "invalid-response",
200
+ "sdk/response-too-large": "invalid-response",
201
+ "sdk/invalid-argument": "invalid-argument",
202
+ "sdk/invalid-config": "configuration",
203
+ "sdk/no-fetch": "configuration",
204
+ "sdk/invalid-webhook-signature": "webhook-verification",
205
+ "sdk/invalid-webhook-payload": "webhook-verification"
206
+ };
207
+ var errorKindOf = (code, status) => {
208
+ const byCode = CODE_KINDS[code];
209
+ if (byCode)
210
+ return byCode;
211
+ if (status === undefined)
212
+ return code === "sdk/http-error" ? "api" : "invalid-argument";
213
+ if (status >= 500)
214
+ return "server";
215
+ return STATUS_KINDS[status] ?? "api";
216
+ };
217
+ var isErrorKind = (kind, ancestor) => {
218
+ for (let current = kind;current; current = KIND_PARENTS[current]) {
219
+ if (current === ancestor)
220
+ return true;
221
+ }
222
+ return false;
223
+ };
224
+ var MAX_ERROR_BODY_LENGTH = 4096;
165
225
  var BRAND = Symbol.for("calmlens.sdk.CalmLensError");
166
226
  var RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]);
167
227
  var RETRYABLE_CODES = new Set([
@@ -171,6 +231,9 @@ var RETRYABLE_CODES = new Set([
171
231
  ]);
172
232
 
173
233
  class CalmLensError extends Error {
234
+ static kind = "error";
235
+ kind;
236
+ body;
174
237
  code;
175
238
  status;
176
239
  details;
@@ -181,7 +244,15 @@ class CalmLensError extends Error {
181
244
  const id = typeof code === "string" ? code : code.id;
182
245
  const defaultMessage = typeof code === "string" ? undefined : code.defaultMessage;
183
246
  super(`[calmlens] ${options.message ?? defaultMessage ?? id}`, { cause: options.cause });
184
- this.name = "CalmLensError";
247
+ const kind = errorKindOf(id, options.status);
248
+ if (new.target === CalmLensError) {
249
+ const KindClass = ERROR_CLASSES[kind];
250
+ if (KindClass !== CalmLensError)
251
+ return new KindClass(code, options);
252
+ }
253
+ this.name = new.target.name;
254
+ this.kind = kind;
255
+ this.body = options.body?.slice(0, MAX_ERROR_BODY_LENGTH);
185
256
  this.code = id;
186
257
  this.status = options.status;
187
258
  this.details = options.details;
@@ -194,7 +265,16 @@ class CalmLensError extends Error {
194
265
  return typeof value === "object" && value !== null && value[BRAND] === true;
195
266
  }
196
267
  static [Symbol.hasInstance](value) {
197
- return CalmLensError.isCalmLensError(value);
268
+ if (!CalmLensError.isCalmLensError(value))
269
+ return false;
270
+ const expected = this.kind;
271
+ if (expected === "error")
272
+ return true;
273
+ const { kind } = value;
274
+ return kind in KIND_PARENTS && isErrorKind(kind, expected);
275
+ }
276
+ isKind(kind) {
277
+ return isErrorKind(this.kind, kind);
198
278
  }
199
279
  isLocal() {
200
280
  return this.status === undefined;
@@ -209,6 +289,231 @@ class CalmLensError extends Error {
209
289
  var invalidArgument = (message, details) => new CalmLensError(SDK_ERROR_CODES.INVALID_ARGUMENT, { message, details });
210
290
  var invalidConfig = (message) => new CalmLensError(SDK_ERROR_CODES.INVALID_CONFIG, { message });
211
291
 
292
+ class CalmLensApiError extends CalmLensError {
293
+ static kind = "api";
294
+ }
295
+
296
+ class CalmLensBadRequestError extends CalmLensApiError {
297
+ static kind = "bad-request";
298
+ }
299
+
300
+ class CalmLensAuthenticationError extends CalmLensApiError {
301
+ static kind = "authentication";
302
+ }
303
+
304
+ class CalmLensPermissionDeniedError extends CalmLensApiError {
305
+ static kind = "permission-denied";
306
+ }
307
+
308
+ class CalmLensNotFoundError extends CalmLensApiError {
309
+ static kind = "not-found";
310
+ }
311
+
312
+ class CalmLensConflictError extends CalmLensApiError {
313
+ static kind = "conflict";
314
+ }
315
+
316
+ class CalmLensPayloadTooLargeError extends CalmLensApiError {
317
+ static kind = "payload-too-large";
318
+ }
319
+
320
+ class CalmLensUnprocessableEntityError extends CalmLensApiError {
321
+ static kind = "unprocessable-entity";
322
+ }
323
+
324
+ class CalmLensRateLimitError extends CalmLensApiError {
325
+ static kind = "rate-limit";
326
+ }
327
+
328
+ class CalmLensServerError extends CalmLensApiError {
329
+ static kind = "server";
330
+ }
331
+
332
+ class CalmLensConnectionError extends CalmLensError {
333
+ static kind = "connection";
334
+ }
335
+
336
+ class CalmLensTimeoutError extends CalmLensError {
337
+ static kind = "timeout";
338
+ }
339
+
340
+ class CalmLensCancelledError extends CalmLensError {
341
+ static kind = "cancelled";
342
+ }
343
+
344
+ class CalmLensInvalidArgumentError extends CalmLensError {
345
+ static kind = "invalid-argument";
346
+ }
347
+
348
+ class CalmLensConfigurationError extends CalmLensInvalidArgumentError {
349
+ static kind = "configuration";
350
+ }
351
+
352
+ class CalmLensInvalidResponseError extends CalmLensError {
353
+ static kind = "invalid-response";
354
+ }
355
+
356
+ class CalmLensWebhookVerificationError extends CalmLensError {
357
+ static kind = "webhook-verification";
358
+ }
359
+ var ERROR_CLASSES = {
360
+ error: CalmLensError,
361
+ api: CalmLensApiError,
362
+ "bad-request": CalmLensBadRequestError,
363
+ authentication: CalmLensAuthenticationError,
364
+ "permission-denied": CalmLensPermissionDeniedError,
365
+ "not-found": CalmLensNotFoundError,
366
+ conflict: CalmLensConflictError,
367
+ "payload-too-large": CalmLensPayloadTooLargeError,
368
+ "unprocessable-entity": CalmLensUnprocessableEntityError,
369
+ "rate-limit": CalmLensRateLimitError,
370
+ server: CalmLensServerError,
371
+ connection: CalmLensConnectionError,
372
+ timeout: CalmLensTimeoutError,
373
+ cancelled: CalmLensCancelledError,
374
+ "invalid-argument": CalmLensInvalidArgumentError,
375
+ configuration: CalmLensConfigurationError,
376
+ "invalid-response": CalmLensInvalidResponseError,
377
+ "webhook-verification": CalmLensWebhookVerificationError
378
+ };
379
+
380
+ // src/client/CalmLensLogging.ts
381
+ var LOG_LEVELS = ["off", "info", "debug"];
382
+ var readEnv = (name) => {
383
+ const runtime = globalThis;
384
+ try {
385
+ const value = runtime.process?.env?.[name] ?? runtime.Deno?.env?.get(name);
386
+ return value === undefined || value.trim() === "" ? undefined : value.trim();
387
+ } catch {
388
+ return;
389
+ }
390
+ };
391
+ var resolveLogLevel = (option, fromEnv) => {
392
+ if (option !== undefined) {
393
+ if (!LOG_LEVELS.includes(option)) {
394
+ throw invalidConfig(`logLevel must be one of ${LOG_LEVELS.join(", ")}`);
395
+ }
396
+ return option;
397
+ }
398
+ const env = fromEnv ? readEnv("CALMLENS_LOG")?.toLowerCase() : undefined;
399
+ return LOG_LEVELS.includes(env) ? env : "off";
400
+ };
401
+ var describeAttempt = (attempt) => {
402
+ const outcome = attempt.status !== null ? `HTTP ${attempt.status}` : attempt.errorCode !== null ? attempt.errorCode : "no response";
403
+ const parts = [
404
+ `[calmlens] ${attempt.operation ?? "request"} ${attempt.method} ${attempt.path}`,
405
+ `attempt ${attempt.attempt}`,
406
+ outcome,
407
+ `${attempt.durationMs}ms`
408
+ ];
409
+ if (attempt.requestId)
410
+ parts.push(`request ${attempt.requestId}`);
411
+ if (attempt.delayMs !== null)
412
+ parts.push(`retrying in ${attempt.delayMs}ms`);
413
+ return parts.join(" · ");
414
+ };
415
+
416
+ // src/client/CalmLensPagination.ts
417
+ var withLastResponse = (value, lastResponse) => {
418
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
419
+ Object.defineProperty(value, "lastResponse", {
420
+ value: lastResponse,
421
+ enumerable: false,
422
+ writable: false,
423
+ configurable: true
424
+ });
425
+ }
426
+ return value;
427
+ };
428
+ var copyLastResponse = (value, from) => {
429
+ const lastResponse = from?.lastResponse;
430
+ return lastResponse ? withLastResponse(value, lastResponse) : value;
431
+ };
432
+ var AUTO_PAGING_TO_ARRAY_MAX = 1e4;
433
+ var assertNewCursor = (sent, cursor) => {
434
+ if (sent.has(cursor)) {
435
+ throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
436
+ message: "The API returned a cursor it had already returned, with more pages to follow",
437
+ details: { cursor }
438
+ });
439
+ }
440
+ sent.add(cursor);
441
+ };
442
+ var requestCursors = new WeakMap;
443
+ var autoPaging = (first) => {
444
+ async function* items() {
445
+ let page = await first;
446
+ const start = requestCursors.get(page);
447
+ const sent = new Set(start === undefined ? [] : [start]);
448
+ for (;; ) {
449
+ const more = page.hasNextPage();
450
+ if (more)
451
+ assertNewCursor(sent, page.nextCursor);
452
+ yield* page.items;
453
+ if (!more)
454
+ return;
455
+ page = await page.getNextPage();
456
+ }
457
+ }
458
+ return {
459
+ [Symbol.asyncIterator]: () => items(),
460
+ async autoPagingToArray(options) {
461
+ const limit = options?.limit;
462
+ if (!Number.isInteger(limit) || limit < 1 || limit > AUTO_PAGING_TO_ARRAY_MAX) {
463
+ throw invalidArgument(`autoPagingToArray needs a limit from 1 to ${AUTO_PAGING_TO_ARRAY_MAX}; iterate with for await for more`);
464
+ }
465
+ const collected = [];
466
+ for await (const item of items()) {
467
+ collected.push(item);
468
+ if (collected.length >= limit)
469
+ break;
470
+ }
471
+ return collected;
472
+ }
473
+ };
474
+ };
475
+ var toListPage = (data, source, cursor) => {
476
+ if (!data || typeof data !== "object" || !Array.isArray(data.items)) {
477
+ throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
478
+ message: "The API returned a list without items"
479
+ });
480
+ }
481
+ const hasNextPage = () => data.hasMore === true && typeof data.nextCursor === "string" && data.nextCursor !== "" && (source.feed || data.items.length > 0);
482
+ const page = data;
483
+ if (cursor !== undefined)
484
+ requestCursors.set(page, cursor);
485
+ const self = Promise.resolve(page);
486
+ const { [Symbol.asyncIterator]: iterate, autoPagingToArray } = autoPaging(self);
487
+ Object.defineProperties(page, {
488
+ hasNextPage: { value: hasNextPage, configurable: true },
489
+ getNextPage: {
490
+ value: () => {
491
+ const next = data.nextCursor ?? undefined;
492
+ return list(async () => {
493
+ if (!hasNextPage()) {
494
+ throw invalidArgument("There is no next page; check hasNextPage() first");
495
+ }
496
+ if (next !== undefined && next === cursor)
497
+ assertNewCursor(new Set([next]), next);
498
+ return toListPage(await source.fetchPage(next), source, next);
499
+ });
500
+ },
501
+ configurable: true
502
+ },
503
+ autoPagingToArray: { value: autoPagingToArray, configurable: true },
504
+ [Symbol.asyncIterator]: { value: iterate, configurable: true }
505
+ });
506
+ return page;
507
+ };
508
+ var list = (load) => {
509
+ const first = (async () => load())();
510
+ return Object.assign(first, autoPaging(first));
511
+ };
512
+ var listPages = (fetchPage, { cursor, feed = false } = {}) => {
513
+ const source = { fetchPage, feed };
514
+ return list(async () => toListPage(await fetchPage(cursor), source, cursor));
515
+ };
516
+
212
517
  // src/client/CalmLensVersion.ts
213
518
  var SDK_VERSION = version;
214
519
  var runtimeName = () => {
@@ -225,7 +530,13 @@ var runtimeName = () => {
225
530
  return `node/${runtime.process.versions.node}`;
226
531
  return "unknown";
227
532
  };
228
- var getUserAgent = () => `calmlens-js/${SDK_VERSION} (${runtimeName()})`;
533
+ var getUserAgent = (appInfo) => {
534
+ const sdk = `calmlens-js/${SDK_VERSION} (${runtimeName()})`;
535
+ if (!appInfo)
536
+ return sdk;
537
+ const app = appInfo.version ? `${appInfo.name}/${appInfo.version}` : appInfo.name;
538
+ return `${sdk} ${app}${appInfo.url ? ` (${appInfo.url})` : ""}`;
539
+ };
229
540
  var isBrowserRuntime = () => typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined";
230
541
  var isReactNativeRuntime = () => globalThis.navigator?.product === "ReactNative";
231
542
 
@@ -369,6 +680,7 @@ var responseInfo = (response) => ({
369
680
  retryAfter: parseRetryAfter(response.headers.get("retry-after"))
370
681
  });
371
682
  var toHttpError = (response, bytes) => {
683
+ const body = new TextDecoder().decode(bytes.subarray(0, MAX_ERROR_BODY_LENGTH * 4)).slice(0, MAX_ERROR_BODY_LENGTH);
372
684
  let data;
373
685
  try {
374
686
  data = JSON.parse(new TextDecoder().decode(bytes));
@@ -380,14 +692,23 @@ var toHttpError = (response, bytes) => {
380
692
  message: message ?? code,
381
693
  ...info,
382
694
  requestId: info.requestId ?? (typeof requestId === "string" ? requestId : undefined),
383
- details
695
+ details,
696
+ body
384
697
  });
385
698
  }
386
699
  return new CalmLensError(SDK_ERROR_CODES.HTTP_ERROR, {
387
700
  message: `HTTP ${response.status}`,
388
- ...responseInfo(response)
701
+ ...responseInfo(response),
702
+ body
389
703
  });
390
704
  };
705
+ var pathOf = (url) => {
706
+ try {
707
+ return new URL(url).pathname;
708
+ } catch {
709
+ return url.split(/[?#]/)[0] ?? "";
710
+ }
711
+ };
391
712
 
392
713
  class CalmLensTransport {
393
714
  settings;
@@ -406,21 +727,62 @@ class CalmLensTransport {
406
727
  if (this.settings.apiKey)
407
728
  headers.set("x-api-key", this.settings.apiKey);
408
729
  if (!isBrowserRuntime())
409
- headers.set("user-agent", getUserAgent());
730
+ headers.set("user-agent", getUserAgent(this.settings.appInfo));
410
731
  if (request.idempotencyKey)
411
732
  headers.set("idempotency-key", request.idempotencyKey);
412
733
  return Object.fromEntries(headers.entries());
413
734
  }
735
+ async backoff(ms, request) {
736
+ const callers = createAttemptSignal(this.signalsFor(request), undefined);
737
+ try {
738
+ await this.sleep(ms, callers.signal);
739
+ } finally {
740
+ callers.release();
741
+ }
742
+ }
743
+ signalsFor(request) {
744
+ return [this.settings.signal, request.signal, request.init?.signal ?? undefined];
745
+ }
746
+ maxRetriesFor(request) {
747
+ return request.maxRetries ?? this.settings.maxRetries;
748
+ }
749
+ report(attempt) {
750
+ const { onAttempt, logger, logLevel } = this.settings;
751
+ try {
752
+ onAttempt?.(attempt);
753
+ } catch {}
754
+ if (!logger || !logLevel || logLevel === "off")
755
+ return;
756
+ const failed = attempt.status === null || attempt.status >= 400;
757
+ if (logLevel === "debug")
758
+ logger.debug(describeAttempt(attempt));
759
+ else if (attempt.delayMs !== null || failed)
760
+ logger.info(describeAttempt(attempt));
761
+ }
414
762
  canRetry(request) {
415
- return this.settings.maxRetries > 0 && (request.method === "GET" || request.method === "HEAD" || !!request.idempotencyKey) && isReplayableBody(request.body);
763
+ return this.maxRetriesFor(request) > 0 && (request.method === "GET" || request.method === "HEAD" || !!request.idempotencyKey) && isReplayableBody(request.body);
416
764
  }
417
765
  async send(request, { allowHttpErrors = false } = {}) {
418
766
  const fetchImpl = request.fetch ?? this.settings.fetch;
419
767
  const retryable = this.canRetry(request);
420
768
  const headers = this.headersFor(request);
769
+ const now = this.settings.now ?? Date.now;
770
+ const path = pathOf(request.url);
421
771
  for (let attemptNumber = 0;; attemptNumber++) {
422
- const canRetryAgain = retryable && attemptNumber < this.settings.maxRetries;
423
- const attempt = createAttemptSignal([this.settings.signal, request.init?.signal ?? undefined], request.timeoutMs);
772
+ const canRetryAgain = retryable && attemptNumber < this.maxRetriesFor(request);
773
+ const attempt = createAttemptSignal(this.signalsFor(request), request.timeoutMs);
774
+ const started = now();
775
+ const report = (outcome, delayMs) => this.report({
776
+ operation: request.operation ?? null,
777
+ method: request.method,
778
+ path,
779
+ attempt: attemptNumber + 1,
780
+ delayMs,
781
+ status: outcome.response?.status ?? outcome.error?.status ?? null,
782
+ requestId: outcome.response?.headers.get("x-request-id") ?? outcome.error?.requestId ?? null,
783
+ durationMs: Math.max(0, now() - started),
784
+ errorCode: outcome.error?.code ?? null
785
+ });
424
786
  let response;
425
787
  try {
426
788
  if (attempt.signal.aborted)
@@ -446,24 +808,31 @@ class CalmLensTransport {
446
808
  attempt.release();
447
809
  const failure = toFailure(cause, attempt);
448
810
  if (canRetryAgain && failure.isRetryable()) {
449
- await this.sleep(getRetryDelayMs(attemptNumber), this.settings.signal);
811
+ const delayMs = getRetryDelayMs(attemptNumber);
812
+ report({ error: failure }, delayMs);
813
+ await this.backoff(delayMs, request);
450
814
  continue;
451
815
  }
816
+ report({ error: failure }, null);
452
817
  throw failure;
453
818
  }
454
819
  if (request.deadline === "headers")
455
820
  attempt.clearDeadline();
456
- if (response.ok)
821
+ if (response.ok) {
822
+ report({ response }, null);
457
823
  return { response, attempt };
824
+ }
458
825
  if (allowHttpErrors) {
459
826
  const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
460
827
  const delayMs = retryAfter !== undefined ? retryAfter * 1000 : getRetryDelayMs(attemptNumber);
461
828
  if (!canRetryAgain || !RETRYABLE_STATUSES2.has(response.status) || delayMs > RETRY_AFTER_MAX_MS) {
829
+ report({ response }, null);
462
830
  return { response, attempt };
463
831
  }
832
+ report({ response }, delayMs);
464
833
  attempt.release();
465
834
  await response.body?.cancel().catch(() => {});
466
- await this.sleep(delayMs, this.settings.signal);
835
+ await this.backoff(delayMs, request);
467
836
  continue;
468
837
  }
469
838
  let error;
@@ -477,9 +846,11 @@ class CalmLensTransport {
477
846
  const retryDelayMs = error.retryAfter !== undefined ? error.retryAfter * 1000 : getRetryDelayMs(attemptNumber);
478
847
  const shouldRetry = canRetryAgain && retryDelayMs <= RETRY_AFTER_MAX_MS && error.isRetryable();
479
848
  if (shouldRetry) {
480
- await this.sleep(retryDelayMs, this.settings.signal);
849
+ report({ error }, retryDelayMs);
850
+ await this.backoff(retryDelayMs, request);
481
851
  continue;
482
852
  }
853
+ report({ error }, null);
483
854
  throw error;
484
855
  }
485
856
  }
@@ -490,8 +861,9 @@ class CalmLensTransport {
490
861
  if (bytes.byteLength === 0 && (response.status === 204 || request.method === "DELETE")) {
491
862
  return;
492
863
  }
864
+ let data;
493
865
  try {
494
- return JSON.parse(new TextDecoder().decode(bytes));
866
+ data = JSON.parse(new TextDecoder().decode(bytes));
495
867
  } catch (cause) {
496
868
  throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
497
869
  message: `Invalid JSON response (HTTP ${response.status})`,
@@ -499,6 +871,12 @@ class CalmLensTransport {
499
871
  cause
500
872
  });
501
873
  }
874
+ return withLastResponse(data, {
875
+ status: response.status,
876
+ requestId: response.headers.get("x-request-id") ?? undefined,
877
+ headers: response.headers,
878
+ idempotencyKey: request.idempotencyKey
879
+ });
502
880
  } catch (cause) {
503
881
  throw toFailure(cause, attempt);
504
882
  } finally {
@@ -951,6 +1329,16 @@ var validateConnectionOptions = (options) => {
951
1329
  }
952
1330
  }
953
1331
  assertHttpUrl("baseUrl", options.baseUrl);
1332
+ const { appInfo, onAttempt, logger } = options;
1333
+ if (appInfo !== undefined && (!appInfo || typeof appInfo.name !== "string" || !/^[\x21-\x7e]+$/.test(appInfo.name) || appInfo.version !== undefined && !/^[\x21-\x7e]+$/.test(String(appInfo.version)) || appInfo.url !== undefined && !/^[\x20-\x7e]+$/.test(String(appInfo.url)))) {
1334
+ throw invalidConfig("appInfo needs a name, and a version, without spaces, and a url, in printable ASCII");
1335
+ }
1336
+ if (onAttempt !== undefined && typeof onAttempt !== "function") {
1337
+ throw invalidConfig("onAttempt must be a function");
1338
+ }
1339
+ if (logger !== undefined && (!logger || typeof logger.debug !== "function" || typeof logger.info !== "function")) {
1340
+ throw invalidConfig("logger must have debug and info methods, as console does");
1341
+ }
954
1342
  };
955
1343
  var validateServerClientOptions = (options) => {
956
1344
  if (!options || typeof options !== "object")
@@ -1196,11 +1584,11 @@ var pollForDecision = async (retrieve, {
1196
1584
  const remaining = deadline - now();
1197
1585
  if (remaining <= 0) {
1198
1586
  throw new CalmLensError(SDK_ERROR_CODES.TIMEOUT, {
1199
- message: `Asset ${asset.id} had no moderation decision after ${timeoutMs}ms (classification status: ${asset.classification.status}, moderation status: ${asset.classification.moderation.status})`,
1587
+ message: `Asset ${asset.id} had no moderation decision after ${timeoutMs}ms (classification status: ${asset.classification.status}, moderation decision: ${asset.classification.moderation.decision})`,
1200
1588
  details: {
1201
1589
  assetId: asset.id,
1202
1590
  classificationStatus: asset.classification.status,
1203
- moderationStatus: asset.classification.moderation.status
1591
+ moderationDecision: asset.classification.moderation.decision
1204
1592
  }
1205
1593
  });
1206
1594
  }
@@ -1542,7 +1930,7 @@ var toUploadData = (payload) => {
1542
1930
  };
1543
1931
  var toRawUploadBody = (payload) => toUploadData(payload);
1544
1932
  var textEncoder = new TextEncoder;
1545
- var toUploadForm = (options, payload) => {
1933
+ var toUploadForm = async (options, payload) => {
1546
1934
  const boundary = `calmlens-${randomUuid()}`;
1547
1935
  const head = `--${boundary}\r
1548
1936
  Content-Disposition: form-data; name="options"\r
@@ -1558,9 +1946,8 @@ Content-Type: ${payload.type.replace(/[\r\n]/g, "")}\r
1558
1946
  --${boundary}--\r
1559
1947
  `;
1560
1948
  const contentType = `multipart/form-data; boundary=${boundary}`;
1561
- const data = toUploadData(payload);
1562
- if (data instanceof Blob)
1563
- return { body: new Blob([head, data, tail]), contentType };
1949
+ const input = toUploadData(payload);
1950
+ const data = input instanceof Blob ? new Uint8Array(await input.arrayBuffer()) : input;
1564
1951
  const headBytes = textEncoder.encode(head);
1565
1952
  const tailBytes = textEncoder.encode(tail);
1566
1953
  if (data instanceof Uint8Array) {
@@ -1728,7 +2115,11 @@ var prepareSubmitAssetOptions = (options, {
1728
2115
  var newIdempotencyKey = () => randomUuid();
1729
2116
  var isTextPayload = (payload) => ("plainText" in payload);
1730
2117
  var hasStringStatus = (value) => !!value && typeof value === "object" && typeof value.status === "string";
1731
- var isAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload) && typeof data.classification?.moderation?.status === "string";
2118
+ var hasDecision = (data) => {
2119
+ const decision = data.classification?.moderation?.decision;
2120
+ return decision === null || typeof decision === "string";
2121
+ };
2122
+ var isAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload) && hasDecision(data);
1732
2123
  var isUploadedAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload);
1733
2124
  var expectUploadedAsset = (data) => {
1734
2125
  if (!isUploadedAsset(data)) {
@@ -1748,6 +2139,47 @@ var expectAsset = (data) => {
1748
2139
  }
1749
2140
  return data;
1750
2141
  };
2142
+ var validateCallOptions = (options) => {
2143
+ if (options === undefined)
2144
+ return;
2145
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
2146
+ throw invalidArgument("Request options must be an object");
2147
+ }
2148
+ const known = [
2149
+ "signal",
2150
+ "timeoutMs",
2151
+ "maxRetries",
2152
+ "idempotencyKey",
2153
+ "headers",
2154
+ "extraQuery",
2155
+ "extraBody"
2156
+ ];
2157
+ const unknown = Object.keys(options).filter((key) => !known.includes(key));
2158
+ if (unknown.length) {
2159
+ throw invalidArgument(`Unknown request options: ${unknown.join(", ")}`, {
2160
+ options: unknown
2161
+ });
2162
+ }
2163
+ const { timeoutMs, maxRetries, idempotencyKey, headers, extraQuery, extraBody } = options;
2164
+ if (timeoutMs !== undefined && (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1)) {
2165
+ throw invalidArgument("timeoutMs must be a positive integer");
2166
+ }
2167
+ if (maxRetries !== undefined && (!Number.isSafeInteger(maxRetries) || maxRetries < 0)) {
2168
+ throw invalidArgument("maxRetries must be a non-negative integer");
2169
+ }
2170
+ if (idempotencyKey !== undefined && (typeof idempotencyKey !== "string" || !idempotencyKey)) {
2171
+ throw invalidArgument("idempotencyKey must be a non-empty string");
2172
+ }
2173
+ for (const [name, value] of Object.entries({ headers, extraQuery, extraBody })) {
2174
+ if (value !== undefined && (!value || typeof value !== "object" || Array.isArray(value))) {
2175
+ throw invalidArgument(`${name} must be an object`);
2176
+ }
2177
+ }
2178
+ if (options.signal !== undefined && !(options.signal instanceof AbortSignal)) {
2179
+ throw invalidArgument("signal must be an AbortSignal");
2180
+ }
2181
+ };
2182
+ var isPlainObject2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1751
2183
  var resolveConnectionOptions = (options) => ({
1752
2184
  ...options,
1753
2185
  baseUrl: (options.baseUrl ?? `https://api.${DOMAIN}/v1`).replace(/\/+$/, "")
@@ -1757,8 +2189,19 @@ class CalmLensConnection {
1757
2189
  options;
1758
2190
  transport;
1759
2191
  hooks;
1760
- constructor(options, apiKey) {
2192
+ call;
2193
+ constructor(options, apiKey, {
2194
+ readEnvironment = false,
2195
+ shared
2196
+ } = {}) {
1761
2197
  this.options = options;
2198
+ if (shared) {
2199
+ this.transport = shared.transport;
2200
+ this.hooks = shared.hooks;
2201
+ this.call = shared.call;
2202
+ return;
2203
+ }
2204
+ this.call = {};
1762
2205
  const resolveFetch = () => {
1763
2206
  const fetchImpl = this.options.fetch ?? globalThis.fetch;
1764
2207
  if (typeof fetchImpl !== "function") {
@@ -1769,15 +2212,51 @@ class CalmLensConnection {
1769
2212
  return fetchImpl;
1770
2213
  };
1771
2214
  this.hooks = getMockHooks(options);
2215
+ const logLevel = resolveLogLevel(options.logLevel, readEnvironment);
1772
2216
  this.transport = new CalmLensTransport({
1773
2217
  apiKey,
1774
2218
  sleep: this.hooks?.sleep,
1775
2219
  fetch: (input, init) => resolveFetch()(input, init),
1776
2220
  signal: options.signal,
1777
2221
  maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
1778
- maxResponseBytes: options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES
2222
+ maxResponseBytes: options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
2223
+ appInfo: options.appInfo,
2224
+ logLevel,
2225
+ logger: logLevel === "off" ? undefined : options.logger ?? console,
2226
+ onAttempt: options.onAttempt,
2227
+ now: this.hooks?.now
1779
2228
  });
1780
2229
  }
2230
+ forCall(operation, requestOptions) {
2231
+ validateCallOptions(requestOptions);
2232
+ return new CalmLensConnection(this.options, undefined, {
2233
+ shared: {
2234
+ transport: this.transport,
2235
+ hooks: this.hooks,
2236
+ call: { ...this.call, ...requestOptions, operation }
2237
+ }
2238
+ });
2239
+ }
2240
+ callRequest() {
2241
+ const { operation, signal, maxRetries } = this.call;
2242
+ return { operation, signal, maxRetries };
2243
+ }
2244
+ callHeaders(headers) {
2245
+ return this.call.headers ? { ...this.call.headers, ...headers } : headers;
2246
+ }
2247
+ callBody(method, body) {
2248
+ const { extraBody } = this.call;
2249
+ if (!extraBody)
2250
+ return body;
2251
+ if (method === "GET" || method === "HEAD") {
2252
+ throw invalidArgument("extraBody needs a request with a body");
2253
+ }
2254
+ if (body === undefined)
2255
+ return extraBody;
2256
+ if (!isPlainObject2(body))
2257
+ throw invalidArgument("extraBody needs a JSON object body");
2258
+ return { ...body, ...extraBody };
2259
+ }
1781
2260
  get sleep() {
1782
2261
  return this.hooks?.sleep ?? sleep;
1783
2262
  }
@@ -1785,11 +2264,12 @@ class CalmLensConnection {
1785
2264
  return this.hooks?.deferUploadChecks ?? false;
1786
2265
  }
1787
2266
  get timeoutMs() {
1788
- return this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2267
+ return this.call.timeoutMs ?? this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1789
2268
  }
1790
2269
  url(path, query) {
1791
- const search = query ? stringifyQuery(query) : "";
1792
- return `${this.options.baseUrl}${path}${search ? `?${search}` : ""}`;
2270
+ const search = [query, this.call.extraQuery].map((values) => values ? stringifyQuery(values) : "").filter(Boolean).join("&");
2271
+ const separator = path.includes("?") ? "&" : "?";
2272
+ return `${this.options.baseUrl}${path}${search ? `${separator}${search}` : ""}`;
1793
2273
  }
1794
2274
  json(method, path, {
1795
2275
  query,
@@ -1797,34 +2277,40 @@ class CalmLensConnection {
1797
2277
  headers,
1798
2278
  idempotencyKey
1799
2279
  } = {}) {
2280
+ const sent = this.callBody(method, body);
1800
2281
  return this.transport.json({
2282
+ ...this.callRequest(),
1801
2283
  method,
1802
2284
  url: this.url(path, query),
1803
- headers: body === undefined ? headers : { ...headers, "Content-Type": "application/json" },
1804
- body: body === undefined ? undefined : JSON.stringify(body),
1805
- idempotencyKey,
2285
+ headers: this.callHeaders(sent === undefined ? headers : { ...headers, "Content-Type": "application/json" }),
2286
+ body: sent === undefined ? undefined : JSON.stringify(sent),
2287
+ idempotencyKey: idempotencyKey ?? this.call.idempotencyKey,
1806
2288
  timeoutMs: this.timeoutMs,
1807
2289
  deadline: "body"
1808
2290
  });
1809
2291
  }
1810
2292
  upload(url, body, headers, idempotencyKey, text) {
1811
2293
  return this.transport.json({
2294
+ ...this.callRequest(),
1812
2295
  method: "POST",
1813
2296
  url,
1814
- headers,
2297
+ headers: this.callHeaders(headers),
1815
2298
  body,
1816
2299
  idempotencyKey,
1817
- timeoutMs: text ? this.timeoutMs : this.options.uploadTimeoutMs,
2300
+ timeoutMs: text ? this.timeoutMs : this.call.timeoutMs ?? this.options.uploadTimeoutMs,
1818
2301
  deadline: "body",
1819
2302
  fetch: this.options.uploadFetch
1820
2303
  });
1821
2304
  }
1822
- submitUpload(uploadsPath, options, wait, authHeaders = {}) {
2305
+ async submitUpload(uploadsPath, options, wait, authHeaders = {}) {
1823
2306
  const isMultipart = "part" in options;
1824
2307
  const payload = isMultipart ? options.part : options.content;
1825
2308
  const multipartOptions = options;
1826
- const idempotencyKey = options.idempotencyKey ?? newIdempotencyKey();
1827
- const fields = uploadFields(options);
2309
+ const idempotencyKey = options.idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey();
2310
+ const fields = {
2311
+ ...uploadFields(options),
2312
+ ...this.call.extraBody
2313
+ };
1828
2314
  if (isTextPayload(payload)) {
1829
2315
  const { sizeInBytes: _size, ...text } = payload;
1830
2316
  const body = isMultipart ? {
@@ -1846,7 +2332,7 @@ class CalmLensConnection {
1846
2332
  setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? multipartOptions.sizeInBytes);
1847
2333
  setOptionalQueryValue(query, "totalSizeInBytes", multipartOptions.totalSizeInBytes);
1848
2334
  }
1849
- const form = toUploadForm(fields, payload);
2335
+ const form = await toUploadForm(fields, payload);
1850
2336
  return this.upload(this.url(`${uploadsPath}?${query}`), form.body, {
1851
2337
  ...authHeaders,
1852
2338
  "Content-Type": form.contentType,
@@ -1866,7 +2352,7 @@ class CalmLensConnection {
1866
2352
  const source = getSplittableContent(content);
1867
2353
  const partSize = this.partSizeBytes;
1868
2354
  const count = Math.ceil(source.size / partSize);
1869
- const key = idempotencyKey ?? newIdempotencyKey();
2355
+ const key = idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey();
1870
2356
  const part = (partNumber) => source.slice((partNumber - 1) * partSize, Math.min(partNumber * partSize, source.size));
1871
2357
  const first = await this.submitUpload(uploadsPath, {
1872
2358
  ...fields,
@@ -1876,11 +2362,18 @@ class CalmLensConnection {
1876
2362
  }, wait, authHeaders);
1877
2363
  const assetId = expectUploadedAsset(first).id;
1878
2364
  onStarted?.(assetId);
2365
+ const laterParts = new CalmLensConnection(this.options, undefined, {
2366
+ shared: {
2367
+ transport: this.transport,
2368
+ hooks: this.hooks,
2369
+ call: { ...this.call, extraBody: undefined }
2370
+ }
2371
+ });
1879
2372
  let result = first;
1880
2373
  for (let partNumber = 2;partNumber <= count; ) {
1881
2374
  const isFinal = partNumber === count;
1882
2375
  try {
1883
- result = await this.uploadPart(partPath(assetId), {
2376
+ result = await laterParts.uploadPart(partPath(assetId), {
1884
2377
  part: { ...part(partNumber), partNumber, isFinal },
1885
2378
  idempotencyKey: `${key}:part-${partNumber}`
1886
2379
  }, authHeaders);
@@ -1903,6 +2396,8 @@ class CalmLensConnection {
1903
2396
  uploadPart(partPath, { part, wait, idempotencyKey }, authHeaders = {}) {
1904
2397
  if (!part)
1905
2398
  throw invalidArgument("Part options are required");
2399
+ if (this.call.extraBody)
2400
+ throw invalidArgument("A part's body is its bytes: extraBody can't apply");
1906
2401
  assertDeclaredPayloadSize(part);
1907
2402
  const validation = validateAssetPayload(part, {
1908
2403
  multipart: true,
@@ -1917,7 +2412,7 @@ class CalmLensConnection {
1917
2412
  if (wait !== undefined)
1918
2413
  query.set("wait", String(wait));
1919
2414
  setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? getAssetPayloadByteLength(part));
1920
- return this.upload(this.url(`${partPath}?${query}`), toRawUploadBody(part), { ...authHeaders, "X-CalmLens-Upload": "part" }, idempotencyKey ?? newIdempotencyKey(), isTextPayload(part));
2415
+ return this.upload(this.url(`${partPath}?${query}`), toRawUploadBody(part), { ...authHeaders, "X-CalmLens-Upload": "part" }, idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey(), isTextPayload(part));
1921
2416
  }
1922
2417
  }
1923
2418
 
@@ -1929,9 +2424,6 @@ var SERVER_OPTION_KEYS = {
1929
2424
  "assets.decide": ["assetId", "confirmPurge", "decision", "note"],
1930
2425
  "assets.delete": ["assetId"],
1931
2426
  "assets.explain": ["assetId", "rerun"],
1932
- "assets.iterate": ["cursor", "filter", "pageSize", "sort"],
1933
- "assets.iterateChildren": ["assetId", "cursor", "pageSize", "sort"],
1934
- "assets.iterateTimeline": ["assetId", "cursor", "pageSize"],
1935
2427
  "assets.list": ["cursor", "filter", "pageSize", "sort"],
1936
2428
  "assets.listChildren": ["assetId", "cursor", "pageSize", "sort"],
1937
2429
  "assets.listTimeline": ["assetId", "cursor", "pageSize"],
@@ -1946,10 +2438,8 @@ var SERVER_OPTION_KEYS = {
1946
2438
  ensureLens: ["active", "description", "identifier", "name", "transform", "type"],
1947
2439
  ensureLenses: ["lenses"],
1948
2440
  "events.list": ["assetId", "cursor", "pageSize", "types"],
1949
- "events.pages": ["assetId", "cursor", "pageSize", "types"],
1950
2441
  "folders.create": ["name", "parentId"],
1951
2442
  "folders.delete": ["folderId"],
1952
- "folders.iterate": ["cursor", "pageSize", "parentId", "search", "sort"],
1953
2443
  "folders.list": ["cursor", "pageSize", "parentId", "search", "sort"],
1954
2444
  "folders.move": ["folderId", "parentId"],
1955
2445
  "folders.retrieve": ["folderId"],
@@ -1957,8 +2447,6 @@ var SERVER_OPTION_KEYS = {
1957
2447
  "hashLists.addEntry": ["assetId", "hash", "hashListId", "label", "quality"],
1958
2448
  "hashLists.create": ["action", "description", "name"],
1959
2449
  "hashLists.delete": ["hashListId"],
1960
- "hashLists.iterate": ["cursor", "pageSize", "sort"],
1961
- "hashLists.iterateEntries": ["cursor", "hashListId", "pageSize", "sort"],
1962
2450
  "hashLists.list": ["cursor", "pageSize", "sort"],
1963
2451
  "hashLists.listEntries": ["cursor", "hashListId", "pageSize", "sort"],
1964
2452
  "hashLists.removeEntry": ["entryId"],
@@ -1966,7 +2454,6 @@ var SERVER_OPTION_KEYS = {
1966
2454
  "hashLists.update": ["action", "description", "hashListId", "name"],
1967
2455
  "lenses.create": ["active", "description", "identifier", "name", "transform", "type"],
1968
2456
  "lenses.delete": ["lensId"],
1969
- "lenses.iterate": ["cursor", "pageSize", "sort"],
1970
2457
  "lenses.list": ["cursor", "pageSize", "sort"],
1971
2458
  "lenses.retrieve": ["lensId"],
1972
2459
  "lenses.update": ["active", "description", "lensId", "name", "transform", "type"],
@@ -1976,7 +2463,6 @@ var SERVER_OPTION_KEYS = {
1976
2463
  "policies.assign": ["policyId"],
1977
2464
  "policies.create": ["description", "name", "presetId", "settings"],
1978
2465
  "policies.delete": ["policyId"],
1979
- "policies.iterate": ["cursor", "pageSize", "sort"],
1980
2466
  "policies.list": ["cursor", "pageSize", "sort"],
1981
2467
  "policies.reset": ["policyId", "presetVersion", "revision"],
1982
2468
  "policies.retrieve": ["policyId"],
@@ -1989,13 +2475,11 @@ var SERVER_OPTION_KEYS = {
1989
2475
  "text.classify": ["authorId", "context", "description", "externalId", "externalUrl", "folderId", "metadata", "name", "processingOptions", "tags", "text", "uploadPresetId", "visibility"],
1990
2476
  "uploadPresets.delete": ["uploadPresetId"],
1991
2477
  "uploadPresets.ensure": ["uploadPresets"],
1992
- "uploadPresets.iterate": ["cursor", "pageSize", "sort"],
1993
2478
  "uploadPresets.list": ["cursor", "pageSize", "sort"]
1994
2479
  };
1995
2480
  var NULLABLE_OPTION_KEYS = {
1996
2481
  "assets.classify": ["authorId", "context", "description", "externalId", "folderId", "metadata", "processingOptions", "tags", "uploadPresetId", "visibility"],
1997
2482
  "assets.create": ["authorId", "context", "description", "externalId", "folderId", "metadata", "processingOptions", "tags", "uploadPresetId", "visibility"],
1998
- "assets.iterate": ["filter"],
1999
2483
  "assets.list": ["filter"],
2000
2484
  "assets.move": ["folderId"],
2001
2485
  "assets.update": ["description", "externalId", "externalUrl", "metadata", "tags", "visibility"],
@@ -2122,6 +2606,31 @@ async function verifyWebhookSignature(options) {
2122
2606
  return matched;
2123
2607
  }
2124
2608
 
2609
+ // src/client/ServedAssetInfo.ts
2610
+ function parseServedAssetInfo(header) {
2611
+ if (!header)
2612
+ return;
2613
+ const dimensions = {};
2614
+ let start = 0;
2615
+ for (const delimiter of `${header},`.matchAll(/"(?:[^"\\]|\\.)*"|[",]/g)) {
2616
+ if (delimiter[0] === '"')
2617
+ return;
2618
+ if (delimiter[0] !== ",")
2619
+ continue;
2620
+ const member = header.slice(start, delimiter.index).trim();
2621
+ start = delimiter.index + 1;
2622
+ const [key] = member.split(/[=; \t]/, 1);
2623
+ if (key !== "width" && key !== "height")
2624
+ continue;
2625
+ const match = /^(?:width|height)=([0-9]{1,15})$/.exec(member);
2626
+ if (!match || dimensions[key] !== undefined || Number(match[1]) === 0)
2627
+ return;
2628
+ dimensions[key] = Number(match[1]);
2629
+ }
2630
+ const { width, height } = dimensions;
2631
+ return width === undefined || height === undefined ? undefined : { width, height };
2632
+ }
2633
+
2125
2634
  // src/client/CalmLensServerClient.ts
2126
2635
  var ENSURE_LENSES_MAX_PER_REQUEST = 100;
2127
2636
  var getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
@@ -2133,6 +2642,37 @@ var getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
2133
2642
  transform: options.transform ?? null
2134
2643
  });
2135
2644
  var requireId = (value, name) => encodePathSegment(value, name);
2645
+ var checkedTextContent = (options) => {
2646
+ if (options && "content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) {
2647
+ throw invalidPayload("Text to classify must be a non-empty string");
2648
+ }
2649
+ return options;
2650
+ };
2651
+ var anySignal = (signals) => {
2652
+ if (typeof AbortSignal.any === "function")
2653
+ return AbortSignal.any(signals);
2654
+ const controller = new AbortController;
2655
+ for (const signal of signals) {
2656
+ if (signal.aborted)
2657
+ controller.abort(signal.reason);
2658
+ else
2659
+ signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
2660
+ }
2661
+ return controller.signal;
2662
+ };
2663
+ var withEnvironmentDefaults = (options) => {
2664
+ if (!options || typeof options !== "object" || getMockHooks(options))
2665
+ return options;
2666
+ const apiKey = options.apiKey ?? readEnv("CALMLENS_API_KEY");
2667
+ const projectId = options.projectId ?? readEnv("CALMLENS_PROJECT_ID");
2668
+ const baseUrl = options.baseUrl ?? readEnv("CALMLENS_BASE_URL");
2669
+ return {
2670
+ ...options,
2671
+ ...apiKey !== undefined && { apiKey },
2672
+ ...projectId !== undefined && { projectId },
2673
+ ...baseUrl !== undefined && { baseUrl }
2674
+ };
2675
+ };
2136
2676
  var checked = (operation, options) => {
2137
2677
  checkOptionKeys(options, operation, SERVER_OPTION_KEYS);
2138
2678
  if (!options || typeof options !== "object" || Array.isArray(options))
@@ -2140,25 +2680,19 @@ var checked = (operation, options) => {
2140
2680
  const nullable = NULLABLE_OPTION_KEYS[operation] ?? [];
2141
2681
  return Object.fromEntries(Object.entries(options).filter(([key, value]) => value !== null || nullable.includes(key)));
2142
2682
  };
2143
- var assertNewCursor = (sent, cursor) => {
2144
- if (sent.has(cursor)) {
2145
- throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
2146
- message: "The API returned a cursor it had already returned, with more pages to follow",
2147
- details: { cursor }
2148
- });
2149
- }
2150
- sent.add(cursor);
2151
- };
2152
2683
  var inspectSymbol = Symbol.for("nodejs.util.inspect.custom");
2153
2684
  var writableCdnResponse = (response, metadata = response) => {
2154
- if (response.status < 200)
2155
- return response;
2156
- const writable = new Response(response.body, response);
2685
+ const writable = response.status < 200 ? response : new Response(response.body, response);
2157
2686
  const { url, redirected, type } = metadata;
2158
2687
  return Object.defineProperties(writable, {
2159
2688
  url: { value: url },
2160
2689
  redirected: { value: redirected },
2161
2690
  type: { value: type },
2691
+ getAssetInfo: {
2692
+ value() {
2693
+ return parseServedAssetInfo(this.headers.get("X-CalmLens-Asset-Info"));
2694
+ }
2695
+ },
2162
2696
  clone: {
2163
2697
  value() {
2164
2698
  return writableCdnResponse(Response.prototype.clone.call(this), { url, redirected, type });
@@ -2169,31 +2703,29 @@ var writableCdnResponse = (response, metadata = response) => {
2169
2703
 
2170
2704
  class CalmLensServerClient {
2171
2705
  #apiKey;
2172
- #options;
2173
2706
  #settings;
2174
2707
  #lenses;
2175
2708
  #connection;
2176
2709
  static async verifyWebhookSignature(options) {
2177
2710
  return verifyWebhookSignature(options);
2178
2711
  }
2179
- constructor(options, lenses) {
2712
+ constructor(clientOptions = {}, lenses) {
2713
+ const options = withEnvironmentDefaults(clientOptions);
2180
2714
  validateServerClientOptions(options);
2181
2715
  if ((isBrowserRuntime() || isReactNativeRuntime()) && !options.dangerouslyAllowBrowser) {
2182
2716
  throw invalidConfig("CalmLensServerClient is running in a browser or app, where anyone could read the API key. Call CalmLens from your server, upload from the browser or app with CalmLensAppClient, or set dangerouslyAllowBrowser: true for trusted internal tools.");
2183
2717
  }
2184
- const { apiKey, ...rest } = options;
2718
+ const { apiKey, projectId, ...rest } = options;
2185
2719
  this.#apiKey = apiKey;
2186
- this.#options = rest;
2187
2720
  this.#settings = {
2721
+ projectId,
2188
2722
  ...resolveConnectionOptions(rest),
2189
2723
  cdnBaseUrl: (rest.cdnBaseUrl ?? getMockHooks(rest)?.defaultCdnBaseUrl ?? DEFAULT_CDN_BASE_URL).replace(/\/+$/, "")
2190
2724
  };
2191
2725
  this.#lenses = lenses ?? { ensuredLenses: new Map, pendingEnsureLenses: new Map };
2192
- this.#connection = new CalmLensConnection(this.#settings, apiKey);
2193
- }
2194
- withRequestOptions(options) {
2195
- validateRequestOptions(options);
2196
- return new CalmLensServerClient({ ...this.#options, ...options, apiKey: this.#apiKey }, this.#lenses);
2726
+ this.#connection = new CalmLensConnection(this.#settings, apiKey, {
2727
+ readEnvironment: !getMockHooks(options)
2728
+ });
2197
2729
  }
2198
2730
  [inspectSymbol]() {
2199
2731
  const { projectId, baseUrl } = this.#settings;
@@ -2203,32 +2735,56 @@ class CalmLensServerClient {
2203
2735
  const { projectId, baseUrl, cdnBaseUrl } = this.#settings;
2204
2736
  return { projectId, baseUrl, cdnBaseUrl };
2205
2737
  }
2206
- get projectPath() {
2738
+ get #projectPath() {
2207
2739
  return `/projects/${encodeURIComponent(this.#settings.projectId)}`;
2208
2740
  }
2209
- request(method, path, options = {}) {
2210
- return this.#connection.json(method, path, options);
2741
+ async#send(operation, requestOptions, method, path, options = {}) {
2742
+ return this.#connection.forCall(operation, requestOptions).json(method, path, options);
2211
2743
  }
2212
- async submitAsset(options, wait) {
2744
+ async request(method, path, {
2745
+ query,
2746
+ body,
2747
+ headers
2748
+ } = {}, requestOptions) {
2749
+ const methods = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"];
2750
+ if (typeof method !== "string" || !methods.includes(method)) {
2751
+ throw invalidArgument(`method must be one of ${methods.join(", ")}`);
2752
+ }
2753
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//")) {
2754
+ throw invalidArgument('path must start with "/", such as "/assets/asset_123"');
2755
+ }
2756
+ const { headers: callHeaders, ...rest } = requestOptions ?? {};
2757
+ return this.#send(undefined, { ...rest, ...(callHeaders || headers) && { headers: { ...callHeaders, ...headers } } }, method, path, { query, body });
2758
+ }
2759
+ #paginate(operation, options, requestOptions, send) {
2760
+ const first = options?.cursor;
2761
+ return listPages(async (cursor) => {
2762
+ const valid = checked(operation, options);
2763
+ return send(cursor === first ? valid : { ...valid, cursor });
2764
+ }, { cursor: typeof first === "string" ? first : undefined, feed: operation === "events.list" });
2765
+ }
2766
+ async#submitAsset(operation, options, wait, requestOptions) {
2767
+ const connection = this.#connection.forCall(operation, requestOptions);
2213
2768
  const body = prepareSubmitAssetOptions(options, {
2214
- deferUploadChecks: this.#connection.deferUploadChecks,
2215
- partSizeBytes: this.#connection.partSizeBytes
2769
+ deferUploadChecks: connection.deferUploadChecks,
2770
+ partSizeBytes: connection.partSizeBytes
2216
2771
  });
2217
- const uploadsPath = `${this.projectPath}/assets`;
2218
- if ("content" in body && splitsIntoParts(body.content, this.#connection.partSizeBytes)) {
2219
- return expectAsset(await this.#connection.submitInParts(uploadsPath, body, wait, {
2772
+ const uploadsPath = `${this.#projectPath}/assets`;
2773
+ if ("content" in body && splitsIntoParts(body.content, connection.partSizeBytes)) {
2774
+ const { idempotencyKey: _key, extraBody: _body, ...readOptions } = requestOptions ?? {};
2775
+ return expectAsset(await connection.submitInParts(uploadsPath, body, wait, {
2220
2776
  partPath: (assetId) => `/assets/${encodeURIComponent(assetId)}/part`,
2221
- retrieve: (assetId) => this.buildAssets().retrieve({ assetId })
2777
+ retrieve: (assetId) => this.#buildAssets().retrieve({ assetId }, readOptions)
2222
2778
  }));
2223
2779
  }
2224
2780
  if ("content" in body || "part" in body) {
2225
- return expectAsset(await this.#connection.submitUpload(uploadsPath, body, wait));
2781
+ return expectAsset(await connection.submitUpload(uploadsPath, body, wait));
2226
2782
  }
2227
2783
  const { idempotencyKey, ...fields } = body;
2228
- const data = await this.#connection.json("POST", uploadsPath, {
2784
+ const data = await connection.json("POST", uploadsPath, {
2229
2785
  query: { wait },
2230
2786
  body: fields,
2231
- idempotencyKey: idempotencyKey ?? newIdempotencyKey()
2787
+ idempotencyKey: idempotencyKey ?? requestOptions?.idempotencyKey ?? newIdempotencyKey()
2232
2788
  });
2233
2789
  return expectAsset(data);
2234
2790
  }
@@ -2238,12 +2794,12 @@ class CalmLensServerClient {
2238
2794
  const { projectId, ...options } = checked("cdn.getAssetUrl", urlOptions);
2239
2795
  return buildAssetUrl(this.#settings.cdnBaseUrl, projectId ?? this.#settings.projectId, options);
2240
2796
  },
2241
- signAssetUrl: async (signOptions) => {
2797
+ signAssetUrl: async (signOptions, requestOptions) => {
2242
2798
  const options = checked("cdn.signAssetUrl", signOptions);
2243
2799
  validateSignAssetUrlOptions(options);
2244
2800
  const { projectId, assetId, externalId, expiresIn, original, ...location } = options;
2245
2801
  const project = requireId(projectId ?? this.#settings.projectId, "Project ID");
2246
- const signed = await this.request("POST", `/projects/${project}/signed-asset-urls`, {
2802
+ const signed = await this.#send("cdn.signAssetUrl", requestOptions, "POST", `/projects/${project}/signed-asset-urls`, {
2247
2803
  body: {
2248
2804
  ...assetId !== undefined ? { assetId } : { externalId },
2249
2805
  expiresIn: expiresIn ?? DEFAULT_SIGNED_URL_EXPIRES_IN,
@@ -2255,18 +2811,24 @@ class CalmLensServerClient {
2255
2811
  message: "The API returned no signed asset URL"
2256
2812
  });
2257
2813
  }
2258
- return { url: appendAssetLocation(signed.url, location), expiresAt: signed.expiresAt };
2814
+ return copyLastResponse({ url: appendAssetLocation(signed.url, location), expiresAt: signed.expiresAt }, signed);
2259
2815
  },
2260
2816
  getAssetInfo: (url, options = {}) => getAssetInfo(url, { ...options, fetch: this.#settings.cdnFetch }),
2261
- serve: async (options) => {
2817
+ serve: async (options, requestOptions) => {
2262
2818
  const { init, resource = "rendered", ...urlOptions } = checked("cdn.serve", options);
2819
+ const connection = this.#connection.forCall("cdn.serve", requestOptions);
2820
+ if (requestOptions?.extraBody)
2821
+ throw invalidArgument("cdn.serve sends no body: extraBody can't apply");
2263
2822
  const url = this.cdn.getAssetUrl({ ...urlOptions, resource });
2823
+ const extraQuery = requestOptions?.extraQuery && stringifyQuery(requestOptions.extraQuery);
2264
2824
  const method = init?.method?.toUpperCase() ?? "GET";
2265
- const { response } = await this.#connection.transport.send({
2825
+ const { response } = await connection.transport.send({
2826
+ ...connection.callRequest(),
2266
2827
  method,
2267
- url,
2828
+ url: extraQuery ? `${url}${url.includes("?") ? "&" : "?"}${extraQuery}` : url,
2829
+ headers: requestOptions?.headers,
2268
2830
  init,
2269
- timeoutMs: this.#connection.timeoutMs,
2831
+ timeoutMs: connection.timeoutMs,
2270
2832
  deadline: "headers",
2271
2833
  fetch: this.#settings.cdnFetch
2272
2834
  }, { allowHttpErrors: true });
@@ -2276,11 +2838,11 @@ class CalmLensServerClient {
2276
2838
  }
2277
2839
  get text() {
2278
2840
  return {
2279
- classify: async (options) => this.buildAssets().classify(toTextAssetOptions(checked("text.classify", options)))
2841
+ classify: async (options, requestOptions) => this.#submitAsset("text.classify", checkedTextContent(toTextAssetOptions(checked("text.classify", options))), true, requestOptions)
2280
2842
  };
2281
2843
  }
2282
2844
  get assets() {
2283
- return this.buildAssets();
2845
+ return this.#buildAssets();
2284
2846
  }
2285
2847
  get uploadTokens() {
2286
2848
  return {
@@ -2289,100 +2851,78 @@ class CalmLensServerClient {
2289
2851
  }
2290
2852
  };
2291
2853
  }
2292
- buildAssets() {
2854
+ #buildAssets() {
2293
2855
  return {
2294
- search: async (options) => this.request("GET", `${this.projectPath}/assets/search`, {
2856
+ search: async (options, requestOptions) => this.#send("assets.search", requestOptions, "GET", `${this.#projectPath}/assets/search`, {
2295
2857
  query: checked("assets.search", options)
2296
2858
  }),
2297
- list: async (options = {}) => this.request("GET", `${this.projectPath}/assets`, {
2298
- query: checked("assets.list", options)
2299
- }),
2300
- iterate: (options = {}) => {
2301
- checked("assets.iterate", options);
2302
- return this.iteratePages((cursor) => this.buildAssets().list({ ...options, cursor }));
2303
- },
2304
- retrieve: async (options) => {
2859
+ list: (options = {}, requestOptions) => this.#paginate("assets.list", options, requestOptions, (query) => this.#send("assets.list", requestOptions, "GET", `${this.#projectPath}/assets`, {
2860
+ query
2861
+ })),
2862
+ retrieve: async (options, requestOptions) => {
2305
2863
  const { assetId } = checked("assets.retrieve", options);
2306
- return this.request("GET", `/assets/${requireId(assetId, "Asset ID")}`);
2864
+ return this.#send("assets.retrieve", requestOptions, "GET", `/assets/${requireId(assetId, "Asset ID")}`);
2307
2865
  },
2308
- update: async (options) => {
2866
+ update: async (options, requestOptions) => {
2309
2867
  const { assetId, ...body } = checked("assets.update", options);
2310
- return this.request("PATCH", `/assets/${requireId(assetId, "Asset ID")}`, { body });
2311
- },
2312
- listChildren: async (options = {}) => {
2313
- const { assetId, ...query } = checked("assets.listChildren", options);
2314
- return this.request("GET", `/assets/${requireId(assetId, "Asset ID")}/children`, {
2315
- query
2316
- });
2868
+ return this.#send("assets.update", requestOptions, "PATCH", `/assets/${requireId(assetId, "Asset ID")}`, { body });
2317
2869
  },
2318
- listTimeline: async (options) => {
2319
- const { assetId, ...query } = checked("assets.listTimeline", options);
2320
- const assetPath = `${this.projectPath}/assets/${requireId(assetId, "Asset ID")}`;
2321
- return this.request("GET", `${assetPath}/timeline`, {
2870
+ listChildren: (options, requestOptions) => this.#paginate("assets.listChildren", options ?? {}, requestOptions, ({ assetId, ...query }) => this.#send("assets.listChildren", requestOptions, "GET", `/assets/${requireId(assetId, "Asset ID")}/children`, { query })),
2871
+ listTimeline: (options, requestOptions) => this.#paginate("assets.listTimeline", options, requestOptions, ({ assetId, ...query }) => {
2872
+ const assetPath = `${this.#projectPath}/assets/${requireId(assetId, "Asset ID")}`;
2873
+ return this.#send("assets.listTimeline", requestOptions, "GET", `${assetPath}/timeline`, {
2322
2874
  query
2323
2875
  });
2324
- },
2325
- iterateTimeline: (options) => {
2326
- checked("assets.iterateTimeline", options);
2327
- requireId(options?.assetId, "Asset ID");
2328
- return this.iteratePages((cursor) => this.buildAssets().listTimeline({ ...options, cursor }));
2329
- },
2330
- iterateChildren: (options) => {
2331
- checked("assets.iterateChildren", options);
2332
- requireId(options?.assetId, "Asset ID");
2333
- return this.iteratePages((cursor) => this.buildAssets().listChildren({ ...options, cursor }));
2334
- },
2335
- create: async (options) => this.submitAsset(checked("assets.create", options), false),
2336
- classify: async (classifyOptions) => {
2337
- const options = checked("assets.classify", classifyOptions);
2338
- if (options && "content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) {
2339
- throw invalidPayload("Text to classify must be a non-empty string");
2340
- }
2341
- return this.submitAsset(options, true);
2342
- },
2343
- uploadPart: async (partOptions) => {
2876
+ }),
2877
+ create: async (options, requestOptions) => this.#submitAsset("assets.create", checked("assets.create", options), false, requestOptions),
2878
+ classify: async (options, requestOptions) => this.#submitAsset("assets.classify", checkedTextContent(checked("assets.classify", options)), true, requestOptions),
2879
+ uploadPart: async (partOptions, requestOptions) => {
2344
2880
  const { assetId, ...options } = checked("assets.uploadPart", partOptions);
2345
2881
  const encodedAssetId = requireId(assetId, "Asset ID");
2346
- return expectAsset(await this.#connection.uploadPart(`/assets/${encodedAssetId}/part`, options));
2882
+ const connection = this.#connection.forCall("assets.uploadPart", requestOptions);
2883
+ return expectAsset(await connection.uploadPart(`/assets/${encodedAssetId}/part`, options));
2347
2884
  },
2348
- move: async (options) => {
2885
+ move: async (options, requestOptions) => {
2349
2886
  const { assetId, folderId } = checked("assets.move", options);
2350
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/move`, {
2887
+ return this.#send("assets.move", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/move`, {
2351
2888
  body: { folderId }
2352
2889
  });
2353
2890
  },
2354
- retry: async (options) => {
2891
+ retry: async (options, requestOptions) => {
2355
2892
  const { assetId } = checked("assets.retry", options);
2356
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/retry`);
2893
+ return this.#send("assets.retry", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/retry`);
2357
2894
  },
2358
- decide: async (options) => {
2895
+ decide: async (options, requestOptions) => {
2359
2896
  const { assetId, ...body } = checked("assets.decide", options);
2360
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/decision`, { body });
2897
+ return this.#send("assets.decide", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/decision`, { body });
2361
2898
  },
2362
- explain: async (options) => {
2899
+ explain: async (options, requestOptions) => {
2363
2900
  const { assetId, rerun } = checked("assets.explain", options);
2364
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/explain`, {
2901
+ return this.#send("assets.explain", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/explain`, {
2365
2902
  body: rerun ? { rerun } : {}
2366
2903
  });
2367
2904
  },
2368
- waitForDecision: async (waitOptions) => {
2905
+ waitForDecision: async (waitOptions, requestOptions) => {
2369
2906
  const { assetId, ...options } = checked("assets.waitForDecision", waitOptions);
2370
2907
  requireId(assetId, "Asset ID");
2371
- const client = options.signal ? this.withRequestOptions({ signal: options.signal }) : this;
2372
- return pollForDecision(() => client.assets.retrieve({ assetId }), options, this.#connection.sleep, this.#connection.hooks?.now);
2908
+ validateCallOptions(requestOptions);
2909
+ const signals = [options.signal, requestOptions?.signal].filter((signal) => signal !== undefined);
2910
+ const signal = signals.length > 1 ? anySignal(signals) : signals[0];
2911
+ const checkOptions = { ...requestOptions, ...signal && { signal } };
2912
+ return pollForDecision(() => this.#send("assets.waitForDecision", checkOptions, "GET", `/assets/${requireId(assetId, "Asset ID")}`), options, this.#connection.sleep, this.#connection.hooks?.now);
2373
2913
  },
2374
- removeContent: async (options) => {
2914
+ removeContent: async (options, requestOptions) => {
2375
2915
  const { assetId } = checked("assets.removeContent", options);
2376
- return this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}/content`);
2916
+ return this.#send("assets.removeContent", requestOptions, "DELETE", `/assets/${requireId(assetId, "Asset ID")}/content`);
2377
2917
  },
2378
- delete: async (options) => {
2918
+ delete: async (options, requestOptions) => {
2379
2919
  const { assetId } = checked("assets.delete", options);
2380
- await this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}`);
2920
+ await this.#send("assets.delete", requestOptions, "DELETE", `/assets/${requireId(assetId, "Asset ID")}`);
2381
2921
  },
2382
- batch: async (options) => {
2922
+ batch: async (options, requestOptions) => {
2383
2923
  const { assetIds, operation } = checked("assets.batch", options);
2384
2924
  validateBatchAssetsOptions({ assetIds, operation });
2385
- return this.request("POST", `${this.projectPath}/assets/batch`, {
2925
+ return this.#send("assets.batch", requestOptions, "POST", `${this.#projectPath}/assets/batch`, {
2386
2926
  body: { assetIds, operation }
2387
2927
  });
2388
2928
  }
@@ -2390,69 +2930,34 @@ class CalmLensServerClient {
2390
2930
  }
2391
2931
  get events() {
2392
2932
  return {
2393
- list: async (options = {}) => {
2394
- const { types, ...query } = checked("events.list", options);
2395
- return this.request("GET", `${this.projectPath}/events`, {
2396
- query: { ...query, types: types?.length ? types.join(",") : undefined }
2397
- });
2398
- },
2399
- pages: (options = {}) => this.iterateEventPages(checked("events.pages", options))
2933
+ list: (options = {}, requestOptions) => this.#paginate("events.list", options, requestOptions, ({ types, ...query }) => this.#send("events.list", requestOptions, "GET", `${this.#projectPath}/events`, {
2934
+ query: { ...query, types: types?.length ? types.join(",") : undefined }
2935
+ }))
2400
2936
  };
2401
2937
  }
2402
- async* iterateEventPages(options) {
2403
- let cursor = options.cursor;
2404
- const sent = new Set(cursor === undefined ? [] : [cursor]);
2405
- for (;; ) {
2406
- const page = await this.events.list({ ...options, cursor });
2407
- if (page.hasMore)
2408
- assertNewCursor(sent, page.nextCursor);
2409
- yield page;
2410
- if (!page.hasMore)
2411
- return;
2412
- cursor = page.nextCursor;
2413
- }
2414
- }
2415
- async* iteratePages(listPage) {
2416
- let cursor;
2417
- const sent = new Set;
2418
- for (;; ) {
2419
- const page = await listPage(cursor);
2420
- const more = !!page.nextCursor && page.hasMore && page.items.length > 0;
2421
- if (more)
2422
- assertNewCursor(sent, page.nextCursor);
2423
- yield* page.items;
2424
- if (!more)
2425
- return;
2426
- cursor = page.nextCursor;
2427
- }
2428
- }
2429
2938
  get folders() {
2430
2939
  return {
2431
- list: async (options = {}) => this.request("GET", `${this.projectPath}/folders`, {
2432
- query: checked("folders.list", options)
2433
- }),
2434
- iterate: (options = {}) => {
2435
- checked("folders.iterate", options);
2436
- return this.iteratePages((cursor) => this.folders.list({ ...options, cursor }));
2437
- },
2438
- retrieve: async (options) => {
2940
+ list: (options = {}, requestOptions) => this.#paginate("folders.list", options, requestOptions, (query) => this.#send("folders.list", requestOptions, "GET", `${this.#projectPath}/folders`, {
2941
+ query
2942
+ })),
2943
+ retrieve: async (options, requestOptions) => {
2439
2944
  const { folderId } = checked("folders.retrieve", options);
2440
- return this.request("GET", `/folders/${requireId(folderId, "Folder ID")}`);
2945
+ return this.#send("folders.retrieve", requestOptions, "GET", `/folders/${requireId(folderId, "Folder ID")}`);
2441
2946
  },
2442
- create: async (options) => this.request("POST", `${this.projectPath}/folders`, {
2947
+ create: async (options, requestOptions) => this.#send("folders.create", requestOptions, "POST", `${this.#projectPath}/folders`, {
2443
2948
  body: checked("folders.create", options)
2444
2949
  }),
2445
- update: async (options) => {
2950
+ update: async (options, requestOptions) => {
2446
2951
  const { folderId, ...body } = checked("folders.update", options);
2447
- return this.request("PATCH", `/folders/${requireId(folderId, "Folder ID")}`, { body });
2952
+ return this.#send("folders.update", requestOptions, "PATCH", `/folders/${requireId(folderId, "Folder ID")}`, { body });
2448
2953
  },
2449
- delete: async (options) => {
2954
+ delete: async (options, requestOptions) => {
2450
2955
  const { folderId } = checked("folders.delete", options);
2451
- await this.request("DELETE", `/folders/${requireId(folderId, "Folder ID")}`);
2956
+ await this.#send("folders.delete", requestOptions, "DELETE", `/folders/${requireId(folderId, "Folder ID")}`);
2452
2957
  },
2453
- move: async (options) => {
2958
+ move: async (options, requestOptions) => {
2454
2959
  const { folderId, parentId } = checked("folders.move", options);
2455
- return this.request("POST", `/folders/${requireId(folderId, "Folder ID")}/move`, {
2960
+ return this.#send("folders.move", requestOptions, "POST", `/folders/${requireId(folderId, "Folder ID")}/move`, {
2456
2961
  body: { parentId }
2457
2962
  });
2458
2963
  }
@@ -2460,121 +2965,103 @@ class CalmLensServerClient {
2460
2965
  }
2461
2966
  get hashLists() {
2462
2967
  return {
2463
- list: async (options = {}) => this.request("GET", `${this.projectPath}/hash-lists`, {
2464
- query: checked("hashLists.list", options)
2465
- }),
2466
- iterate: (options = {}) => {
2467
- checked("hashLists.iterate", options);
2468
- return this.iteratePages((cursor) => this.hashLists.list({ ...options, cursor }));
2469
- },
2470
- retrieve: async (options) => {
2968
+ list: (options = {}, requestOptions) => this.#paginate("hashLists.list", options, requestOptions, (query) => this.#send("hashLists.list", requestOptions, "GET", `${this.#projectPath}/hash-lists`, {
2969
+ query
2970
+ })),
2971
+ retrieve: async (options, requestOptions) => {
2471
2972
  const { hashListId } = checked("hashLists.retrieve", options);
2472
- return this.request("GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
2973
+ return this.#send("hashLists.retrieve", requestOptions, "GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
2473
2974
  },
2474
- create: async (options) => this.request("POST", `${this.projectPath}/hash-lists`, {
2975
+ create: async (options, requestOptions) => this.#send("hashLists.create", requestOptions, "POST", `${this.#projectPath}/hash-lists`, {
2475
2976
  body: checked("hashLists.create", options)
2476
2977
  }),
2477
- update: async (options) => {
2978
+ update: async (options, requestOptions) => {
2478
2979
  const { hashListId, ...body } = checked("hashLists.update", options);
2479
- return this.request("PATCH", `/hash-lists/${requireId(hashListId, "Hash list ID")}`, {
2980
+ return this.#send("hashLists.update", requestOptions, "PATCH", `/hash-lists/${requireId(hashListId, "Hash list ID")}`, {
2480
2981
  body
2481
2982
  });
2482
2983
  },
2483
- delete: async (options) => {
2984
+ delete: async (options, requestOptions) => {
2484
2985
  const { hashListId } = checked("hashLists.delete", options);
2485
- await this.request("DELETE", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
2486
- },
2487
- iterateEntries: (options) => {
2488
- checked("hashLists.iterateEntries", options);
2489
- requireId(options?.hashListId, "Hash list ID");
2490
- return this.iteratePages((cursor) => this.hashLists.listEntries({ ...options, cursor }));
2491
- },
2492
- listEntries: async (options) => {
2493
- const { hashListId, ...query } = checked("hashLists.listEntries", options);
2494
- return this.request("GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, {
2495
- query
2496
- });
2986
+ await this.#send("hashLists.delete", requestOptions, "DELETE", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
2497
2987
  },
2498
- addEntry: async (options) => {
2988
+ listEntries: (options, requestOptions) => this.#paginate("hashLists.listEntries", options, requestOptions, ({ hashListId, ...query }) => this.#send("hashLists.listEntries", requestOptions, "GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, {
2989
+ query
2990
+ })),
2991
+ addEntry: async (options, requestOptions) => {
2499
2992
  const { hashListId, ...body } = checked("hashLists.addEntry", options);
2500
- return this.request("POST", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, { body });
2993
+ return this.#send("hashLists.addEntry", requestOptions, "POST", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, { body });
2501
2994
  },
2502
- removeEntry: async (options) => {
2995
+ removeEntry: async (options, requestOptions) => {
2503
2996
  const { entryId } = checked("hashLists.removeEntry", options);
2504
- await this.request("DELETE", `/hash-list-entries/${requireId(entryId, "Hash list entry ID")}`);
2997
+ await this.#send("hashLists.removeEntry", requestOptions, "DELETE", `/hash-list-entries/${requireId(entryId, "Hash list entry ID")}`);
2505
2998
  }
2506
2999
  };
2507
3000
  }
2508
3001
  get policies() {
2509
3002
  const policyPath = (policyId) => `/policies/${requireId(policyId, "Policy ID")}`;
2510
3003
  return {
2511
- list: async (options = {}) => this.request("GET", "/policies", { query: checked("policies.list", options) }),
2512
- iterate: (options = {}) => {
2513
- checked("policies.iterate", options);
2514
- return this.iteratePages((cursor) => this.policies.list({ ...options, cursor }));
2515
- },
2516
- retrieve: async (options) => this.request("GET", policyPath(checked("policies.retrieve", options).policyId)),
2517
- create: async (options) => this.request("POST", "/policies", { body: checked("policies.create", options) }),
2518
- update: async (options) => {
3004
+ list: (options = {}, requestOptions) => this.#paginate("policies.list", options, requestOptions, (query) => this.#send("policies.list", requestOptions, "GET", "/policies", { query })),
3005
+ retrieve: async (options, requestOptions) => this.#send("policies.retrieve", requestOptions, "GET", policyPath(checked("policies.retrieve", options).policyId)),
3006
+ create: async (options, requestOptions) => this.#send("policies.create", requestOptions, "POST", "/policies", {
3007
+ body: checked("policies.create", options)
3008
+ }),
3009
+ update: async (options, requestOptions) => {
2519
3010
  const { policyId, ...body } = checked("policies.update", options);
2520
- return this.request("PATCH", policyPath(policyId), { body });
3011
+ return this.#send("policies.update", requestOptions, "PATCH", policyPath(policyId), {
3012
+ body
3013
+ });
2521
3014
  },
2522
- reset: async (options) => {
3015
+ reset: async (options, requestOptions) => {
2523
3016
  const { policyId, ...body } = checked("policies.reset", options);
2524
- return this.request("POST", `${policyPath(policyId)}/reset`, { body });
3017
+ return this.#send("policies.reset", requestOptions, "POST", `${policyPath(policyId)}/reset`, { body });
2525
3018
  },
2526
- upgrade: async (options) => {
3019
+ upgrade: async (options, requestOptions) => {
2527
3020
  const { policyId, ...body } = checked("policies.upgrade", options);
2528
- return this.request("POST", `${policyPath(policyId)}/upgrade`, { body });
3021
+ return this.#send("policies.upgrade", requestOptions, "POST", `${policyPath(policyId)}/upgrade`, { body });
2529
3022
  },
2530
- setAutomaticUpdates: async (options) => {
3023
+ setAutomaticUpdates: async (options, requestOptions) => {
2531
3024
  const { policyId, ...body } = checked("policies.setAutomaticUpdates", options);
2532
- return this.request("PUT", `${policyPath(policyId)}/automatic-updates`, { body });
3025
+ return this.#send("policies.setAutomaticUpdates", requestOptions, "PUT", `${policyPath(policyId)}/automatic-updates`, { body });
2533
3026
  },
2534
- delete: async (options) => {
2535
- await this.request("DELETE", policyPath(checked("policies.delete", options).policyId));
3027
+ delete: async (options, requestOptions) => {
3028
+ await this.#send("policies.delete", requestOptions, "DELETE", policyPath(checked("policies.delete", options).policyId));
2536
3029
  },
2537
- retrieveAssigned: async () => this.request("GET", `${this.projectPath}/policy`),
2538
- assign: async (options) => this.request("PUT", `${this.projectPath}/policy`, {
3030
+ retrieveAssigned: async (requestOptions) => this.#send("policies.retrieveAssigned", requestOptions, "GET", `${this.#projectPath}/policy`),
3031
+ assign: async (options, requestOptions) => this.#send("policies.assign", requestOptions, "PUT", `${this.#projectPath}/policy`, {
2539
3032
  body: checked("policies.assign", options)
2540
3033
  })
2541
3034
  };
2542
3035
  }
2543
3036
  get uploadPresets() {
2544
3037
  return {
2545
- list: async (options = {}) => this.request("GET", `${this.projectPath}/upload-presets`, {
2546
- query: checked("uploadPresets.list", options)
2547
- }),
2548
- iterate: (options = {}) => {
2549
- checked("uploadPresets.iterate", options);
2550
- return this.iteratePages((cursor) => this.uploadPresets.list({ ...options, cursor }));
2551
- },
2552
- ensure: async (options) => this.request("PUT", `${this.projectPath}/upload-presets`, {
3038
+ list: (options = {}, requestOptions) => this.#paginate("uploadPresets.list", options, requestOptions, (query) => this.#send("uploadPresets.list", requestOptions, "GET", `${this.#projectPath}/upload-presets`, { query })),
3039
+ ensure: async (options, requestOptions) => this.#send("uploadPresets.ensure", requestOptions, "PUT", `${this.#projectPath}/upload-presets`, {
2553
3040
  body: checked("uploadPresets.ensure", options)
2554
3041
  }),
2555
- delete: async (options) => {
3042
+ delete: async (options, requestOptions) => {
2556
3043
  const { uploadPresetId } = checked("uploadPresets.delete", options);
2557
- await this.request("DELETE", `/upload-presets/${requireId(uploadPresetId, "Upload preset ID")}`);
3044
+ await this.#send("uploadPresets.delete", requestOptions, "DELETE", `/upload-presets/${requireId(uploadPresetId, "Upload preset ID")}`);
2558
3045
  }
2559
3046
  };
2560
3047
  }
2561
3048
  get projectSettings() {
2562
3049
  return {
2563
- get: async () => this.request("GET", `${this.projectPath}/settings`),
2564
- update: async (options) => this.request("PUT", `${this.projectPath}/settings`, {
3050
+ get: async (requestOptions) => this.#send("projectSettings.get", requestOptions, "GET", `${this.#projectPath}/settings`),
3051
+ update: async (options, requestOptions) => this.#send("projectSettings.update", requestOptions, "PUT", `${this.#projectPath}/settings`, {
2565
3052
  body: checked("projectSettings.update", options)
2566
3053
  })
2567
3054
  };
2568
3055
  }
2569
3056
  get metadataFields() {
2570
3057
  return {
2571
- list: async () => this.request("GET", `${this.projectPath}/metadata-fields`),
2572
- ensure: async (options) => this.request("PUT", `${this.projectPath}/metadata-fields`, {
3058
+ list: async (requestOptions) => this.#send("metadataFields.list", requestOptions, "GET", `${this.#projectPath}/metadata-fields`),
3059
+ ensure: async (options, requestOptions) => this.#send("metadataFields.ensure", requestOptions, "PUT", `${this.#projectPath}/metadata-fields`, {
2573
3060
  body: checked("metadataFields.ensure", options)
2574
3061
  }),
2575
- delete: async (options) => {
3062
+ delete: async (options, requestOptions) => {
2576
3063
  const { fieldId, ...query } = checked("metadataFields.delete", options);
2577
- await this.request("DELETE", `${this.projectPath}/metadata-fields/${requireId(fieldId, "Metadata field ID")}`, { query });
3064
+ await this.#send("metadataFields.delete", requestOptions, "DELETE", `${this.#projectPath}/metadata-fields/${requireId(fieldId, "Metadata field ID")}`, { query });
2578
3065
  }
2579
3066
  };
2580
3067
  }
@@ -2586,42 +3073,39 @@ class CalmLensServerClient {
2586
3073
  this.#lenses.ensuredLenses.delete(cacheKey);
2587
3074
  };
2588
3075
  return {
2589
- list: async (options = {}) => this.request("GET", `${this.projectPath}/lenses`, {
2590
- query: checked("lenses.list", options)
2591
- }),
2592
- iterate: (options = {}) => {
2593
- checked("lenses.iterate", options);
2594
- return this.iteratePages((cursor) => this.lenses.list({ ...options, cursor }));
2595
- },
2596
- create: async (options) => {
2597
- const lens = await this.request("POST", `${this.projectPath}/lenses`, {
3076
+ list: (options = {}, requestOptions) => this.#paginate("lenses.list", options, requestOptions, (query) => this.#send("lenses.list", requestOptions, "GET", `${this.#projectPath}/lenses`, {
3077
+ query
3078
+ })),
3079
+ create: async (options, requestOptions) => {
3080
+ const lens = await this.#send("lenses.create", requestOptions, "POST", `${this.#projectPath}/lenses`, {
2598
3081
  body: checked("lenses.create", options)
2599
3082
  });
2600
3083
  forget((cached) => cached.identifier === lens.identifier);
2601
3084
  return lens;
2602
3085
  },
2603
- retrieve: async (options) => this.request("GET", lensPath(checked("lenses.retrieve", options).lensId)),
2604
- update: async (options) => {
3086
+ retrieve: async (options, requestOptions) => this.#send("lenses.retrieve", requestOptions, "GET", lensPath(checked("lenses.retrieve", options).lensId)),
3087
+ update: async (options, requestOptions) => {
2605
3088
  const { lensId, ...body } = checked("lenses.update", options);
2606
- const lens = await this.request("PATCH", lensPath(lensId), { body });
3089
+ const lens = await this.#send("lenses.update", requestOptions, "PATCH", lensPath(lensId), { body });
2607
3090
  forget((cached) => cached.id === lens.id);
2608
3091
  return lens;
2609
3092
  },
2610
- delete: async (options) => {
3093
+ delete: async (options, requestOptions) => {
2611
3094
  const { lensId } = checked("lenses.delete", options);
2612
- await this.request("DELETE", lensPath(lensId));
3095
+ await this.#send("lenses.delete", requestOptions, "DELETE", lensPath(lensId));
2613
3096
  forget((cached) => cached.id === lensId);
2614
3097
  }
2615
3098
  };
2616
3099
  }
2617
- async ensureLens(options) {
3100
+ async ensureLens(options, requestOptions) {
2618
3101
  checked("ensureLens", options);
2619
3102
  if (!options?.identifier)
2620
3103
  throw invalidArgument("Lens identifier is required");
2621
- const [lens] = await this.ensureLenses({ lenses: [options] });
3104
+ const [lens] = await this.ensureLenses({ lenses: [options] }, requestOptions);
2622
3105
  return lens;
2623
3106
  }
2624
- async ensureLenses(options) {
3107
+ async ensureLenses(options, requestOptions) {
3108
+ validateCallOptions(requestOptions);
2625
3109
  const { lenses } = checked("ensureLenses", options);
2626
3110
  if (!Array.isArray(lenses) || lenses.length === 0) {
2627
3111
  throw invalidArgument("At least one lens is required");
@@ -2645,7 +3129,7 @@ class CalmLensServerClient {
2645
3129
  const batchCacheKey = JSON.stringify([...missingKeys].sort());
2646
3130
  let pending = pendingEnsureLenses.get(batchCacheKey);
2647
3131
  if (!pending) {
2648
- pending = this.submitEnsureLenses(missingOptions);
3132
+ pending = this.#submitEnsureLenses(missingOptions, requestOptions);
2649
3133
  pendingEnsureLenses.set(batchCacheKey, pending);
2650
3134
  pending.then(() => pendingEnsureLenses.delete(batchCacheKey), () => pendingEnsureLenses.delete(batchCacheKey));
2651
3135
  }
@@ -2661,15 +3145,13 @@ class CalmLensServerClient {
2661
3145
  return lens;
2662
3146
  });
2663
3147
  }
2664
- async submitEnsureLenses(options) {
3148
+ async#submitEnsureLenses(options, requestOptions) {
2665
3149
  for (let start = 0;start < options.length; start += ENSURE_LENSES_MAX_PER_REQUEST) {
2666
- await this.submitEnsureLensesChunk(options.slice(start, start + ENSURE_LENSES_MAX_PER_REQUEST));
3150
+ await this.#submitEnsureLensesChunk(options.slice(start, start + ENSURE_LENSES_MAX_PER_REQUEST), requestOptions);
2667
3151
  }
2668
3152
  }
2669
- async submitEnsureLensesChunk(options) {
2670
- const result = await this.request("PUT", `${this.projectPath}/lenses`, {
2671
- body: { lenses: options }
2672
- });
3153
+ async#submitEnsureLensesChunk(options, requestOptions) {
3154
+ const result = await this.#send("ensureLenses", requestOptions, "PUT", `${this.#projectPath}/lenses`, { body: { lenses: options } });
2673
3155
  const returned = Array.isArray(result?.lenses) ? result.lenses : [];
2674
3156
  if (returned.length !== options.length) {
2675
3157
  throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
@@ -2810,6 +3292,9 @@ function mergeDefs(...defs) {
2810
3292
  function esc(str) {
2811
3293
  return JSON.stringify(str);
2812
3294
  }
3295
+ function slugify(input) {
3296
+ return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
3297
+ }
2813
3298
  var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
2814
3299
  function isObject(data) {
2815
3300
  return typeof data === "object" && data !== null && !Array.isArray(data);
@@ -2829,7 +3314,7 @@ var allowsEval = /* @__PURE__ */ cached(() => {
2829
3314
  return false;
2830
3315
  }
2831
3316
  });
2832
- function isPlainObject2(o) {
3317
+ function isPlainObject3(o) {
2833
3318
  if (isObject(o) === false)
2834
3319
  return false;
2835
3320
  const ctor = o.constructor;
@@ -2846,7 +3331,7 @@ function isPlainObject2(o) {
2846
3331
  return true;
2847
3332
  }
2848
3333
  function shallowClone(o) {
2849
- if (isPlainObject2(o))
3334
+ if (isPlainObject3(o))
2850
3335
  return { ...o };
2851
3336
  if (Array.isArray(o))
2852
3337
  return [...o];
@@ -2941,7 +3426,7 @@ function omit(schema, mask) {
2941
3426
  return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
2942
3427
  }
2943
3428
  function extend(schema, shape) {
2944
- if (!isPlainObject2(shape)) {
3429
+ if (!isPlainObject3(shape)) {
2945
3430
  throw new Error("Invalid input to extend: expected a plain object");
2946
3431
  }
2947
3432
  const checks = schema._zod.def.checks;
@@ -2963,7 +3448,7 @@ function extended(schema, shape) {
2963
3448
  return newShape;
2964
3449
  }
2965
3450
  function safeExtend(schema, shape) {
2966
- if (!isPlainObject2(shape)) {
3451
+ if (!isPlainObject3(shape)) {
2967
3452
  throw new Error("Invalid input to safeExtend: expected a plain object");
2968
3453
  }
2969
3454
  return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
@@ -3626,11 +4111,62 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
3626
4111
  return _safeParseAsync(_Err)(schema, value, _ctx);
3627
4112
  };
3628
4113
  // ../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/regexes.js
4114
+ var cuid = /^[cC][0-9a-z]{6,}$/;
4115
+ var cuid2 = /^[0-9a-z]+$/;
4116
+ var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
4117
+ var xid = /^[0-9a-vA-V]{20}$/;
4118
+ var ksuid = /^[A-Za-z0-9]{27}$/;
4119
+ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
4120
+ function nanoidOfLength(length) {
4121
+ return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
4122
+ }
4123
+ var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
4124
+ var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
4125
+ var uuid = (version) => {
4126
+ if (!version)
4127
+ return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
4128
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
4129
+ };
4130
+ var email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
4131
+ var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;
4132
+ function emoji() {
4133
+ return new RegExp(_emoji, "u");
4134
+ }
4135
+ var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
4136
+ var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
4137
+ var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
4138
+ var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
3629
4139
  var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
3630
4140
  var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
4141
+ var httpProtocol = /^https?$/;
4142
+ var e164 = /^\+[1-9]\d{6,14}$/;
4143
+ var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
4144
+ function anchor(source) {
4145
+ return new RegExp(`^${source}$`);
4146
+ }
4147
+ var date = /* @__PURE__ */ anchor(dateSource);
4148
+ function timeSource(args) {
4149
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
4150
+ const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
4151
+ return regex;
4152
+ }
4153
+ function time(args) {
4154
+ return new RegExp(`^${timeSource(args)}$`);
4155
+ }
4156
+ function datetime(args) {
4157
+ const opts = ["Z"];
4158
+ if (args.offset)
4159
+ opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
4160
+ const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`;
4161
+ const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
4162
+ return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
4163
+ }
4164
+ var anyString = /^[\s\S]{0,}$/;
3631
4165
  var number = /^-?\d+(?:\.\d+)?$/;
3632
4166
  var boolean = /^(?:true|false)$/i;
3633
-
4167
+ var lowercase = /^[^A-Z]*$/;
4168
+ var uppercase = /^[^a-z]*$/;
4169
+
3634
4170
  // ../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/checks.js
3635
4171
  var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
3636
4172
  var _a;
@@ -3839,6 +4375,107 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals"
3839
4375
  });
3840
4376
  };
3841
4377
  });
4378
+ var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
4379
+ var _a, _b;
4380
+ $ZodCheck.init(inst, def);
4381
+ if (def.pattern)
4382
+ (_a = inst._zod).check ?? (_a.check = (payload) => {
4383
+ def.pattern.lastIndex = 0;
4384
+ if (def.pattern.test(payload.value))
4385
+ return;
4386
+ payload.issues.push({
4387
+ origin: "string",
4388
+ code: "invalid_format",
4389
+ format: def.format,
4390
+ input: payload.value,
4391
+ ...def.pattern ? { pattern: def.pattern.toString() } : {},
4392
+ inst,
4393
+ continue: !def.abort
4394
+ });
4395
+ });
4396
+ else
4397
+ (_b = inst._zod).check ?? (_b.check = () => {});
4398
+ });
4399
+ var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
4400
+ $ZodCheckStringFormat.init(inst, def);
4401
+ inst._zod.check = (payload) => {
4402
+ def.pattern.lastIndex = 0;
4403
+ if (def.pattern.test(payload.value))
4404
+ return;
4405
+ payload.issues.push({
4406
+ origin: "string",
4407
+ code: "invalid_format",
4408
+ format: "regex",
4409
+ input: payload.value,
4410
+ pattern: def.pattern.toString(),
4411
+ inst,
4412
+ continue: !def.abort
4413
+ });
4414
+ };
4415
+ });
4416
+ var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
4417
+ def.pattern ?? (def.pattern = lowercase);
4418
+ $ZodCheckStringFormat.init(inst, def);
4419
+ });
4420
+ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
4421
+ def.pattern ?? (def.pattern = uppercase);
4422
+ $ZodCheckStringFormat.init(inst, def);
4423
+ });
4424
+ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
4425
+ $ZodCheck.init(inst, def);
4426
+ const escapedRegex = escapeRegex(def.includes);
4427
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
4428
+ def.pattern = pattern;
4429
+ inst._zod.check = (payload) => {
4430
+ if (payload.value.includes(def.includes, def.position))
4431
+ return;
4432
+ payload.issues.push({
4433
+ origin: "string",
4434
+ code: "invalid_format",
4435
+ format: "includes",
4436
+ includes: def.includes,
4437
+ input: payload.value,
4438
+ inst,
4439
+ continue: !def.abort
4440
+ });
4441
+ };
4442
+ });
4443
+ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
4444
+ $ZodCheck.init(inst, def);
4445
+ const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
4446
+ def.pattern ?? (def.pattern = pattern);
4447
+ inst._zod.check = (payload) => {
4448
+ if (payload.value.startsWith(def.prefix))
4449
+ return;
4450
+ payload.issues.push({
4451
+ origin: "string",
4452
+ code: "invalid_format",
4453
+ format: "starts_with",
4454
+ prefix: def.prefix,
4455
+ input: payload.value,
4456
+ inst,
4457
+ continue: !def.abort
4458
+ });
4459
+ };
4460
+ });
4461
+ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
4462
+ $ZodCheck.init(inst, def);
4463
+ const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
4464
+ def.pattern ?? (def.pattern = pattern);
4465
+ inst._zod.check = (payload) => {
4466
+ if (payload.value.endsWith(def.suffix))
4467
+ return;
4468
+ payload.issues.push({
4469
+ origin: "string",
4470
+ code: "invalid_format",
4471
+ format: "ends_with",
4472
+ suffix: def.suffix,
4473
+ input: payload.value,
4474
+ inst,
4475
+ continue: !def.abort
4476
+ });
4477
+ };
4478
+ });
3842
4479
  var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
3843
4480
  $ZodCheck.init(inst, def);
3844
4481
  inst._zod.check = (payload) => {
@@ -4024,8 +4661,363 @@ function standardProps(inst) {
4024
4661
  version: 1
4025
4662
  };
4026
4663
  }
4664
+ var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
4665
+ $ZodType.init(inst, def);
4666
+ inst._zod.pattern = def.pattern ?? anyString;
4667
+ inst._zod.parse = (payload, _) => {
4668
+ if (def.coerce)
4669
+ try {
4670
+ payload.value = String(payload.value);
4671
+ } catch (_) {}
4672
+ if (typeof payload.value === "string")
4673
+ return payload;
4674
+ payload.issues.push({
4675
+ expected: "string",
4676
+ code: "invalid_type",
4677
+ input: payload.value,
4678
+ inst
4679
+ });
4680
+ return payload;
4681
+ };
4682
+ });
4683
+ var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
4684
+ $ZodCheckStringFormat.init(inst, def);
4685
+ $ZodString.init(inst, def);
4686
+ });
4687
+ var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
4688
+ def.pattern ?? (def.pattern = guid);
4689
+ $ZodStringFormat.init(inst, def);
4690
+ });
4691
+ var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
4692
+ if (def.version) {
4693
+ const versionMap = {
4694
+ v1: 1,
4695
+ v2: 2,
4696
+ v3: 3,
4697
+ v4: 4,
4698
+ v5: 5,
4699
+ v6: 6,
4700
+ v7: 7,
4701
+ v8: 8
4702
+ };
4703
+ const v = versionMap[def.version];
4704
+ if (v === undefined)
4705
+ throw new Error(`Invalid UUID version: "${def.version}"`);
4706
+ def.pattern ?? (def.pattern = uuid(v));
4707
+ } else
4708
+ def.pattern ?? (def.pattern = uuid());
4709
+ $ZodStringFormat.init(inst, def);
4710
+ });
4711
+ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
4712
+ def.pattern ?? (def.pattern = email);
4713
+ $ZodStringFormat.init(inst, def);
4714
+ });
4715
+ var URL_BAD_FORMAT = 1;
4716
+ var URL_UNPARSEABLE = 2;
4717
+ function canParseURL(input) {
4718
+ try {
4719
+ if (typeof URL !== "undefined" && typeof URL.canParse === "function")
4720
+ return URL.canParse(input);
4721
+ new URL(input);
4722
+ return true;
4723
+ } catch {
4724
+ return false;
4725
+ }
4726
+ }
4727
+ function validateURL(trimmed, def) {
4728
+ if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) {
4729
+ return canParseURL(trimmed) || URL_UNPARSEABLE;
4730
+ }
4731
+ return parseURLObject(trimmed, def);
4732
+ }
4733
+ function parseURLObject(trimmed, def) {
4734
+ if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) {
4735
+ return URL_BAD_FORMAT;
4736
+ }
4737
+ try {
4738
+ if (typeof URL !== "undefined") {
4739
+ const URLStatic = URL;
4740
+ if (typeof URLStatic.parse === "function")
4741
+ return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;
4742
+ }
4743
+ return new URL(trimmed);
4744
+ } catch {
4745
+ return URL_UNPARSEABLE;
4746
+ }
4747
+ }
4748
+ var asciiTabOrNewline = /[\t\n\r]/g;
4749
+ function stripTabAndNewline(value) {
4750
+ return value.replace(asciiTabOrNewline, "");
4751
+ }
4752
+ function urlHostnameOk(url, hostname) {
4753
+ hostname.lastIndex = 0;
4754
+ return hostname.test(url.hostname);
4755
+ }
4756
+ function urlProtocolOk(url, protocol) {
4757
+ protocol.lastIndex = 0;
4758
+ return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
4759
+ }
4760
+ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
4761
+ $ZodStringFormat.init(inst, def);
4762
+ inst._zod.check = (payload) => {
4763
+ try {
4764
+ const trimmed = payload.value.trim();
4765
+ const url = validateURL(trimmed, def);
4766
+ if (url === URL_BAD_FORMAT) {
4767
+ payload.issues.push({
4768
+ code: "invalid_format",
4769
+ format: "url",
4770
+ note: "Invalid URL format",
4771
+ input: payload.value,
4772
+ inst,
4773
+ continue: !def.abort
4774
+ });
4775
+ return;
4776
+ }
4777
+ if (url === URL_UNPARSEABLE) {
4778
+ payload.issues.push({
4779
+ code: "invalid_format",
4780
+ format: "url",
4781
+ input: payload.value,
4782
+ inst,
4783
+ continue: !def.abort
4784
+ });
4785
+ return;
4786
+ }
4787
+ if (url === true) {
4788
+ payload.value = stripTabAndNewline(trimmed);
4789
+ return;
4790
+ }
4791
+ if (def.hostname && !urlHostnameOk(url, def.hostname)) {
4792
+ payload.issues.push({
4793
+ code: "invalid_format",
4794
+ format: "url",
4795
+ note: "Invalid hostname",
4796
+ pattern: def.hostname.source,
4797
+ input: payload.value,
4798
+ inst,
4799
+ continue: !def.abort
4800
+ });
4801
+ }
4802
+ if (def.protocol && !urlProtocolOk(url, def.protocol)) {
4803
+ payload.issues.push({
4804
+ code: "invalid_format",
4805
+ format: "url",
4806
+ note: "Invalid protocol",
4807
+ pattern: def.protocol.source,
4808
+ input: payload.value,
4809
+ inst,
4810
+ continue: !def.abort
4811
+ });
4812
+ }
4813
+ payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);
4814
+ return;
4815
+ } catch (_) {
4816
+ payload.issues.push({
4817
+ code: "invalid_format",
4818
+ format: "url",
4819
+ input: payload.value,
4820
+ inst,
4821
+ continue: !def.abort
4822
+ });
4823
+ }
4824
+ };
4825
+ });
4826
+ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
4827
+ def.pattern ?? (def.pattern = emoji());
4828
+ $ZodStringFormat.init(inst, def);
4829
+ });
4830
+ var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
4831
+ if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))
4832
+ throw new Error(`Invalid nanoid length: ${def.length}`);
4833
+ def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length));
4834
+ $ZodStringFormat.init(inst, def);
4835
+ });
4836
+ var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
4837
+ def.pattern ?? (def.pattern = cuid);
4838
+ $ZodStringFormat.init(inst, def);
4839
+ });
4840
+ var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
4841
+ def.pattern ?? (def.pattern = cuid2);
4842
+ $ZodStringFormat.init(inst, def);
4843
+ });
4844
+ var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
4845
+ def.pattern ?? (def.pattern = ulid);
4846
+ $ZodStringFormat.init(inst, def);
4847
+ });
4848
+ var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
4849
+ def.pattern ?? (def.pattern = xid);
4850
+ $ZodStringFormat.init(inst, def);
4851
+ });
4852
+ var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
4853
+ def.pattern ?? (def.pattern = ksuid);
4854
+ $ZodStringFormat.init(inst, def);
4855
+ });
4856
+ var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
4857
+ def.pattern ?? (def.pattern = datetime(def));
4858
+ $ZodStringFormat.init(inst, def);
4859
+ });
4860
+ var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
4861
+ def.pattern ?? (def.pattern = date);
4862
+ $ZodStringFormat.init(inst, def);
4863
+ });
4864
+ var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
4865
+ def.pattern ?? (def.pattern = time(def));
4866
+ $ZodStringFormat.init(inst, def);
4867
+ });
4868
+ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
4869
+ def.pattern ?? (def.pattern = duration);
4870
+ $ZodStringFormat.init(inst, def);
4871
+ });
4872
+ var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
4873
+ def.pattern ?? (def.pattern = ipv4);
4874
+ $ZodStringFormat.init(inst, def);
4875
+ });
4876
+ var ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
4877
+ function isValidIPv6(value) {
4878
+ if (!ipv6Alphabet.test(value))
4879
+ return false;
4880
+ return canParseURL(`http://[${value}]`);
4881
+ }
4882
+ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
4883
+ def.pattern ?? (def.pattern = ipv6);
4884
+ $ZodStringFormat.init(inst, def);
4885
+ inst._zod.check = (payload) => {
4886
+ if (!isValidIPv6(payload.value)) {
4887
+ payload.issues.push({
4888
+ code: "invalid_format",
4889
+ format: "ipv6",
4890
+ input: payload.value,
4891
+ inst,
4892
+ continue: !def.abort
4893
+ });
4894
+ }
4895
+ };
4896
+ });
4897
+ var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
4898
+ def.pattern ?? (def.pattern = cidrv4);
4899
+ $ZodStringFormat.init(inst, def);
4900
+ });
4901
+ function isValidCIDRv6(value) {
4902
+ const parts = value.split("/");
4903
+ if (parts.length !== 2)
4904
+ return false;
4905
+ const [address, prefix] = parts;
4906
+ if (!prefix)
4907
+ return false;
4908
+ const prefixNum = Number(prefix);
4909
+ if (`${prefixNum}` !== prefix)
4910
+ return false;
4911
+ if (prefixNum < 0 || prefixNum > 128)
4912
+ return false;
4913
+ return isValidIPv6(address);
4914
+ }
4915
+ var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
4916
+ def.pattern ?? (def.pattern = cidrv6);
4917
+ $ZodStringFormat.init(inst, def);
4918
+ inst._zod.check = (payload) => {
4919
+ if (!isValidCIDRv6(payload.value)) {
4920
+ payload.issues.push({
4921
+ code: "invalid_format",
4922
+ format: "cidrv6",
4923
+ input: payload.value,
4924
+ inst,
4925
+ continue: !def.abort
4926
+ });
4927
+ }
4928
+ };
4929
+ });
4930
+ function isValidBase64(data) {
4931
+ if (data === "")
4932
+ return true;
4933
+ if (/\s/.test(data))
4934
+ return false;
4935
+ if (data.length % 4 !== 0)
4936
+ return false;
4937
+ try {
4938
+ atob(data);
4939
+ return true;
4940
+ } catch {
4941
+ return false;
4942
+ }
4943
+ }
4027
4944
  var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;
4945
+ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
4946
+ def.pattern ?? (def.pattern = base64Charset);
4947
+ $ZodStringFormat.init(inst, def);
4948
+ inst._zod.check = (payload) => {
4949
+ if (isValidBase64(payload.value))
4950
+ return;
4951
+ payload.issues.push({
4952
+ code: "invalid_format",
4953
+ format: "base64",
4954
+ input: payload.value,
4955
+ inst,
4956
+ continue: !def.abort
4957
+ });
4958
+ };
4959
+ });
4028
4960
  var base64urlCharset = /^[A-Za-z0-9_-]*$/;
4961
+ function isValidBase64URL(data) {
4962
+ if (!base64urlCharset.test(data))
4963
+ return false;
4964
+ const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
4965
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
4966
+ return isValidBase64(padded);
4967
+ }
4968
+ var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
4969
+ def.pattern ?? (def.pattern = base64urlCharset);
4970
+ $ZodStringFormat.init(inst, def);
4971
+ inst._zod.check = (payload) => {
4972
+ if (isValidBase64URL(payload.value))
4973
+ return;
4974
+ payload.issues.push({
4975
+ code: "invalid_format",
4976
+ format: "base64url",
4977
+ input: payload.value,
4978
+ inst,
4979
+ continue: !def.abort
4980
+ });
4981
+ };
4982
+ });
4983
+ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
4984
+ def.pattern ?? (def.pattern = e164);
4985
+ $ZodStringFormat.init(inst, def);
4986
+ });
4987
+ function isValidJWT(token, algorithm = null) {
4988
+ try {
4989
+ const tokensParts = token.split(".");
4990
+ if (tokensParts.length !== 3)
4991
+ return false;
4992
+ const [header] = tokensParts;
4993
+ if (!header)
4994
+ return false;
4995
+ const parsedHeader = JSON.parse(atob(header));
4996
+ if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
4997
+ return false;
4998
+ if (!parsedHeader.alg)
4999
+ return false;
5000
+ if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
5001
+ return false;
5002
+ return true;
5003
+ } catch {
5004
+ return false;
5005
+ }
5006
+ }
5007
+ var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
5008
+ $ZodStringFormat.init(inst, def);
5009
+ inst._zod.check = (payload) => {
5010
+ if (isValidJWT(payload.value, def.alg))
5011
+ return;
5012
+ payload.issues.push({
5013
+ code: "invalid_format",
5014
+ format: "jwt",
5015
+ input: payload.value,
5016
+ inst,
5017
+ continue: !def.abort
5018
+ });
5019
+ };
5020
+ });
4029
5021
  var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
4030
5022
  $ZodType.init(inst, def);
4031
5023
  inst._zod.pattern = number;
@@ -4548,7 +5540,7 @@ function mergeValues(a, b) {
4548
5540
  if (a instanceof Date && b instanceof Date && +a === +b) {
4549
5541
  return { valid: true, data: a };
4550
5542
  }
4551
- if (isPlainObject2(a) && isPlainObject2(b)) {
5543
+ if (isPlainObject3(a) && isPlainObject3(b)) {
4552
5544
  const bKeys = Object.keys(b);
4553
5545
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
4554
5546
  const newObj = { ...a, ...b };
@@ -5505,6 +6497,243 @@ function snapshotChecks(def) {
5505
6497
  def.checks = [...def.checks];
5506
6498
  return def;
5507
6499
  }
6500
+ function _email(Class, params) {
6501
+ return new Class({
6502
+ type: "string",
6503
+ format: "email",
6504
+ check: "string_format",
6505
+ abort: false,
6506
+ ...normalizeParams(params)
6507
+ });
6508
+ }
6509
+ function _guid(Class, params) {
6510
+ return new Class({
6511
+ type: "string",
6512
+ format: "guid",
6513
+ check: "string_format",
6514
+ abort: false,
6515
+ ...normalizeParams(params)
6516
+ });
6517
+ }
6518
+ function _uuid(Class, params) {
6519
+ return new Class({
6520
+ type: "string",
6521
+ format: "uuid",
6522
+ check: "string_format",
6523
+ abort: false,
6524
+ ...normalizeParams(params)
6525
+ });
6526
+ }
6527
+ function _uuidv4(Class, params) {
6528
+ return new Class({
6529
+ type: "string",
6530
+ format: "uuid",
6531
+ check: "string_format",
6532
+ abort: false,
6533
+ version: "v4",
6534
+ ...normalizeParams(params)
6535
+ });
6536
+ }
6537
+ function _uuidv6(Class, params) {
6538
+ return new Class({
6539
+ type: "string",
6540
+ format: "uuid",
6541
+ check: "string_format",
6542
+ abort: false,
6543
+ version: "v6",
6544
+ ...normalizeParams(params)
6545
+ });
6546
+ }
6547
+ function _uuidv7(Class, params) {
6548
+ return new Class({
6549
+ type: "string",
6550
+ format: "uuid",
6551
+ check: "string_format",
6552
+ abort: false,
6553
+ version: "v7",
6554
+ ...normalizeParams(params)
6555
+ });
6556
+ }
6557
+ function _url(Class, params) {
6558
+ return new Class({
6559
+ type: "string",
6560
+ format: "url",
6561
+ check: "string_format",
6562
+ abort: false,
6563
+ ...normalizeParams(params)
6564
+ });
6565
+ }
6566
+ function _emoji2(Class, params) {
6567
+ return new Class({
6568
+ type: "string",
6569
+ format: "emoji",
6570
+ check: "string_format",
6571
+ abort: false,
6572
+ ...normalizeParams(params)
6573
+ });
6574
+ }
6575
+ function _nanoid(Class, params) {
6576
+ return new Class({
6577
+ type: "string",
6578
+ format: "nanoid",
6579
+ check: "string_format",
6580
+ abort: false,
6581
+ ...normalizeParams(params)
6582
+ });
6583
+ }
6584
+ function _cuid(Class, params) {
6585
+ return new Class({
6586
+ type: "string",
6587
+ format: "cuid",
6588
+ check: "string_format",
6589
+ abort: false,
6590
+ ...normalizeParams(params)
6591
+ });
6592
+ }
6593
+ function _cuid2(Class, params) {
6594
+ return new Class({
6595
+ type: "string",
6596
+ format: "cuid2",
6597
+ check: "string_format",
6598
+ abort: false,
6599
+ ...normalizeParams(params)
6600
+ });
6601
+ }
6602
+ function _ulid(Class, params) {
6603
+ return new Class({
6604
+ type: "string",
6605
+ format: "ulid",
6606
+ check: "string_format",
6607
+ abort: false,
6608
+ ...normalizeParams(params)
6609
+ });
6610
+ }
6611
+ function _xid(Class, params) {
6612
+ return new Class({
6613
+ type: "string",
6614
+ format: "xid",
6615
+ check: "string_format",
6616
+ abort: false,
6617
+ ...normalizeParams(params)
6618
+ });
6619
+ }
6620
+ function _ksuid(Class, params) {
6621
+ return new Class({
6622
+ type: "string",
6623
+ format: "ksuid",
6624
+ check: "string_format",
6625
+ abort: false,
6626
+ ...normalizeParams(params)
6627
+ });
6628
+ }
6629
+ function _ipv4(Class, params) {
6630
+ return new Class({
6631
+ type: "string",
6632
+ format: "ipv4",
6633
+ check: "string_format",
6634
+ abort: false,
6635
+ ...normalizeParams(params)
6636
+ });
6637
+ }
6638
+ function _ipv6(Class, params) {
6639
+ return new Class({
6640
+ type: "string",
6641
+ format: "ipv6",
6642
+ check: "string_format",
6643
+ abort: false,
6644
+ ...normalizeParams(params)
6645
+ });
6646
+ }
6647
+ function _cidrv4(Class, params) {
6648
+ return new Class({
6649
+ type: "string",
6650
+ format: "cidrv4",
6651
+ check: "string_format",
6652
+ abort: false,
6653
+ ...normalizeParams(params)
6654
+ });
6655
+ }
6656
+ function _cidrv6(Class, params) {
6657
+ return new Class({
6658
+ type: "string",
6659
+ format: "cidrv6",
6660
+ check: "string_format",
6661
+ abort: false,
6662
+ ...normalizeParams(params)
6663
+ });
6664
+ }
6665
+ function _base64(Class, params) {
6666
+ return new Class({
6667
+ type: "string",
6668
+ format: "base64",
6669
+ check: "string_format",
6670
+ abort: false,
6671
+ ...normalizeParams(params)
6672
+ });
6673
+ }
6674
+ function _base64url(Class, params) {
6675
+ return new Class({
6676
+ type: "string",
6677
+ format: "base64url",
6678
+ check: "string_format",
6679
+ abort: false,
6680
+ ...normalizeParams(params)
6681
+ });
6682
+ }
6683
+ function _e164(Class, params) {
6684
+ return new Class({
6685
+ type: "string",
6686
+ format: "e164",
6687
+ check: "string_format",
6688
+ abort: false,
6689
+ ...normalizeParams(params)
6690
+ });
6691
+ }
6692
+ function _jwt(Class, params) {
6693
+ return new Class({
6694
+ type: "string",
6695
+ format: "jwt",
6696
+ check: "string_format",
6697
+ abort: false,
6698
+ ...normalizeParams(params)
6699
+ });
6700
+ }
6701
+ function _isoDateTime(Class, params) {
6702
+ return new Class({
6703
+ type: "string",
6704
+ format: "datetime",
6705
+ check: "string_format",
6706
+ offset: false,
6707
+ local: false,
6708
+ precision: null,
6709
+ ...normalizeParams(params)
6710
+ });
6711
+ }
6712
+ function _isoDate(Class, params) {
6713
+ return new Class({
6714
+ type: "string",
6715
+ format: "date",
6716
+ check: "string_format",
6717
+ ...normalizeParams(params)
6718
+ });
6719
+ }
6720
+ function _isoTime(Class, params) {
6721
+ return new Class({
6722
+ type: "string",
6723
+ format: "time",
6724
+ check: "string_format",
6725
+ precision: null,
6726
+ ...normalizeParams(params)
6727
+ });
6728
+ }
6729
+ function _isoDuration(Class, params) {
6730
+ return new Class({
6731
+ type: "string",
6732
+ format: "duration",
6733
+ check: "string_format",
6734
+ ...normalizeParams(params)
6735
+ });
6736
+ }
5508
6737
  function _number(Class, params) {
5509
6738
  return new Class(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) }));
5510
6739
  }
@@ -5595,12 +6824,73 @@ function _length(length, params) {
5595
6824
  length
5596
6825
  });
5597
6826
  }
6827
+ function _regex(pattern, params) {
6828
+ return new $ZodCheckRegex({
6829
+ check: "string_format",
6830
+ format: "regex",
6831
+ ...normalizeParams(params),
6832
+ pattern
6833
+ });
6834
+ }
6835
+ function _lowercase(params) {
6836
+ return new $ZodCheckLowerCase({
6837
+ check: "string_format",
6838
+ format: "lowercase",
6839
+ ...normalizeParams(params)
6840
+ });
6841
+ }
6842
+ function _uppercase(params) {
6843
+ return new $ZodCheckUpperCase({
6844
+ check: "string_format",
6845
+ format: "uppercase",
6846
+ ...normalizeParams(params)
6847
+ });
6848
+ }
6849
+ function _includes(includes, params) {
6850
+ return new $ZodCheckIncludes({
6851
+ check: "string_format",
6852
+ format: "includes",
6853
+ ...normalizeParams(params),
6854
+ includes
6855
+ });
6856
+ }
6857
+ function _startsWith(prefix, params) {
6858
+ return new $ZodCheckStartsWith({
6859
+ check: "string_format",
6860
+ format: "starts_with",
6861
+ ...normalizeParams(params),
6862
+ prefix
6863
+ });
6864
+ }
6865
+ function _endsWith(suffix, params) {
6866
+ return new $ZodCheckEndsWith({
6867
+ check: "string_format",
6868
+ format: "ends_with",
6869
+ ...normalizeParams(params),
6870
+ suffix
6871
+ });
6872
+ }
5598
6873
  function _overwrite(tx) {
5599
6874
  return new $ZodCheckOverwrite({
5600
6875
  check: "overwrite",
5601
6876
  tx
5602
6877
  });
5603
6878
  }
6879
+ function _normalize(form) {
6880
+ return _overwrite((input) => input.normalize(form));
6881
+ }
6882
+ function _trim() {
6883
+ return _overwrite((input) => input.trim());
6884
+ }
6885
+ function _toLowerCase() {
6886
+ return _overwrite((input) => input.toLowerCase());
6887
+ }
6888
+ function _toUpperCase() {
6889
+ return _overwrite((input) => input.toUpperCase());
6890
+ }
6891
+ function _slugify() {
6892
+ return _overwrite((input) => slugify(input));
6893
+ }
5604
6894
  function _array(Class, element, params) {
5605
6895
  return new Class({
5606
6896
  type: "array",
@@ -6258,10 +7548,50 @@ function aggregateChecks(schema) {
6258
7548
  addPattern(agg, pattern);
6259
7549
  return agg;
6260
7550
  }
7551
+ var formatMap = {
7552
+ guid: "uuid",
7553
+ url: "uri",
7554
+ datetime: "date-time",
7555
+ json_string: "json-string",
7556
+ regex: ""
7557
+ };
6261
7558
  var exactPatterns = new Map([
6262
7559
  [base64Charset, base64],
6263
7560
  [base64urlCharset, base64url]
6264
7561
  ]);
7562
+ var exactPattern = (p) => exactPatterns.get(p) ?? p;
7563
+ var stringProcessor = (schema, ctx, _json, _params) => {
7564
+ const json = _json;
7565
+ json.type = "string";
7566
+ const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
7567
+ if (typeof minimum === "number")
7568
+ json.minLength = minimum;
7569
+ if (typeof maximum === "number")
7570
+ json.maxLength = maximum;
7571
+ if (format) {
7572
+ json.format = formatMap[format] ?? format;
7573
+ if (json.format === "")
7574
+ delete json.format;
7575
+ if (format === "time" || laxFormat) {
7576
+ delete json.format;
7577
+ }
7578
+ }
7579
+ if (contentEncoding)
7580
+ json.contentEncoding = contentEncoding;
7581
+ if (patterns && patterns.size > 0) {
7582
+ const patternList = [...patterns].map(exactPattern);
7583
+ if (patternList.length === 1)
7584
+ json.pattern = patternList[0].source;
7585
+ else if (patternList.length > 1) {
7586
+ json.allOf = [
7587
+ ...patternList.map((regex) => ({
7588
+ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
7589
+ pattern: regex.source
7590
+ }))
7591
+ ];
7592
+ }
7593
+ }
7594
+ };
6265
7595
  var numberProcessor = (schema, ctx, _json, params) => {
6266
7596
  const json = _json;
6267
7597
  const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
@@ -6852,6 +8182,240 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
6852
8182
  return this._zod.def;
6853
8183
  }
6854
8184
  });
8185
+ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
8186
+ $ZodString.init(inst, def);
8187
+ ZodType.init(inst, def);
8188
+ inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
8189
+ }, /* @__PURE__ */ derived({
8190
+ format: (inst) => aggregateChecks(inst).format ?? null,
8191
+ minLength: (inst) => aggregateChecks(inst).minimum ?? null,
8192
+ maxLength: (inst) => aggregateChecks(inst).maximum ?? null
8193
+ }, {
8194
+ regex(...args) {
8195
+ return this.check(_regex(...args));
8196
+ },
8197
+ includes(...args) {
8198
+ return this.check(_includes(...args));
8199
+ },
8200
+ startsWith(...args) {
8201
+ return this.check(_startsWith(...args));
8202
+ },
8203
+ endsWith(...args) {
8204
+ return this.check(_endsWith(...args));
8205
+ },
8206
+ min(...args) {
8207
+ return this.check(_minLength(...args));
8208
+ },
8209
+ max(...args) {
8210
+ return this.check(_maxLength(...args));
8211
+ },
8212
+ length(...args) {
8213
+ return this.check(_length(...args));
8214
+ },
8215
+ nonempty(...args) {
8216
+ return this.check(_minLength(1, ...args));
8217
+ },
8218
+ lowercase(params) {
8219
+ return this.check(_lowercase(params));
8220
+ },
8221
+ uppercase(params) {
8222
+ return this.check(_uppercase(params));
8223
+ },
8224
+ trim() {
8225
+ return this.check(_trim());
8226
+ },
8227
+ normalize(...args) {
8228
+ return this.check(_normalize(...args));
8229
+ },
8230
+ toLowerCase() {
8231
+ return this.check(_toLowerCase());
8232
+ },
8233
+ toUpperCase() {
8234
+ return this.check(_toUpperCase());
8235
+ },
8236
+ slugify() {
8237
+ return this.check(_slugify());
8238
+ }
8239
+ }));
8240
+ var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
8241
+ $ZodString.init(inst, def);
8242
+ _ZodString.init(inst, def);
8243
+ }, {
8244
+ email(params) {
8245
+ return this.check(_email(ZodEmail, params));
8246
+ },
8247
+ url(params) {
8248
+ return this.check(_url(ZodURL, params));
8249
+ },
8250
+ jwt(params) {
8251
+ return this.check(_jwt(ZodJWT, params));
8252
+ },
8253
+ emoji(params) {
8254
+ return this.check(_emoji2(ZodEmoji, params));
8255
+ },
8256
+ guid(params) {
8257
+ return this.check(_guid(ZodGUID, params));
8258
+ },
8259
+ uuid(params) {
8260
+ return this.check(_uuid(ZodUUID, params));
8261
+ },
8262
+ uuidv4(params) {
8263
+ return this.check(_uuidv4(ZodUUID, params));
8264
+ },
8265
+ uuidv6(params) {
8266
+ return this.check(_uuidv6(ZodUUID, params));
8267
+ },
8268
+ uuidv7(params) {
8269
+ return this.check(_uuidv7(ZodUUID, params));
8270
+ },
8271
+ nanoid(params) {
8272
+ return this.check(_nanoid(ZodNanoID, params));
8273
+ },
8274
+ cuid(params) {
8275
+ return this.check(_cuid(ZodCUID, params));
8276
+ },
8277
+ cuid2(params) {
8278
+ return this.check(_cuid2(ZodCUID2, params));
8279
+ },
8280
+ ulid(params) {
8281
+ return this.check(_ulid(ZodULID, params));
8282
+ },
8283
+ base64(params) {
8284
+ return this.check(_base64(ZodBase64, params));
8285
+ },
8286
+ base64url(params) {
8287
+ return this.check(_base64url(ZodBase64URL, params));
8288
+ },
8289
+ xid(params) {
8290
+ return this.check(_xid(ZodXID, params));
8291
+ },
8292
+ ksuid(params) {
8293
+ return this.check(_ksuid(ZodKSUID, params));
8294
+ },
8295
+ ipv4(params) {
8296
+ return this.check(_ipv4(ZodIPv4, params));
8297
+ },
8298
+ ipv6(params) {
8299
+ return this.check(_ipv6(ZodIPv6, params));
8300
+ },
8301
+ cidrv4(params) {
8302
+ return this.check(_cidrv4(ZodCIDRv4, params));
8303
+ },
8304
+ cidrv6(params) {
8305
+ return this.check(_cidrv6(ZodCIDRv6, params));
8306
+ },
8307
+ e164(params) {
8308
+ return this.check(_e164(ZodE164, params));
8309
+ },
8310
+ datetime(params) {
8311
+ return this.check(_isoDateTime(ZodISODateTime, params));
8312
+ },
8313
+ date(params) {
8314
+ return this.check(_isoDate(ZodISODate, params));
8315
+ },
8316
+ time(params) {
8317
+ return this.check(_isoTime(ZodISOTime, params));
8318
+ },
8319
+ duration(params) {
8320
+ return this.check(_isoDuration(ZodISODuration, params));
8321
+ }
8322
+ });
8323
+ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
8324
+ $ZodStringFormat.init(inst, def);
8325
+ _ZodString.init(inst, def);
8326
+ });
8327
+ var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
8328
+ $ZodISODateTime.init(inst, def);
8329
+ ZodStringFormat.init(inst, def);
8330
+ });
8331
+ var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
8332
+ $ZodISODate.init(inst, def);
8333
+ ZodStringFormat.init(inst, def);
8334
+ });
8335
+ var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
8336
+ $ZodISOTime.init(inst, def);
8337
+ ZodStringFormat.init(inst, def);
8338
+ });
8339
+ var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
8340
+ $ZodISODuration.init(inst, def);
8341
+ ZodStringFormat.init(inst, def);
8342
+ });
8343
+ var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
8344
+ $ZodEmail.init(inst, def);
8345
+ ZodStringFormat.init(inst, def);
8346
+ });
8347
+ var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
8348
+ $ZodGUID.init(inst, def);
8349
+ ZodStringFormat.init(inst, def);
8350
+ });
8351
+ var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
8352
+ $ZodUUID.init(inst, def);
8353
+ ZodStringFormat.init(inst, def);
8354
+ });
8355
+ var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
8356
+ $ZodURL.init(inst, def);
8357
+ ZodStringFormat.init(inst, def);
8358
+ });
8359
+ var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
8360
+ $ZodEmoji.init(inst, def);
8361
+ ZodStringFormat.init(inst, def);
8362
+ });
8363
+ var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
8364
+ $ZodNanoID.init(inst, def);
8365
+ ZodStringFormat.init(inst, def);
8366
+ });
8367
+ var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
8368
+ $ZodCUID.init(inst, def);
8369
+ ZodStringFormat.init(inst, def);
8370
+ });
8371
+ var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
8372
+ $ZodCUID2.init(inst, def);
8373
+ ZodStringFormat.init(inst, def);
8374
+ });
8375
+ var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
8376
+ $ZodULID.init(inst, def);
8377
+ ZodStringFormat.init(inst, def);
8378
+ });
8379
+ var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
8380
+ $ZodXID.init(inst, def);
8381
+ ZodStringFormat.init(inst, def);
8382
+ });
8383
+ var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
8384
+ $ZodKSUID.init(inst, def);
8385
+ ZodStringFormat.init(inst, def);
8386
+ });
8387
+ var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
8388
+ $ZodIPv4.init(inst, def);
8389
+ ZodStringFormat.init(inst, def);
8390
+ });
8391
+ var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
8392
+ $ZodIPv6.init(inst, def);
8393
+ ZodStringFormat.init(inst, def);
8394
+ });
8395
+ var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
8396
+ $ZodCIDRv4.init(inst, def);
8397
+ ZodStringFormat.init(inst, def);
8398
+ });
8399
+ var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
8400
+ $ZodCIDRv6.init(inst, def);
8401
+ ZodStringFormat.init(inst, def);
8402
+ });
8403
+ var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
8404
+ $ZodBase64.init(inst, def);
8405
+ ZodStringFormat.init(inst, def);
8406
+ });
8407
+ var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
8408
+ $ZodBase64URL.init(inst, def);
8409
+ ZodStringFormat.init(inst, def);
8410
+ });
8411
+ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
8412
+ $ZodE164.init(inst, def);
8413
+ ZodStringFormat.init(inst, def);
8414
+ });
8415
+ var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
8416
+ $ZodJWT.init(inst, def);
8417
+ ZodStringFormat.init(inst, def);
8418
+ });
6855
8419
  var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
6856
8420
  $ZodNumber.init(inst, def);
6857
8421
  ZodType.init(inst, def);
@@ -8753,10 +10317,10 @@ var collect = async (items) => {
8753
10317
  var readConfigurationState = async (client, config) => {
8754
10318
  const presetsNamePolicies = Object.values(config.uploadPresets ?? {}).some((preset) => preset.policy !== undefined);
8755
10319
  const [policies, assignedPolicy, uploadPresets, lenses, metadataFields, settings] = await Promise.all([
8756
- config.policies || config.policy !== undefined || presetsNamePolicies ? collect(client.policies.iterate()) : [],
10320
+ config.policies || config.policy !== undefined || presetsNamePolicies ? collect(client.policies.list()) : [],
8757
10321
  config.policy !== undefined ? client.policies.retrieveAssigned() : undefined,
8758
- config.uploadPresets ? collect(client.uploadPresets.iterate()) : [],
8759
- config.lenses ? collect(client.lenses.iterate()) : [],
10322
+ config.uploadPresets ? collect(client.uploadPresets.list()) : [],
10323
+ config.lenses ? collect(client.lenses.list()) : [],
8760
10324
  config.metadataFields ? client.metadataFields.list() : undefined,
8761
10325
  config.settings ? client.projectSettings.get() : undefined
8762
10326
  ]);
@@ -9007,7 +10571,7 @@ var applyConfiguration = async (client, config, state, plan, log = () => {}) =>
9007
10571
  // src/cli/listen.ts
9008
10572
  import { randomBytes } from "node:crypto";
9009
10573
 
9010
- // src/contract/Ids-BESMSxGb.js
10574
+ // src/contract/Ids-l0is4BI5.js
9011
10575
  var __defProp = Object.defineProperty;
9012
10576
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
9013
10577
  var __exportAll = (all, no_symbols) => {
@@ -9173,7 +10737,7 @@ var allowsEval2 = /* @__PURE__ */ cached2(() => {
9173
10737
  return false;
9174
10738
  }
9175
10739
  });
9176
- function isPlainObject3(o) {
10740
+ function isPlainObject4(o) {
9177
10741
  if (isObject3(o) === false)
9178
10742
  return false;
9179
10743
  const ctor = o.constructor;
@@ -9189,7 +10753,7 @@ function isPlainObject3(o) {
9189
10753
  return true;
9190
10754
  }
9191
10755
  function shallowClone2(o) {
9192
- if (isPlainObject3(o))
10756
+ if (isPlainObject4(o))
9193
10757
  return { ...o };
9194
10758
  if (Array.isArray(o))
9195
10759
  return [...o];
@@ -9300,7 +10864,7 @@ function omit2(schema, mask) {
9300
10864
  }));
9301
10865
  }
9302
10866
  function extend2(schema, shape) {
9303
- if (!isPlainObject3(shape))
10867
+ if (!isPlainObject4(shape))
9304
10868
  throw new Error("Invalid input to extend: expected a plain object");
9305
10869
  const checks = schema._zod.def.checks;
9306
10870
  if (checks && checks.length > 0) {
@@ -9318,7 +10882,7 @@ function extended2(schema, shape) {
9318
10882
  return newShape;
9319
10883
  }
9320
10884
  function safeExtend2(schema, shape) {
9321
- if (!isPlainObject3(shape))
10885
+ if (!isPlainObject4(shape))
9322
10886
  throw new Error("Invalid input to safeExtend: expected a plain object");
9323
10887
  return clone2(schema, mergeDefs2(schema._zod.def, { shape: extended2(schema, shape) }));
9324
10888
  }
@@ -10105,7 +11669,7 @@ var regexes_exports = /* @__PURE__ */ __exportAll({
10105
11669
  ipv4: () => ipv4$1,
10106
11670
  ipv6: () => ipv6$1,
10107
11671
  ksuid: () => ksuid$1,
10108
- lowercase: () => lowercase,
11672
+ lowercase: () => lowercase2,
10109
11673
  mac: () => mac$1,
10110
11674
  md5_base64: () => md5_base64,
10111
11675
  md5_base64url: () => md5_base64url,
@@ -10132,7 +11696,7 @@ var regexes_exports = /* @__PURE__ */ __exportAll({
10132
11696
  ulid: () => ulid$1,
10133
11697
  undefined: () => _undefined$2,
10134
11698
  unicodeEmail: () => unicodeEmail,
10135
- uppercase: () => uppercase,
11699
+ uppercase: () => uppercase2,
10136
11700
  uuid: () => uuid$1,
10137
11701
  uuid4: () => uuid4,
10138
11702
  uuid6: () => uuid6,
@@ -10186,28 +11750,28 @@ var e164$1 = /^\+[1-9]\d{6,14}$/;
10186
11750
  var creditCard$1 = /^\d(?:[ -]?\d){11,18}$/;
10187
11751
  var currencyCode$1 = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;
10188
11752
  var iban$1 = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/;
10189
- var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
10190
- function anchor(source) {
11753
+ var dateSource2 = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
11754
+ function anchor2(source) {
10191
11755
  return new RegExp(`^${source}$`);
10192
11756
  }
10193
- var date$2 = /* @__PURE__ */ anchor(dateSource);
10194
- function timeSource(args) {
11757
+ var date$2 = /* @__PURE__ */ anchor2(dateSource2);
11758
+ function timeSource2(args) {
10195
11759
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
10196
11760
  return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
10197
11761
  }
10198
11762
  function time$1(args) {
10199
- return new RegExp(`^${timeSource(args)}$`);
11763
+ return new RegExp(`^${timeSource2(args)}$`);
10200
11764
  }
10201
11765
  function datetime$1(args) {
10202
11766
  const opts = ["Z"];
10203
11767
  if (args.offset)
10204
11768
  opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
10205
- const qualified = `${timeSource({
11769
+ const qualified = `${timeSource2({
10206
11770
  precision: args.precision,
10207
11771
  seconds: true
10208
11772
  })}(?:${opts.join("|")})`;
10209
- const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
10210
- return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
11773
+ const timeRegex = args.local ? `${qualified}|${timeSource2({ precision: args.precision })}` : qualified;
11774
+ return new RegExp(`^${dateSource2}T(?:${timeRegex})$`);
10211
11775
  }
10212
11776
  var anyString2 = /^[\s\S]{0,}$/;
10213
11777
  var string$1 = (params) => {
@@ -10220,8 +11784,8 @@ var number$1 = /^-?\d+(?:\.\d+)?$/;
10220
11784
  var boolean$1 = /^(?:true|false)$/i;
10221
11785
  var _null$2 = /^null$/i;
10222
11786
  var _undefined$2 = /^undefined$/i;
10223
- var lowercase = /^[^A-Z]*$/;
10224
- var uppercase = /^[^a-z]*$/;
11787
+ var lowercase2 = /^[^A-Z]*$/;
11788
+ var uppercase2 = /^[^a-z]*$/;
10225
11789
  var hex$1 = /^[0-9a-fA-F]*$/;
10226
11790
  function fixedBase64(bodyLength, padding) {
10227
11791
  return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
@@ -10584,11 +12148,11 @@ var $ZodCheckRegex2 = /* @__PURE__ */ $constructor2("$ZodCheckRegex", (inst, def
10584
12148
  };
10585
12149
  });
10586
12150
  var $ZodCheckLowerCase2 = /* @__PURE__ */ $constructor2("$ZodCheckLowerCase", (inst, def) => {
10587
- def.pattern ?? (def.pattern = lowercase);
12151
+ def.pattern ?? (def.pattern = lowercase2);
10588
12152
  $ZodCheckStringFormat2.init(inst, def);
10589
12153
  });
10590
12154
  var $ZodCheckUpperCase2 = /* @__PURE__ */ $constructor2("$ZodCheckUpperCase", (inst, def) => {
10591
- def.pattern ?? (def.pattern = uppercase);
12155
+ def.pattern ?? (def.pattern = uppercase2);
10592
12156
  $ZodCheckStringFormat2.init(inst, def);
10593
12157
  });
10594
12158
  var $ZodCheckIncludes2 = /* @__PURE__ */ $constructor2("$ZodCheckIncludes", (inst, def) => {
@@ -10940,7 +12504,7 @@ var $ZodEmail2 = /* @__PURE__ */ $constructor2("$ZodEmail", (inst, def) => {
10940
12504
  def.pattern ?? (def.pattern = email$1);
10941
12505
  $ZodStringFormat2.init(inst, def);
10942
12506
  });
10943
- function canParseURL(input) {
12507
+ function canParseURL2(input) {
10944
12508
  try {
10945
12509
  if (typeof URL !== "undefined" && typeof URL.canParse === "function")
10946
12510
  return URL.canParse(input);
@@ -10950,12 +12514,12 @@ function canParseURL(input) {
10950
12514
  return false;
10951
12515
  }
10952
12516
  }
10953
- function validateURL(trimmed, def) {
12517
+ function validateURL2(trimmed, def) {
10954
12518
  if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def))
10955
- return canParseURL(trimmed) || 2;
10956
- return parseURLObject(trimmed, def);
12519
+ return canParseURL2(trimmed) || 2;
12520
+ return parseURLObject2(trimmed, def);
10957
12521
  }
10958
- function parseURLObject(trimmed, def) {
12522
+ function parseURLObject2(trimmed, def) {
10959
12523
  if (!def.normalize && def.protocol?.source === httpProtocol2.source && !/^https?:\/\//i.test(trimmed))
10960
12524
  return 1;
10961
12525
  try {
@@ -10969,15 +12533,15 @@ function parseURLObject(trimmed, def) {
10969
12533
  return 2;
10970
12534
  }
10971
12535
  }
10972
- var asciiTabOrNewline = /[\t\n\r]/g;
10973
- function stripTabAndNewline(value) {
10974
- return value.replace(asciiTabOrNewline, "");
12536
+ var asciiTabOrNewline2 = /[\t\n\r]/g;
12537
+ function stripTabAndNewline2(value) {
12538
+ return value.replace(asciiTabOrNewline2, "");
10975
12539
  }
10976
- function urlHostnameOk(url, hostname) {
12540
+ function urlHostnameOk2(url, hostname) {
10977
12541
  hostname.lastIndex = 0;
10978
12542
  return hostname.test(url.hostname);
10979
12543
  }
10980
- function urlProtocolOk(url, protocol) {
12544
+ function urlProtocolOk2(url, protocol) {
10981
12545
  protocol.lastIndex = 0;
10982
12546
  return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
10983
12547
  }
@@ -10986,7 +12550,7 @@ var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => {
10986
12550
  inst._zod.check = (payload) => {
10987
12551
  try {
10988
12552
  const trimmed = payload.value.trim();
10989
- const url = validateURL(trimmed, def);
12553
+ const url = validateURL2(trimmed, def);
10990
12554
  if (url === 1) {
10991
12555
  payload.issues.push({
10992
12556
  code: "invalid_format",
@@ -11009,10 +12573,10 @@ var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => {
11009
12573
  return;
11010
12574
  }
11011
12575
  if (url === true) {
11012
- payload.value = stripTabAndNewline(trimmed);
12576
+ payload.value = stripTabAndNewline2(trimmed);
11013
12577
  return;
11014
12578
  }
11015
- if (def.hostname && !urlHostnameOk(url, def.hostname))
12579
+ if (def.hostname && !urlHostnameOk2(url, def.hostname))
11016
12580
  payload.issues.push({
11017
12581
  code: "invalid_format",
11018
12582
  format: "url",
@@ -11022,7 +12586,7 @@ var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => {
11022
12586
  inst,
11023
12587
  continue: !def.abort
11024
12588
  });
11025
- if (def.protocol && !urlProtocolOk(url, def.protocol))
12589
+ if (def.protocol && !urlProtocolOk2(url, def.protocol))
11026
12590
  payload.issues.push({
11027
12591
  code: "invalid_format",
11028
12592
  format: "url",
@@ -11032,7 +12596,7 @@ var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => {
11032
12596
  inst,
11033
12597
  continue: !def.abort
11034
12598
  });
11035
- payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);
12599
+ payload.value = def.normalize ? url.href : stripTabAndNewline2(trimmed);
11036
12600
  return;
11037
12601
  } catch (_) {
11038
12602
  payload.issues.push({
@@ -11095,17 +12659,17 @@ var $ZodIPv42 = /* @__PURE__ */ $constructor2("$ZodIPv4", (inst, def) => {
11095
12659
  def.pattern ?? (def.pattern = ipv4$1);
11096
12660
  $ZodStringFormat2.init(inst, def);
11097
12661
  });
11098
- var ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
11099
- function isValidIPv6(value) {
11100
- if (!ipv6Alphabet.test(value))
12662
+ var ipv6Alphabet2 = /^[0-9a-fA-F:.]+$/;
12663
+ function isValidIPv62(value) {
12664
+ if (!ipv6Alphabet2.test(value))
11101
12665
  return false;
11102
- return canParseURL(`http://[${value}]`);
12666
+ return canParseURL2(`http://[${value}]`);
11103
12667
  }
11104
12668
  var $ZodIPv62 = /* @__PURE__ */ $constructor2("$ZodIPv6", (inst, def) => {
11105
12669
  def.pattern ?? (def.pattern = ipv6$1);
11106
12670
  $ZodStringFormat2.init(inst, def);
11107
12671
  inst._zod.check = (payload) => {
11108
- if (!isValidIPv6(payload.value))
12672
+ if (!isValidIPv62(payload.value))
11109
12673
  payload.issues.push({
11110
12674
  code: "invalid_format",
11111
12675
  format: "ipv6",
@@ -11123,7 +12687,7 @@ var $ZodCIDRv42 = /* @__PURE__ */ $constructor2("$ZodCIDRv4", (inst, def) => {
11123
12687
  def.pattern ?? (def.pattern = cidrv4$1);
11124
12688
  $ZodStringFormat2.init(inst, def);
11125
12689
  });
11126
- function isValidCIDRv6(value) {
12690
+ function isValidCIDRv62(value) {
11127
12691
  const parts = value.split("/");
11128
12692
  if (parts.length !== 2)
11129
12693
  return false;
@@ -11135,13 +12699,13 @@ function isValidCIDRv6(value) {
11135
12699
  return false;
11136
12700
  if (prefixNum < 0 || prefixNum > 128)
11137
12701
  return false;
11138
- return isValidIPv6(address);
12702
+ return isValidIPv62(address);
11139
12703
  }
11140
12704
  var $ZodCIDRv62 = /* @__PURE__ */ $constructor2("$ZodCIDRv6", (inst, def) => {
11141
12705
  def.pattern ?? (def.pattern = cidrv6$1);
11142
12706
  $ZodStringFormat2.init(inst, def);
11143
12707
  inst._zod.check = (payload) => {
11144
- if (!isValidCIDRv6(payload.value))
12708
+ if (!isValidCIDRv62(payload.value))
11145
12709
  payload.issues.push({
11146
12710
  code: "invalid_format",
11147
12711
  format: "cidrv6",
@@ -11151,7 +12715,7 @@ var $ZodCIDRv62 = /* @__PURE__ */ $constructor2("$ZodCIDRv6", (inst, def) => {
11151
12715
  });
11152
12716
  };
11153
12717
  });
11154
- function isValidBase64(data) {
12718
+ function isValidBase642(data) {
11155
12719
  if (data === "")
11156
12720
  return true;
11157
12721
  if (/\s/.test(data))
@@ -11170,7 +12734,7 @@ var $ZodBase642 = /* @__PURE__ */ $constructor2("$ZodBase64", (inst, def) => {
11170
12734
  def.pattern ?? (def.pattern = base64Charset2);
11171
12735
  $ZodStringFormat2.init(inst, def);
11172
12736
  inst._zod.check = (payload) => {
11173
- if (isValidBase64(payload.value))
12737
+ if (isValidBase642(payload.value))
11174
12738
  return;
11175
12739
  payload.issues.push({
11176
12740
  code: "invalid_format",
@@ -11182,17 +12746,17 @@ var $ZodBase642 = /* @__PURE__ */ $constructor2("$ZodBase64", (inst, def) => {
11182
12746
  };
11183
12747
  });
11184
12748
  var base64urlCharset2 = /^[A-Za-z0-9_-]*$/;
11185
- function isValidBase64URL(data) {
12749
+ function isValidBase64URL2(data) {
11186
12750
  if (!base64urlCharset2.test(data))
11187
12751
  return false;
11188
12752
  const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
11189
- return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
12753
+ return isValidBase642(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
11190
12754
  }
11191
12755
  var $ZodBase64URL2 = /* @__PURE__ */ $constructor2("$ZodBase64URL", (inst, def) => {
11192
12756
  def.pattern ?? (def.pattern = base64urlCharset2);
11193
12757
  $ZodStringFormat2.init(inst, def);
11194
12758
  inst._zod.check = (payload) => {
11195
- if (isValidBase64URL(payload.value))
12759
+ if (isValidBase64URL2(payload.value))
11196
12760
  return;
11197
12761
  payload.issues.push({
11198
12762
  code: "invalid_format",
@@ -11283,7 +12847,7 @@ var $ZodIBAN2 = /* @__PURE__ */ $constructor2("$ZodIBAN", (inst, def) => {
11283
12847
  });
11284
12848
  };
11285
12849
  });
11286
- function isValidJWT(token, algorithm = null) {
12850
+ function isValidJWT2(token, algorithm = null) {
11287
12851
  try {
11288
12852
  const tokensParts = token.split(".");
11289
12853
  if (tokensParts.length !== 3)
@@ -11306,7 +12870,7 @@ function isValidJWT(token, algorithm = null) {
11306
12870
  var $ZodJWT2 = /* @__PURE__ */ $constructor2("$ZodJWT", (inst, def) => {
11307
12871
  $ZodStringFormat2.init(inst, def);
11308
12872
  inst._zod.check = (payload) => {
11309
- if (isValidJWT(payload.value, def.alg))
12873
+ if (isValidJWT2(payload.value, def.alg))
11310
12874
  return;
11311
12875
  payload.issues.push({
11312
12876
  code: "invalid_format",
@@ -12092,7 +13656,7 @@ function mergeValues2(a, b) {
12092
13656
  valid: true,
12093
13657
  data: a
12094
13658
  };
12095
- if (isPlainObject3(a) && isPlainObject3(b)) {
13659
+ if (isPlainObject4(a) && isPlainObject4(b)) {
12096
13660
  const bKeys = Object.keys(b);
12097
13661
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
12098
13662
  const newObj = {
@@ -12322,7 +13886,7 @@ var $ZodRecord2 = /* @__PURE__ */ $constructor2("$ZodRecord", (inst, def) => {
12322
13886
  memo?.attach(inst);
12323
13887
  inst._zod.parse = (payload, ctx) => {
12324
13888
  const input = payload.value;
12325
- if (!isPlainObject3(input)) {
13889
+ if (!isPlainObject4(input)) {
12326
13890
  payload.issues.push({
12327
13891
  expected: "record",
12328
13892
  code: "invalid_type",
@@ -13676,7 +15240,7 @@ function _url2(Class, params) {
13676
15240
  ...normalizeParams2(params)
13677
15241
  });
13678
15242
  }
13679
- function _emoji2(Class, params) {
15243
+ function _emoji3(Class, params) {
13680
15244
  return new Class({
13681
15245
  type: "string",
13682
15246
  format: "emoji",
@@ -14957,7 +16521,7 @@ function aggregateChecks2(schema) {
14957
16521
  addPattern2(agg, pattern);
14958
16522
  return agg;
14959
16523
  }
14960
- var formatMap = {
16524
+ var formatMap2 = {
14961
16525
  guid: "uuid",
14962
16526
  url: "uri",
14963
16527
  datetime: "date-time",
@@ -14965,7 +16529,7 @@ var formatMap = {
14965
16529
  regex: ""
14966
16530
  };
14967
16531
  var exactPatterns2 = /* @__PURE__ */ new Map([[base64Charset2, base64$1], [base64urlCharset2, base64url$1]]);
14968
- var exactPattern = (p) => exactPatterns2.get(p) ?? p;
16532
+ var exactPattern2 = (p) => exactPatterns2.get(p) ?? p;
14969
16533
  var stringProcessor2 = (schema, ctx, _json, _params) => {
14970
16534
  const json = _json;
14971
16535
  json.type = "string";
@@ -14975,7 +16539,7 @@ var stringProcessor2 = (schema, ctx, _json, _params) => {
14975
16539
  if (typeof maximum === "number")
14976
16540
  json.maxLength = maximum;
14977
16541
  if (format) {
14978
- json.format = formatMap[format] ?? format;
16542
+ json.format = formatMap2[format] ?? format;
14979
16543
  if (json.format === "")
14980
16544
  delete json.format;
14981
16545
  if (format === "time" || laxFormat)
@@ -14984,7 +16548,7 @@ var stringProcessor2 = (schema, ctx, _json, _params) => {
14984
16548
  if (contentEncoding)
14985
16549
  json.contentEncoding = contentEncoding;
14986
16550
  if (patterns && patterns.size > 0) {
14987
- const patternList = [...patterns].map(exactPattern);
16551
+ const patternList = [...patterns].map(exactPattern2);
14988
16552
  if (patternList.length === 1)
14989
16553
  json.pattern = patternList[0].source;
14990
16554
  else if (patternList.length > 1)
@@ -15401,7 +16965,7 @@ var recordProcessor2 = (schema, ctx, _json, params) => {
15401
16965
  });
15402
16966
  json.patternProperties = {};
15403
16967
  for (const pattern of patterns)
15404
- assignProp2(json.patternProperties, exactPattern(pattern).source, valueSchema);
16968
+ assignProp2(json.patternProperties, exactPattern2(pattern).source, valueSchema);
15405
16969
  } else {
15406
16970
  if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
15407
16971
  json.propertyNames = processSchema2(def.keyType, ctx, {
@@ -15622,15 +17186,15 @@ var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync2(ZodRealError2);
15622
17186
  var schemas_exports = /* @__PURE__ */ __exportAll({
15623
17187
  ZodAny: () => ZodAny,
15624
17188
  ZodArray: () => ZodArray2,
15625
- ZodBase64: () => ZodBase64,
15626
- ZodBase64URL: () => ZodBase64URL,
17189
+ ZodBase64: () => ZodBase642,
17190
+ ZodBase64URL: () => ZodBase64URL2,
15627
17191
  ZodBigInt: () => ZodBigInt,
15628
17192
  ZodBigIntFormat: () => ZodBigIntFormat,
15629
17193
  ZodBoolean: () => ZodBoolean2,
15630
- ZodCIDRv4: () => ZodCIDRv4,
15631
- ZodCIDRv6: () => ZodCIDRv6,
15632
- ZodCUID: () => ZodCUID,
15633
- ZodCUID2: () => ZodCUID2,
17194
+ ZodCIDRv4: () => ZodCIDRv42,
17195
+ ZodCIDRv6: () => ZodCIDRv62,
17196
+ ZodCUID: () => ZodCUID3,
17197
+ ZodCUID2: () => ZodCUID22,
15634
17198
  ZodCatch: () => ZodCatch2,
15635
17199
  ZodCodec: () => ZodCodec,
15636
17200
  ZodCreditCard: () => ZodCreditCard,
@@ -15639,31 +17203,31 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
15639
17203
  ZodDate: () => ZodDate,
15640
17204
  ZodDefault: () => ZodDefault2,
15641
17205
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
15642
- ZodE164: () => ZodE164,
15643
- ZodEmail: () => ZodEmail,
15644
- ZodEmoji: () => ZodEmoji,
17206
+ ZodE164: () => ZodE1642,
17207
+ ZodEmail: () => ZodEmail2,
17208
+ ZodEmoji: () => ZodEmoji2,
15645
17209
  ZodEnum: () => ZodEnum2,
15646
17210
  ZodExactOptional: () => ZodExactOptional2,
15647
17211
  ZodFile: () => ZodFile,
15648
17212
  ZodFunction: () => ZodFunction,
15649
- ZodGUID: () => ZodGUID,
17213
+ ZodGUID: () => ZodGUID2,
15650
17214
  ZodIBAN: () => ZodIBAN,
15651
- ZodIPv4: () => ZodIPv4,
15652
- ZodIPv6: () => ZodIPv6,
15653
- ZodISODate: () => ZodISODate,
15654
- ZodISODateTime: () => ZodISODateTime,
15655
- ZodISODuration: () => ZodISODuration,
15656
- ZodISOTime: () => ZodISOTime,
17215
+ ZodIPv4: () => ZodIPv42,
17216
+ ZodIPv6: () => ZodIPv62,
17217
+ ZodISODate: () => ZodISODate2,
17218
+ ZodISODateTime: () => ZodISODateTime2,
17219
+ ZodISODuration: () => ZodISODuration2,
17220
+ ZodISOTime: () => ZodISOTime2,
15657
17221
  ZodInstanceOf: () => ZodInstanceOf,
15658
17222
  ZodIntersection: () => ZodIntersection2,
15659
- ZodJWT: () => ZodJWT,
15660
- ZodKSUID: () => ZodKSUID,
17223
+ ZodJWT: () => ZodJWT2,
17224
+ ZodKSUID: () => ZodKSUID2,
15661
17225
  ZodLazy: () => ZodLazy,
15662
17226
  ZodLiteral: () => ZodLiteral2,
15663
17227
  ZodMAC: () => ZodMAC,
15664
17228
  ZodMap: () => ZodMap,
15665
17229
  ZodNaN: () => ZodNaN,
15666
- ZodNanoID: () => ZodNanoID,
17230
+ ZodNanoID: () => ZodNanoID2,
15667
17231
  ZodNever: () => ZodNever2,
15668
17232
  ZodNonOptional: () => ZodNonOptional2,
15669
17233
  ZodNull: () => ZodNull,
@@ -15679,24 +17243,24 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
15679
17243
  ZodReadonly: () => ZodReadonly2,
15680
17244
  ZodRecord: () => ZodRecord,
15681
17245
  ZodSet: () => ZodSet,
15682
- ZodString: () => ZodString,
15683
- ZodStringFormat: () => ZodStringFormat,
17246
+ ZodString: () => ZodString2,
17247
+ ZodStringFormat: () => ZodStringFormat2,
15684
17248
  ZodSuccess: () => ZodSuccess,
15685
17249
  ZodSymbol: () => ZodSymbol,
15686
17250
  ZodTemplateLiteral: () => ZodTemplateLiteral,
15687
17251
  ZodTransform: () => ZodTransform2,
15688
17252
  ZodTuple: () => ZodTuple2,
15689
17253
  ZodType: () => ZodType2,
15690
- ZodULID: () => ZodULID,
15691
- ZodURL: () => ZodURL,
15692
- ZodUUID: () => ZodUUID,
17254
+ ZodULID: () => ZodULID2,
17255
+ ZodURL: () => ZodURL2,
17256
+ ZodUUID: () => ZodUUID2,
15693
17257
  ZodUndefined: () => ZodUndefined,
15694
17258
  ZodUnion: () => ZodUnion2,
15695
17259
  ZodUnknown: () => ZodUnknown2,
15696
17260
  ZodVoid: () => ZodVoid,
15697
- ZodXID: () => ZodXID,
17261
+ ZodXID: () => ZodXID2,
15698
17262
  ZodXor: () => ZodXor,
15699
- _ZodString: () => _ZodString,
17263
+ _ZodString: () => _ZodString2,
15700
17264
  _default: () => _default2,
15701
17265
  _function: () => _function,
15702
17266
  any: () => any,
@@ -15773,7 +17337,7 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
15773
17337
  refine: () => refine2,
15774
17338
  set: () => set,
15775
17339
  strictObject: () => strictObject,
15776
- string: () => string2,
17340
+ string: () => string3,
15777
17341
  stringFormat: () => stringFormat,
15778
17342
  stringbool: () => stringbool,
15779
17343
  success: () => success,
@@ -15975,7 +17539,7 @@ var ZodType2 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => {
15975
17539
  return this._zod.def;
15976
17540
  }
15977
17541
  });
15978
- var _ZodString = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => {
17542
+ var _ZodString2 = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => {
15979
17543
  $ZodString2.init(inst, def);
15980
17544
  ZodType2.init(inst, def);
15981
17545
  inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor2(inst, ctx, json, params);
@@ -16030,285 +17594,285 @@ var _ZodString = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => {
16030
17594
  return this.check(/* @__PURE__ */ _slugify2());
16031
17595
  }
16032
17596
  }));
16033
- var ZodString = /* @__PURE__ */ $constructor2("ZodString", (inst, def) => {
17597
+ var ZodString2 = /* @__PURE__ */ $constructor2("ZodString", (inst, def) => {
16034
17598
  $ZodString2.init(inst, def);
16035
- _ZodString.init(inst, def);
17599
+ _ZodString2.init(inst, def);
16036
17600
  }, {
16037
17601
  email(params) {
16038
- return this.check(/* @__PURE__ */ _email2(ZodEmail, params));
17602
+ return this.check(/* @__PURE__ */ _email2(ZodEmail2, params));
16039
17603
  },
16040
17604
  url(params) {
16041
- return this.check(/* @__PURE__ */ _url2(ZodURL, params));
17605
+ return this.check(/* @__PURE__ */ _url2(ZodURL2, params));
16042
17606
  },
16043
17607
  jwt(params) {
16044
- return this.check(/* @__PURE__ */ _jwt2(ZodJWT, params));
17608
+ return this.check(/* @__PURE__ */ _jwt2(ZodJWT2, params));
16045
17609
  },
16046
17610
  emoji(params) {
16047
- return this.check(/* @__PURE__ */ _emoji2(ZodEmoji, params));
17611
+ return this.check(/* @__PURE__ */ _emoji3(ZodEmoji2, params));
16048
17612
  },
16049
17613
  guid(params) {
16050
- return this.check(/* @__PURE__ */ _guid2(ZodGUID, params));
17614
+ return this.check(/* @__PURE__ */ _guid2(ZodGUID2, params));
16051
17615
  },
16052
17616
  uuid(params) {
16053
- return this.check(/* @__PURE__ */ _uuid2(ZodUUID, params));
17617
+ return this.check(/* @__PURE__ */ _uuid2(ZodUUID2, params));
16054
17618
  },
16055
17619
  uuidv4(params) {
16056
- return this.check(/* @__PURE__ */ _uuidv42(ZodUUID, params));
17620
+ return this.check(/* @__PURE__ */ _uuidv42(ZodUUID2, params));
16057
17621
  },
16058
17622
  uuidv6(params) {
16059
- return this.check(/* @__PURE__ */ _uuidv62(ZodUUID, params));
17623
+ return this.check(/* @__PURE__ */ _uuidv62(ZodUUID2, params));
16060
17624
  },
16061
17625
  uuidv7(params) {
16062
- return this.check(/* @__PURE__ */ _uuidv72(ZodUUID, params));
17626
+ return this.check(/* @__PURE__ */ _uuidv72(ZodUUID2, params));
16063
17627
  },
16064
17628
  nanoid(params) {
16065
- return this.check(/* @__PURE__ */ _nanoid2(ZodNanoID, params));
17629
+ return this.check(/* @__PURE__ */ _nanoid2(ZodNanoID2, params));
16066
17630
  },
16067
17631
  cuid(params) {
16068
- return this.check(/* @__PURE__ */ _cuid3(ZodCUID, params));
17632
+ return this.check(/* @__PURE__ */ _cuid3(ZodCUID3, params));
16069
17633
  },
16070
17634
  cuid2(params) {
16071
- return this.check(/* @__PURE__ */ _cuid22(ZodCUID2, params));
17635
+ return this.check(/* @__PURE__ */ _cuid22(ZodCUID22, params));
16072
17636
  },
16073
17637
  ulid(params) {
16074
- return this.check(/* @__PURE__ */ _ulid2(ZodULID, params));
17638
+ return this.check(/* @__PURE__ */ _ulid2(ZodULID2, params));
16075
17639
  },
16076
17640
  base64(params) {
16077
- return this.check(/* @__PURE__ */ _base642(ZodBase64, params));
17641
+ return this.check(/* @__PURE__ */ _base642(ZodBase642, params));
16078
17642
  },
16079
17643
  base64url(params) {
16080
- return this.check(/* @__PURE__ */ _base64url2(ZodBase64URL, params));
17644
+ return this.check(/* @__PURE__ */ _base64url2(ZodBase64URL2, params));
16081
17645
  },
16082
17646
  xid(params) {
16083
- return this.check(/* @__PURE__ */ _xid2(ZodXID, params));
17647
+ return this.check(/* @__PURE__ */ _xid2(ZodXID2, params));
16084
17648
  },
16085
17649
  ksuid(params) {
16086
- return this.check(/* @__PURE__ */ _ksuid2(ZodKSUID, params));
17650
+ return this.check(/* @__PURE__ */ _ksuid2(ZodKSUID2, params));
16087
17651
  },
16088
17652
  ipv4(params) {
16089
- return this.check(/* @__PURE__ */ _ipv42(ZodIPv4, params));
17653
+ return this.check(/* @__PURE__ */ _ipv42(ZodIPv42, params));
16090
17654
  },
16091
17655
  ipv6(params) {
16092
- return this.check(/* @__PURE__ */ _ipv62(ZodIPv6, params));
17656
+ return this.check(/* @__PURE__ */ _ipv62(ZodIPv62, params));
16093
17657
  },
16094
17658
  cidrv4(params) {
16095
- return this.check(/* @__PURE__ */ _cidrv42(ZodCIDRv4, params));
17659
+ return this.check(/* @__PURE__ */ _cidrv42(ZodCIDRv42, params));
16096
17660
  },
16097
17661
  cidrv6(params) {
16098
- return this.check(/* @__PURE__ */ _cidrv62(ZodCIDRv6, params));
17662
+ return this.check(/* @__PURE__ */ _cidrv62(ZodCIDRv62, params));
16099
17663
  },
16100
17664
  e164(params) {
16101
- return this.check(/* @__PURE__ */ _e1642(ZodE164, params));
17665
+ return this.check(/* @__PURE__ */ _e1642(ZodE1642, params));
16102
17666
  },
16103
17667
  datetime(params) {
16104
- return this.check(/* @__PURE__ */ _isoDateTime2(ZodISODateTime, params));
17668
+ return this.check(/* @__PURE__ */ _isoDateTime2(ZodISODateTime2, params));
16105
17669
  },
16106
17670
  date(params) {
16107
- return this.check(/* @__PURE__ */ _isoDate2(ZodISODate, params));
17671
+ return this.check(/* @__PURE__ */ _isoDate2(ZodISODate2, params));
16108
17672
  },
16109
17673
  time(params) {
16110
- return this.check(/* @__PURE__ */ _isoTime2(ZodISOTime, params));
17674
+ return this.check(/* @__PURE__ */ _isoTime2(ZodISOTime2, params));
16111
17675
  },
16112
17676
  duration(params) {
16113
- return this.check(/* @__PURE__ */ _isoDuration2(ZodISODuration, params));
17677
+ return this.check(/* @__PURE__ */ _isoDuration2(ZodISODuration2, params));
16114
17678
  }
16115
17679
  });
16116
- function string2(params) {
16117
- return /* @__PURE__ */ _string2(ZodString, params);
17680
+ function string3(params) {
17681
+ return /* @__PURE__ */ _string2(ZodString2, params);
16118
17682
  }
16119
- var ZodStringFormat = /* @__PURE__ */ $constructor2("ZodStringFormat", (inst, def) => {
17683
+ var ZodStringFormat2 = /* @__PURE__ */ $constructor2("ZodStringFormat", (inst, def) => {
16120
17684
  $ZodStringFormat2.init(inst, def);
16121
- _ZodString.init(inst, def);
17685
+ _ZodString2.init(inst, def);
16122
17686
  });
16123
- var ZodISODateTime = /* @__PURE__ */ $constructor2("ZodISODateTime", (inst, def) => {
17687
+ var ZodISODateTime2 = /* @__PURE__ */ $constructor2("ZodISODateTime", (inst, def) => {
16124
17688
  $ZodISODateTime2.init(inst, def);
16125
- ZodStringFormat.init(inst, def);
17689
+ ZodStringFormat2.init(inst, def);
16126
17690
  });
16127
- var ZodISODate = /* @__PURE__ */ $constructor2("ZodISODate", (inst, def) => {
17691
+ var ZodISODate2 = /* @__PURE__ */ $constructor2("ZodISODate", (inst, def) => {
16128
17692
  $ZodISODate2.init(inst, def);
16129
- ZodStringFormat.init(inst, def);
17693
+ ZodStringFormat2.init(inst, def);
16130
17694
  });
16131
- var ZodISOTime = /* @__PURE__ */ $constructor2("ZodISOTime", (inst, def) => {
17695
+ var ZodISOTime2 = /* @__PURE__ */ $constructor2("ZodISOTime", (inst, def) => {
16132
17696
  $ZodISOTime2.init(inst, def);
16133
- ZodStringFormat.init(inst, def);
17697
+ ZodStringFormat2.init(inst, def);
16134
17698
  });
16135
- var ZodISODuration = /* @__PURE__ */ $constructor2("ZodISODuration", (inst, def) => {
17699
+ var ZodISODuration2 = /* @__PURE__ */ $constructor2("ZodISODuration", (inst, def) => {
16136
17700
  $ZodISODuration2.init(inst, def);
16137
- ZodStringFormat.init(inst, def);
17701
+ ZodStringFormat2.init(inst, def);
16138
17702
  });
16139
- var ZodEmail = /* @__PURE__ */ $constructor2("ZodEmail", (inst, def) => {
17703
+ var ZodEmail2 = /* @__PURE__ */ $constructor2("ZodEmail", (inst, def) => {
16140
17704
  $ZodEmail2.init(inst, def);
16141
- ZodStringFormat.init(inst, def);
17705
+ ZodStringFormat2.init(inst, def);
16142
17706
  });
16143
17707
  function email2(params) {
16144
- return /* @__PURE__ */ _email2(ZodEmail, params);
17708
+ return /* @__PURE__ */ _email2(ZodEmail2, params);
16145
17709
  }
16146
- var ZodGUID = /* @__PURE__ */ $constructor2("ZodGUID", (inst, def) => {
17710
+ var ZodGUID2 = /* @__PURE__ */ $constructor2("ZodGUID", (inst, def) => {
16147
17711
  $ZodGUID2.init(inst, def);
16148
- ZodStringFormat.init(inst, def);
17712
+ ZodStringFormat2.init(inst, def);
16149
17713
  });
16150
17714
  function guid2(params) {
16151
- return /* @__PURE__ */ _guid2(ZodGUID, params);
17715
+ return /* @__PURE__ */ _guid2(ZodGUID2, params);
16152
17716
  }
16153
- var ZodUUID = /* @__PURE__ */ $constructor2("ZodUUID", (inst, def) => {
17717
+ var ZodUUID2 = /* @__PURE__ */ $constructor2("ZodUUID", (inst, def) => {
16154
17718
  $ZodUUID2.init(inst, def);
16155
- ZodStringFormat.init(inst, def);
17719
+ ZodStringFormat2.init(inst, def);
16156
17720
  });
16157
17721
  function uuid2(params) {
16158
- return /* @__PURE__ */ _uuid2(ZodUUID, params);
17722
+ return /* @__PURE__ */ _uuid2(ZodUUID2, params);
16159
17723
  }
16160
17724
  function uuidv4(params) {
16161
- return /* @__PURE__ */ _uuidv42(ZodUUID, params);
17725
+ return /* @__PURE__ */ _uuidv42(ZodUUID2, params);
16162
17726
  }
16163
17727
  function uuidv6(params) {
16164
- return /* @__PURE__ */ _uuidv62(ZodUUID, params);
17728
+ return /* @__PURE__ */ _uuidv62(ZodUUID2, params);
16165
17729
  }
16166
17730
  function uuidv7(params) {
16167
- return /* @__PURE__ */ _uuidv72(ZodUUID, params);
17731
+ return /* @__PURE__ */ _uuidv72(ZodUUID2, params);
16168
17732
  }
16169
- var ZodURL = /* @__PURE__ */ $constructor2("ZodURL", (inst, def) => {
17733
+ var ZodURL2 = /* @__PURE__ */ $constructor2("ZodURL", (inst, def) => {
16170
17734
  $ZodURL2.init(inst, def);
16171
- ZodStringFormat.init(inst, def);
17735
+ ZodStringFormat2.init(inst, def);
16172
17736
  });
16173
17737
  function url(params) {
16174
- return /* @__PURE__ */ _url2(ZodURL, params);
17738
+ return /* @__PURE__ */ _url2(ZodURL2, params);
16175
17739
  }
16176
17740
  function httpUrl(params) {
16177
- return /* @__PURE__ */ _url2(ZodURL, {
17741
+ return /* @__PURE__ */ _url2(ZodURL2, {
16178
17742
  protocol: httpProtocol2,
16179
17743
  hostname: domain,
16180
17744
  ...normalizeParams2(params)
16181
17745
  });
16182
17746
  }
16183
- var ZodEmoji = /* @__PURE__ */ $constructor2("ZodEmoji", (inst, def) => {
17747
+ var ZodEmoji2 = /* @__PURE__ */ $constructor2("ZodEmoji", (inst, def) => {
16184
17748
  $ZodEmoji2.init(inst, def);
16185
- ZodStringFormat.init(inst, def);
17749
+ ZodStringFormat2.init(inst, def);
16186
17750
  });
16187
17751
  function emoji2(params) {
16188
- return /* @__PURE__ */ _emoji2(ZodEmoji, params);
17752
+ return /* @__PURE__ */ _emoji3(ZodEmoji2, params);
16189
17753
  }
16190
- var ZodNanoID = /* @__PURE__ */ $constructor2("ZodNanoID", (inst, def) => {
17754
+ var ZodNanoID2 = /* @__PURE__ */ $constructor2("ZodNanoID", (inst, def) => {
16191
17755
  $ZodNanoID2.init(inst, def);
16192
- ZodStringFormat.init(inst, def);
17756
+ ZodStringFormat2.init(inst, def);
16193
17757
  });
16194
17758
  function nanoid2(params) {
16195
- return /* @__PURE__ */ _nanoid2(ZodNanoID, params);
17759
+ return /* @__PURE__ */ _nanoid2(ZodNanoID2, params);
16196
17760
  }
16197
- var ZodCUID = /* @__PURE__ */ $constructor2("ZodCUID", (inst, def) => {
17761
+ var ZodCUID3 = /* @__PURE__ */ $constructor2("ZodCUID", (inst, def) => {
16198
17762
  $ZodCUID3.init(inst, def);
16199
- ZodStringFormat.init(inst, def);
17763
+ ZodStringFormat2.init(inst, def);
16200
17764
  });
16201
17765
  function cuid3(params) {
16202
- return /* @__PURE__ */ _cuid3(ZodCUID, params);
17766
+ return /* @__PURE__ */ _cuid3(ZodCUID3, params);
16203
17767
  }
16204
- var ZodCUID2 = /* @__PURE__ */ $constructor2("ZodCUID2", (inst, def) => {
17768
+ var ZodCUID22 = /* @__PURE__ */ $constructor2("ZodCUID2", (inst, def) => {
16205
17769
  $ZodCUID22.init(inst, def);
16206
- ZodStringFormat.init(inst, def);
17770
+ ZodStringFormat2.init(inst, def);
16207
17771
  });
16208
17772
  function cuid22(params) {
16209
- return /* @__PURE__ */ _cuid22(ZodCUID2, params);
17773
+ return /* @__PURE__ */ _cuid22(ZodCUID22, params);
16210
17774
  }
16211
- var ZodULID = /* @__PURE__ */ $constructor2("ZodULID", (inst, def) => {
17775
+ var ZodULID2 = /* @__PURE__ */ $constructor2("ZodULID", (inst, def) => {
16212
17776
  $ZodULID2.init(inst, def);
16213
- ZodStringFormat.init(inst, def);
17777
+ ZodStringFormat2.init(inst, def);
16214
17778
  });
16215
17779
  function ulid2(params) {
16216
- return /* @__PURE__ */ _ulid2(ZodULID, params);
17780
+ return /* @__PURE__ */ _ulid2(ZodULID2, params);
16217
17781
  }
16218
- var ZodXID = /* @__PURE__ */ $constructor2("ZodXID", (inst, def) => {
17782
+ var ZodXID2 = /* @__PURE__ */ $constructor2("ZodXID", (inst, def) => {
16219
17783
  $ZodXID2.init(inst, def);
16220
- ZodStringFormat.init(inst, def);
17784
+ ZodStringFormat2.init(inst, def);
16221
17785
  });
16222
17786
  function xid2(params) {
16223
- return /* @__PURE__ */ _xid2(ZodXID, params);
17787
+ return /* @__PURE__ */ _xid2(ZodXID2, params);
16224
17788
  }
16225
- var ZodKSUID = /* @__PURE__ */ $constructor2("ZodKSUID", (inst, def) => {
17789
+ var ZodKSUID2 = /* @__PURE__ */ $constructor2("ZodKSUID", (inst, def) => {
16226
17790
  $ZodKSUID2.init(inst, def);
16227
- ZodStringFormat.init(inst, def);
17791
+ ZodStringFormat2.init(inst, def);
16228
17792
  });
16229
17793
  function ksuid2(params) {
16230
- return /* @__PURE__ */ _ksuid2(ZodKSUID, params);
17794
+ return /* @__PURE__ */ _ksuid2(ZodKSUID2, params);
16231
17795
  }
16232
- var ZodIPv4 = /* @__PURE__ */ $constructor2("ZodIPv4", (inst, def) => {
17796
+ var ZodIPv42 = /* @__PURE__ */ $constructor2("ZodIPv4", (inst, def) => {
16233
17797
  $ZodIPv42.init(inst, def);
16234
- ZodStringFormat.init(inst, def);
17798
+ ZodStringFormat2.init(inst, def);
16235
17799
  });
16236
17800
  function ipv42(params) {
16237
- return /* @__PURE__ */ _ipv42(ZodIPv4, params);
17801
+ return /* @__PURE__ */ _ipv42(ZodIPv42, params);
16238
17802
  }
16239
17803
  var ZodMAC = /* @__PURE__ */ $constructor2("ZodMAC", (inst, def) => {
16240
17804
  $ZodMAC2.init(inst, def);
16241
- ZodStringFormat.init(inst, def);
17805
+ ZodStringFormat2.init(inst, def);
16242
17806
  });
16243
17807
  function mac2(params) {
16244
17808
  return /* @__PURE__ */ _mac2(ZodMAC, params);
16245
17809
  }
16246
- var ZodIPv6 = /* @__PURE__ */ $constructor2("ZodIPv6", (inst, def) => {
17810
+ var ZodIPv62 = /* @__PURE__ */ $constructor2("ZodIPv6", (inst, def) => {
16247
17811
  $ZodIPv62.init(inst, def);
16248
- ZodStringFormat.init(inst, def);
17812
+ ZodStringFormat2.init(inst, def);
16249
17813
  });
16250
17814
  function ipv62(params) {
16251
- return /* @__PURE__ */ _ipv62(ZodIPv6, params);
17815
+ return /* @__PURE__ */ _ipv62(ZodIPv62, params);
16252
17816
  }
16253
- var ZodCIDRv4 = /* @__PURE__ */ $constructor2("ZodCIDRv4", (inst, def) => {
17817
+ var ZodCIDRv42 = /* @__PURE__ */ $constructor2("ZodCIDRv4", (inst, def) => {
16254
17818
  $ZodCIDRv42.init(inst, def);
16255
- ZodStringFormat.init(inst, def);
17819
+ ZodStringFormat2.init(inst, def);
16256
17820
  });
16257
17821
  function cidrv42(params) {
16258
- return /* @__PURE__ */ _cidrv42(ZodCIDRv4, params);
17822
+ return /* @__PURE__ */ _cidrv42(ZodCIDRv42, params);
16259
17823
  }
16260
- var ZodCIDRv6 = /* @__PURE__ */ $constructor2("ZodCIDRv6", (inst, def) => {
17824
+ var ZodCIDRv62 = /* @__PURE__ */ $constructor2("ZodCIDRv6", (inst, def) => {
16261
17825
  $ZodCIDRv62.init(inst, def);
16262
- ZodStringFormat.init(inst, def);
17826
+ ZodStringFormat2.init(inst, def);
16263
17827
  });
16264
17828
  function cidrv62(params) {
16265
- return /* @__PURE__ */ _cidrv62(ZodCIDRv6, params);
17829
+ return /* @__PURE__ */ _cidrv62(ZodCIDRv62, params);
16266
17830
  }
16267
- var ZodBase64 = /* @__PURE__ */ $constructor2("ZodBase64", (inst, def) => {
17831
+ var ZodBase642 = /* @__PURE__ */ $constructor2("ZodBase64", (inst, def) => {
16268
17832
  $ZodBase642.init(inst, def);
16269
- ZodStringFormat.init(inst, def);
17833
+ ZodStringFormat2.init(inst, def);
16270
17834
  });
16271
17835
  function base642(params) {
16272
- return /* @__PURE__ */ _base642(ZodBase64, params);
17836
+ return /* @__PURE__ */ _base642(ZodBase642, params);
16273
17837
  }
16274
- var ZodBase64URL = /* @__PURE__ */ $constructor2("ZodBase64URL", (inst, def) => {
17838
+ var ZodBase64URL2 = /* @__PURE__ */ $constructor2("ZodBase64URL", (inst, def) => {
16275
17839
  $ZodBase64URL2.init(inst, def);
16276
- ZodStringFormat.init(inst, def);
17840
+ ZodStringFormat2.init(inst, def);
16277
17841
  });
16278
17842
  function base64url2(params) {
16279
- return /* @__PURE__ */ _base64url2(ZodBase64URL, params);
17843
+ return /* @__PURE__ */ _base64url2(ZodBase64URL2, params);
16280
17844
  }
16281
- var ZodE164 = /* @__PURE__ */ $constructor2("ZodE164", (inst, def) => {
17845
+ var ZodE1642 = /* @__PURE__ */ $constructor2("ZodE164", (inst, def) => {
16282
17846
  $ZodE1642.init(inst, def);
16283
- ZodStringFormat.init(inst, def);
17847
+ ZodStringFormat2.init(inst, def);
16284
17848
  });
16285
17849
  function e1642(params) {
16286
- return /* @__PURE__ */ _e1642(ZodE164, params);
17850
+ return /* @__PURE__ */ _e1642(ZodE1642, params);
16287
17851
  }
16288
17852
  var ZodCreditCard = /* @__PURE__ */ $constructor2("ZodCreditCard", (inst, def) => {
16289
17853
  $ZodCreditCard2.init(inst, def);
16290
- ZodStringFormat.init(inst, def);
17854
+ ZodStringFormat2.init(inst, def);
16291
17855
  });
16292
17856
  function creditCard2(params) {
16293
17857
  return /* @__PURE__ */ _creditCard2(ZodCreditCard, params);
16294
17858
  }
16295
17859
  var ZodIBAN = /* @__PURE__ */ $constructor2("ZodIBAN", (inst, def) => {
16296
17860
  $ZodIBAN2.init(inst, def);
16297
- ZodStringFormat.init(inst, def);
17861
+ ZodStringFormat2.init(inst, def);
16298
17862
  });
16299
17863
  function iban2(params) {
16300
17864
  return /* @__PURE__ */ _iban2(ZodIBAN, params);
16301
17865
  }
16302
- var ZodJWT = /* @__PURE__ */ $constructor2("ZodJWT", (inst, def) => {
17866
+ var ZodJWT2 = /* @__PURE__ */ $constructor2("ZodJWT", (inst, def) => {
16303
17867
  $ZodJWT2.init(inst, def);
16304
- ZodStringFormat.init(inst, def);
17868
+ ZodStringFormat2.init(inst, def);
16305
17869
  });
16306
17870
  function jwt(params) {
16307
- return /* @__PURE__ */ _jwt2(ZodJWT, params);
17871
+ return /* @__PURE__ */ _jwt2(ZodJWT2, params);
16308
17872
  }
16309
17873
  var ZodCustomStringFormat = /* @__PURE__ */ $constructor2("ZodCustomStringFormat", (inst, def) => {
16310
17874
  $ZodCustomStringFormat2.init(inst, def);
16311
- ZodStringFormat.init(inst, def);
17875
+ ZodStringFormat2.init(inst, def);
16312
17876
  });
16313
17877
  function stringFormat(format, fnOrRegex, _params = {}) {
16314
17878
  return /* @__PURE__ */ _stringFormat2(ZodCustomStringFormat, format, fnOrRegex, _params);
@@ -16761,7 +18325,7 @@ function record(keyType, valueType, params) {
16761
18325
  if (!valueType || !valueType._zod)
16762
18326
  return new ZodRecord({
16763
18327
  type: "record",
16764
- keyType: string2(),
18328
+ keyType: string3(),
16765
18329
  valueType: keyType,
16766
18330
  ...normalizeParams2(valueType)
16767
18331
  });
@@ -17213,17 +18777,17 @@ function _instanceof(cls, params = {}) {
17213
18777
  var stringbool = (...args) => /* @__PURE__ */ _stringbool2({
17214
18778
  Codec: ZodCodec,
17215
18779
  Boolean: ZodBoolean2,
17216
- String: ZodString
18780
+ String: ZodString2
17217
18781
  }, ...args);
17218
18782
  function json(params) {
17219
18783
  const jsonSchema = lazy(() => {
17220
18784
  return union2([
17221
- string2(params),
18785
+ string3(params),
17222
18786
  number3(),
17223
18787
  boolean3(),
17224
18788
  _null3(),
17225
18789
  array2(jsonSchema),
17226
- record(string2(), jsonSchema)
18790
+ record(string3(), jsonSchema)
17227
18791
  ]);
17228
18792
  });
17229
18793
  return jsonSchema;
@@ -17241,6 +18805,14 @@ ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
17241
18805
  ...schemas_exports,
17242
18806
  ...checks_exports
17243
18807
  });
18808
+ var createMetaType = (type) => {
18809
+ return Object.assign((value) => {
18810
+ return {
18811
+ type,
18812
+ data: value ?? {}
18813
+ };
18814
+ }, type);
18815
+ };
17244
18816
  (/* @__PURE__ */ __commonJSMin((exports, module) => {
17245
18817
  const CHARS_GLOBAL_BACKSLASH_SUPPORTED_RX = /[\0\b\t\n\r\x1a"'\\]/g;
17246
18818
  const CHARS_ESCAPE_BACKSLASH_SUPPORTED_MAP = {
@@ -17277,6 +18849,45 @@ ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
17277
18849
  }
17278
18850
  module.exports = escapeString;
17279
18851
  }))();
18852
+ var isZodTypeExtends = (type, zodType) => {
18853
+ if (type instanceof zodType)
18854
+ return type;
18855
+ if (type.def.type === "union") {
18856
+ for (const option of type.def.options)
18857
+ if (isZodTypeExtends(option, zodType))
18858
+ return option;
18859
+ return false;
18860
+ }
18861
+ const rootType = type.def.innerType ?? type.def.in;
18862
+ if (rootType)
18863
+ return isZodTypeExtends(rootType, zodType);
18864
+ return false;
18865
+ };
18866
+ createMetaType({
18867
+ id: "foreignKey",
18868
+ check: (type) => {
18869
+ if (isZodTypeExtends(type, ZodString) || isZodTypeExtends(type, ZodNumber))
18870
+ return { success: true };
18871
+ return {
18872
+ success: false,
18873
+ message: "Foreign key must be a string or number"
18874
+ };
18875
+ }
18876
+ });
18877
+ createMetaType({
18878
+ id: "primaryKey",
18879
+ check: (type) => {
18880
+ if (isZodTypeExtends(type, ZodString) || isZodTypeExtends(type, ZodNumber))
18881
+ return { success: true };
18882
+ return {
18883
+ success: false,
18884
+ message: "Primary key must be a string or number"
18885
+ };
18886
+ }
18887
+ });
18888
+ createMetaType({ id: "updatedAt" });
18889
+ createMetaType({ id: "monotonicTimestamp" });
18890
+ createMetaType({ id: "backfill" });
17280
18891
  var ID_PREFIXES = {
17281
18892
  organisation: "org",
17282
18893
  project: "proj",
@@ -17418,6 +19029,19 @@ var deliverEvent = async (event, options) => {
17418
19029
  const baseDelay = delays[attempt - 1];
17419
19030
  const delayMs = isRetryable(result) && baseDelay !== undefined ? Math.max(baseDelay, Math.min(MAX_RETRY_AFTER_MS, (result.retryAfterSeconds ?? 0) * 1000)) : undefined;
17420
19031
  log(formatForwardLine(event, result, new Date, { attempt, attempts, delayMs }));
19032
+ options.onDelivery?.({
19033
+ type: "delivery",
19034
+ eventId: event.id,
19035
+ eventType: event.type,
19036
+ deliveryId,
19037
+ attempt,
19038
+ attempts,
19039
+ ok: result.ok,
19040
+ status: result.status ?? null,
19041
+ error: result.error ?? null,
19042
+ durationMs: result.durationMs,
19043
+ retryInMs: delayMs ?? null
19044
+ });
17421
19045
  if (delayMs === undefined || options.signal?.aborted)
17422
19046
  return result;
17423
19047
  await sleep2(delayMs, options.signal);
@@ -17509,20 +19133,25 @@ var DEVICE_POLL_INTERVAL_SECONDS = 5;
17509
19133
 
17510
19134
  // src/cli/login.ts
17511
19135
  var DEFAULT_API_URL = "https://api.calmlens.com/v1";
17512
- var credentialsPath = () => {
19136
+ var PROFILE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
19137
+ var credentialsPath = (profile) => {
19138
+ if (profile !== undefined && !PROFILE_PATTERN.test(profile)) {
19139
+ throw new Error(`"${profile}" isn't a profile name: use letters, digits, - and _, up to 64 characters.`);
19140
+ }
17513
19141
  const base = process.env.CALMLENS_CONFIG_DIR ?? (process.platform === "win32" ? join(process.env.APPDATA ?? join(homedir(), "AppData", "Roaming"), "calmlens") : join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "calmlens"));
17514
- return join(base, "credentials.json");
19142
+ return join(base, profile ? `credentials-${profile}.json` : "credentials.json");
17515
19143
  };
17516
- var readCredentials = async () => {
19144
+ var readCredentials = async (profile) => {
19145
+ const path = credentialsPath(profile);
17517
19146
  try {
17518
- const stored = JSON.parse(await readFile(credentialsPath(), "utf8"));
19147
+ const stored = JSON.parse(await readFile(path, "utf8"));
17519
19148
  return stored.apiKey && stored.projectId && stored.apiUrl ? stored : undefined;
17520
19149
  } catch {
17521
19150
  return;
17522
19151
  }
17523
19152
  };
17524
- var writeCredentials = async (credentials) => {
17525
- const path = credentialsPath();
19153
+ var writeCredentials = async (credentials, profile) => {
19154
+ const path = credentialsPath(profile);
17526
19155
  await mkdir(dirname(path), { recursive: true, mode: 448 });
17527
19156
  await writeFile(path, `${JSON.stringify(credentials, null, 2)}
17528
19157
  `, { mode: 384 });
@@ -17585,7 +19214,7 @@ var login = async (options) => {
17585
19214
  projectId: polled.body.project_id,
17586
19215
  apiUrl: options.apiUrl
17587
19216
  };
17588
- await writeCredentials(credentials);
19217
+ await writeCredentials(credentials, options.profile);
17589
19218
  return credentials;
17590
19219
  }
17591
19220
  if (polled.body.error === "authorization_pending")
@@ -17597,12 +19226,12 @@ var login = async (options) => {
17597
19226
  throw new Error(polled.body.error === "access_denied" ? "The sign-in was declined." : polled.body.error === "expired_token" ? "The code expired. Run `calmlens login` again." : polled.body.error_description ?? "The sign-in failed.");
17598
19227
  }
17599
19228
  };
17600
- var logout = async () => {
17601
- const stored = await readCredentials();
19229
+ var logout = async (profile) => {
19230
+ const stored = await readCredentials(profile);
17602
19231
  if (!stored)
17603
19232
  return "signed-out";
17604
19233
  const revoked = await post(oauthUrl(stored.apiUrl, "/oauth/revoke"), { token: stored.apiKey }).then((result) => result.ok).catch(() => false);
17605
- await rm(credentialsPath(), { force: true });
19234
+ await rm(credentialsPath(profile), { force: true });
17606
19235
  return revoked ? "revoked" : "forgotten";
17607
19236
  };
17608
19237
 
@@ -17610,11 +19239,11 @@ var logout = async () => {
17610
19239
  var HELP = `CalmLens CLI
17611
19240
 
17612
19241
  Usage:
17613
- calmlens login [--read-only] [--no-browser]
17614
- calmlens logout
19242
+ calmlens login [--read-only] [--no-browser] [--profile <name>]
19243
+ calmlens logout [--profile <name>]
17615
19244
  calmlens listen --forward-to <url> [options]
17616
19245
  calmlens trigger [sexual|violence|self-harm|harassment|hate|criminal-activity|clean] [options]
17617
- calmlens plan [--config <path>] [--prune]
19246
+ calmlens plan [--config <path>] [--prune] [--detailed-exitcode]
17618
19247
  calmlens apply [--config <path>] [--prune]
17619
19248
 
17620
19249
  Install it with \`brew install calmlens/sdks/calmlens\` (after
@@ -17657,7 +19286,14 @@ Options:
17657
19286
  --config <path> For plan and apply: the configuration file (default: calmlens.config.json)
17658
19287
  --prune For plan and apply: also delete upload presets, lenses and metadata
17659
19288
  fields the file doesn't list (never policies)
17660
- --api-url <url> API base URL (default: $CALMLENS_API_URL or https://api.calmlens.com/v1)
19289
+ --api-url <url> API base URL (default: $CALMLENS_BASE_URL or https://api.calmlens.com/v1)
19290
+ --profile <name> Use, or sign in to, a named login, so several projects can be signed in
19291
+ at once (default: $CALMLENS_PROFILE, else the default login)
19292
+ --json For listen, trigger, plan and apply: print JSON on stdout (listen: one
19293
+ line per delivery attempt) and messages on stderr
19294
+ --detailed-exitcode For plan: exit 0 with no changes, 2 with changes and 1 on an error
19295
+ --log-level <level> Log the CLI's API requests to stderr: off, info (retries and failures)
19296
+ or debug (every request) (default: $CALMLENS_LOG, else off)
17661
19297
  -v, --version Show the CLI version
17662
19298
  -h, --help Show this help
17663
19299
  `;
@@ -17667,6 +19303,15 @@ var fail = (message) => {
17667
19303
  `);
17668
19304
  process.exit(1);
17669
19305
  };
19306
+ var LOG_LEVELS2 = ["off", "info", "debug"];
19307
+ var stderrLogger = {
19308
+ debug: (message) => process.stderr.write(`${message}
19309
+ `),
19310
+ info: (message) => process.stderr.write(`${message}
19311
+ `)
19312
+ };
19313
+ var printJson = (value) => process.stdout.write(`${JSON.stringify(value)}
19314
+ `);
17670
19315
  var describeError = (error) => {
17671
19316
  if (error instanceof CalmLensError) {
17672
19317
  return `${error.message.replace(/^\[calmlens\] /, "")} (${error.code})`;
@@ -17690,6 +19335,10 @@ var main = async () => {
17690
19335
  config: { type: "string" },
17691
19336
  prune: { type: "boolean" },
17692
19337
  "no-browser": { type: "boolean" },
19338
+ profile: { type: "string" },
19339
+ json: { type: "boolean" },
19340
+ "detailed-exitcode": { type: "boolean" },
19341
+ "log-level": { type: "string" },
17693
19342
  help: { type: "boolean", short: "h" },
17694
19343
  version: { type: "boolean", short: "v" }
17695
19344
  }
@@ -17711,15 +19360,26 @@ var main = async () => {
17711
19360
  fail(`Couldn't read ${values["env-file"]}.`);
17712
19361
  }
17713
19362
  }
19363
+ const json = Boolean(values.json);
19364
+ const say = (text) => (json ? process.stderr : process.stdout).write(text);
19365
+ const profile = values.profile ?? (process.env.CALMLENS_PROFILE?.trim() || undefined);
19366
+ if (profile !== undefined && !PROFILE_PATTERN.test(profile)) {
19367
+ fail(`"${profile}" isn't a profile name: use letters, digits, - and _, up to 64 characters.`);
19368
+ }
19369
+ const logLevel = values["log-level"] ?? process.env.CALMLENS_LOG?.trim().toLowerCase();
19370
+ if (logLevel !== undefined && !LOG_LEVELS2.includes(logLevel)) {
19371
+ fail(`--log-level must be one of ${LOG_LEVELS2.join(", ")}.`);
19372
+ }
17714
19373
  if (command === "login") {
17715
19374
  try {
17716
19375
  const credentials = await login({
17717
- apiUrl: values["api-url"] ?? process.env.CALMLENS_API_URL ?? DEFAULT_API_URL,
19376
+ profile,
19377
+ apiUrl: values["api-url"] ?? process.env.CALMLENS_BASE_URL ?? DEFAULT_API_URL,
17718
19378
  readOnly: Boolean(values["read-only"]),
17719
19379
  openBrowser: !values["no-browser"],
17720
19380
  write: (text) => process.stdout.write(text)
17721
19381
  });
17722
- process.stdout.write(`Signed in to project ${credentials.projectId}. Saved to ${credentialsPath()}.
19382
+ process.stdout.write(`Signed in to project ${credentials.projectId}. Saved to ${credentialsPath(profile)}.
17723
19383
  `);
17724
19384
  } catch (error) {
17725
19385
  fail(`Sign-in failed: ${describeError(error)}`);
@@ -17727,7 +19387,7 @@ var main = async () => {
17727
19387
  return;
17728
19388
  }
17729
19389
  if (command === "logout") {
17730
- const result = await logout();
19390
+ const result = await logout(profile);
17731
19391
  process.stdout.write(result === "revoked" ? `Signed out and revoked the key.
17732
19392
  ` : result === "forgotten" ? `Signed out here, but CalmLens couldn't be reached: revoke the key in the portal under API keys.
17733
19393
  ` : `You're not signed in.
@@ -17736,17 +19396,22 @@ var main = async () => {
17736
19396
  }
17737
19397
  const explicitKey = values["api-key"] ?? process.env.CALMLENS_API_KEY;
17738
19398
  const explicitProject = values["project-id"] ?? process.env.CALMLENS_PROJECT_ID;
17739
- const stored = explicitKey || explicitProject ? undefined : await readCredentials();
19399
+ const stored = explicitKey || explicitProject ? undefined : await readCredentials(profile);
19400
+ if (profile !== undefined && !stored && !(explicitKey && explicitProject)) {
19401
+ fail(`No login for profile "${profile}". Run \`calmlens login --profile ${profile}\`.`);
19402
+ }
17740
19403
  const apiKey = explicitKey ?? stored?.apiKey;
17741
19404
  const projectId = explicitProject ?? stored?.projectId;
17742
19405
  if (!apiKey || !projectId) {
17743
19406
  fail("Run `calmlens login`, or set CALMLENS_API_KEY and CALMLENS_PROJECT_ID (or pass --api-key and --project-id).\n" + "Both are on the Developer → API Keys page of the CalmLens portal.");
17744
19407
  }
17745
- const baseUrl = values["api-url"] ?? process.env.CALMLENS_API_URL ?? stored?.apiUrl;
19408
+ const baseUrl = values["api-url"] ?? process.env.CALMLENS_BASE_URL ?? stored?.apiUrl;
17746
19409
  const client = new CalmLensServerClient({
17747
19410
  apiKey,
17748
19411
  projectId,
17749
- ...baseUrl ? { baseUrl } : {}
19412
+ ...baseUrl ? { baseUrl } : {},
19413
+ logLevel: logLevel ?? "off",
19414
+ logger: stderrLogger
17750
19415
  });
17751
19416
  if (command === "listen") {
17752
19417
  const forwardTo = values["forward-to"];
@@ -17769,8 +19434,15 @@ var main = async () => {
17769
19434
  eventTypes,
17770
19435
  intervalMs: intervalSeconds * 1000,
17771
19436
  signal: controller.signal,
19437
+ ...json && {
19438
+ log: (line) => process.stderr.write(`${line}
19439
+ `),
19440
+ onDelivery: printJson
19441
+ },
17772
19442
  onReady: ({ unavailableTypes }) => {
17773
- process.stdout.write([
19443
+ if (json)
19444
+ printJson({ type: "ready", projectId, forwardTo, unavailableTypes });
19445
+ say([
17774
19446
  `Forwarding CalmLens events for project ${projectId} to ${forwardTo}`,
17775
19447
  configuredSecret ? "Signing with your CALMLENS_WEBHOOK_SECRET." : `Signing secret: ${secret}
17776
19448
  Set CALMLENS_WEBHOOK_SECRET to this value in your app, or pass --secret.`,
@@ -17808,7 +19480,10 @@ var main = async () => {
17808
19480
  name: `cli-trigger-${kind}`,
17809
19481
  content: { plainText: text, type: "text/plain" }
17810
19482
  });
17811
- process.stdout.write(`Created asset ${asset.id}: ${asset.classification.moderation.status}.
19483
+ if (json)
19484
+ printJson(asset);
19485
+ else
19486
+ process.stdout.write(`Created asset ${asset.id}: ${asset.classification.moderation.decision}.
17812
19487
  `);
17813
19488
  } catch (error) {
17814
19489
  fail(`Trigger failed: ${describeError(error)}`);
@@ -17827,13 +19502,19 @@ var main = async () => {
17827
19502
  const config = parseConfiguration(text, path);
17828
19503
  const state = await readConfigurationState(client, config);
17829
19504
  const plan = planConfiguration(config, state, { prune: Boolean(values.prune) });
17830
- process.stdout.write(formatPlan(plan));
17831
- if (command === "apply" && plan.changes.length) {
17832
- await applyConfiguration(client, config, state, plan, (line) => process.stdout.write(`${line}
19505
+ say(formatPlan(plan));
19506
+ const applying = command === "apply" && plan.changes.length > 0;
19507
+ if (applying) {
19508
+ await applyConfiguration(client, config, state, plan, (line) => say(`${line}
17833
19509
  `));
17834
- process.stdout.write(`Applied.
19510
+ say(`Applied.
17835
19511
  `);
17836
19512
  }
19513
+ if (json)
19514
+ printJson({ changes: plan.changes, unchanged: plan.unchanged, applied: applying });
19515
+ if (command === "plan" && values["detailed-exitcode"] && plan.changes.length) {
19516
+ process.exitCode = 2;
19517
+ }
17837
19518
  } catch (error) {
17838
19519
  if (error instanceof CalmLensError && error.code.endsWith("/revision-conflict"))
17839
19520
  fail(`${describeError(error)}