calmlens 0.25.0 → 0.27.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 (95) hide show
  1. package/README.md +15 -15
  2. package/bin/calmlens.js +2383 -677
  3. package/cjs/{BrowserUpload-AO2-2U5Z.js → BrowserUpload-CTqIjCV5.js} +1 -1
  4. package/{esm/BrowserUpload-D2lemMIU.d.ts → cjs/BrowserUpload-D4sEmd0X.d.ts} +2 -2
  5. package/{esm/CalmLensAppClient-Dt0t9Bk6.d.ts → cjs/CalmLensAppClient-CCeFnKX8.d.ts} +5 -11
  6. package/cjs/{CalmLensAppClient-nv6qwja0.js → CalmLensAppClient-CZm-9g22.js} +23 -16
  7. package/cjs/{CalmLensOptionKeys-BvCac9NO.js → CalmLensOptionKeys-C1w3SqmL.js} +165 -95
  8. package/cjs/CalmLensServerClient-B7PfocET.d.ts +346 -0
  9. package/cjs/{CalmLensServerClient-B60kCBCR.js → CalmLensServerClient-ucq3ITjd.js} +281 -315
  10. package/cjs/{CalmLensTypes-BhR7LFDu.d.ts → CalmLensTypes-HUERg5hI.d.ts} +142 -155
  11. package/cjs/{Classification-CxRedzgH-C9qlYW_J.d.ts → Classification-CMM2tZpJ-IdIh63n0.d.ts} +6 -7
  12. package/cjs/{Core-Cw4IxFUq.js → Core-D-1KCqT7.js} +39 -16
  13. package/cjs/{Core-DSMxC2GL.d.ts → Core-DXAs8mcx.d.ts} +10 -3
  14. package/{esm/ModerationContextLimits-Bqr0duav.js → cjs/ModerationContextLimits-BcYKgU2X.js} +859 -44
  15. package/cjs/ReactUpload-BTciTpwB.d.ts +27 -0
  16. package/cjs/{ReactUpload--oDFltw2.js → ReactUpload-BymgWiC8.js} +38 -2
  17. package/cjs/{TestTriggers-CiFcTHX3-BmfH4J3f.js → TestTriggers-Cvi7e2KA-DcT1pc_W.js} +91 -22
  18. package/{esm/TestTriggers-BJ4B-MXR-D1tGifPU.d.ts → cjs/TestTriggers-Dnukm-jm-DoEB7jJc.d.ts} +1 -1
  19. package/cjs/{UploadController-ObdgTaBl.js → UploadController-C8GPbDKI.js} +16 -3
  20. package/{esm/WebhookPayload-DLGGOGW6.d.ts → cjs/WebhookPayload-mUmOFH55.d.ts} +152 -9
  21. package/cjs/app.d.ts +6 -6
  22. package/cjs/app.js +20 -2
  23. package/cjs/elements.d.ts +5 -5
  24. package/cjs/elements.js +105 -68
  25. package/cjs/{index-AAWuerkU.d.ts → index-Ck7x1YjM.d.ts} +3 -3
  26. package/cjs/index.d.ts +5 -5
  27. package/cjs/index.js +19 -1
  28. package/cjs/react-native.d.ts +3 -3
  29. package/cjs/react-native.js +7 -5
  30. package/cjs/react.d.ts +5 -4
  31. package/cjs/react.js +11 -15
  32. package/cjs/server.d.ts +6 -6
  33. package/cjs/server.js +20 -2
  34. package/cjs/test-inputs.d.ts +1 -1
  35. package/cjs/test-inputs.js +13 -13
  36. package/cjs/testing.d.ts +18 -21
  37. package/cjs/testing.js +99 -147
  38. package/cjs/{ui-CcuGKTcL.d.ts → ui-BfJNO3c6.d.ts} +2 -2
  39. package/cjs/{ui-CA16jyfZ.js → ui-CW8BqtZk.js} +7 -5
  40. package/cjs/ui.d.ts +3 -3
  41. package/cjs/ui.js +4 -3
  42. package/cjs/vue.d.ts +15 -8
  43. package/cjs/vue.js +30 -17
  44. package/esm/{BrowserUpload-Co4T6uGk.js → BrowserUpload-C01iLeOs.js} +1 -1
  45. package/{cjs/BrowserUpload-D2lemMIU.d.ts → esm/BrowserUpload-D4sEmd0X.d.ts} +2 -2
  46. package/{cjs/CalmLensAppClient-Dt0t9Bk6.d.ts → esm/CalmLensAppClient-CCeFnKX8.d.ts} +5 -11
  47. package/esm/{CalmLensAppClient-BRzy4dwn.js → CalmLensAppClient-CgDogQQC.js} +23 -16
  48. package/esm/{CalmLensOptionKeys-bE3rb5PN.js → CalmLensOptionKeys-CEwNbpEz.js} +160 -96
  49. package/esm/CalmLensServerClient-B7PfocET.d.ts +346 -0
  50. package/esm/{CalmLensServerClient-_PRi90wI.js → CalmLensServerClient-TT6zrAG5.js} +281 -315
  51. package/esm/{CalmLensTypes-BhR7LFDu.d.ts → CalmLensTypes-HUERg5hI.d.ts} +142 -155
  52. package/esm/{Classification-CxRedzgH-C9qlYW_J.d.ts → Classification-CMM2tZpJ-IdIh63n0.d.ts} +6 -7
  53. package/esm/{Core-CtbYmeXG.js → Core-CP6NaqJz.js} +39 -16
  54. package/esm/{Core-DSMxC2GL.d.ts → Core-DXAs8mcx.d.ts} +10 -3
  55. package/{cjs/ModerationContextLimits-Cn9RvnZH.js → esm/ModerationContextLimits-BmV8QD32.js} +476 -301
  56. package/esm/{ReactUpload-B5itHBSF.js → ReactUpload-B72Oq3qE.js} +34 -4
  57. package/esm/ReactUpload-BTciTpwB.d.ts +27 -0
  58. package/esm/{TestTriggers-CiFcTHX3-BK2-sgOC.js → TestTriggers-Cvi7e2KA-BA83CRJb.js} +87 -23
  59. package/{cjs/TestTriggers-BJ4B-MXR-D1tGifPU.d.ts → esm/TestTriggers-Dnukm-jm-DoEB7jJc.d.ts} +1 -1
  60. package/esm/{UploadController-C7fL3Iz9.js → UploadController-Q7xTqh5w.js} +11 -4
  61. package/{cjs/WebhookPayload-DLGGOGW6.d.ts → esm/WebhookPayload-mUmOFH55.d.ts} +152 -9
  62. package/esm/app.d.ts +6 -6
  63. package/esm/app.js +3 -3
  64. package/esm/elements.d.ts +5 -5
  65. package/esm/elements.js +105 -69
  66. package/esm/{index-AAWuerkU.d.ts → index-Ck7x1YjM.d.ts} +3 -3
  67. package/esm/index.d.ts +5 -5
  68. package/esm/index.js +1 -1
  69. package/esm/react-native.d.ts +3 -3
  70. package/esm/react-native.js +6 -6
  71. package/esm/react.d.ts +5 -4
  72. package/esm/react.js +10 -16
  73. package/esm/server.d.ts +6 -6
  74. package/esm/server.js +3 -3
  75. package/esm/styles.css +37 -14
  76. package/esm/svelte/CalmLensAsset.svelte +1 -1
  77. package/esm/svelte/CalmLensUploader.svelte +17 -17
  78. package/esm/svelte/context.js +21 -0
  79. package/esm/svelte/index.d.ts +12 -0
  80. package/esm/svelte/index.js +1 -0
  81. package/esm/test-inputs.d.ts +1 -1
  82. package/esm/test-inputs.js +1 -1
  83. package/esm/testing.d.ts +18 -21
  84. package/esm/testing.js +93 -141
  85. package/esm/{ui-B98AucZA.js → ui-BBDJJkFL.js} +7 -5
  86. package/esm/{ui-CcuGKTcL.d.ts → ui-BfJNO3c6.d.ts} +2 -2
  87. package/esm/ui.d.ts +3 -3
  88. package/esm/ui.js +4 -4
  89. package/esm/vue.d.ts +15 -8
  90. package/esm/vue.js +30 -19
  91. package/package.json +16 -6
  92. package/cjs/CalmLensServerClient-7XjQaeKu.d.ts +0 -353
  93. package/cjs/ReactUpload-CW4NzAsh.d.ts +0 -17
  94. package/esm/CalmLensServerClient-7XjQaeKu.d.ts +0 -353
  95. package/esm/ReactUpload-CW4NzAsh.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.25.0";
6
+ var version = "0.27.1";
7
7
 
8
8
  // src/contract/ModerationCategories-CHFRoeWV.js
9
9
  var CLASSIFICATION_CATEGORIES = [
@@ -90,9 +90,6 @@ var API_ERROR_CODES = {
90
90
  ASSET_NOT_RETRYABLE: "asset/not-retryable",
91
91
  ASSET_CONTENT_UNAVAILABLE: "asset/content-unavailable",
92
92
  ASSET_CONTENT_PURGED: "asset/content-purged",
93
- ASSET_NOT_DECIDED: "asset/not-decided",
94
- ASSET_POLICY_CHANGED: "asset/policy-changed",
95
- ASSET_REVIEWED: "asset/reviewed",
96
93
  SUPPORT_TICKET_NOT_FOUND: "support-ticket/not-found",
97
94
  DUPLICATE_EXTERNAL_ID: "asset/duplicate-external-id",
98
95
  FOLDER_NOT_FOUND: "folder/not-found",
@@ -162,6 +159,66 @@ var SDK_ERROR_CODES = {
162
159
  INVALID_WEBHOOK_PAYLOAD: "sdk/invalid-webhook-payload"
163
160
  };
164
161
  var CALMLENS_ERROR_CODES = { ...API_ERROR_CODES, ...SDK_ERROR_CODES };
162
+ var KIND_PARENTS = {
163
+ error: null,
164
+ api: "error",
165
+ "bad-request": "api",
166
+ authentication: "api",
167
+ "permission-denied": "api",
168
+ "not-found": "api",
169
+ conflict: "api",
170
+ "payload-too-large": "api",
171
+ "unprocessable-entity": "api",
172
+ "rate-limit": "api",
173
+ server: "api",
174
+ connection: "error",
175
+ timeout: "error",
176
+ cancelled: "error",
177
+ "invalid-argument": "error",
178
+ configuration: "invalid-argument",
179
+ "invalid-response": "error",
180
+ "webhook-verification": "error"
181
+ };
182
+ var STATUS_KINDS = {
183
+ 400: "bad-request",
184
+ 401: "authentication",
185
+ 403: "permission-denied",
186
+ 404: "not-found",
187
+ 409: "conflict",
188
+ 413: "payload-too-large",
189
+ 422: "unprocessable-entity",
190
+ 429: "rate-limit"
191
+ };
192
+ var CODE_KINDS = {
193
+ "sdk/transport-error": "connection",
194
+ "sdk/timeout": "timeout",
195
+ "sdk/cancelled": "cancelled",
196
+ "sdk/invalid-response": "invalid-response",
197
+ "sdk/response-too-large": "invalid-response",
198
+ "sdk/invalid-argument": "invalid-argument",
199
+ "sdk/invalid-config": "configuration",
200
+ "sdk/no-fetch": "configuration",
201
+ "sdk/invalid-webhook-signature": "webhook-verification",
202
+ "sdk/invalid-webhook-payload": "webhook-verification"
203
+ };
204
+ var errorKindOf = (code, status) => {
205
+ const byCode = CODE_KINDS[code];
206
+ if (byCode)
207
+ return byCode;
208
+ if (status === undefined)
209
+ return code === "sdk/http-error" ? "api" : "invalid-argument";
210
+ if (status >= 500)
211
+ return "server";
212
+ return STATUS_KINDS[status] ?? "api";
213
+ };
214
+ var isErrorKind = (kind, ancestor) => {
215
+ for (let current = kind;current; current = KIND_PARENTS[current]) {
216
+ if (current === ancestor)
217
+ return true;
218
+ }
219
+ return false;
220
+ };
221
+ var MAX_ERROR_BODY_LENGTH = 4096;
165
222
  var BRAND = Symbol.for("calmlens.sdk.CalmLensError");
166
223
  var RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]);
167
224
  var RETRYABLE_CODES = new Set([
@@ -171,6 +228,9 @@ var RETRYABLE_CODES = new Set([
171
228
  ]);
172
229
 
173
230
  class CalmLensError extends Error {
231
+ static kind = "error";
232
+ kind;
233
+ body;
174
234
  code;
175
235
  status;
176
236
  details;
@@ -181,7 +241,15 @@ class CalmLensError extends Error {
181
241
  const id = typeof code === "string" ? code : code.id;
182
242
  const defaultMessage = typeof code === "string" ? undefined : code.defaultMessage;
183
243
  super(`[calmlens] ${options.message ?? defaultMessage ?? id}`, { cause: options.cause });
184
- this.name = "CalmLensError";
244
+ const kind = errorKindOf(id, options.status);
245
+ if (new.target === CalmLensError) {
246
+ const KindClass = ERROR_CLASSES[kind];
247
+ if (KindClass !== CalmLensError)
248
+ return new KindClass(code, options);
249
+ }
250
+ this.name = new.target.name;
251
+ this.kind = kind;
252
+ this.body = options.body?.slice(0, MAX_ERROR_BODY_LENGTH);
185
253
  this.code = id;
186
254
  this.status = options.status;
187
255
  this.details = options.details;
@@ -194,7 +262,16 @@ class CalmLensError extends Error {
194
262
  return typeof value === "object" && value !== null && value[BRAND] === true;
195
263
  }
196
264
  static [Symbol.hasInstance](value) {
197
- return CalmLensError.isCalmLensError(value);
265
+ if (!CalmLensError.isCalmLensError(value))
266
+ return false;
267
+ const expected = this.kind;
268
+ if (expected === "error")
269
+ return true;
270
+ const { kind } = value;
271
+ return kind in KIND_PARENTS && isErrorKind(kind, expected);
272
+ }
273
+ isKind(kind) {
274
+ return isErrorKind(this.kind, kind);
198
275
  }
199
276
  isLocal() {
200
277
  return this.status === undefined;
@@ -209,6 +286,231 @@ class CalmLensError extends Error {
209
286
  var invalidArgument = (message, details) => new CalmLensError(SDK_ERROR_CODES.INVALID_ARGUMENT, { message, details });
210
287
  var invalidConfig = (message) => new CalmLensError(SDK_ERROR_CODES.INVALID_CONFIG, { message });
211
288
 
289
+ class CalmLensApiError extends CalmLensError {
290
+ static kind = "api";
291
+ }
292
+
293
+ class CalmLensBadRequestError extends CalmLensApiError {
294
+ static kind = "bad-request";
295
+ }
296
+
297
+ class CalmLensAuthenticationError extends CalmLensApiError {
298
+ static kind = "authentication";
299
+ }
300
+
301
+ class CalmLensPermissionDeniedError extends CalmLensApiError {
302
+ static kind = "permission-denied";
303
+ }
304
+
305
+ class CalmLensNotFoundError extends CalmLensApiError {
306
+ static kind = "not-found";
307
+ }
308
+
309
+ class CalmLensConflictError extends CalmLensApiError {
310
+ static kind = "conflict";
311
+ }
312
+
313
+ class CalmLensPayloadTooLargeError extends CalmLensApiError {
314
+ static kind = "payload-too-large";
315
+ }
316
+
317
+ class CalmLensUnprocessableEntityError extends CalmLensApiError {
318
+ static kind = "unprocessable-entity";
319
+ }
320
+
321
+ class CalmLensRateLimitError extends CalmLensApiError {
322
+ static kind = "rate-limit";
323
+ }
324
+
325
+ class CalmLensServerError extends CalmLensApiError {
326
+ static kind = "server";
327
+ }
328
+
329
+ class CalmLensConnectionError extends CalmLensError {
330
+ static kind = "connection";
331
+ }
332
+
333
+ class CalmLensTimeoutError extends CalmLensError {
334
+ static kind = "timeout";
335
+ }
336
+
337
+ class CalmLensCancelledError extends CalmLensError {
338
+ static kind = "cancelled";
339
+ }
340
+
341
+ class CalmLensInvalidArgumentError extends CalmLensError {
342
+ static kind = "invalid-argument";
343
+ }
344
+
345
+ class CalmLensConfigurationError extends CalmLensInvalidArgumentError {
346
+ static kind = "configuration";
347
+ }
348
+
349
+ class CalmLensInvalidResponseError extends CalmLensError {
350
+ static kind = "invalid-response";
351
+ }
352
+
353
+ class CalmLensWebhookVerificationError extends CalmLensError {
354
+ static kind = "webhook-verification";
355
+ }
356
+ var ERROR_CLASSES = {
357
+ error: CalmLensError,
358
+ api: CalmLensApiError,
359
+ "bad-request": CalmLensBadRequestError,
360
+ authentication: CalmLensAuthenticationError,
361
+ "permission-denied": CalmLensPermissionDeniedError,
362
+ "not-found": CalmLensNotFoundError,
363
+ conflict: CalmLensConflictError,
364
+ "payload-too-large": CalmLensPayloadTooLargeError,
365
+ "unprocessable-entity": CalmLensUnprocessableEntityError,
366
+ "rate-limit": CalmLensRateLimitError,
367
+ server: CalmLensServerError,
368
+ connection: CalmLensConnectionError,
369
+ timeout: CalmLensTimeoutError,
370
+ cancelled: CalmLensCancelledError,
371
+ "invalid-argument": CalmLensInvalidArgumentError,
372
+ configuration: CalmLensConfigurationError,
373
+ "invalid-response": CalmLensInvalidResponseError,
374
+ "webhook-verification": CalmLensWebhookVerificationError
375
+ };
376
+
377
+ // src/client/CalmLensLogging.ts
378
+ var LOG_LEVELS = ["off", "info", "debug"];
379
+ var readEnv = (name) => {
380
+ const runtime = globalThis;
381
+ try {
382
+ const value = runtime.process?.env?.[name] ?? runtime.Deno?.env?.get(name);
383
+ return value === undefined || value.trim() === "" ? undefined : value.trim();
384
+ } catch {
385
+ return;
386
+ }
387
+ };
388
+ var resolveLogLevel = (option, fromEnv) => {
389
+ if (option !== undefined) {
390
+ if (!LOG_LEVELS.includes(option)) {
391
+ throw invalidConfig(`logLevel must be one of ${LOG_LEVELS.join(", ")}`);
392
+ }
393
+ return option;
394
+ }
395
+ const env = fromEnv ? readEnv("CALMLENS_LOG")?.toLowerCase() : undefined;
396
+ return LOG_LEVELS.includes(env) ? env : "off";
397
+ };
398
+ var describeAttempt = (attempt) => {
399
+ const outcome = attempt.status !== null ? `HTTP ${attempt.status}` : attempt.errorCode !== null ? attempt.errorCode : "no response";
400
+ const parts = [
401
+ `[calmlens] ${attempt.operation ?? "request"} ${attempt.method} ${attempt.path}`,
402
+ `attempt ${attempt.attempt}`,
403
+ outcome,
404
+ `${attempt.durationMs}ms`
405
+ ];
406
+ if (attempt.requestId)
407
+ parts.push(`request ${attempt.requestId}`);
408
+ if (attempt.delayMs !== null)
409
+ parts.push(`retrying in ${attempt.delayMs}ms`);
410
+ return parts.join(" · ");
411
+ };
412
+
413
+ // src/client/CalmLensPagination.ts
414
+ var withLastResponse = (value, lastResponse) => {
415
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
416
+ Object.defineProperty(value, "lastResponse", {
417
+ value: lastResponse,
418
+ enumerable: false,
419
+ writable: false,
420
+ configurable: true
421
+ });
422
+ }
423
+ return value;
424
+ };
425
+ var copyLastResponse = (value, from) => {
426
+ const lastResponse = from?.lastResponse;
427
+ return lastResponse ? withLastResponse(value, lastResponse) : value;
428
+ };
429
+ var AUTO_PAGING_TO_ARRAY_MAX = 1e4;
430
+ var assertNewCursor = (sent, cursor) => {
431
+ if (sent.has(cursor)) {
432
+ throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
433
+ message: "The API returned a cursor it had already returned, with more pages to follow",
434
+ details: { cursor }
435
+ });
436
+ }
437
+ sent.add(cursor);
438
+ };
439
+ var requestCursors = new WeakMap;
440
+ var autoPaging = (first) => {
441
+ async function* items() {
442
+ let page = await first;
443
+ const start = requestCursors.get(page);
444
+ const sent = new Set(start === undefined ? [] : [start]);
445
+ for (;; ) {
446
+ const more = page.hasNextPage();
447
+ if (more)
448
+ assertNewCursor(sent, page.nextCursor);
449
+ yield* page.items;
450
+ if (!more)
451
+ return;
452
+ page = await page.getNextPage();
453
+ }
454
+ }
455
+ return {
456
+ [Symbol.asyncIterator]: () => items(),
457
+ async autoPagingToArray(options) {
458
+ const limit = options?.limit;
459
+ if (!Number.isInteger(limit) || limit < 1 || limit > AUTO_PAGING_TO_ARRAY_MAX) {
460
+ throw invalidArgument(`autoPagingToArray needs a limit from 1 to ${AUTO_PAGING_TO_ARRAY_MAX}; iterate with for await for more`);
461
+ }
462
+ const collected = [];
463
+ for await (const item of items()) {
464
+ collected.push(item);
465
+ if (collected.length >= limit)
466
+ break;
467
+ }
468
+ return collected;
469
+ }
470
+ };
471
+ };
472
+ var toListPage = (data, source, cursor) => {
473
+ if (!data || typeof data !== "object" || !Array.isArray(data.items)) {
474
+ throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
475
+ message: "The API returned a list without items"
476
+ });
477
+ }
478
+ const hasNextPage = () => data.hasMore === true && typeof data.nextCursor === "string" && data.nextCursor !== "" && (source.feed || data.items.length > 0);
479
+ const page = data;
480
+ if (cursor !== undefined)
481
+ requestCursors.set(page, cursor);
482
+ const self = Promise.resolve(page);
483
+ const { [Symbol.asyncIterator]: iterate, autoPagingToArray } = autoPaging(self);
484
+ Object.defineProperties(page, {
485
+ hasNextPage: { value: hasNextPage, configurable: true },
486
+ getNextPage: {
487
+ value: () => {
488
+ const next = data.nextCursor ?? undefined;
489
+ return list(async () => {
490
+ if (!hasNextPage()) {
491
+ throw invalidArgument("There is no next page; check hasNextPage() first");
492
+ }
493
+ if (next !== undefined && next === cursor)
494
+ assertNewCursor(new Set([next]), next);
495
+ return toListPage(await source.fetchPage(next), source, next);
496
+ });
497
+ },
498
+ configurable: true
499
+ },
500
+ autoPagingToArray: { value: autoPagingToArray, configurable: true },
501
+ [Symbol.asyncIterator]: { value: iterate, configurable: true }
502
+ });
503
+ return page;
504
+ };
505
+ var list = (load) => {
506
+ const first = (async () => load())();
507
+ return Object.assign(first, autoPaging(first));
508
+ };
509
+ var listPages = (fetchPage, { cursor, feed = false } = {}) => {
510
+ const source = { fetchPage, feed };
511
+ return list(async () => toListPage(await fetchPage(cursor), source, cursor));
512
+ };
513
+
212
514
  // src/client/CalmLensVersion.ts
213
515
  var SDK_VERSION = version;
214
516
  var runtimeName = () => {
@@ -225,7 +527,13 @@ var runtimeName = () => {
225
527
  return `node/${runtime.process.versions.node}`;
226
528
  return "unknown";
227
529
  };
228
- var getUserAgent = () => `calmlens-js/${SDK_VERSION} (${runtimeName()})`;
530
+ var getUserAgent = (appInfo) => {
531
+ const sdk = `calmlens-js/${SDK_VERSION} (${runtimeName()})`;
532
+ if (!appInfo)
533
+ return sdk;
534
+ const app = appInfo.version ? `${appInfo.name}/${appInfo.version}` : appInfo.name;
535
+ return `${sdk} ${app}${appInfo.url ? ` (${appInfo.url})` : ""}`;
536
+ };
229
537
  var isBrowserRuntime = () => typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined";
230
538
  var isReactNativeRuntime = () => globalThis.navigator?.product === "ReactNative";
231
539
 
@@ -369,6 +677,7 @@ var responseInfo = (response) => ({
369
677
  retryAfter: parseRetryAfter(response.headers.get("retry-after"))
370
678
  });
371
679
  var toHttpError = (response, bytes) => {
680
+ const body = new TextDecoder().decode(bytes.subarray(0, MAX_ERROR_BODY_LENGTH * 4)).slice(0, MAX_ERROR_BODY_LENGTH);
372
681
  let data;
373
682
  try {
374
683
  data = JSON.parse(new TextDecoder().decode(bytes));
@@ -380,14 +689,23 @@ var toHttpError = (response, bytes) => {
380
689
  message: message ?? code,
381
690
  ...info,
382
691
  requestId: info.requestId ?? (typeof requestId === "string" ? requestId : undefined),
383
- details
692
+ details,
693
+ body
384
694
  });
385
695
  }
386
696
  return new CalmLensError(SDK_ERROR_CODES.HTTP_ERROR, {
387
697
  message: `HTTP ${response.status}`,
388
- ...responseInfo(response)
698
+ ...responseInfo(response),
699
+ body
389
700
  });
390
701
  };
702
+ var pathOf = (url) => {
703
+ try {
704
+ return new URL(url).pathname;
705
+ } catch {
706
+ return url.split(/[?#]/)[0] ?? "";
707
+ }
708
+ };
391
709
 
392
710
  class CalmLensTransport {
393
711
  settings;
@@ -406,21 +724,62 @@ class CalmLensTransport {
406
724
  if (this.settings.apiKey)
407
725
  headers.set("x-api-key", this.settings.apiKey);
408
726
  if (!isBrowserRuntime())
409
- headers.set("user-agent", getUserAgent());
727
+ headers.set("user-agent", getUserAgent(this.settings.appInfo));
410
728
  if (request.idempotencyKey)
411
729
  headers.set("idempotency-key", request.idempotencyKey);
412
730
  return Object.fromEntries(headers.entries());
413
731
  }
732
+ async backoff(ms, request) {
733
+ const callers = createAttemptSignal(this.signalsFor(request), undefined);
734
+ try {
735
+ await this.sleep(ms, callers.signal);
736
+ } finally {
737
+ callers.release();
738
+ }
739
+ }
740
+ signalsFor(request) {
741
+ return [this.settings.signal, request.signal, request.init?.signal ?? undefined];
742
+ }
743
+ maxRetriesFor(request) {
744
+ return request.maxRetries ?? this.settings.maxRetries;
745
+ }
746
+ report(attempt) {
747
+ const { onAttempt, logger, logLevel } = this.settings;
748
+ try {
749
+ onAttempt?.(attempt);
750
+ } catch {}
751
+ if (!logger || !logLevel || logLevel === "off")
752
+ return;
753
+ const failed = attempt.status === null || attempt.status >= 400;
754
+ if (logLevel === "debug")
755
+ logger.debug(describeAttempt(attempt));
756
+ else if (attempt.delayMs !== null || failed)
757
+ logger.info(describeAttempt(attempt));
758
+ }
414
759
  canRetry(request) {
415
- return this.settings.maxRetries > 0 && (request.method === "GET" || request.method === "HEAD" || !!request.idempotencyKey) && isReplayableBody(request.body);
760
+ return this.maxRetriesFor(request) > 0 && (request.method === "GET" || request.method === "HEAD" || !!request.idempotencyKey) && isReplayableBody(request.body);
416
761
  }
417
762
  async send(request, { allowHttpErrors = false } = {}) {
418
763
  const fetchImpl = request.fetch ?? this.settings.fetch;
419
764
  const retryable = this.canRetry(request);
420
765
  const headers = this.headersFor(request);
766
+ const now = this.settings.now ?? Date.now;
767
+ const path = pathOf(request.url);
421
768
  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);
769
+ const canRetryAgain = retryable && attemptNumber < this.maxRetriesFor(request);
770
+ const attempt = createAttemptSignal(this.signalsFor(request), request.timeoutMs);
771
+ const started = now();
772
+ const report = (outcome, delayMs) => this.report({
773
+ operation: request.operation ?? null,
774
+ method: request.method,
775
+ path,
776
+ attempt: attemptNumber + 1,
777
+ delayMs,
778
+ status: outcome.response?.status ?? outcome.error?.status ?? null,
779
+ requestId: outcome.response?.headers.get("x-request-id") ?? outcome.error?.requestId ?? null,
780
+ durationMs: Math.max(0, now() - started),
781
+ errorCode: outcome.error?.code ?? null
782
+ });
424
783
  let response;
425
784
  try {
426
785
  if (attempt.signal.aborted)
@@ -446,24 +805,31 @@ class CalmLensTransport {
446
805
  attempt.release();
447
806
  const failure = toFailure(cause, attempt);
448
807
  if (canRetryAgain && failure.isRetryable()) {
449
- await this.sleep(getRetryDelayMs(attemptNumber), this.settings.signal);
808
+ const delayMs = getRetryDelayMs(attemptNumber);
809
+ report({ error: failure }, delayMs);
810
+ await this.backoff(delayMs, request);
450
811
  continue;
451
812
  }
813
+ report({ error: failure }, null);
452
814
  throw failure;
453
815
  }
454
816
  if (request.deadline === "headers")
455
817
  attempt.clearDeadline();
456
- if (response.ok)
818
+ if (response.ok) {
819
+ report({ response }, null);
457
820
  return { response, attempt };
821
+ }
458
822
  if (allowHttpErrors) {
459
823
  const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
460
824
  const delayMs = retryAfter !== undefined ? retryAfter * 1000 : getRetryDelayMs(attemptNumber);
461
825
  if (!canRetryAgain || !RETRYABLE_STATUSES2.has(response.status) || delayMs > RETRY_AFTER_MAX_MS) {
826
+ report({ response }, null);
462
827
  return { response, attempt };
463
828
  }
829
+ report({ response }, delayMs);
464
830
  attempt.release();
465
831
  await response.body?.cancel().catch(() => {});
466
- await this.sleep(delayMs, this.settings.signal);
832
+ await this.backoff(delayMs, request);
467
833
  continue;
468
834
  }
469
835
  let error;
@@ -477,9 +843,11 @@ class CalmLensTransport {
477
843
  const retryDelayMs = error.retryAfter !== undefined ? error.retryAfter * 1000 : getRetryDelayMs(attemptNumber);
478
844
  const shouldRetry = canRetryAgain && retryDelayMs <= RETRY_AFTER_MAX_MS && error.isRetryable();
479
845
  if (shouldRetry) {
480
- await this.sleep(retryDelayMs, this.settings.signal);
846
+ report({ error }, retryDelayMs);
847
+ await this.backoff(retryDelayMs, request);
481
848
  continue;
482
849
  }
850
+ report({ error }, null);
483
851
  throw error;
484
852
  }
485
853
  }
@@ -490,8 +858,9 @@ class CalmLensTransport {
490
858
  if (bytes.byteLength === 0 && (response.status === 204 || request.method === "DELETE")) {
491
859
  return;
492
860
  }
861
+ let data;
493
862
  try {
494
- return JSON.parse(new TextDecoder().decode(bytes));
863
+ data = JSON.parse(new TextDecoder().decode(bytes));
495
864
  } catch (cause) {
496
865
  throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
497
866
  message: `Invalid JSON response (HTTP ${response.status})`,
@@ -499,6 +868,12 @@ class CalmLensTransport {
499
868
  cause
500
869
  });
501
870
  }
871
+ return withLastResponse(data, {
872
+ status: response.status,
873
+ requestId: response.headers.get("x-request-id") ?? undefined,
874
+ headers: response.headers,
875
+ idempotencyKey: request.idempotencyKey
876
+ });
502
877
  } catch (cause) {
503
878
  throw toFailure(cause, attempt);
504
879
  } finally {
@@ -951,6 +1326,16 @@ var validateConnectionOptions = (options) => {
951
1326
  }
952
1327
  }
953
1328
  assertHttpUrl("baseUrl", options.baseUrl);
1329
+ const { appInfo, onAttempt, logger } = options;
1330
+ 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)))) {
1331
+ throw invalidConfig("appInfo needs a name, and a version, without spaces, and a url, in printable ASCII");
1332
+ }
1333
+ if (onAttempt !== undefined && typeof onAttempt !== "function") {
1334
+ throw invalidConfig("onAttempt must be a function");
1335
+ }
1336
+ if (logger !== undefined && (!logger || typeof logger.debug !== "function" || typeof logger.info !== "function")) {
1337
+ throw invalidConfig("logger must have debug and info methods, as console does");
1338
+ }
954
1339
  };
955
1340
  var validateServerClientOptions = (options) => {
956
1341
  if (!options || typeof options !== "object")
@@ -1196,11 +1581,11 @@ var pollForDecision = async (retrieve, {
1196
1581
  const remaining = deadline - now();
1197
1582
  if (remaining <= 0) {
1198
1583
  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})`,
1584
+ message: `Asset ${asset.id} had no moderation decision after ${timeoutMs}ms (classification status: ${asset.classification.status}, moderation decision: ${asset.classification.moderation.decision})`,
1200
1585
  details: {
1201
1586
  assetId: asset.id,
1202
1587
  classificationStatus: asset.classification.status,
1203
- moderationStatus: asset.classification.moderation.status
1588
+ moderationDecision: asset.classification.moderation.decision
1204
1589
  }
1205
1590
  });
1206
1591
  }
@@ -1387,8 +1772,9 @@ var getRawBase64 = (value) => {
1387
1772
  return value.slice(markerIndex + 8);
1388
1773
  };
1389
1774
  var validateBase64PayloadString = (payload, options) => {
1390
- const raw = getRawBase64(payload.base64).replace(/\s/g, "");
1391
- if (options?.multipart && raw.length % 4 !== 0)
1775
+ const raw = getRawBase64(payload.base64);
1776
+ const whitespace = /\s/.test(raw) ? raw.match(/\s/g)?.length ?? 0 : 0;
1777
+ if (options?.multipart && (raw.length - whitespace) % 4 !== 0)
1392
1778
  return {
1393
1779
  ok: false,
1394
1780
  error: BASE64_PART_BOUNDARY_ERROR
@@ -1411,7 +1797,7 @@ var assetToData = (payload) => {
1411
1797
  throw new Error("Invalid asset payload");
1412
1798
  const raw = getRawBase64(payload.base64);
1413
1799
  if (typeof Buffer !== "undefined")
1414
- return Uint8Array.from(Buffer.from(raw, "base64"));
1800
+ return Buffer.from(raw, "base64");
1415
1801
  const binary = atob(raw);
1416
1802
  return Uint8Array.from(binary, (char) => char.charCodeAt(0));
1417
1803
  };
@@ -1461,7 +1847,7 @@ var validateAssetPayload = (payload, options) => {
1461
1847
  // src/contract/Media-B2PMcUf7.js
1462
1848
  var MAX_MEDIA_UPLOAD_BYTES = 52428800;
1463
1849
  var MAX_LONG_MEDIA_UPLOAD_BYTES = 2147483648;
1464
- // src/contract/ModerationContextLimits-BIMUlk2e.js
1850
+ // src/contract/ModerationContextLimits-k930WU8i.js
1465
1851
  var countModerationContextCharacters = (text) => {
1466
1852
  let count = 0;
1467
1853
  for (const _ of text)
@@ -1542,7 +1928,7 @@ var toUploadData = (payload) => {
1542
1928
  };
1543
1929
  var toRawUploadBody = (payload) => toUploadData(payload);
1544
1930
  var textEncoder = new TextEncoder;
1545
- var toUploadForm = (options, payload) => {
1931
+ var toUploadForm = async (options, payload) => {
1546
1932
  const boundary = `calmlens-${randomUuid()}`;
1547
1933
  const head = `--${boundary}\r
1548
1934
  Content-Disposition: form-data; name="options"\r
@@ -1558,9 +1944,8 @@ Content-Type: ${payload.type.replace(/[\r\n]/g, "")}\r
1558
1944
  --${boundary}--\r
1559
1945
  `;
1560
1946
  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 };
1947
+ const input = toUploadData(payload);
1948
+ const data = input instanceof Blob ? new Uint8Array(await input.arrayBuffer()) : input;
1564
1949
  const headBytes = textEncoder.encode(head);
1565
1950
  const tailBytes = textEncoder.encode(tail);
1566
1951
  if (data instanceof Uint8Array) {
@@ -1651,10 +2036,29 @@ var assertUploadSize = (type, size, inParts) => {
1651
2036
  });
1652
2037
  }
1653
2038
  };
1654
- var prepareSubmitAssetOptions = (options, {
2039
+ var isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
2040
+ var withContentObject = (options) => {
2041
+ if (!options || typeof options !== "object" || !("content" in options))
2042
+ return options;
2043
+ const content = options.content;
2044
+ if (!isBlob(content))
2045
+ return options;
2046
+ if (!content.type) {
2047
+ throw invalidPayload('The Blob has no type: create it with one, such as new Blob([bytes], { type: "image/png" }), or pass { data, type }');
2048
+ }
2049
+ const fileName = typeof File !== "undefined" && content instanceof File ? content.name : undefined;
2050
+ const named = options;
2051
+ return {
2052
+ ...options,
2053
+ ...named.name || !fileName ? {} : { name: fileName },
2054
+ content: { data: content, type: content.type }
2055
+ };
2056
+ };
2057
+ var prepareSubmitAssetOptions = (input, {
1655
2058
  deferUploadChecks = false,
1656
2059
  partSizeBytes = DEFAULT_PART_SIZE_BYTES
1657
2060
  } = {}) => {
2061
+ const options = withContentObject(input);
1658
2062
  if (!options || typeof options !== "object") {
1659
2063
  throw invalidArgument("Asset options are required");
1660
2064
  }
@@ -1728,7 +2132,11 @@ var prepareSubmitAssetOptions = (options, {
1728
2132
  var newIdempotencyKey = () => randomUuid();
1729
2133
  var isTextPayload = (payload) => ("plainText" in payload);
1730
2134
  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";
2135
+ var hasDecision = (data) => {
2136
+ const decision = data.classification?.moderation?.decision;
2137
+ return decision === null || typeof decision === "string";
2138
+ };
2139
+ var isAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload) && hasDecision(data);
1732
2140
  var isUploadedAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload);
1733
2141
  var expectUploadedAsset = (data) => {
1734
2142
  if (!isUploadedAsset(data)) {
@@ -1748,6 +2156,47 @@ var expectAsset = (data) => {
1748
2156
  }
1749
2157
  return data;
1750
2158
  };
2159
+ var validateCallOptions = (options) => {
2160
+ if (options === undefined)
2161
+ return;
2162
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
2163
+ throw invalidArgument("Request options must be an object");
2164
+ }
2165
+ const known = [
2166
+ "signal",
2167
+ "timeoutMs",
2168
+ "maxRetries",
2169
+ "idempotencyKey",
2170
+ "headers",
2171
+ "extraQuery",
2172
+ "extraBody"
2173
+ ];
2174
+ const unknown = Object.keys(options).filter((key) => !known.includes(key));
2175
+ if (unknown.length) {
2176
+ throw invalidArgument(`Unknown request options: ${unknown.join(", ")}`, {
2177
+ options: unknown
2178
+ });
2179
+ }
2180
+ const { timeoutMs, maxRetries, idempotencyKey, headers, extraQuery, extraBody } = options;
2181
+ if (timeoutMs !== undefined && (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1)) {
2182
+ throw invalidArgument("timeoutMs must be a positive integer");
2183
+ }
2184
+ if (maxRetries !== undefined && (!Number.isSafeInteger(maxRetries) || maxRetries < 0)) {
2185
+ throw invalidArgument("maxRetries must be a non-negative integer");
2186
+ }
2187
+ if (idempotencyKey !== undefined && (typeof idempotencyKey !== "string" || !idempotencyKey)) {
2188
+ throw invalidArgument("idempotencyKey must be a non-empty string");
2189
+ }
2190
+ for (const [name, value] of Object.entries({ headers, extraQuery, extraBody })) {
2191
+ if (value !== undefined && (!value || typeof value !== "object" || Array.isArray(value))) {
2192
+ throw invalidArgument(`${name} must be an object`);
2193
+ }
2194
+ }
2195
+ if (options.signal !== undefined && !(options.signal instanceof AbortSignal)) {
2196
+ throw invalidArgument("signal must be an AbortSignal");
2197
+ }
2198
+ };
2199
+ var isPlainObject2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1751
2200
  var resolveConnectionOptions = (options) => ({
1752
2201
  ...options,
1753
2202
  baseUrl: (options.baseUrl ?? `https://api.${DOMAIN}/v1`).replace(/\/+$/, "")
@@ -1757,8 +2206,19 @@ class CalmLensConnection {
1757
2206
  options;
1758
2207
  transport;
1759
2208
  hooks;
1760
- constructor(options, apiKey) {
2209
+ call;
2210
+ constructor(options, apiKey, {
2211
+ readEnvironment = false,
2212
+ shared
2213
+ } = {}) {
1761
2214
  this.options = options;
2215
+ if (shared) {
2216
+ this.transport = shared.transport;
2217
+ this.hooks = shared.hooks;
2218
+ this.call = shared.call;
2219
+ return;
2220
+ }
2221
+ this.call = {};
1762
2222
  const resolveFetch = () => {
1763
2223
  const fetchImpl = this.options.fetch ?? globalThis.fetch;
1764
2224
  if (typeof fetchImpl !== "function") {
@@ -1769,15 +2229,51 @@ class CalmLensConnection {
1769
2229
  return fetchImpl;
1770
2230
  };
1771
2231
  this.hooks = getMockHooks(options);
2232
+ const logLevel = resolveLogLevel(options.logLevel, readEnvironment);
1772
2233
  this.transport = new CalmLensTransport({
1773
2234
  apiKey,
1774
2235
  sleep: this.hooks?.sleep,
1775
2236
  fetch: (input, init) => resolveFetch()(input, init),
1776
2237
  signal: options.signal,
1777
2238
  maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
1778
- maxResponseBytes: options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES
2239
+ maxResponseBytes: options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
2240
+ appInfo: options.appInfo,
2241
+ logLevel,
2242
+ logger: logLevel === "off" ? undefined : options.logger ?? console,
2243
+ onAttempt: options.onAttempt,
2244
+ now: this.hooks?.now
1779
2245
  });
1780
2246
  }
2247
+ forCall(operation, requestOptions) {
2248
+ validateCallOptions(requestOptions);
2249
+ return new CalmLensConnection(this.options, undefined, {
2250
+ shared: {
2251
+ transport: this.transport,
2252
+ hooks: this.hooks,
2253
+ call: { ...this.call, ...requestOptions, operation }
2254
+ }
2255
+ });
2256
+ }
2257
+ callRequest() {
2258
+ const { operation, signal, maxRetries } = this.call;
2259
+ return { operation, signal, maxRetries };
2260
+ }
2261
+ callHeaders(headers) {
2262
+ return this.call.headers ? { ...this.call.headers, ...headers } : headers;
2263
+ }
2264
+ callBody(method, body) {
2265
+ const { extraBody } = this.call;
2266
+ if (!extraBody)
2267
+ return body;
2268
+ if (method === "GET" || method === "HEAD") {
2269
+ throw invalidArgument("extraBody needs a request with a body");
2270
+ }
2271
+ if (body === undefined)
2272
+ return extraBody;
2273
+ if (!isPlainObject2(body))
2274
+ throw invalidArgument("extraBody needs a JSON object body");
2275
+ return { ...body, ...extraBody };
2276
+ }
1781
2277
  get sleep() {
1782
2278
  return this.hooks?.sleep ?? sleep;
1783
2279
  }
@@ -1785,11 +2281,12 @@ class CalmLensConnection {
1785
2281
  return this.hooks?.deferUploadChecks ?? false;
1786
2282
  }
1787
2283
  get timeoutMs() {
1788
- return this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2284
+ return this.call.timeoutMs ?? this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1789
2285
  }
1790
2286
  url(path, query) {
1791
- const search = query ? stringifyQuery(query) : "";
1792
- return `${this.options.baseUrl}${path}${search ? `?${search}` : ""}`;
2287
+ const search = [query, this.call.extraQuery].map((values) => values ? stringifyQuery(values) : "").filter(Boolean).join("&");
2288
+ const separator = path.includes("?") ? "&" : "?";
2289
+ return `${this.options.baseUrl}${path}${search ? `${separator}${search}` : ""}`;
1793
2290
  }
1794
2291
  json(method, path, {
1795
2292
  query,
@@ -1797,34 +2294,40 @@ class CalmLensConnection {
1797
2294
  headers,
1798
2295
  idempotencyKey
1799
2296
  } = {}) {
2297
+ const sent = this.callBody(method, body);
1800
2298
  return this.transport.json({
2299
+ ...this.callRequest(),
1801
2300
  method,
1802
2301
  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,
2302
+ headers: this.callHeaders(sent === undefined ? headers : { ...headers, "Content-Type": "application/json" }),
2303
+ body: sent === undefined ? undefined : JSON.stringify(sent),
2304
+ idempotencyKey: idempotencyKey ?? this.call.idempotencyKey,
1806
2305
  timeoutMs: this.timeoutMs,
1807
2306
  deadline: "body"
1808
2307
  });
1809
2308
  }
1810
2309
  upload(url, body, headers, idempotencyKey, text) {
1811
2310
  return this.transport.json({
2311
+ ...this.callRequest(),
1812
2312
  method: "POST",
1813
2313
  url,
1814
- headers,
2314
+ headers: this.callHeaders(headers),
1815
2315
  body,
1816
2316
  idempotencyKey,
1817
- timeoutMs: text ? this.timeoutMs : this.options.uploadTimeoutMs,
2317
+ timeoutMs: text ? this.timeoutMs : this.call.timeoutMs ?? this.options.uploadTimeoutMs,
1818
2318
  deadline: "body",
1819
2319
  fetch: this.options.uploadFetch
1820
2320
  });
1821
2321
  }
1822
- submitUpload(uploadsPath, options, wait, authHeaders = {}) {
2322
+ async submitUpload(uploadsPath, options, wait, authHeaders = {}) {
1823
2323
  const isMultipart = "part" in options;
1824
2324
  const payload = isMultipart ? options.part : options.content;
1825
2325
  const multipartOptions = options;
1826
- const idempotencyKey = options.idempotencyKey ?? newIdempotencyKey();
1827
- const fields = uploadFields(options);
2326
+ const idempotencyKey = options.idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey();
2327
+ const fields = {
2328
+ ...uploadFields(options),
2329
+ ...this.call.extraBody
2330
+ };
1828
2331
  if (isTextPayload(payload)) {
1829
2332
  const { sizeInBytes: _size, ...text } = payload;
1830
2333
  const body = isMultipart ? {
@@ -1846,7 +2349,7 @@ class CalmLensConnection {
1846
2349
  setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? multipartOptions.sizeInBytes);
1847
2350
  setOptionalQueryValue(query, "totalSizeInBytes", multipartOptions.totalSizeInBytes);
1848
2351
  }
1849
- const form = toUploadForm(fields, payload);
2352
+ const form = await toUploadForm(fields, payload);
1850
2353
  return this.upload(this.url(`${uploadsPath}?${query}`), form.body, {
1851
2354
  ...authHeaders,
1852
2355
  "Content-Type": form.contentType,
@@ -1866,7 +2369,7 @@ class CalmLensConnection {
1866
2369
  const source = getSplittableContent(content);
1867
2370
  const partSize = this.partSizeBytes;
1868
2371
  const count = Math.ceil(source.size / partSize);
1869
- const key = idempotencyKey ?? newIdempotencyKey();
2372
+ const key = idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey();
1870
2373
  const part = (partNumber) => source.slice((partNumber - 1) * partSize, Math.min(partNumber * partSize, source.size));
1871
2374
  const first = await this.submitUpload(uploadsPath, {
1872
2375
  ...fields,
@@ -1876,11 +2379,18 @@ class CalmLensConnection {
1876
2379
  }, wait, authHeaders);
1877
2380
  const assetId = expectUploadedAsset(first).id;
1878
2381
  onStarted?.(assetId);
2382
+ const laterParts = new CalmLensConnection(this.options, undefined, {
2383
+ shared: {
2384
+ transport: this.transport,
2385
+ hooks: this.hooks,
2386
+ call: { ...this.call, extraBody: undefined }
2387
+ }
2388
+ });
1879
2389
  let result = first;
1880
2390
  for (let partNumber = 2;partNumber <= count; ) {
1881
2391
  const isFinal = partNumber === count;
1882
2392
  try {
1883
- result = await this.uploadPart(partPath(assetId), {
2393
+ result = await laterParts.uploadPart(partPath(assetId), {
1884
2394
  part: { ...part(partNumber), partNumber, isFinal },
1885
2395
  idempotencyKey: `${key}:part-${partNumber}`
1886
2396
  }, authHeaders);
@@ -1903,6 +2413,8 @@ class CalmLensConnection {
1903
2413
  uploadPart(partPath, { part, wait, idempotencyKey }, authHeaders = {}) {
1904
2414
  if (!part)
1905
2415
  throw invalidArgument("Part options are required");
2416
+ if (this.call.extraBody)
2417
+ throw invalidArgument("A part's body is its bytes: extraBody can't apply");
1906
2418
  assertDeclaredPayloadSize(part);
1907
2419
  const validation = validateAssetPayload(part, {
1908
2420
  multipart: true,
@@ -1917,7 +2429,7 @@ class CalmLensConnection {
1917
2429
  if (wait !== undefined)
1918
2430
  query.set("wait", String(wait));
1919
2431
  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));
2432
+ return this.upload(this.url(`${partPath}?${query}`), toRawUploadBody(part), { ...authHeaders, "X-CalmLens-Upload": "part" }, idempotencyKey ?? this.call.idempotencyKey ?? newIdempotencyKey(), isTextPayload(part));
1921
2433
  }
1922
2434
  }
1923
2435
 
@@ -1928,10 +2440,6 @@ var SERVER_OPTION_KEYS = {
1928
2440
  "assets.create": ["authorId", "content", "context", "description", "externalId", "externalUrl", "folderId", "isFinal", "metadata", "name", "part", "processingOptions", "sizeInBytes", "tags", "totalSizeInBytes", "uploadPresetId", "url", "visibility"],
1929
2441
  "assets.decide": ["assetId", "confirmPurge", "decision", "note"],
1930
2442
  "assets.delete": ["assetId"],
1931
- "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
2443
  "assets.list": ["cursor", "filter", "pageSize", "sort"],
1936
2444
  "assets.listChildren": ["assetId", "cursor", "pageSize", "sort"],
1937
2445
  "assets.listTimeline": ["assetId", "cursor", "pageSize"],
@@ -1946,10 +2454,8 @@ var SERVER_OPTION_KEYS = {
1946
2454
  ensureLens: ["active", "description", "identifier", "name", "transform", "type"],
1947
2455
  ensureLenses: ["lenses"],
1948
2456
  "events.list": ["assetId", "cursor", "pageSize", "types"],
1949
- "events.pages": ["assetId", "cursor", "pageSize", "types"],
1950
2457
  "folders.create": ["name", "parentId"],
1951
2458
  "folders.delete": ["folderId"],
1952
- "folders.iterate": ["cursor", "pageSize", "parentId", "search", "sort"],
1953
2459
  "folders.list": ["cursor", "pageSize", "parentId", "search", "sort"],
1954
2460
  "folders.move": ["folderId", "parentId"],
1955
2461
  "folders.retrieve": ["folderId"],
@@ -1957,8 +2463,6 @@ var SERVER_OPTION_KEYS = {
1957
2463
  "hashLists.addEntry": ["assetId", "hash", "hashListId", "label", "quality"],
1958
2464
  "hashLists.create": ["action", "description", "name"],
1959
2465
  "hashLists.delete": ["hashListId"],
1960
- "hashLists.iterate": ["cursor", "pageSize", "sort"],
1961
- "hashLists.iterateEntries": ["cursor", "hashListId", "pageSize", "sort"],
1962
2466
  "hashLists.list": ["cursor", "pageSize", "sort"],
1963
2467
  "hashLists.listEntries": ["cursor", "hashListId", "pageSize", "sort"],
1964
2468
  "hashLists.removeEntry": ["entryId"],
@@ -1966,7 +2470,6 @@ var SERVER_OPTION_KEYS = {
1966
2470
  "hashLists.update": ["action", "description", "hashListId", "name"],
1967
2471
  "lenses.create": ["active", "description", "identifier", "name", "transform", "type"],
1968
2472
  "lenses.delete": ["lensId"],
1969
- "lenses.iterate": ["cursor", "pageSize", "sort"],
1970
2473
  "lenses.list": ["cursor", "pageSize", "sort"],
1971
2474
  "lenses.retrieve": ["lensId"],
1972
2475
  "lenses.update": ["active", "description", "lensId", "name", "transform", "type"],
@@ -1976,7 +2479,6 @@ var SERVER_OPTION_KEYS = {
1976
2479
  "policies.assign": ["policyId"],
1977
2480
  "policies.create": ["description", "name", "presetId", "settings"],
1978
2481
  "policies.delete": ["policyId"],
1979
- "policies.iterate": ["cursor", "pageSize", "sort"],
1980
2482
  "policies.list": ["cursor", "pageSize", "sort"],
1981
2483
  "policies.reset": ["policyId", "presetVersion", "revision"],
1982
2484
  "policies.retrieve": ["policyId"],
@@ -1989,13 +2491,11 @@ var SERVER_OPTION_KEYS = {
1989
2491
  "text.classify": ["authorId", "context", "description", "externalId", "externalUrl", "folderId", "metadata", "name", "processingOptions", "tags", "text", "uploadPresetId", "visibility"],
1990
2492
  "uploadPresets.delete": ["uploadPresetId"],
1991
2493
  "uploadPresets.ensure": ["uploadPresets"],
1992
- "uploadPresets.iterate": ["cursor", "pageSize", "sort"],
1993
2494
  "uploadPresets.list": ["cursor", "pageSize", "sort"]
1994
2495
  };
1995
2496
  var NULLABLE_OPTION_KEYS = {
1996
2497
  "assets.classify": ["authorId", "context", "description", "externalId", "folderId", "metadata", "processingOptions", "tags", "uploadPresetId", "visibility"],
1997
2498
  "assets.create": ["authorId", "context", "description", "externalId", "folderId", "metadata", "processingOptions", "tags", "uploadPresetId", "visibility"],
1998
- "assets.iterate": ["filter"],
1999
2499
  "assets.list": ["filter"],
2000
2500
  "assets.move": ["folderId"],
2001
2501
  "assets.update": ["description", "externalId", "externalUrl", "metadata", "tags", "visibility"],
@@ -2122,6 +2622,31 @@ async function verifyWebhookSignature(options) {
2122
2622
  return matched;
2123
2623
  }
2124
2624
 
2625
+ // src/client/ServedAssetInfo.ts
2626
+ function parseServedAssetInfo(header) {
2627
+ if (!header)
2628
+ return;
2629
+ const dimensions = {};
2630
+ let start = 0;
2631
+ for (const delimiter of `${header},`.matchAll(/"(?:[^"\\]|\\.)*"|[",]/g)) {
2632
+ if (delimiter[0] === '"')
2633
+ return;
2634
+ if (delimiter[0] !== ",")
2635
+ continue;
2636
+ const member = header.slice(start, delimiter.index).trim();
2637
+ start = delimiter.index + 1;
2638
+ const [key] = member.split(/[=; \t]/, 1);
2639
+ if (key !== "width" && key !== "height")
2640
+ continue;
2641
+ const match = /^(?:width|height)=([0-9]{1,15})$/.exec(member);
2642
+ if (!match || dimensions[key] !== undefined || Number(match[1]) === 0)
2643
+ return;
2644
+ dimensions[key] = Number(match[1]);
2645
+ }
2646
+ const { width, height } = dimensions;
2647
+ return width === undefined || height === undefined ? undefined : { width, height };
2648
+ }
2649
+
2125
2650
  // src/client/CalmLensServerClient.ts
2126
2651
  var ENSURE_LENSES_MAX_PER_REQUEST = 100;
2127
2652
  var getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
@@ -2133,6 +2658,37 @@ var getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
2133
2658
  transform: options.transform ?? null
2134
2659
  });
2135
2660
  var requireId = (value, name) => encodePathSegment(value, name);
2661
+ var checkedTextContent = (options) => {
2662
+ if (options && "content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) {
2663
+ throw invalidPayload("Text to classify must be a non-empty string");
2664
+ }
2665
+ return options;
2666
+ };
2667
+ var anySignal = (signals) => {
2668
+ if (typeof AbortSignal.any === "function")
2669
+ return AbortSignal.any(signals);
2670
+ const controller = new AbortController;
2671
+ for (const signal of signals) {
2672
+ if (signal.aborted)
2673
+ controller.abort(signal.reason);
2674
+ else
2675
+ signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
2676
+ }
2677
+ return controller.signal;
2678
+ };
2679
+ var withEnvironmentDefaults = (options) => {
2680
+ if (!options || typeof options !== "object" || getMockHooks(options))
2681
+ return options;
2682
+ const apiKey = options.apiKey ?? readEnv("CALMLENS_API_KEY");
2683
+ const projectId = options.projectId ?? readEnv("CALMLENS_PROJECT_ID");
2684
+ const baseUrl = options.baseUrl ?? readEnv("CALMLENS_BASE_URL");
2685
+ return {
2686
+ ...options,
2687
+ ...apiKey !== undefined && { apiKey },
2688
+ ...projectId !== undefined && { projectId },
2689
+ ...baseUrl !== undefined && { baseUrl }
2690
+ };
2691
+ };
2136
2692
  var checked = (operation, options) => {
2137
2693
  checkOptionKeys(options, operation, SERVER_OPTION_KEYS);
2138
2694
  if (!options || typeof options !== "object" || Array.isArray(options))
@@ -2140,25 +2696,19 @@ var checked = (operation, options) => {
2140
2696
  const nullable = NULLABLE_OPTION_KEYS[operation] ?? [];
2141
2697
  return Object.fromEntries(Object.entries(options).filter(([key, value]) => value !== null || nullable.includes(key)));
2142
2698
  };
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
2699
  var inspectSymbol = Symbol.for("nodejs.util.inspect.custom");
2153
2700
  var writableCdnResponse = (response, metadata = response) => {
2154
- if (response.status < 200)
2155
- return response;
2156
- const writable = new Response(response.body, response);
2701
+ const writable = response.status < 200 ? response : new Response(response.body, response);
2157
2702
  const { url, redirected, type } = metadata;
2158
2703
  return Object.defineProperties(writable, {
2159
2704
  url: { value: url },
2160
2705
  redirected: { value: redirected },
2161
2706
  type: { value: type },
2707
+ getAssetInfo: {
2708
+ value() {
2709
+ return parseServedAssetInfo(this.headers.get("X-CalmLens-Asset-Info"));
2710
+ }
2711
+ },
2162
2712
  clone: {
2163
2713
  value() {
2164
2714
  return writableCdnResponse(Response.prototype.clone.call(this), { url, redirected, type });
@@ -2169,31 +2719,29 @@ var writableCdnResponse = (response, metadata = response) => {
2169
2719
 
2170
2720
  class CalmLensServerClient {
2171
2721
  #apiKey;
2172
- #options;
2173
2722
  #settings;
2174
2723
  #lenses;
2175
2724
  #connection;
2176
2725
  static async verifyWebhookSignature(options) {
2177
2726
  return verifyWebhookSignature(options);
2178
2727
  }
2179
- constructor(options, lenses) {
2728
+ constructor(clientOptions = {}, lenses) {
2729
+ const options = withEnvironmentDefaults(clientOptions);
2180
2730
  validateServerClientOptions(options);
2181
2731
  if ((isBrowserRuntime() || isReactNativeRuntime()) && !options.dangerouslyAllowBrowser) {
2182
2732
  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
2733
  }
2184
- const { apiKey, ...rest } = options;
2734
+ const { apiKey, projectId, ...rest } = options;
2185
2735
  this.#apiKey = apiKey;
2186
- this.#options = rest;
2187
2736
  this.#settings = {
2737
+ projectId,
2188
2738
  ...resolveConnectionOptions(rest),
2189
2739
  cdnBaseUrl: (rest.cdnBaseUrl ?? getMockHooks(rest)?.defaultCdnBaseUrl ?? DEFAULT_CDN_BASE_URL).replace(/\/+$/, "")
2190
2740
  };
2191
2741
  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);
2742
+ this.#connection = new CalmLensConnection(this.#settings, apiKey, {
2743
+ readEnvironment: !getMockHooks(options)
2744
+ });
2197
2745
  }
2198
2746
  [inspectSymbol]() {
2199
2747
  const { projectId, baseUrl } = this.#settings;
@@ -2203,32 +2751,56 @@ class CalmLensServerClient {
2203
2751
  const { projectId, baseUrl, cdnBaseUrl } = this.#settings;
2204
2752
  return { projectId, baseUrl, cdnBaseUrl };
2205
2753
  }
2206
- get projectPath() {
2754
+ get #projectPath() {
2207
2755
  return `/projects/${encodeURIComponent(this.#settings.projectId)}`;
2208
2756
  }
2209
- request(method, path, options = {}) {
2210
- return this.#connection.json(method, path, options);
2757
+ async#send(operation, requestOptions, method, path, options = {}) {
2758
+ return this.#connection.forCall(operation, requestOptions).json(method, path, options);
2211
2759
  }
2212
- async submitAsset(options, wait) {
2760
+ async request(method, path, {
2761
+ query,
2762
+ body,
2763
+ headers
2764
+ } = {}, requestOptions) {
2765
+ const methods = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"];
2766
+ if (typeof method !== "string" || !methods.includes(method)) {
2767
+ throw invalidArgument(`method must be one of ${methods.join(", ")}`);
2768
+ }
2769
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//")) {
2770
+ throw invalidArgument('path must start with "/", such as "/assets/asset_123"');
2771
+ }
2772
+ const { headers: callHeaders, ...rest } = requestOptions ?? {};
2773
+ return this.#send(undefined, { ...rest, ...(callHeaders || headers) && { headers: { ...callHeaders, ...headers } } }, method, path, { query, body });
2774
+ }
2775
+ #paginate(operation, options, requestOptions, send) {
2776
+ const first = options?.cursor;
2777
+ return listPages(async (cursor) => {
2778
+ const valid = checked(operation, options);
2779
+ return send(cursor === first ? valid : { ...valid, cursor });
2780
+ }, { cursor: typeof first === "string" ? first : undefined, feed: operation === "events.list" });
2781
+ }
2782
+ async#submitAsset(operation, options, wait, requestOptions) {
2783
+ const connection = this.#connection.forCall(operation, requestOptions);
2213
2784
  const body = prepareSubmitAssetOptions(options, {
2214
- deferUploadChecks: this.#connection.deferUploadChecks,
2215
- partSizeBytes: this.#connection.partSizeBytes
2785
+ deferUploadChecks: connection.deferUploadChecks,
2786
+ partSizeBytes: connection.partSizeBytes
2216
2787
  });
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, {
2788
+ const uploadsPath = `${this.#projectPath}/assets`;
2789
+ if ("content" in body && splitsIntoParts(body.content, connection.partSizeBytes)) {
2790
+ const { idempotencyKey: _key, extraBody: _body, ...readOptions } = requestOptions ?? {};
2791
+ return expectAsset(await connection.submitInParts(uploadsPath, body, wait, {
2220
2792
  partPath: (assetId) => `/assets/${encodeURIComponent(assetId)}/part`,
2221
- retrieve: (assetId) => this.buildAssets().retrieve({ assetId })
2793
+ retrieve: (assetId) => this.#buildAssets().retrieve({ assetId }, readOptions)
2222
2794
  }));
2223
2795
  }
2224
2796
  if ("content" in body || "part" in body) {
2225
- return expectAsset(await this.#connection.submitUpload(uploadsPath, body, wait));
2797
+ return expectAsset(await connection.submitUpload(uploadsPath, body, wait));
2226
2798
  }
2227
2799
  const { idempotencyKey, ...fields } = body;
2228
- const data = await this.#connection.json("POST", uploadsPath, {
2800
+ const data = await connection.json("POST", uploadsPath, {
2229
2801
  query: { wait },
2230
2802
  body: fields,
2231
- idempotencyKey: idempotencyKey ?? newIdempotencyKey()
2803
+ idempotencyKey: idempotencyKey ?? requestOptions?.idempotencyKey ?? newIdempotencyKey()
2232
2804
  });
2233
2805
  return expectAsset(data);
2234
2806
  }
@@ -2238,12 +2810,12 @@ class CalmLensServerClient {
2238
2810
  const { projectId, ...options } = checked("cdn.getAssetUrl", urlOptions);
2239
2811
  return buildAssetUrl(this.#settings.cdnBaseUrl, projectId ?? this.#settings.projectId, options);
2240
2812
  },
2241
- signAssetUrl: async (signOptions) => {
2813
+ signAssetUrl: async (signOptions, requestOptions) => {
2242
2814
  const options = checked("cdn.signAssetUrl", signOptions);
2243
2815
  validateSignAssetUrlOptions(options);
2244
2816
  const { projectId, assetId, externalId, expiresIn, original, ...location } = options;
2245
2817
  const project = requireId(projectId ?? this.#settings.projectId, "Project ID");
2246
- const signed = await this.request("POST", `/projects/${project}/signed-asset-urls`, {
2818
+ const signed = await this.#send("cdn.signAssetUrl", requestOptions, "POST", `/projects/${project}/signed-asset-urls`, {
2247
2819
  body: {
2248
2820
  ...assetId !== undefined ? { assetId } : { externalId },
2249
2821
  expiresIn: expiresIn ?? DEFAULT_SIGNED_URL_EXPIRES_IN,
@@ -2255,18 +2827,24 @@ class CalmLensServerClient {
2255
2827
  message: "The API returned no signed asset URL"
2256
2828
  });
2257
2829
  }
2258
- return { url: appendAssetLocation(signed.url, location), expiresAt: signed.expiresAt };
2830
+ return copyLastResponse({ url: appendAssetLocation(signed.url, location), expiresAt: signed.expiresAt }, signed);
2259
2831
  },
2260
2832
  getAssetInfo: (url, options = {}) => getAssetInfo(url, { ...options, fetch: this.#settings.cdnFetch }),
2261
- serve: async (options) => {
2833
+ serve: async (options, requestOptions) => {
2262
2834
  const { init, resource = "rendered", ...urlOptions } = checked("cdn.serve", options);
2835
+ const connection = this.#connection.forCall("cdn.serve", requestOptions);
2836
+ if (requestOptions?.extraBody)
2837
+ throw invalidArgument("cdn.serve sends no body: extraBody can't apply");
2263
2838
  const url = this.cdn.getAssetUrl({ ...urlOptions, resource });
2839
+ const extraQuery = requestOptions?.extraQuery && stringifyQuery(requestOptions.extraQuery);
2264
2840
  const method = init?.method?.toUpperCase() ?? "GET";
2265
- const { response } = await this.#connection.transport.send({
2841
+ const { response } = await connection.transport.send({
2842
+ ...connection.callRequest(),
2266
2843
  method,
2267
- url,
2844
+ url: extraQuery ? `${url}${url.includes("?") ? "&" : "?"}${extraQuery}` : url,
2845
+ headers: requestOptions?.headers,
2268
2846
  init,
2269
- timeoutMs: this.#connection.timeoutMs,
2847
+ timeoutMs: connection.timeoutMs,
2270
2848
  deadline: "headers",
2271
2849
  fetch: this.#settings.cdnFetch
2272
2850
  }, { allowHttpErrors: true });
@@ -2276,11 +2854,11 @@ class CalmLensServerClient {
2276
2854
  }
2277
2855
  get text() {
2278
2856
  return {
2279
- classify: async (options) => this.buildAssets().classify(toTextAssetOptions(checked("text.classify", options)))
2857
+ classify: async (options, requestOptions) => this.#submitAsset("text.classify", checkedTextContent(toTextAssetOptions(checked("text.classify", options))), true, requestOptions)
2280
2858
  };
2281
2859
  }
2282
2860
  get assets() {
2283
- return this.buildAssets();
2861
+ return this.#buildAssets();
2284
2862
  }
2285
2863
  get uploadTokens() {
2286
2864
  return {
@@ -2289,100 +2867,72 @@ class CalmLensServerClient {
2289
2867
  }
2290
2868
  };
2291
2869
  }
2292
- buildAssets() {
2870
+ #buildAssets() {
2293
2871
  return {
2294
- search: async (options) => this.request("GET", `${this.projectPath}/assets/search`, {
2872
+ search: async (options, requestOptions) => this.#send("assets.search", requestOptions, "GET", `${this.#projectPath}/assets/search`, {
2295
2873
  query: checked("assets.search", options)
2296
2874
  }),
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) => {
2875
+ list: (options = {}, requestOptions) => this.#paginate("assets.list", options, requestOptions, (query) => this.#send("assets.list", requestOptions, "GET", `${this.#projectPath}/assets`, {
2876
+ query
2877
+ })),
2878
+ retrieve: async (options, requestOptions) => {
2305
2879
  const { assetId } = checked("assets.retrieve", options);
2306
- return this.request("GET", `/assets/${requireId(assetId, "Asset ID")}`);
2880
+ return this.#send("assets.retrieve", requestOptions, "GET", `/assets/${requireId(assetId, "Asset ID")}`);
2307
2881
  },
2308
- update: async (options) => {
2882
+ update: async (options, requestOptions) => {
2309
2883
  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
- });
2884
+ return this.#send("assets.update", requestOptions, "PATCH", `/assets/${requireId(assetId, "Asset ID")}`, { body });
2317
2885
  },
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`, {
2886
+ listChildren: (options, requestOptions) => this.#paginate("assets.listChildren", options ?? {}, requestOptions, ({ assetId, ...query }) => this.#send("assets.listChildren", requestOptions, "GET", `/assets/${requireId(assetId, "Asset ID")}/children`, { query })),
2887
+ listTimeline: (options, requestOptions) => this.#paginate("assets.listTimeline", options, requestOptions, ({ assetId, ...query }) => {
2888
+ const assetPath = `${this.#projectPath}/assets/${requireId(assetId, "Asset ID")}`;
2889
+ return this.#send("assets.listTimeline", requestOptions, "GET", `${assetPath}/timeline`, {
2322
2890
  query
2323
2891
  });
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) => {
2892
+ }),
2893
+ create: async (options, requestOptions) => this.#submitAsset("assets.create", checked("assets.create", options), false, requestOptions),
2894
+ classify: async (options, requestOptions) => this.#submitAsset("assets.classify", checkedTextContent(checked("assets.classify", options)), true, requestOptions),
2895
+ uploadPart: async (partOptions, requestOptions) => {
2344
2896
  const { assetId, ...options } = checked("assets.uploadPart", partOptions);
2345
2897
  const encodedAssetId = requireId(assetId, "Asset ID");
2346
- return expectAsset(await this.#connection.uploadPart(`/assets/${encodedAssetId}/part`, options));
2898
+ const connection = this.#connection.forCall("assets.uploadPart", requestOptions);
2899
+ return expectAsset(await connection.uploadPart(`/assets/${encodedAssetId}/part`, options));
2347
2900
  },
2348
- move: async (options) => {
2901
+ move: async (options, requestOptions) => {
2349
2902
  const { assetId, folderId } = checked("assets.move", options);
2350
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/move`, {
2903
+ return this.#send("assets.move", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/move`, {
2351
2904
  body: { folderId }
2352
2905
  });
2353
2906
  },
2354
- retry: async (options) => {
2907
+ retry: async (options, requestOptions) => {
2355
2908
  const { assetId } = checked("assets.retry", options);
2356
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/retry`);
2909
+ return this.#send("assets.retry", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/retry`);
2357
2910
  },
2358
- decide: async (options) => {
2911
+ decide: async (options, requestOptions) => {
2359
2912
  const { assetId, ...body } = checked("assets.decide", options);
2360
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/decision`, { body });
2361
- },
2362
- explain: async (options) => {
2363
- const { assetId, rerun } = checked("assets.explain", options);
2364
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/explain`, {
2365
- body: rerun ? { rerun } : {}
2366
- });
2913
+ return this.#send("assets.decide", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/decision`, { body });
2367
2914
  },
2368
- waitForDecision: async (waitOptions) => {
2915
+ waitForDecision: async (waitOptions, requestOptions) => {
2369
2916
  const { assetId, ...options } = checked("assets.waitForDecision", waitOptions);
2370
2917
  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);
2918
+ validateCallOptions(requestOptions);
2919
+ const signals = [options.signal, requestOptions?.signal].filter((signal) => signal !== undefined);
2920
+ const signal = signals.length > 1 ? anySignal(signals) : signals[0];
2921
+ const checkOptions = { ...requestOptions, ...signal && { signal } };
2922
+ return pollForDecision(() => this.#send("assets.waitForDecision", checkOptions, "GET", `/assets/${requireId(assetId, "Asset ID")}`), options, this.#connection.sleep, this.#connection.hooks?.now);
2373
2923
  },
2374
- removeContent: async (options) => {
2924
+ removeContent: async (options, requestOptions) => {
2375
2925
  const { assetId } = checked("assets.removeContent", options);
2376
- return this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}/content`);
2926
+ return this.#send("assets.removeContent", requestOptions, "DELETE", `/assets/${requireId(assetId, "Asset ID")}/content`);
2377
2927
  },
2378
- delete: async (options) => {
2928
+ delete: async (options, requestOptions) => {
2379
2929
  const { assetId } = checked("assets.delete", options);
2380
- await this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}`);
2930
+ await this.#send("assets.delete", requestOptions, "DELETE", `/assets/${requireId(assetId, "Asset ID")}`);
2381
2931
  },
2382
- batch: async (options) => {
2932
+ batch: async (options, requestOptions) => {
2383
2933
  const { assetIds, operation } = checked("assets.batch", options);
2384
2934
  validateBatchAssetsOptions({ assetIds, operation });
2385
- return this.request("POST", `${this.projectPath}/assets/batch`, {
2935
+ return this.#send("assets.batch", requestOptions, "POST", `${this.#projectPath}/assets/batch`, {
2386
2936
  body: { assetIds, operation }
2387
2937
  });
2388
2938
  }
@@ -2390,69 +2940,34 @@ class CalmLensServerClient {
2390
2940
  }
2391
2941
  get events() {
2392
2942
  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))
2943
+ list: (options = {}, requestOptions) => this.#paginate("events.list", options, requestOptions, ({ types, ...query }) => this.#send("events.list", requestOptions, "GET", `${this.#projectPath}/events`, {
2944
+ query: { ...query, types: types?.length ? types.join(",") : undefined }
2945
+ }))
2400
2946
  };
2401
2947
  }
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
2948
  get folders() {
2430
2949
  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) => {
2950
+ list: (options = {}, requestOptions) => this.#paginate("folders.list", options, requestOptions, (query) => this.#send("folders.list", requestOptions, "GET", `${this.#projectPath}/folders`, {
2951
+ query
2952
+ })),
2953
+ retrieve: async (options, requestOptions) => {
2439
2954
  const { folderId } = checked("folders.retrieve", options);
2440
- return this.request("GET", `/folders/${requireId(folderId, "Folder ID")}`);
2955
+ return this.#send("folders.retrieve", requestOptions, "GET", `/folders/${requireId(folderId, "Folder ID")}`);
2441
2956
  },
2442
- create: async (options) => this.request("POST", `${this.projectPath}/folders`, {
2957
+ create: async (options, requestOptions) => this.#send("folders.create", requestOptions, "POST", `${this.#projectPath}/folders`, {
2443
2958
  body: checked("folders.create", options)
2444
2959
  }),
2445
- update: async (options) => {
2960
+ update: async (options, requestOptions) => {
2446
2961
  const { folderId, ...body } = checked("folders.update", options);
2447
- return this.request("PATCH", `/folders/${requireId(folderId, "Folder ID")}`, { body });
2962
+ return this.#send("folders.update", requestOptions, "PATCH", `/folders/${requireId(folderId, "Folder ID")}`, { body });
2448
2963
  },
2449
- delete: async (options) => {
2964
+ delete: async (options, requestOptions) => {
2450
2965
  const { folderId } = checked("folders.delete", options);
2451
- await this.request("DELETE", `/folders/${requireId(folderId, "Folder ID")}`);
2966
+ await this.#send("folders.delete", requestOptions, "DELETE", `/folders/${requireId(folderId, "Folder ID")}`);
2452
2967
  },
2453
- move: async (options) => {
2968
+ move: async (options, requestOptions) => {
2454
2969
  const { folderId, parentId } = checked("folders.move", options);
2455
- return this.request("POST", `/folders/${requireId(folderId, "Folder ID")}/move`, {
2970
+ return this.#send("folders.move", requestOptions, "POST", `/folders/${requireId(folderId, "Folder ID")}/move`, {
2456
2971
  body: { parentId }
2457
2972
  });
2458
2973
  }
@@ -2460,121 +2975,103 @@ class CalmLensServerClient {
2460
2975
  }
2461
2976
  get hashLists() {
2462
2977
  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) => {
2978
+ list: (options = {}, requestOptions) => this.#paginate("hashLists.list", options, requestOptions, (query) => this.#send("hashLists.list", requestOptions, "GET", `${this.#projectPath}/hash-lists`, {
2979
+ query
2980
+ })),
2981
+ retrieve: async (options, requestOptions) => {
2471
2982
  const { hashListId } = checked("hashLists.retrieve", options);
2472
- return this.request("GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
2983
+ return this.#send("hashLists.retrieve", requestOptions, "GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
2473
2984
  },
2474
- create: async (options) => this.request("POST", `${this.projectPath}/hash-lists`, {
2985
+ create: async (options, requestOptions) => this.#send("hashLists.create", requestOptions, "POST", `${this.#projectPath}/hash-lists`, {
2475
2986
  body: checked("hashLists.create", options)
2476
2987
  }),
2477
- update: async (options) => {
2988
+ update: async (options, requestOptions) => {
2478
2989
  const { hashListId, ...body } = checked("hashLists.update", options);
2479
- return this.request("PATCH", `/hash-lists/${requireId(hashListId, "Hash list ID")}`, {
2990
+ return this.#send("hashLists.update", requestOptions, "PATCH", `/hash-lists/${requireId(hashListId, "Hash list ID")}`, {
2480
2991
  body
2481
2992
  });
2482
2993
  },
2483
- delete: async (options) => {
2994
+ delete: async (options, requestOptions) => {
2484
2995
  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 }));
2996
+ await this.#send("hashLists.delete", requestOptions, "DELETE", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
2491
2997
  },
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
- });
2497
- },
2498
- addEntry: async (options) => {
2998
+ 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`, {
2999
+ query
3000
+ })),
3001
+ addEntry: async (options, requestOptions) => {
2499
3002
  const { hashListId, ...body } = checked("hashLists.addEntry", options);
2500
- return this.request("POST", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, { body });
3003
+ return this.#send("hashLists.addEntry", requestOptions, "POST", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, { body });
2501
3004
  },
2502
- removeEntry: async (options) => {
3005
+ removeEntry: async (options, requestOptions) => {
2503
3006
  const { entryId } = checked("hashLists.removeEntry", options);
2504
- await this.request("DELETE", `/hash-list-entries/${requireId(entryId, "Hash list entry ID")}`);
3007
+ await this.#send("hashLists.removeEntry", requestOptions, "DELETE", `/hash-list-entries/${requireId(entryId, "Hash list entry ID")}`);
2505
3008
  }
2506
3009
  };
2507
3010
  }
2508
3011
  get policies() {
2509
3012
  const policyPath = (policyId) => `/policies/${requireId(policyId, "Policy ID")}`;
2510
3013
  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) => {
3014
+ list: (options = {}, requestOptions) => this.#paginate("policies.list", options, requestOptions, (query) => this.#send("policies.list", requestOptions, "GET", "/policies", { query })),
3015
+ retrieve: async (options, requestOptions) => this.#send("policies.retrieve", requestOptions, "GET", policyPath(checked("policies.retrieve", options).policyId)),
3016
+ create: async (options, requestOptions) => this.#send("policies.create", requestOptions, "POST", "/policies", {
3017
+ body: checked("policies.create", options)
3018
+ }),
3019
+ update: async (options, requestOptions) => {
2519
3020
  const { policyId, ...body } = checked("policies.update", options);
2520
- return this.request("PATCH", policyPath(policyId), { body });
3021
+ return this.#send("policies.update", requestOptions, "PATCH", policyPath(policyId), {
3022
+ body
3023
+ });
2521
3024
  },
2522
- reset: async (options) => {
3025
+ reset: async (options, requestOptions) => {
2523
3026
  const { policyId, ...body } = checked("policies.reset", options);
2524
- return this.request("POST", `${policyPath(policyId)}/reset`, { body });
3027
+ return this.#send("policies.reset", requestOptions, "POST", `${policyPath(policyId)}/reset`, { body });
2525
3028
  },
2526
- upgrade: async (options) => {
3029
+ upgrade: async (options, requestOptions) => {
2527
3030
  const { policyId, ...body } = checked("policies.upgrade", options);
2528
- return this.request("POST", `${policyPath(policyId)}/upgrade`, { body });
3031
+ return this.#send("policies.upgrade", requestOptions, "POST", `${policyPath(policyId)}/upgrade`, { body });
2529
3032
  },
2530
- setAutomaticUpdates: async (options) => {
3033
+ setAutomaticUpdates: async (options, requestOptions) => {
2531
3034
  const { policyId, ...body } = checked("policies.setAutomaticUpdates", options);
2532
- return this.request("PUT", `${policyPath(policyId)}/automatic-updates`, { body });
3035
+ return this.#send("policies.setAutomaticUpdates", requestOptions, "PUT", `${policyPath(policyId)}/automatic-updates`, { body });
2533
3036
  },
2534
- delete: async (options) => {
2535
- await this.request("DELETE", policyPath(checked("policies.delete", options).policyId));
3037
+ delete: async (options, requestOptions) => {
3038
+ await this.#send("policies.delete", requestOptions, "DELETE", policyPath(checked("policies.delete", options).policyId));
2536
3039
  },
2537
- retrieveAssigned: async () => this.request("GET", `${this.projectPath}/policy`),
2538
- assign: async (options) => this.request("PUT", `${this.projectPath}/policy`, {
3040
+ retrieveAssigned: async (requestOptions) => this.#send("policies.retrieveAssigned", requestOptions, "GET", `${this.#projectPath}/policy`),
3041
+ assign: async (options, requestOptions) => this.#send("policies.assign", requestOptions, "PUT", `${this.#projectPath}/policy`, {
2539
3042
  body: checked("policies.assign", options)
2540
3043
  })
2541
3044
  };
2542
3045
  }
2543
3046
  get uploadPresets() {
2544
3047
  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`, {
3048
+ list: (options = {}, requestOptions) => this.#paginate("uploadPresets.list", options, requestOptions, (query) => this.#send("uploadPresets.list", requestOptions, "GET", `${this.#projectPath}/upload-presets`, { query })),
3049
+ ensure: async (options, requestOptions) => this.#send("uploadPresets.ensure", requestOptions, "PUT", `${this.#projectPath}/upload-presets`, {
2553
3050
  body: checked("uploadPresets.ensure", options)
2554
3051
  }),
2555
- delete: async (options) => {
3052
+ delete: async (options, requestOptions) => {
2556
3053
  const { uploadPresetId } = checked("uploadPresets.delete", options);
2557
- await this.request("DELETE", `/upload-presets/${requireId(uploadPresetId, "Upload preset ID")}`);
3054
+ await this.#send("uploadPresets.delete", requestOptions, "DELETE", `/upload-presets/${requireId(uploadPresetId, "Upload preset ID")}`);
2558
3055
  }
2559
3056
  };
2560
3057
  }
2561
3058
  get projectSettings() {
2562
3059
  return {
2563
- get: async () => this.request("GET", `${this.projectPath}/settings`),
2564
- update: async (options) => this.request("PUT", `${this.projectPath}/settings`, {
3060
+ get: async (requestOptions) => this.#send("projectSettings.get", requestOptions, "GET", `${this.#projectPath}/settings`),
3061
+ update: async (options, requestOptions) => this.#send("projectSettings.update", requestOptions, "PUT", `${this.#projectPath}/settings`, {
2565
3062
  body: checked("projectSettings.update", options)
2566
3063
  })
2567
3064
  };
2568
3065
  }
2569
3066
  get metadataFields() {
2570
3067
  return {
2571
- list: async () => this.request("GET", `${this.projectPath}/metadata-fields`),
2572
- ensure: async (options) => this.request("PUT", `${this.projectPath}/metadata-fields`, {
3068
+ list: async (requestOptions) => this.#send("metadataFields.list", requestOptions, "GET", `${this.#projectPath}/metadata-fields`),
3069
+ ensure: async (options, requestOptions) => this.#send("metadataFields.ensure", requestOptions, "PUT", `${this.#projectPath}/metadata-fields`, {
2573
3070
  body: checked("metadataFields.ensure", options)
2574
3071
  }),
2575
- delete: async (options) => {
3072
+ delete: async (options, requestOptions) => {
2576
3073
  const { fieldId, ...query } = checked("metadataFields.delete", options);
2577
- await this.request("DELETE", `${this.projectPath}/metadata-fields/${requireId(fieldId, "Metadata field ID")}`, { query });
3074
+ await this.#send("metadataFields.delete", requestOptions, "DELETE", `${this.#projectPath}/metadata-fields/${requireId(fieldId, "Metadata field ID")}`, { query });
2578
3075
  }
2579
3076
  };
2580
3077
  }
@@ -2586,42 +3083,39 @@ class CalmLensServerClient {
2586
3083
  this.#lenses.ensuredLenses.delete(cacheKey);
2587
3084
  };
2588
3085
  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`, {
3086
+ list: (options = {}, requestOptions) => this.#paginate("lenses.list", options, requestOptions, (query) => this.#send("lenses.list", requestOptions, "GET", `${this.#projectPath}/lenses`, {
3087
+ query
3088
+ })),
3089
+ create: async (options, requestOptions) => {
3090
+ const lens = await this.#send("lenses.create", requestOptions, "POST", `${this.#projectPath}/lenses`, {
2598
3091
  body: checked("lenses.create", options)
2599
3092
  });
2600
3093
  forget((cached) => cached.identifier === lens.identifier);
2601
3094
  return lens;
2602
3095
  },
2603
- retrieve: async (options) => this.request("GET", lensPath(checked("lenses.retrieve", options).lensId)),
2604
- update: async (options) => {
3096
+ retrieve: async (options, requestOptions) => this.#send("lenses.retrieve", requestOptions, "GET", lensPath(checked("lenses.retrieve", options).lensId)),
3097
+ update: async (options, requestOptions) => {
2605
3098
  const { lensId, ...body } = checked("lenses.update", options);
2606
- const lens = await this.request("PATCH", lensPath(lensId), { body });
3099
+ const lens = await this.#send("lenses.update", requestOptions, "PATCH", lensPath(lensId), { body });
2607
3100
  forget((cached) => cached.id === lens.id);
2608
3101
  return lens;
2609
3102
  },
2610
- delete: async (options) => {
3103
+ delete: async (options, requestOptions) => {
2611
3104
  const { lensId } = checked("lenses.delete", options);
2612
- await this.request("DELETE", lensPath(lensId));
3105
+ await this.#send("lenses.delete", requestOptions, "DELETE", lensPath(lensId));
2613
3106
  forget((cached) => cached.id === lensId);
2614
3107
  }
2615
3108
  };
2616
3109
  }
2617
- async ensureLens(options) {
3110
+ async ensureLens(options, requestOptions) {
2618
3111
  checked("ensureLens", options);
2619
3112
  if (!options?.identifier)
2620
3113
  throw invalidArgument("Lens identifier is required");
2621
- const [lens] = await this.ensureLenses({ lenses: [options] });
3114
+ const [lens] = await this.ensureLenses({ lenses: [options] }, requestOptions);
2622
3115
  return lens;
2623
3116
  }
2624
- async ensureLenses(options) {
3117
+ async ensureLenses(options, requestOptions) {
3118
+ validateCallOptions(requestOptions);
2625
3119
  const { lenses } = checked("ensureLenses", options);
2626
3120
  if (!Array.isArray(lenses) || lenses.length === 0) {
2627
3121
  throw invalidArgument("At least one lens is required");
@@ -2645,7 +3139,7 @@ class CalmLensServerClient {
2645
3139
  const batchCacheKey = JSON.stringify([...missingKeys].sort());
2646
3140
  let pending = pendingEnsureLenses.get(batchCacheKey);
2647
3141
  if (!pending) {
2648
- pending = this.submitEnsureLenses(missingOptions);
3142
+ pending = this.#submitEnsureLenses(missingOptions, requestOptions);
2649
3143
  pendingEnsureLenses.set(batchCacheKey, pending);
2650
3144
  pending.then(() => pendingEnsureLenses.delete(batchCacheKey), () => pendingEnsureLenses.delete(batchCacheKey));
2651
3145
  }
@@ -2661,15 +3155,13 @@ class CalmLensServerClient {
2661
3155
  return lens;
2662
3156
  });
2663
3157
  }
2664
- async submitEnsureLenses(options) {
3158
+ async#submitEnsureLenses(options, requestOptions) {
2665
3159
  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));
3160
+ await this.#submitEnsureLensesChunk(options.slice(start, start + ENSURE_LENSES_MAX_PER_REQUEST), requestOptions);
2667
3161
  }
2668
3162
  }
2669
- async submitEnsureLensesChunk(options) {
2670
- const result = await this.request("PUT", `${this.projectPath}/lenses`, {
2671
- body: { lenses: options }
2672
- });
3163
+ async#submitEnsureLensesChunk(options, requestOptions) {
3164
+ const result = await this.#send("ensureLenses", requestOptions, "PUT", `${this.#projectPath}/lenses`, { body: { lenses: options } });
2673
3165
  const returned = Array.isArray(result?.lenses) ? result.lenses : [];
2674
3166
  if (returned.length !== options.length) {
2675
3167
  throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
@@ -2810,6 +3302,9 @@ function mergeDefs(...defs) {
2810
3302
  function esc(str) {
2811
3303
  return JSON.stringify(str);
2812
3304
  }
3305
+ function slugify(input) {
3306
+ return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
3307
+ }
2813
3308
  var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
2814
3309
  function isObject(data) {
2815
3310
  return typeof data === "object" && data !== null && !Array.isArray(data);
@@ -2829,7 +3324,7 @@ var allowsEval = /* @__PURE__ */ cached(() => {
2829
3324
  return false;
2830
3325
  }
2831
3326
  });
2832
- function isPlainObject2(o) {
3327
+ function isPlainObject3(o) {
2833
3328
  if (isObject(o) === false)
2834
3329
  return false;
2835
3330
  const ctor = o.constructor;
@@ -2846,7 +3341,7 @@ function isPlainObject2(o) {
2846
3341
  return true;
2847
3342
  }
2848
3343
  function shallowClone(o) {
2849
- if (isPlainObject2(o))
3344
+ if (isPlainObject3(o))
2850
3345
  return { ...o };
2851
3346
  if (Array.isArray(o))
2852
3347
  return [...o];
@@ -2941,7 +3436,7 @@ function omit(schema, mask) {
2941
3436
  return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
2942
3437
  }
2943
3438
  function extend(schema, shape) {
2944
- if (!isPlainObject2(shape)) {
3439
+ if (!isPlainObject3(shape)) {
2945
3440
  throw new Error("Invalid input to extend: expected a plain object");
2946
3441
  }
2947
3442
  const checks = schema._zod.def.checks;
@@ -2963,7 +3458,7 @@ function extended(schema, shape) {
2963
3458
  return newShape;
2964
3459
  }
2965
3460
  function safeExtend(schema, shape) {
2966
- if (!isPlainObject2(shape)) {
3461
+ if (!isPlainObject3(shape)) {
2967
3462
  throw new Error("Invalid input to safeExtend: expected a plain object");
2968
3463
  }
2969
3464
  return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
@@ -3626,15 +4121,65 @@ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
3626
4121
  return _safeParseAsync(_Err)(schema, value, _ctx);
3627
4122
  };
3628
4123
  // ../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/regexes.js
4124
+ var cuid = /^[cC][0-9a-z]{6,}$/;
4125
+ var cuid2 = /^[0-9a-z]+$/;
4126
+ var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
4127
+ var xid = /^[0-9a-vA-V]{20}$/;
4128
+ var ksuid = /^[A-Za-z0-9]{27}$/;
4129
+ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
4130
+ function nanoidOfLength(length) {
4131
+ return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
4132
+ }
4133
+ var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
4134
+ 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})$/;
4135
+ var uuid = (version) => {
4136
+ if (!version)
4137
+ 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)$/;
4138
+ 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})$`);
4139
+ };
4140
+ 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,}$/;
4141
+ var _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;
4142
+ function emoji() {
4143
+ return new RegExp(_emoji, "u");
4144
+ }
4145
+ 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])$/;
4146
+ 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}|:))$/;
4147
+ 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])$/;
4148
+ 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
4149
  var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
3630
4150
  var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
3631
- var number = /^-?\d+(?:\.\d+)?$/;
3632
- var boolean = /^(?:true|false)$/i;
3633
-
3634
- // ../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/checks.js
3635
- var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
3636
- var _a;
3637
- inst._zod ?? (inst._zod = {});
4151
+ var httpProtocol = /^https?$/;
4152
+ var e164 = /^\+[1-9]\d{6,14}$/;
4153
+ 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])))`;
4154
+ function anchor(source) {
4155
+ return new RegExp(`^${source}$`);
4156
+ }
4157
+ var date = /* @__PURE__ */ anchor(dateSource);
4158
+ function timeSource(args) {
4159
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
4160
+ 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+)?)?`;
4161
+ return regex;
4162
+ }
4163
+ function time(args) {
4164
+ return new RegExp(`^${timeSource(args)}$`);
4165
+ }
4166
+ function datetime(args) {
4167
+ const opts = ["Z"];
4168
+ if (args.offset)
4169
+ opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
4170
+ const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`;
4171
+ const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
4172
+ return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
4173
+ }
4174
+ var anyString = /^[\s\S]{0,}$/;
4175
+ var number = /^-?\d+(?:\.\d+)?$/;
4176
+ var lowercase = /^[^A-Z]*$/;
4177
+ var uppercase = /^[^a-z]*$/;
4178
+
4179
+ // ../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/checks.js
4180
+ var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
4181
+ var _a;
4182
+ inst._zod ?? (inst._zod = {});
3638
4183
  inst._zod.def = def;
3639
4184
  (_a = inst._zod).onattach ?? (_a.onattach = []);
3640
4185
  });
@@ -3839,6 +4384,107 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals"
3839
4384
  });
3840
4385
  };
3841
4386
  });
4387
+ var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
4388
+ var _a, _b;
4389
+ $ZodCheck.init(inst, def);
4390
+ if (def.pattern)
4391
+ (_a = inst._zod).check ?? (_a.check = (payload) => {
4392
+ def.pattern.lastIndex = 0;
4393
+ if (def.pattern.test(payload.value))
4394
+ return;
4395
+ payload.issues.push({
4396
+ origin: "string",
4397
+ code: "invalid_format",
4398
+ format: def.format,
4399
+ input: payload.value,
4400
+ ...def.pattern ? { pattern: def.pattern.toString() } : {},
4401
+ inst,
4402
+ continue: !def.abort
4403
+ });
4404
+ });
4405
+ else
4406
+ (_b = inst._zod).check ?? (_b.check = () => {});
4407
+ });
4408
+ var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
4409
+ $ZodCheckStringFormat.init(inst, def);
4410
+ inst._zod.check = (payload) => {
4411
+ def.pattern.lastIndex = 0;
4412
+ if (def.pattern.test(payload.value))
4413
+ return;
4414
+ payload.issues.push({
4415
+ origin: "string",
4416
+ code: "invalid_format",
4417
+ format: "regex",
4418
+ input: payload.value,
4419
+ pattern: def.pattern.toString(),
4420
+ inst,
4421
+ continue: !def.abort
4422
+ });
4423
+ };
4424
+ });
4425
+ var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
4426
+ def.pattern ?? (def.pattern = lowercase);
4427
+ $ZodCheckStringFormat.init(inst, def);
4428
+ });
4429
+ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
4430
+ def.pattern ?? (def.pattern = uppercase);
4431
+ $ZodCheckStringFormat.init(inst, def);
4432
+ });
4433
+ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
4434
+ $ZodCheck.init(inst, def);
4435
+ const escapedRegex = escapeRegex(def.includes);
4436
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
4437
+ def.pattern = pattern;
4438
+ inst._zod.check = (payload) => {
4439
+ if (payload.value.includes(def.includes, def.position))
4440
+ return;
4441
+ payload.issues.push({
4442
+ origin: "string",
4443
+ code: "invalid_format",
4444
+ format: "includes",
4445
+ includes: def.includes,
4446
+ input: payload.value,
4447
+ inst,
4448
+ continue: !def.abort
4449
+ });
4450
+ };
4451
+ });
4452
+ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
4453
+ $ZodCheck.init(inst, def);
4454
+ const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
4455
+ def.pattern ?? (def.pattern = pattern);
4456
+ inst._zod.check = (payload) => {
4457
+ if (payload.value.startsWith(def.prefix))
4458
+ return;
4459
+ payload.issues.push({
4460
+ origin: "string",
4461
+ code: "invalid_format",
4462
+ format: "starts_with",
4463
+ prefix: def.prefix,
4464
+ input: payload.value,
4465
+ inst,
4466
+ continue: !def.abort
4467
+ });
4468
+ };
4469
+ });
4470
+ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
4471
+ $ZodCheck.init(inst, def);
4472
+ const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
4473
+ def.pattern ?? (def.pattern = pattern);
4474
+ inst._zod.check = (payload) => {
4475
+ if (payload.value.endsWith(def.suffix))
4476
+ return;
4477
+ payload.issues.push({
4478
+ origin: "string",
4479
+ code: "invalid_format",
4480
+ format: "ends_with",
4481
+ suffix: def.suffix,
4482
+ input: payload.value,
4483
+ inst,
4484
+ continue: !def.abort
4485
+ });
4486
+ };
4487
+ });
3842
4488
  var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
3843
4489
  $ZodCheck.init(inst, def);
3844
4490
  inst._zod.check = (payload) => {
@@ -4009,23 +4655,378 @@ async function validateAsync2(inst, value) {
4009
4655
  const ctx = { async: true };
4010
4656
  return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx);
4011
4657
  }
4012
- function standardProps(inst) {
4013
- return {
4014
- validate: (value) => {
4015
- const ctx = { async: false };
4016
- try {
4017
- const r = inst._zod.run({ value, issues: [] }, ctx);
4018
- if (!(r instanceof Promise))
4019
- return toStandardResult(r, ctx);
4020
- } catch (_) {}
4021
- return validateAsync2(inst, value);
4022
- },
4023
- vendor: "zod",
4024
- version: 1
4658
+ function standardProps(inst) {
4659
+ return {
4660
+ validate: (value) => {
4661
+ const ctx = { async: false };
4662
+ try {
4663
+ const r = inst._zod.run({ value, issues: [] }, ctx);
4664
+ if (!(r instanceof Promise))
4665
+ return toStandardResult(r, ctx);
4666
+ } catch (_) {}
4667
+ return validateAsync2(inst, value);
4668
+ },
4669
+ vendor: "zod",
4670
+ version: 1
4671
+ };
4672
+ }
4673
+ var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
4674
+ $ZodType.init(inst, def);
4675
+ inst._zod.pattern = def.pattern ?? anyString;
4676
+ inst._zod.parse = (payload, _) => {
4677
+ if (def.coerce)
4678
+ try {
4679
+ payload.value = String(payload.value);
4680
+ } catch (_) {}
4681
+ if (typeof payload.value === "string")
4682
+ return payload;
4683
+ payload.issues.push({
4684
+ expected: "string",
4685
+ code: "invalid_type",
4686
+ input: payload.value,
4687
+ inst
4688
+ });
4689
+ return payload;
4690
+ };
4691
+ });
4692
+ var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
4693
+ $ZodCheckStringFormat.init(inst, def);
4694
+ $ZodString.init(inst, def);
4695
+ });
4696
+ var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
4697
+ def.pattern ?? (def.pattern = guid);
4698
+ $ZodStringFormat.init(inst, def);
4699
+ });
4700
+ var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
4701
+ if (def.version) {
4702
+ const versionMap = {
4703
+ v1: 1,
4704
+ v2: 2,
4705
+ v3: 3,
4706
+ v4: 4,
4707
+ v5: 5,
4708
+ v6: 6,
4709
+ v7: 7,
4710
+ v8: 8
4711
+ };
4712
+ const v = versionMap[def.version];
4713
+ if (v === undefined)
4714
+ throw new Error(`Invalid UUID version: "${def.version}"`);
4715
+ def.pattern ?? (def.pattern = uuid(v));
4716
+ } else
4717
+ def.pattern ?? (def.pattern = uuid());
4718
+ $ZodStringFormat.init(inst, def);
4719
+ });
4720
+ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
4721
+ def.pattern ?? (def.pattern = email);
4722
+ $ZodStringFormat.init(inst, def);
4723
+ });
4724
+ var URL_BAD_FORMAT = 1;
4725
+ var URL_UNPARSEABLE = 2;
4726
+ function canParseURL(input) {
4727
+ try {
4728
+ if (typeof URL !== "undefined" && typeof URL.canParse === "function")
4729
+ return URL.canParse(input);
4730
+ new URL(input);
4731
+ return true;
4732
+ } catch {
4733
+ return false;
4734
+ }
4735
+ }
4736
+ function validateURL(trimmed, def) {
4737
+ if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) {
4738
+ return canParseURL(trimmed) || URL_UNPARSEABLE;
4739
+ }
4740
+ return parseURLObject(trimmed, def);
4741
+ }
4742
+ function parseURLObject(trimmed, def) {
4743
+ if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) {
4744
+ return URL_BAD_FORMAT;
4745
+ }
4746
+ try {
4747
+ if (typeof URL !== "undefined") {
4748
+ const URLStatic = URL;
4749
+ if (typeof URLStatic.parse === "function")
4750
+ return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;
4751
+ }
4752
+ return new URL(trimmed);
4753
+ } catch {
4754
+ return URL_UNPARSEABLE;
4755
+ }
4756
+ }
4757
+ var asciiTabOrNewline = /[\t\n\r]/g;
4758
+ function stripTabAndNewline(value) {
4759
+ return value.replace(asciiTabOrNewline, "");
4760
+ }
4761
+ function urlHostnameOk(url, hostname) {
4762
+ hostname.lastIndex = 0;
4763
+ return hostname.test(url.hostname);
4764
+ }
4765
+ function urlProtocolOk(url, protocol) {
4766
+ protocol.lastIndex = 0;
4767
+ return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
4768
+ }
4769
+ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
4770
+ $ZodStringFormat.init(inst, def);
4771
+ inst._zod.check = (payload) => {
4772
+ try {
4773
+ const trimmed = payload.value.trim();
4774
+ const url = validateURL(trimmed, def);
4775
+ if (url === URL_BAD_FORMAT) {
4776
+ payload.issues.push({
4777
+ code: "invalid_format",
4778
+ format: "url",
4779
+ note: "Invalid URL format",
4780
+ input: payload.value,
4781
+ inst,
4782
+ continue: !def.abort
4783
+ });
4784
+ return;
4785
+ }
4786
+ if (url === URL_UNPARSEABLE) {
4787
+ payload.issues.push({
4788
+ code: "invalid_format",
4789
+ format: "url",
4790
+ input: payload.value,
4791
+ inst,
4792
+ continue: !def.abort
4793
+ });
4794
+ return;
4795
+ }
4796
+ if (url === true) {
4797
+ payload.value = stripTabAndNewline(trimmed);
4798
+ return;
4799
+ }
4800
+ if (def.hostname && !urlHostnameOk(url, def.hostname)) {
4801
+ payload.issues.push({
4802
+ code: "invalid_format",
4803
+ format: "url",
4804
+ note: "Invalid hostname",
4805
+ pattern: def.hostname.source,
4806
+ input: payload.value,
4807
+ inst,
4808
+ continue: !def.abort
4809
+ });
4810
+ }
4811
+ if (def.protocol && !urlProtocolOk(url, def.protocol)) {
4812
+ payload.issues.push({
4813
+ code: "invalid_format",
4814
+ format: "url",
4815
+ note: "Invalid protocol",
4816
+ pattern: def.protocol.source,
4817
+ input: payload.value,
4818
+ inst,
4819
+ continue: !def.abort
4820
+ });
4821
+ }
4822
+ payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);
4823
+ return;
4824
+ } catch (_) {
4825
+ payload.issues.push({
4826
+ code: "invalid_format",
4827
+ format: "url",
4828
+ input: payload.value,
4829
+ inst,
4830
+ continue: !def.abort
4831
+ });
4832
+ }
4833
+ };
4834
+ });
4835
+ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
4836
+ def.pattern ?? (def.pattern = emoji());
4837
+ $ZodStringFormat.init(inst, def);
4838
+ });
4839
+ var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
4840
+ if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))
4841
+ throw new Error(`Invalid nanoid length: ${def.length}`);
4842
+ def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length));
4843
+ $ZodStringFormat.init(inst, def);
4844
+ });
4845
+ var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
4846
+ def.pattern ?? (def.pattern = cuid);
4847
+ $ZodStringFormat.init(inst, def);
4848
+ });
4849
+ var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
4850
+ def.pattern ?? (def.pattern = cuid2);
4851
+ $ZodStringFormat.init(inst, def);
4852
+ });
4853
+ var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
4854
+ def.pattern ?? (def.pattern = ulid);
4855
+ $ZodStringFormat.init(inst, def);
4856
+ });
4857
+ var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
4858
+ def.pattern ?? (def.pattern = xid);
4859
+ $ZodStringFormat.init(inst, def);
4860
+ });
4861
+ var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
4862
+ def.pattern ?? (def.pattern = ksuid);
4863
+ $ZodStringFormat.init(inst, def);
4864
+ });
4865
+ var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
4866
+ def.pattern ?? (def.pattern = datetime(def));
4867
+ $ZodStringFormat.init(inst, def);
4868
+ });
4869
+ var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
4870
+ def.pattern ?? (def.pattern = date);
4871
+ $ZodStringFormat.init(inst, def);
4872
+ });
4873
+ var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
4874
+ def.pattern ?? (def.pattern = time(def));
4875
+ $ZodStringFormat.init(inst, def);
4876
+ });
4877
+ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
4878
+ def.pattern ?? (def.pattern = duration);
4879
+ $ZodStringFormat.init(inst, def);
4880
+ });
4881
+ var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
4882
+ def.pattern ?? (def.pattern = ipv4);
4883
+ $ZodStringFormat.init(inst, def);
4884
+ });
4885
+ var ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
4886
+ function isValidIPv6(value) {
4887
+ if (!ipv6Alphabet.test(value))
4888
+ return false;
4889
+ return canParseURL(`http://[${value}]`);
4890
+ }
4891
+ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
4892
+ def.pattern ?? (def.pattern = ipv6);
4893
+ $ZodStringFormat.init(inst, def);
4894
+ inst._zod.check = (payload) => {
4895
+ if (!isValidIPv6(payload.value)) {
4896
+ payload.issues.push({
4897
+ code: "invalid_format",
4898
+ format: "ipv6",
4899
+ input: payload.value,
4900
+ inst,
4901
+ continue: !def.abort
4902
+ });
4903
+ }
4904
+ };
4905
+ });
4906
+ var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
4907
+ def.pattern ?? (def.pattern = cidrv4);
4908
+ $ZodStringFormat.init(inst, def);
4909
+ });
4910
+ function isValidCIDRv6(value) {
4911
+ const parts = value.split("/");
4912
+ if (parts.length !== 2)
4913
+ return false;
4914
+ const [address, prefix] = parts;
4915
+ if (!prefix)
4916
+ return false;
4917
+ const prefixNum = Number(prefix);
4918
+ if (`${prefixNum}` !== prefix)
4919
+ return false;
4920
+ if (prefixNum < 0 || prefixNum > 128)
4921
+ return false;
4922
+ return isValidIPv6(address);
4923
+ }
4924
+ var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
4925
+ def.pattern ?? (def.pattern = cidrv6);
4926
+ $ZodStringFormat.init(inst, def);
4927
+ inst._zod.check = (payload) => {
4928
+ if (!isValidCIDRv6(payload.value)) {
4929
+ payload.issues.push({
4930
+ code: "invalid_format",
4931
+ format: "cidrv6",
4932
+ input: payload.value,
4933
+ inst,
4934
+ continue: !def.abort
4935
+ });
4936
+ }
4025
4937
  };
4938
+ });
4939
+ function isValidBase64(data) {
4940
+ if (data === "")
4941
+ return true;
4942
+ if (/\s/.test(data))
4943
+ return false;
4944
+ if (data.length % 4 !== 0)
4945
+ return false;
4946
+ try {
4947
+ atob(data);
4948
+ return true;
4949
+ } catch {
4950
+ return false;
4951
+ }
4026
4952
  }
4027
4953
  var base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;
4954
+ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
4955
+ def.pattern ?? (def.pattern = base64Charset);
4956
+ $ZodStringFormat.init(inst, def);
4957
+ inst._zod.check = (payload) => {
4958
+ if (isValidBase64(payload.value))
4959
+ return;
4960
+ payload.issues.push({
4961
+ code: "invalid_format",
4962
+ format: "base64",
4963
+ input: payload.value,
4964
+ inst,
4965
+ continue: !def.abort
4966
+ });
4967
+ };
4968
+ });
4028
4969
  var base64urlCharset = /^[A-Za-z0-9_-]*$/;
4970
+ function isValidBase64URL(data) {
4971
+ if (!base64urlCharset.test(data))
4972
+ return false;
4973
+ const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
4974
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
4975
+ return isValidBase64(padded);
4976
+ }
4977
+ var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
4978
+ def.pattern ?? (def.pattern = base64urlCharset);
4979
+ $ZodStringFormat.init(inst, def);
4980
+ inst._zod.check = (payload) => {
4981
+ if (isValidBase64URL(payload.value))
4982
+ return;
4983
+ payload.issues.push({
4984
+ code: "invalid_format",
4985
+ format: "base64url",
4986
+ input: payload.value,
4987
+ inst,
4988
+ continue: !def.abort
4989
+ });
4990
+ };
4991
+ });
4992
+ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
4993
+ def.pattern ?? (def.pattern = e164);
4994
+ $ZodStringFormat.init(inst, def);
4995
+ });
4996
+ function isValidJWT(token, algorithm = null) {
4997
+ try {
4998
+ const tokensParts = token.split(".");
4999
+ if (tokensParts.length !== 3)
5000
+ return false;
5001
+ const [header] = tokensParts;
5002
+ if (!header)
5003
+ return false;
5004
+ const parsedHeader = JSON.parse(atob(header));
5005
+ if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
5006
+ return false;
5007
+ if (!parsedHeader.alg)
5008
+ return false;
5009
+ if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
5010
+ return false;
5011
+ return true;
5012
+ } catch {
5013
+ return false;
5014
+ }
5015
+ }
5016
+ var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
5017
+ $ZodStringFormat.init(inst, def);
5018
+ inst._zod.check = (payload) => {
5019
+ if (isValidJWT(payload.value, def.alg))
5020
+ return;
5021
+ payload.issues.push({
5022
+ code: "invalid_format",
5023
+ format: "jwt",
5024
+ input: payload.value,
5025
+ inst,
5026
+ continue: !def.abort
5027
+ });
5028
+ };
5029
+ });
4029
5030
  var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
4030
5031
  $ZodType.init(inst, def);
4031
5032
  inst._zod.pattern = number;
@@ -4053,26 +5054,6 @@ var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, d
4053
5054
  $ZodCheckNumberFormat.init(inst, def);
4054
5055
  $ZodNumber.init(inst, def);
4055
5056
  });
4056
- var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
4057
- $ZodType.init(inst, def);
4058
- inst._zod.pattern = boolean;
4059
- inst._zod.parse = (payload, _ctx) => {
4060
- if (def.coerce)
4061
- try {
4062
- payload.value = Boolean(payload.value);
4063
- } catch (_) {}
4064
- const input = payload.value;
4065
- if (typeof input === "boolean")
4066
- return payload;
4067
- payload.issues.push({
4068
- expected: "boolean",
4069
- code: "invalid_type",
4070
- input,
4071
- inst
4072
- });
4073
- return payload;
4074
- };
4075
- });
4076
5057
  var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
4077
5058
  $ZodType.init(inst, def);
4078
5059
  inst._zod.parse = (payload) => payload;
@@ -4548,7 +5529,7 @@ function mergeValues(a, b) {
4548
5529
  if (a instanceof Date && b instanceof Date && +a === +b) {
4549
5530
  return { valid: true, data: a };
4550
5531
  }
4551
- if (isPlainObject2(a) && isPlainObject2(b)) {
5532
+ if (isPlainObject3(a) && isPlainObject3(b)) {
4552
5533
  const bKeys = Object.keys(b);
4553
5534
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
4554
5535
  const newObj = { ...a, ...b };
@@ -5452,58 +6433,295 @@ function en_default() {
5452
6433
  localeError: error()
5453
6434
  };
5454
6435
  }
5455
- // ../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/registries.js
5456
- var _a2;
5457
- class $ZodRegistry {
5458
- constructor() {
5459
- this._map = new WeakMap;
5460
- this._idmap = new Map;
5461
- }
5462
- add(schema, ..._meta) {
5463
- const meta = _meta[0];
5464
- this._map.set(schema, meta);
5465
- if (meta && typeof meta === "object" && "id" in meta) {
5466
- this._idmap.set(meta.id, schema);
5467
- }
5468
- return this;
5469
- }
5470
- clear() {
5471
- this._map = new WeakMap;
5472
- this._idmap = new Map;
5473
- return this;
5474
- }
5475
- remove(schema) {
5476
- const meta = this._map.get(schema);
5477
- if (meta && typeof meta === "object" && "id" in meta) {
5478
- this._idmap.delete(meta.id);
5479
- }
5480
- this._map.delete(schema);
5481
- return this;
5482
- }
5483
- get(schema) {
5484
- const p = schema._zod.parent;
5485
- if (p) {
5486
- const pm = { ...this.get(p) ?? {} };
5487
- delete pm.id;
5488
- const f = { ...pm, ...this._map.get(schema) };
5489
- return Object.keys(f).length ? f : undefined;
5490
- }
5491
- return this._map.get(schema);
5492
- }
5493
- has(schema) {
5494
- return this._map.has(schema);
5495
- }
6436
+ // ../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/registries.js
6437
+ var _a2;
6438
+ class $ZodRegistry {
6439
+ constructor() {
6440
+ this._map = new WeakMap;
6441
+ this._idmap = new Map;
6442
+ }
6443
+ add(schema, ..._meta) {
6444
+ const meta = _meta[0];
6445
+ this._map.set(schema, meta);
6446
+ if (meta && typeof meta === "object" && "id" in meta) {
6447
+ this._idmap.set(meta.id, schema);
6448
+ }
6449
+ return this;
6450
+ }
6451
+ clear() {
6452
+ this._map = new WeakMap;
6453
+ this._idmap = new Map;
6454
+ return this;
6455
+ }
6456
+ remove(schema) {
6457
+ const meta = this._map.get(schema);
6458
+ if (meta && typeof meta === "object" && "id" in meta) {
6459
+ this._idmap.delete(meta.id);
6460
+ }
6461
+ this._map.delete(schema);
6462
+ return this;
6463
+ }
6464
+ get(schema) {
6465
+ const p = schema._zod.parent;
6466
+ if (p) {
6467
+ const pm = { ...this.get(p) ?? {} };
6468
+ delete pm.id;
6469
+ const f = { ...pm, ...this._map.get(schema) };
6470
+ return Object.keys(f).length ? f : undefined;
6471
+ }
6472
+ return this._map.get(schema);
6473
+ }
6474
+ has(schema) {
6475
+ return this._map.has(schema);
6476
+ }
6477
+ }
6478
+ function registry() {
6479
+ return new $ZodRegistry;
6480
+ }
6481
+ (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
6482
+ var globalRegistry = globalThis.__zod_globalRegistry;
6483
+ // ../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/api.js
6484
+ function snapshotChecks(def) {
6485
+ if (def.checks)
6486
+ def.checks = [...def.checks];
6487
+ return def;
6488
+ }
6489
+ function _email(Class, params) {
6490
+ return new Class({
6491
+ type: "string",
6492
+ format: "email",
6493
+ check: "string_format",
6494
+ abort: false,
6495
+ ...normalizeParams(params)
6496
+ });
6497
+ }
6498
+ function _guid(Class, params) {
6499
+ return new Class({
6500
+ type: "string",
6501
+ format: "guid",
6502
+ check: "string_format",
6503
+ abort: false,
6504
+ ...normalizeParams(params)
6505
+ });
6506
+ }
6507
+ function _uuid(Class, params) {
6508
+ return new Class({
6509
+ type: "string",
6510
+ format: "uuid",
6511
+ check: "string_format",
6512
+ abort: false,
6513
+ ...normalizeParams(params)
6514
+ });
6515
+ }
6516
+ function _uuidv4(Class, params) {
6517
+ return new Class({
6518
+ type: "string",
6519
+ format: "uuid",
6520
+ check: "string_format",
6521
+ abort: false,
6522
+ version: "v4",
6523
+ ...normalizeParams(params)
6524
+ });
6525
+ }
6526
+ function _uuidv6(Class, params) {
6527
+ return new Class({
6528
+ type: "string",
6529
+ format: "uuid",
6530
+ check: "string_format",
6531
+ abort: false,
6532
+ version: "v6",
6533
+ ...normalizeParams(params)
6534
+ });
6535
+ }
6536
+ function _uuidv7(Class, params) {
6537
+ return new Class({
6538
+ type: "string",
6539
+ format: "uuid",
6540
+ check: "string_format",
6541
+ abort: false,
6542
+ version: "v7",
6543
+ ...normalizeParams(params)
6544
+ });
6545
+ }
6546
+ function _url(Class, params) {
6547
+ return new Class({
6548
+ type: "string",
6549
+ format: "url",
6550
+ check: "string_format",
6551
+ abort: false,
6552
+ ...normalizeParams(params)
6553
+ });
6554
+ }
6555
+ function _emoji2(Class, params) {
6556
+ return new Class({
6557
+ type: "string",
6558
+ format: "emoji",
6559
+ check: "string_format",
6560
+ abort: false,
6561
+ ...normalizeParams(params)
6562
+ });
6563
+ }
6564
+ function _nanoid(Class, params) {
6565
+ return new Class({
6566
+ type: "string",
6567
+ format: "nanoid",
6568
+ check: "string_format",
6569
+ abort: false,
6570
+ ...normalizeParams(params)
6571
+ });
6572
+ }
6573
+ function _cuid(Class, params) {
6574
+ return new Class({
6575
+ type: "string",
6576
+ format: "cuid",
6577
+ check: "string_format",
6578
+ abort: false,
6579
+ ...normalizeParams(params)
6580
+ });
5496
6581
  }
5497
- function registry() {
5498
- return new $ZodRegistry;
6582
+ function _cuid2(Class, params) {
6583
+ return new Class({
6584
+ type: "string",
6585
+ format: "cuid2",
6586
+ check: "string_format",
6587
+ abort: false,
6588
+ ...normalizeParams(params)
6589
+ });
5499
6590
  }
5500
- (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
5501
- var globalRegistry = globalThis.__zod_globalRegistry;
5502
- // ../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/api.js
5503
- function snapshotChecks(def) {
5504
- if (def.checks)
5505
- def.checks = [...def.checks];
5506
- return def;
6591
+ function _ulid(Class, params) {
6592
+ return new Class({
6593
+ type: "string",
6594
+ format: "ulid",
6595
+ check: "string_format",
6596
+ abort: false,
6597
+ ...normalizeParams(params)
6598
+ });
6599
+ }
6600
+ function _xid(Class, params) {
6601
+ return new Class({
6602
+ type: "string",
6603
+ format: "xid",
6604
+ check: "string_format",
6605
+ abort: false,
6606
+ ...normalizeParams(params)
6607
+ });
6608
+ }
6609
+ function _ksuid(Class, params) {
6610
+ return new Class({
6611
+ type: "string",
6612
+ format: "ksuid",
6613
+ check: "string_format",
6614
+ abort: false,
6615
+ ...normalizeParams(params)
6616
+ });
6617
+ }
6618
+ function _ipv4(Class, params) {
6619
+ return new Class({
6620
+ type: "string",
6621
+ format: "ipv4",
6622
+ check: "string_format",
6623
+ abort: false,
6624
+ ...normalizeParams(params)
6625
+ });
6626
+ }
6627
+ function _ipv6(Class, params) {
6628
+ return new Class({
6629
+ type: "string",
6630
+ format: "ipv6",
6631
+ check: "string_format",
6632
+ abort: false,
6633
+ ...normalizeParams(params)
6634
+ });
6635
+ }
6636
+ function _cidrv4(Class, params) {
6637
+ return new Class({
6638
+ type: "string",
6639
+ format: "cidrv4",
6640
+ check: "string_format",
6641
+ abort: false,
6642
+ ...normalizeParams(params)
6643
+ });
6644
+ }
6645
+ function _cidrv6(Class, params) {
6646
+ return new Class({
6647
+ type: "string",
6648
+ format: "cidrv6",
6649
+ check: "string_format",
6650
+ abort: false,
6651
+ ...normalizeParams(params)
6652
+ });
6653
+ }
6654
+ function _base64(Class, params) {
6655
+ return new Class({
6656
+ type: "string",
6657
+ format: "base64",
6658
+ check: "string_format",
6659
+ abort: false,
6660
+ ...normalizeParams(params)
6661
+ });
6662
+ }
6663
+ function _base64url(Class, params) {
6664
+ return new Class({
6665
+ type: "string",
6666
+ format: "base64url",
6667
+ check: "string_format",
6668
+ abort: false,
6669
+ ...normalizeParams(params)
6670
+ });
6671
+ }
6672
+ function _e164(Class, params) {
6673
+ return new Class({
6674
+ type: "string",
6675
+ format: "e164",
6676
+ check: "string_format",
6677
+ abort: false,
6678
+ ...normalizeParams(params)
6679
+ });
6680
+ }
6681
+ function _jwt(Class, params) {
6682
+ return new Class({
6683
+ type: "string",
6684
+ format: "jwt",
6685
+ check: "string_format",
6686
+ abort: false,
6687
+ ...normalizeParams(params)
6688
+ });
6689
+ }
6690
+ function _isoDateTime(Class, params) {
6691
+ return new Class({
6692
+ type: "string",
6693
+ format: "datetime",
6694
+ check: "string_format",
6695
+ offset: false,
6696
+ local: false,
6697
+ precision: null,
6698
+ ...normalizeParams(params)
6699
+ });
6700
+ }
6701
+ function _isoDate(Class, params) {
6702
+ return new Class({
6703
+ type: "string",
6704
+ format: "date",
6705
+ check: "string_format",
6706
+ ...normalizeParams(params)
6707
+ });
6708
+ }
6709
+ function _isoTime(Class, params) {
6710
+ return new Class({
6711
+ type: "string",
6712
+ format: "time",
6713
+ check: "string_format",
6714
+ precision: null,
6715
+ ...normalizeParams(params)
6716
+ });
6717
+ }
6718
+ function _isoDuration(Class, params) {
6719
+ return new Class({
6720
+ type: "string",
6721
+ format: "duration",
6722
+ check: "string_format",
6723
+ ...normalizeParams(params)
6724
+ });
5507
6725
  }
5508
6726
  function _number(Class, params) {
5509
6727
  return new Class(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) }));
@@ -5517,12 +6735,6 @@ function _int(Class, params) {
5517
6735
  ...normalizeParams(params)
5518
6736
  });
5519
6737
  }
5520
- function _boolean(Class, params) {
5521
- return new Class({
5522
- type: "boolean",
5523
- ...normalizeParams(params)
5524
- });
5525
- }
5526
6738
  function _unknown(Class) {
5527
6739
  return new Class({
5528
6740
  type: "unknown"
@@ -5595,12 +6807,73 @@ function _length(length, params) {
5595
6807
  length
5596
6808
  });
5597
6809
  }
6810
+ function _regex(pattern, params) {
6811
+ return new $ZodCheckRegex({
6812
+ check: "string_format",
6813
+ format: "regex",
6814
+ ...normalizeParams(params),
6815
+ pattern
6816
+ });
6817
+ }
6818
+ function _lowercase(params) {
6819
+ return new $ZodCheckLowerCase({
6820
+ check: "string_format",
6821
+ format: "lowercase",
6822
+ ...normalizeParams(params)
6823
+ });
6824
+ }
6825
+ function _uppercase(params) {
6826
+ return new $ZodCheckUpperCase({
6827
+ check: "string_format",
6828
+ format: "uppercase",
6829
+ ...normalizeParams(params)
6830
+ });
6831
+ }
6832
+ function _includes(includes, params) {
6833
+ return new $ZodCheckIncludes({
6834
+ check: "string_format",
6835
+ format: "includes",
6836
+ ...normalizeParams(params),
6837
+ includes
6838
+ });
6839
+ }
6840
+ function _startsWith(prefix, params) {
6841
+ return new $ZodCheckStartsWith({
6842
+ check: "string_format",
6843
+ format: "starts_with",
6844
+ ...normalizeParams(params),
6845
+ prefix
6846
+ });
6847
+ }
6848
+ function _endsWith(suffix, params) {
6849
+ return new $ZodCheckEndsWith({
6850
+ check: "string_format",
6851
+ format: "ends_with",
6852
+ ...normalizeParams(params),
6853
+ suffix
6854
+ });
6855
+ }
5598
6856
  function _overwrite(tx) {
5599
6857
  return new $ZodCheckOverwrite({
5600
6858
  check: "overwrite",
5601
6859
  tx
5602
6860
  });
5603
6861
  }
6862
+ function _normalize(form) {
6863
+ return _overwrite((input) => input.normalize(form));
6864
+ }
6865
+ function _trim() {
6866
+ return _overwrite((input) => input.trim());
6867
+ }
6868
+ function _toLowerCase() {
6869
+ return _overwrite((input) => input.toLowerCase());
6870
+ }
6871
+ function _toUpperCase() {
6872
+ return _overwrite((input) => input.toUpperCase());
6873
+ }
6874
+ function _slugify() {
6875
+ return _overwrite((input) => slugify(input));
6876
+ }
5604
6877
  function _array(Class, element, params) {
5605
6878
  return new Class({
5606
6879
  type: "array",
@@ -6258,10 +7531,50 @@ function aggregateChecks(schema) {
6258
7531
  addPattern(agg, pattern);
6259
7532
  return agg;
6260
7533
  }
7534
+ var formatMap = {
7535
+ guid: "uuid",
7536
+ url: "uri",
7537
+ datetime: "date-time",
7538
+ json_string: "json-string",
7539
+ regex: ""
7540
+ };
6261
7541
  var exactPatterns = new Map([
6262
7542
  [base64Charset, base64],
6263
7543
  [base64urlCharset, base64url]
6264
7544
  ]);
7545
+ var exactPattern = (p) => exactPatterns.get(p) ?? p;
7546
+ var stringProcessor = (schema, ctx, _json, _params) => {
7547
+ const json = _json;
7548
+ json.type = "string";
7549
+ const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
7550
+ if (typeof minimum === "number")
7551
+ json.minLength = minimum;
7552
+ if (typeof maximum === "number")
7553
+ json.maxLength = maximum;
7554
+ if (format) {
7555
+ json.format = formatMap[format] ?? format;
7556
+ if (json.format === "")
7557
+ delete json.format;
7558
+ if (format === "time" || laxFormat) {
7559
+ delete json.format;
7560
+ }
7561
+ }
7562
+ if (contentEncoding)
7563
+ json.contentEncoding = contentEncoding;
7564
+ if (patterns && patterns.size > 0) {
7565
+ const patternList = [...patterns].map(exactPattern);
7566
+ if (patternList.length === 1)
7567
+ json.pattern = patternList[0].source;
7568
+ else if (patternList.length > 1) {
7569
+ json.allOf = [
7570
+ ...patternList.map((regex) => ({
7571
+ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
7572
+ pattern: regex.source
7573
+ }))
7574
+ ];
7575
+ }
7576
+ }
7577
+ };
6265
7578
  var numberProcessor = (schema, ctx, _json, params) => {
6266
7579
  const json = _json;
6267
7580
  const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
@@ -6304,9 +7617,6 @@ var numberProcessor = (schema, ctx, _json, params) => {
6304
7617
  json.allOf = [...json.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))];
6305
7618
  }
6306
7619
  };
6307
- var booleanProcessor = (_schema, _ctx, json, _params) => {
6308
- json.type = "boolean";
6309
- };
6310
7620
  var neverProcessor = (_schema, _ctx, json, _params) => {
6311
7621
  json.not = {};
6312
7622
  };
@@ -6852,6 +8162,240 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
6852
8162
  return this._zod.def;
6853
8163
  }
6854
8164
  });
8165
+ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
8166
+ $ZodString.init(inst, def);
8167
+ ZodType.init(inst, def);
8168
+ inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
8169
+ }, /* @__PURE__ */ derived({
8170
+ format: (inst) => aggregateChecks(inst).format ?? null,
8171
+ minLength: (inst) => aggregateChecks(inst).minimum ?? null,
8172
+ maxLength: (inst) => aggregateChecks(inst).maximum ?? null
8173
+ }, {
8174
+ regex(...args) {
8175
+ return this.check(_regex(...args));
8176
+ },
8177
+ includes(...args) {
8178
+ return this.check(_includes(...args));
8179
+ },
8180
+ startsWith(...args) {
8181
+ return this.check(_startsWith(...args));
8182
+ },
8183
+ endsWith(...args) {
8184
+ return this.check(_endsWith(...args));
8185
+ },
8186
+ min(...args) {
8187
+ return this.check(_minLength(...args));
8188
+ },
8189
+ max(...args) {
8190
+ return this.check(_maxLength(...args));
8191
+ },
8192
+ length(...args) {
8193
+ return this.check(_length(...args));
8194
+ },
8195
+ nonempty(...args) {
8196
+ return this.check(_minLength(1, ...args));
8197
+ },
8198
+ lowercase(params) {
8199
+ return this.check(_lowercase(params));
8200
+ },
8201
+ uppercase(params) {
8202
+ return this.check(_uppercase(params));
8203
+ },
8204
+ trim() {
8205
+ return this.check(_trim());
8206
+ },
8207
+ normalize(...args) {
8208
+ return this.check(_normalize(...args));
8209
+ },
8210
+ toLowerCase() {
8211
+ return this.check(_toLowerCase());
8212
+ },
8213
+ toUpperCase() {
8214
+ return this.check(_toUpperCase());
8215
+ },
8216
+ slugify() {
8217
+ return this.check(_slugify());
8218
+ }
8219
+ }));
8220
+ var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
8221
+ $ZodString.init(inst, def);
8222
+ _ZodString.init(inst, def);
8223
+ }, {
8224
+ email(params) {
8225
+ return this.check(_email(ZodEmail, params));
8226
+ },
8227
+ url(params) {
8228
+ return this.check(_url(ZodURL, params));
8229
+ },
8230
+ jwt(params) {
8231
+ return this.check(_jwt(ZodJWT, params));
8232
+ },
8233
+ emoji(params) {
8234
+ return this.check(_emoji2(ZodEmoji, params));
8235
+ },
8236
+ guid(params) {
8237
+ return this.check(_guid(ZodGUID, params));
8238
+ },
8239
+ uuid(params) {
8240
+ return this.check(_uuid(ZodUUID, params));
8241
+ },
8242
+ uuidv4(params) {
8243
+ return this.check(_uuidv4(ZodUUID, params));
8244
+ },
8245
+ uuidv6(params) {
8246
+ return this.check(_uuidv6(ZodUUID, params));
8247
+ },
8248
+ uuidv7(params) {
8249
+ return this.check(_uuidv7(ZodUUID, params));
8250
+ },
8251
+ nanoid(params) {
8252
+ return this.check(_nanoid(ZodNanoID, params));
8253
+ },
8254
+ cuid(params) {
8255
+ return this.check(_cuid(ZodCUID, params));
8256
+ },
8257
+ cuid2(params) {
8258
+ return this.check(_cuid2(ZodCUID2, params));
8259
+ },
8260
+ ulid(params) {
8261
+ return this.check(_ulid(ZodULID, params));
8262
+ },
8263
+ base64(params) {
8264
+ return this.check(_base64(ZodBase64, params));
8265
+ },
8266
+ base64url(params) {
8267
+ return this.check(_base64url(ZodBase64URL, params));
8268
+ },
8269
+ xid(params) {
8270
+ return this.check(_xid(ZodXID, params));
8271
+ },
8272
+ ksuid(params) {
8273
+ return this.check(_ksuid(ZodKSUID, params));
8274
+ },
8275
+ ipv4(params) {
8276
+ return this.check(_ipv4(ZodIPv4, params));
8277
+ },
8278
+ ipv6(params) {
8279
+ return this.check(_ipv6(ZodIPv6, params));
8280
+ },
8281
+ cidrv4(params) {
8282
+ return this.check(_cidrv4(ZodCIDRv4, params));
8283
+ },
8284
+ cidrv6(params) {
8285
+ return this.check(_cidrv6(ZodCIDRv6, params));
8286
+ },
8287
+ e164(params) {
8288
+ return this.check(_e164(ZodE164, params));
8289
+ },
8290
+ datetime(params) {
8291
+ return this.check(_isoDateTime(ZodISODateTime, params));
8292
+ },
8293
+ date(params) {
8294
+ return this.check(_isoDate(ZodISODate, params));
8295
+ },
8296
+ time(params) {
8297
+ return this.check(_isoTime(ZodISOTime, params));
8298
+ },
8299
+ duration(params) {
8300
+ return this.check(_isoDuration(ZodISODuration, params));
8301
+ }
8302
+ });
8303
+ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
8304
+ $ZodStringFormat.init(inst, def);
8305
+ _ZodString.init(inst, def);
8306
+ });
8307
+ var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
8308
+ $ZodISODateTime.init(inst, def);
8309
+ ZodStringFormat.init(inst, def);
8310
+ });
8311
+ var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
8312
+ $ZodISODate.init(inst, def);
8313
+ ZodStringFormat.init(inst, def);
8314
+ });
8315
+ var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
8316
+ $ZodISOTime.init(inst, def);
8317
+ ZodStringFormat.init(inst, def);
8318
+ });
8319
+ var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
8320
+ $ZodISODuration.init(inst, def);
8321
+ ZodStringFormat.init(inst, def);
8322
+ });
8323
+ var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
8324
+ $ZodEmail.init(inst, def);
8325
+ ZodStringFormat.init(inst, def);
8326
+ });
8327
+ var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
8328
+ $ZodGUID.init(inst, def);
8329
+ ZodStringFormat.init(inst, def);
8330
+ });
8331
+ var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
8332
+ $ZodUUID.init(inst, def);
8333
+ ZodStringFormat.init(inst, def);
8334
+ });
8335
+ var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
8336
+ $ZodURL.init(inst, def);
8337
+ ZodStringFormat.init(inst, def);
8338
+ });
8339
+ var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
8340
+ $ZodEmoji.init(inst, def);
8341
+ ZodStringFormat.init(inst, def);
8342
+ });
8343
+ var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
8344
+ $ZodNanoID.init(inst, def);
8345
+ ZodStringFormat.init(inst, def);
8346
+ });
8347
+ var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
8348
+ $ZodCUID.init(inst, def);
8349
+ ZodStringFormat.init(inst, def);
8350
+ });
8351
+ var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
8352
+ $ZodCUID2.init(inst, def);
8353
+ ZodStringFormat.init(inst, def);
8354
+ });
8355
+ var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
8356
+ $ZodULID.init(inst, def);
8357
+ ZodStringFormat.init(inst, def);
8358
+ });
8359
+ var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
8360
+ $ZodXID.init(inst, def);
8361
+ ZodStringFormat.init(inst, def);
8362
+ });
8363
+ var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
8364
+ $ZodKSUID.init(inst, def);
8365
+ ZodStringFormat.init(inst, def);
8366
+ });
8367
+ var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
8368
+ $ZodIPv4.init(inst, def);
8369
+ ZodStringFormat.init(inst, def);
8370
+ });
8371
+ var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
8372
+ $ZodIPv6.init(inst, def);
8373
+ ZodStringFormat.init(inst, def);
8374
+ });
8375
+ var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
8376
+ $ZodCIDRv4.init(inst, def);
8377
+ ZodStringFormat.init(inst, def);
8378
+ });
8379
+ var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
8380
+ $ZodCIDRv6.init(inst, def);
8381
+ ZodStringFormat.init(inst, def);
8382
+ });
8383
+ var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
8384
+ $ZodBase64.init(inst, def);
8385
+ ZodStringFormat.init(inst, def);
8386
+ });
8387
+ var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
8388
+ $ZodBase64URL.init(inst, def);
8389
+ ZodStringFormat.init(inst, def);
8390
+ });
8391
+ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
8392
+ $ZodE164.init(inst, def);
8393
+ ZodStringFormat.init(inst, def);
8394
+ });
8395
+ var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
8396
+ $ZodJWT.init(inst, def);
8397
+ ZodStringFormat.init(inst, def);
8398
+ });
6855
8399
  var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
6856
8400
  $ZodNumber.init(inst, def);
6857
8401
  ZodType.init(inst, def);
@@ -6928,14 +8472,6 @@ var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def
6928
8472
  function int(params) {
6929
8473
  return _int(ZodNumberFormat, params);
6930
8474
  }
6931
- var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
6932
- $ZodBoolean.init(inst, def);
6933
- ZodType.init(inst, def);
6934
- inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params);
6935
- });
6936
- function boolean2(params) {
6937
- return _boolean(ZodBoolean, params);
6938
- }
6939
8475
  var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
6940
8476
  $ZodUnknown.init(inst, def);
6941
8477
  ZodType.init(inst, def);
@@ -7332,8 +8868,68 @@ function refine(fn, _params = {}) {
7332
8868
  function superRefine(fn, params) {
7333
8869
  return _superRefine(fn, params);
7334
8870
  }
8871
+ // src/contract/LazySchema-D_3-dV1e.js
8872
+ var registryMap = globalRegistry._map;
8873
+ var lazySchema = (build) => {
8874
+ let schema;
8875
+ const real = () => {
8876
+ if (!schema) {
8877
+ const built = build();
8878
+ schema = built;
8879
+ const meta = registryMap.get(built);
8880
+ if (meta !== undefined)
8881
+ registryMap.set(proxy, meta);
8882
+ const internals = built._zod;
8883
+ const process2 = internals.processJSONSchema;
8884
+ if (process2)
8885
+ internals.processJSONSchema = (context, json, params) => {
8886
+ const record = context.seen.get(proxy);
8887
+ if (!record || context.seen.has(built))
8888
+ return process2(context, json, params);
8889
+ context.seen.set(built, record);
8890
+ try {
8891
+ return process2(context, json, params);
8892
+ } finally {
8893
+ if (context.seen.get(built) === record)
8894
+ context.seen.delete(built);
8895
+ }
8896
+ };
8897
+ }
8898
+ return schema;
8899
+ };
8900
+ const proxy = new Proxy({}, {
8901
+ get(_, key) {
8902
+ const target = real();
8903
+ return Reflect.get(target, key, target);
8904
+ },
8905
+ set(_, key, value) {
8906
+ const target = real();
8907
+ return Reflect.set(target, key, value, target);
8908
+ },
8909
+ has(_, key) {
8910
+ return Reflect.has(real(), key);
8911
+ },
8912
+ ownKeys() {
8913
+ return Reflect.ownKeys(real());
8914
+ },
8915
+ getOwnPropertyDescriptor(_, key) {
8916
+ const descriptor = Reflect.getOwnPropertyDescriptor(real(), key);
8917
+ return descriptor && {
8918
+ ...descriptor,
8919
+ configurable: true
8920
+ };
8921
+ },
8922
+ getPrototypeOf() {
8923
+ return Reflect.getPrototypeOf(real());
8924
+ },
8925
+ defineProperty(_, key, descriptor) {
8926
+ return Reflect.defineProperty(real(), key, descriptor);
8927
+ }
8928
+ });
8929
+ return proxy;
8930
+ };
7335
8931
 
7336
- // src/contract/Jurisdiction-CtB_d_2M.js
8932
+ // src/contract/Jurisdiction-CQN8qnzX.js
7337
8933
  var JURISDICTIONS = {
7338
8934
  global: {
7339
8935
  name: "Global",
@@ -7376,20 +8972,13 @@ var JURISDICTIONS = {
7376
8972
  optional: false
7377
8973
  }
7378
8974
  };
7379
- var JURISDICTION_SCHEMA = _enum(Object.keys(JURISDICTIONS));
8975
+ var JURISDICTION_SCHEMA = /* @__PURE__ */ lazySchema(() => _enum(Object.keys(JURISDICTIONS)));
7380
8976
  Object.keys(JURISDICTIONS).filter((code) => !JURISDICTIONS[code].optional);
7381
- var OPTIONAL_JURISDICTIONS = Object.keys(JURISDICTIONS).filter((code) => JURISDICTIONS[code].optional);
7382
- _enum(OPTIONAL_JURISDICTIONS).array().refine((codes) => new Set(codes).size === codes.length, { message: "jurisdiction/duplicate" });
7383
- var SERVED_JURISDICTIONS_SCHEMA = JURISDICTION_SCHEMA.array().min(1).refine((regions) => regions.includes("global") && new Set(regions).size === regions.length, { message: "jurisdiction/global-required-or-duplicate" });
8977
+ Object.keys(JURISDICTIONS).filter((code) => JURISDICTIONS[code].optional);
7384
8978
  var COUNTRIES = new Set("AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW".split(" "));
7385
- var VIEWER_REGION_SCHEMA = _enum([...COUNTRIES]).describe("Viewer's ISO 3166-1 alpha-2 country, supplied by your integration; not the proxy server's country. EU is not a viewer country.");
7386
8979
  var EU_COUNTRIES2 = new Set("AT BE BG HR CY CZ DK EE FI FR DE GR HU IE IT LV LT LU MT NL PL PT RO SK SI ES SE".split(" "));
7387
- var VIEWER_CLAIMS_SCHEMA = object({
7388
- region: VIEWER_REGION_SCHEMA.optional().describe("Viewer country. Defaults to the country of the connection reaching CalmLens; proxies should forward the viewer country explicitly."),
7389
- ageConfirmed: boolean2().optional().describe("Your platform's confirmation that the viewer passed its age check, so age-restricted content may be delivered. Defaults to false. Your platform confirms the viewer's age. Viewer claims are assertions from your application; CalmLens doesn't verify them. To restrict who can load an age-restricted asset, make it private and issue signed URLs only to viewers who passed your age check.")
7390
- }).strict();
7391
8980
 
7392
- // src/contract/TestRegionalActions-DUzwPr1a.js
8981
+ // src/contract/TestRegionalActions-BhyWuU49.js
7393
8982
  var msg = (text) => text;
7394
8983
  var MODERATION_QUALIFIER_INFO = {
7395
8984
  "sexual-pornographic-media": {
@@ -8405,16 +9994,16 @@ MODERATION_QUALIFIERS.reduce((groups, qualifier) => {
8405
9994
  function getModerationQualifierInfo(qualifier) {
8406
9995
  return MODERATION_QUALIFIER_INFO[qualifier];
8407
9996
  }
8408
- var TEST_REGIONAL_ACTIONS_SCHEMA = array(object({
9997
+ var TEST_REGIONAL_ACTIONS_SCHEMA = /* @__PURE__ */ lazySchema(() => array(object({
8409
9998
  region: JURISDICTION_SCHEMA.exclude(["global"]),
8410
9999
  action: _enum([
8411
10000
  "limit",
8412
10001
  "age-restrict",
8413
10002
  "block"
8414
10003
  ])
8415
- }).strict()).max(7).refine((entries) => new Set(entries.map((entry) => entry.region)).size === entries.length, "Choose each region once");
10004
+ }).strict()).max(7).refine((entries) => new Set(entries.map((entry) => entry.region)).size === entries.length, "Choose each region once"));
8416
10005
 
8417
- // src/contract/TestTriggers-CiFcTHX3.js
10006
+ // src/contract/TestTriggers-Cvi7e2KA.js
8418
10007
  var TEST_IMAGE_GRID_LEVELS = [
8419
10008
  72,
8420
10009
  128,
@@ -8496,19 +10085,19 @@ var detectionShape = {
8496
10085
  var fitsImage = ({ box: [left, top, width, height] }) => left + width <= 1e4 && top + height <= 1e4;
8497
10086
  var BOX_MESSAGE = msg("A box must lie inside the image: left + width and top + height are at most 10000.");
8498
10087
  var ageYears = number2().int().min(0).max(120);
8499
- var TEST_DETECTED_PERSON_SCHEMA = object(detectionShape).strict().refine(fitsImage, BOX_MESSAGE);
8500
- var TEST_DETECTED_FACE_SCHEMA = object({
10088
+ var TEST_DETECTED_PERSON_SCHEMA = /* @__PURE__ */ lazySchema(() => object(detectionShape).strict().refine(fitsImage, BOX_MESSAGE));
10089
+ var TEST_DETECTED_FACE_SCHEMA = /* @__PURE__ */ lazySchema(() => object({
8501
10090
  ...detectionShape,
8502
10091
  age: union([_enum(["adult", "minor"]), object({
8503
10092
  low: ageYears,
8504
10093
  high: ageYears
8505
10094
  }).strict().refine(({ low, high }) => low <= high, msg("An age range's low must not be above its high."))]).optional()
8506
- }).strict().refine(fitsImage, BOX_MESSAGE);
8507
- var TEST_DETECTIONS_SCHEMA = object({
10095
+ }).strict().refine(fitsImage, BOX_MESSAGE));
10096
+ var TEST_DETECTIONS_SCHEMA = /* @__PURE__ */ lazySchema(() => object({
8508
10097
  people: union([array(TEST_DETECTED_PERSON_SCHEMA).max(32), literal("unavailable")]).optional(),
8509
10098
  faces: union([array(TEST_DETECTED_FACE_SCHEMA).max(32), literal("unavailable")]).optional()
8510
- }).strict();
8511
- var TEST_INPUT_SCHEMA = object({
10099
+ }).strict());
10100
+ var TEST_INPUT_SCHEMA = /* @__PURE__ */ lazySchema(() => object({
8512
10101
  regionalActions: TEST_REGIONAL_ACTIONS_SCHEMA.optional(),
8513
10102
  unassessedCategories: array(_enum(CLASSIFICATION_CATEGORIES)).max(CLASSIFICATION_CATEGORIES.length).optional(),
8514
10103
  instances: array(object({
@@ -8541,7 +10130,7 @@ var TEST_INPUT_SCHEMA = object({
8541
10130
  code: "custom",
8542
10131
  message: msg("An unassessed category cannot also have assessed instances.")
8543
10132
  });
8544
- });
10133
+ }));
8545
10134
  var TEST_INPUT_PRESETS = {
8546
10135
  clean: { instances: [] },
8547
10136
  limited: { instances: [{
@@ -8753,10 +10342,10 @@ var collect = async (items) => {
8753
10342
  var readConfigurationState = async (client, config) => {
8754
10343
  const presetsNamePolicies = Object.values(config.uploadPresets ?? {}).some((preset) => preset.policy !== undefined);
8755
10344
  const [policies, assignedPolicy, uploadPresets, lenses, metadataFields, settings] = await Promise.all([
8756
- config.policies || config.policy !== undefined || presetsNamePolicies ? collect(client.policies.iterate()) : [],
10345
+ config.policies || config.policy !== undefined || presetsNamePolicies ? collect(client.policies.list()) : [],
8757
10346
  config.policy !== undefined ? client.policies.retrieveAssigned() : undefined,
8758
- config.uploadPresets ? collect(client.uploadPresets.iterate()) : [],
8759
- config.lenses ? collect(client.lenses.iterate()) : [],
10347
+ config.uploadPresets ? collect(client.uploadPresets.list()) : [],
10348
+ config.lenses ? collect(client.lenses.list()) : [],
8760
10349
  config.metadataFields ? client.metadataFields.list() : undefined,
8761
10350
  config.settings ? client.projectSettings.get() : undefined
8762
10351
  ]);
@@ -9007,7 +10596,7 @@ var applyConfiguration = async (client, config, state, plan, log = () => {}) =>
9007
10596
  // src/cli/listen.ts
9008
10597
  import { randomBytes } from "node:crypto";
9009
10598
 
9010
- // src/contract/Ids-BESMSxGb.js
10599
+ // src/contract/Ids-C2cLdFM0.js
9011
10600
  var __defProp = Object.defineProperty;
9012
10601
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
9013
10602
  var __exportAll = (all, no_symbols) => {
@@ -9173,7 +10762,7 @@ var allowsEval2 = /* @__PURE__ */ cached2(() => {
9173
10762
  return false;
9174
10763
  }
9175
10764
  });
9176
- function isPlainObject3(o) {
10765
+ function isPlainObject4(o) {
9177
10766
  if (isObject3(o) === false)
9178
10767
  return false;
9179
10768
  const ctor = o.constructor;
@@ -9189,7 +10778,7 @@ function isPlainObject3(o) {
9189
10778
  return true;
9190
10779
  }
9191
10780
  function shallowClone2(o) {
9192
- if (isPlainObject3(o))
10781
+ if (isPlainObject4(o))
9193
10782
  return { ...o };
9194
10783
  if (Array.isArray(o))
9195
10784
  return [...o];
@@ -9300,7 +10889,7 @@ function omit2(schema, mask) {
9300
10889
  }));
9301
10890
  }
9302
10891
  function extend2(schema, shape) {
9303
- if (!isPlainObject3(shape))
10892
+ if (!isPlainObject4(shape))
9304
10893
  throw new Error("Invalid input to extend: expected a plain object");
9305
10894
  const checks = schema._zod.def.checks;
9306
10895
  if (checks && checks.length > 0) {
@@ -9318,7 +10907,7 @@ function extended2(schema, shape) {
9318
10907
  return newShape;
9319
10908
  }
9320
10909
  function safeExtend2(schema, shape) {
9321
- if (!isPlainObject3(shape))
10910
+ if (!isPlainObject4(shape))
9322
10911
  throw new Error("Invalid input to safeExtend: expected a plain object");
9323
10912
  return clone2(schema, mergeDefs2(schema._zod.def, { shape: extended2(schema, shape) }));
9324
10913
  }
@@ -10105,7 +11694,7 @@ var regexes_exports = /* @__PURE__ */ __exportAll({
10105
11694
  ipv4: () => ipv4$1,
10106
11695
  ipv6: () => ipv6$1,
10107
11696
  ksuid: () => ksuid$1,
10108
- lowercase: () => lowercase,
11697
+ lowercase: () => lowercase2,
10109
11698
  mac: () => mac$1,
10110
11699
  md5_base64: () => md5_base64,
10111
11700
  md5_base64url: () => md5_base64url,
@@ -10132,7 +11721,7 @@ var regexes_exports = /* @__PURE__ */ __exportAll({
10132
11721
  ulid: () => ulid$1,
10133
11722
  undefined: () => _undefined$2,
10134
11723
  unicodeEmail: () => unicodeEmail,
10135
- uppercase: () => uppercase,
11724
+ uppercase: () => uppercase2,
10136
11725
  uuid: () => uuid$1,
10137
11726
  uuid4: () => uuid4,
10138
11727
  uuid6: () => uuid6,
@@ -10186,28 +11775,28 @@ var e164$1 = /^\+[1-9]\d{6,14}$/;
10186
11775
  var creditCard$1 = /^\d(?:[ -]?\d){11,18}$/;
10187
11776
  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
11777
  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) {
11778
+ 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])))`;
11779
+ function anchor2(source) {
10191
11780
  return new RegExp(`^${source}$`);
10192
11781
  }
10193
- var date$2 = /* @__PURE__ */ anchor(dateSource);
10194
- function timeSource(args) {
11782
+ var date$2 = /* @__PURE__ */ anchor2(dateSource2);
11783
+ function timeSource2(args) {
10195
11784
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
10196
11785
  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
11786
  }
10198
11787
  function time$1(args) {
10199
- return new RegExp(`^${timeSource(args)}$`);
11788
+ return new RegExp(`^${timeSource2(args)}$`);
10200
11789
  }
10201
11790
  function datetime$1(args) {
10202
11791
  const opts = ["Z"];
10203
11792
  if (args.offset)
10204
11793
  opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
10205
- const qualified = `${timeSource({
11794
+ const qualified = `${timeSource2({
10206
11795
  precision: args.precision,
10207
11796
  seconds: true
10208
11797
  })}(?:${opts.join("|")})`;
10209
- const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
10210
- return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
11798
+ const timeRegex = args.local ? `${qualified}|${timeSource2({ precision: args.precision })}` : qualified;
11799
+ return new RegExp(`^${dateSource2}T(?:${timeRegex})$`);
10211
11800
  }
10212
11801
  var anyString2 = /^[\s\S]{0,}$/;
10213
11802
  var string$1 = (params) => {
@@ -10220,8 +11809,8 @@ var number$1 = /^-?\d+(?:\.\d+)?$/;
10220
11809
  var boolean$1 = /^(?:true|false)$/i;
10221
11810
  var _null$2 = /^null$/i;
10222
11811
  var _undefined$2 = /^undefined$/i;
10223
- var lowercase = /^[^A-Z]*$/;
10224
- var uppercase = /^[^a-z]*$/;
11812
+ var lowercase2 = /^[^A-Z]*$/;
11813
+ var uppercase2 = /^[^a-z]*$/;
10225
11814
  var hex$1 = /^[0-9a-fA-F]*$/;
10226
11815
  function fixedBase64(bodyLength, padding) {
10227
11816
  return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
@@ -10584,11 +12173,11 @@ var $ZodCheckRegex2 = /* @__PURE__ */ $constructor2("$ZodCheckRegex", (inst, def
10584
12173
  };
10585
12174
  });
10586
12175
  var $ZodCheckLowerCase2 = /* @__PURE__ */ $constructor2("$ZodCheckLowerCase", (inst, def) => {
10587
- def.pattern ?? (def.pattern = lowercase);
12176
+ def.pattern ?? (def.pattern = lowercase2);
10588
12177
  $ZodCheckStringFormat2.init(inst, def);
10589
12178
  });
10590
12179
  var $ZodCheckUpperCase2 = /* @__PURE__ */ $constructor2("$ZodCheckUpperCase", (inst, def) => {
10591
- def.pattern ?? (def.pattern = uppercase);
12180
+ def.pattern ?? (def.pattern = uppercase2);
10592
12181
  $ZodCheckStringFormat2.init(inst, def);
10593
12182
  });
10594
12183
  var $ZodCheckIncludes2 = /* @__PURE__ */ $constructor2("$ZodCheckIncludes", (inst, def) => {
@@ -10940,7 +12529,7 @@ var $ZodEmail2 = /* @__PURE__ */ $constructor2("$ZodEmail", (inst, def) => {
10940
12529
  def.pattern ?? (def.pattern = email$1);
10941
12530
  $ZodStringFormat2.init(inst, def);
10942
12531
  });
10943
- function canParseURL(input) {
12532
+ function canParseURL2(input) {
10944
12533
  try {
10945
12534
  if (typeof URL !== "undefined" && typeof URL.canParse === "function")
10946
12535
  return URL.canParse(input);
@@ -10950,12 +12539,12 @@ function canParseURL(input) {
10950
12539
  return false;
10951
12540
  }
10952
12541
  }
10953
- function validateURL(trimmed, def) {
12542
+ function validateURL2(trimmed, def) {
10954
12543
  if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def))
10955
- return canParseURL(trimmed) || 2;
10956
- return parseURLObject(trimmed, def);
12544
+ return canParseURL2(trimmed) || 2;
12545
+ return parseURLObject2(trimmed, def);
10957
12546
  }
10958
- function parseURLObject(trimmed, def) {
12547
+ function parseURLObject2(trimmed, def) {
10959
12548
  if (!def.normalize && def.protocol?.source === httpProtocol2.source && !/^https?:\/\//i.test(trimmed))
10960
12549
  return 1;
10961
12550
  try {
@@ -10969,15 +12558,15 @@ function parseURLObject(trimmed, def) {
10969
12558
  return 2;
10970
12559
  }
10971
12560
  }
10972
- var asciiTabOrNewline = /[\t\n\r]/g;
10973
- function stripTabAndNewline(value) {
10974
- return value.replace(asciiTabOrNewline, "");
12561
+ var asciiTabOrNewline2 = /[\t\n\r]/g;
12562
+ function stripTabAndNewline2(value) {
12563
+ return value.replace(asciiTabOrNewline2, "");
10975
12564
  }
10976
- function urlHostnameOk(url, hostname) {
12565
+ function urlHostnameOk2(url, hostname) {
10977
12566
  hostname.lastIndex = 0;
10978
12567
  return hostname.test(url.hostname);
10979
12568
  }
10980
- function urlProtocolOk(url, protocol) {
12569
+ function urlProtocolOk2(url, protocol) {
10981
12570
  protocol.lastIndex = 0;
10982
12571
  return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
10983
12572
  }
@@ -10986,7 +12575,7 @@ var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => {
10986
12575
  inst._zod.check = (payload) => {
10987
12576
  try {
10988
12577
  const trimmed = payload.value.trim();
10989
- const url = validateURL(trimmed, def);
12578
+ const url = validateURL2(trimmed, def);
10990
12579
  if (url === 1) {
10991
12580
  payload.issues.push({
10992
12581
  code: "invalid_format",
@@ -11009,10 +12598,10 @@ var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => {
11009
12598
  return;
11010
12599
  }
11011
12600
  if (url === true) {
11012
- payload.value = stripTabAndNewline(trimmed);
12601
+ payload.value = stripTabAndNewline2(trimmed);
11013
12602
  return;
11014
12603
  }
11015
- if (def.hostname && !urlHostnameOk(url, def.hostname))
12604
+ if (def.hostname && !urlHostnameOk2(url, def.hostname))
11016
12605
  payload.issues.push({
11017
12606
  code: "invalid_format",
11018
12607
  format: "url",
@@ -11022,7 +12611,7 @@ var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => {
11022
12611
  inst,
11023
12612
  continue: !def.abort
11024
12613
  });
11025
- if (def.protocol && !urlProtocolOk(url, def.protocol))
12614
+ if (def.protocol && !urlProtocolOk2(url, def.protocol))
11026
12615
  payload.issues.push({
11027
12616
  code: "invalid_format",
11028
12617
  format: "url",
@@ -11032,7 +12621,7 @@ var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => {
11032
12621
  inst,
11033
12622
  continue: !def.abort
11034
12623
  });
11035
- payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);
12624
+ payload.value = def.normalize ? url.href : stripTabAndNewline2(trimmed);
11036
12625
  return;
11037
12626
  } catch (_) {
11038
12627
  payload.issues.push({
@@ -11095,17 +12684,17 @@ var $ZodIPv42 = /* @__PURE__ */ $constructor2("$ZodIPv4", (inst, def) => {
11095
12684
  def.pattern ?? (def.pattern = ipv4$1);
11096
12685
  $ZodStringFormat2.init(inst, def);
11097
12686
  });
11098
- var ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
11099
- function isValidIPv6(value) {
11100
- if (!ipv6Alphabet.test(value))
12687
+ var ipv6Alphabet2 = /^[0-9a-fA-F:.]+$/;
12688
+ function isValidIPv62(value) {
12689
+ if (!ipv6Alphabet2.test(value))
11101
12690
  return false;
11102
- return canParseURL(`http://[${value}]`);
12691
+ return canParseURL2(`http://[${value}]`);
11103
12692
  }
11104
12693
  var $ZodIPv62 = /* @__PURE__ */ $constructor2("$ZodIPv6", (inst, def) => {
11105
12694
  def.pattern ?? (def.pattern = ipv6$1);
11106
12695
  $ZodStringFormat2.init(inst, def);
11107
12696
  inst._zod.check = (payload) => {
11108
- if (!isValidIPv6(payload.value))
12697
+ if (!isValidIPv62(payload.value))
11109
12698
  payload.issues.push({
11110
12699
  code: "invalid_format",
11111
12700
  format: "ipv6",
@@ -11123,7 +12712,7 @@ var $ZodCIDRv42 = /* @__PURE__ */ $constructor2("$ZodCIDRv4", (inst, def) => {
11123
12712
  def.pattern ?? (def.pattern = cidrv4$1);
11124
12713
  $ZodStringFormat2.init(inst, def);
11125
12714
  });
11126
- function isValidCIDRv6(value) {
12715
+ function isValidCIDRv62(value) {
11127
12716
  const parts = value.split("/");
11128
12717
  if (parts.length !== 2)
11129
12718
  return false;
@@ -11135,13 +12724,13 @@ function isValidCIDRv6(value) {
11135
12724
  return false;
11136
12725
  if (prefixNum < 0 || prefixNum > 128)
11137
12726
  return false;
11138
- return isValidIPv6(address);
12727
+ return isValidIPv62(address);
11139
12728
  }
11140
12729
  var $ZodCIDRv62 = /* @__PURE__ */ $constructor2("$ZodCIDRv6", (inst, def) => {
11141
12730
  def.pattern ?? (def.pattern = cidrv6$1);
11142
12731
  $ZodStringFormat2.init(inst, def);
11143
12732
  inst._zod.check = (payload) => {
11144
- if (!isValidCIDRv6(payload.value))
12733
+ if (!isValidCIDRv62(payload.value))
11145
12734
  payload.issues.push({
11146
12735
  code: "invalid_format",
11147
12736
  format: "cidrv6",
@@ -11151,7 +12740,7 @@ var $ZodCIDRv62 = /* @__PURE__ */ $constructor2("$ZodCIDRv6", (inst, def) => {
11151
12740
  });
11152
12741
  };
11153
12742
  });
11154
- function isValidBase64(data) {
12743
+ function isValidBase642(data) {
11155
12744
  if (data === "")
11156
12745
  return true;
11157
12746
  if (/\s/.test(data))
@@ -11170,7 +12759,7 @@ var $ZodBase642 = /* @__PURE__ */ $constructor2("$ZodBase64", (inst, def) => {
11170
12759
  def.pattern ?? (def.pattern = base64Charset2);
11171
12760
  $ZodStringFormat2.init(inst, def);
11172
12761
  inst._zod.check = (payload) => {
11173
- if (isValidBase64(payload.value))
12762
+ if (isValidBase642(payload.value))
11174
12763
  return;
11175
12764
  payload.issues.push({
11176
12765
  code: "invalid_format",
@@ -11182,17 +12771,17 @@ var $ZodBase642 = /* @__PURE__ */ $constructor2("$ZodBase64", (inst, def) => {
11182
12771
  };
11183
12772
  });
11184
12773
  var base64urlCharset2 = /^[A-Za-z0-9_-]*$/;
11185
- function isValidBase64URL(data) {
12774
+ function isValidBase64URL2(data) {
11186
12775
  if (!base64urlCharset2.test(data))
11187
12776
  return false;
11188
12777
  const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
11189
- return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
12778
+ return isValidBase642(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
11190
12779
  }
11191
12780
  var $ZodBase64URL2 = /* @__PURE__ */ $constructor2("$ZodBase64URL", (inst, def) => {
11192
12781
  def.pattern ?? (def.pattern = base64urlCharset2);
11193
12782
  $ZodStringFormat2.init(inst, def);
11194
12783
  inst._zod.check = (payload) => {
11195
- if (isValidBase64URL(payload.value))
12784
+ if (isValidBase64URL2(payload.value))
11196
12785
  return;
11197
12786
  payload.issues.push({
11198
12787
  code: "invalid_format",
@@ -11283,7 +12872,7 @@ var $ZodIBAN2 = /* @__PURE__ */ $constructor2("$ZodIBAN", (inst, def) => {
11283
12872
  });
11284
12873
  };
11285
12874
  });
11286
- function isValidJWT(token, algorithm = null) {
12875
+ function isValidJWT2(token, algorithm = null) {
11287
12876
  try {
11288
12877
  const tokensParts = token.split(".");
11289
12878
  if (tokensParts.length !== 3)
@@ -11306,7 +12895,7 @@ function isValidJWT(token, algorithm = null) {
11306
12895
  var $ZodJWT2 = /* @__PURE__ */ $constructor2("$ZodJWT", (inst, def) => {
11307
12896
  $ZodStringFormat2.init(inst, def);
11308
12897
  inst._zod.check = (payload) => {
11309
- if (isValidJWT(payload.value, def.alg))
12898
+ if (isValidJWT2(payload.value, def.alg))
11310
12899
  return;
11311
12900
  payload.issues.push({
11312
12901
  code: "invalid_format",
@@ -12092,7 +13681,7 @@ function mergeValues2(a, b) {
12092
13681
  valid: true,
12093
13682
  data: a
12094
13683
  };
12095
- if (isPlainObject3(a) && isPlainObject3(b)) {
13684
+ if (isPlainObject4(a) && isPlainObject4(b)) {
12096
13685
  const bKeys = Object.keys(b);
12097
13686
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
12098
13687
  const newObj = {
@@ -12322,7 +13911,7 @@ var $ZodRecord2 = /* @__PURE__ */ $constructor2("$ZodRecord", (inst, def) => {
12322
13911
  memo?.attach(inst);
12323
13912
  inst._zod.parse = (payload, ctx) => {
12324
13913
  const input = payload.value;
12325
- if (!isPlainObject3(input)) {
13914
+ if (!isPlainObject4(input)) {
12326
13915
  payload.issues.push({
12327
13916
  expected: "record",
12328
13917
  code: "invalid_type",
@@ -13598,7 +15187,7 @@ function registry2() {
13598
15187
  return new $ZodRegistry2;
13599
15188
  }
13600
15189
  (_a3 = globalThis).__zod_globalRegistry ?? (_a3.__zod_globalRegistry = registry2());
13601
- var globalRegistry2 = globalThis.__zod_globalRegistry;
15190
+ var globalRegistry$1 = globalThis.__zod_globalRegistry;
13602
15191
  function snapshotChecks2(def) {
13603
15192
  if (def.checks)
13604
15193
  def.checks = [...def.checks];
@@ -13676,7 +15265,7 @@ function _url2(Class, params) {
13676
15265
  ...normalizeParams2(params)
13677
15266
  });
13678
15267
  }
13679
- function _emoji2(Class, params) {
15268
+ function _emoji3(Class, params) {
13680
15269
  return new Class({
13681
15270
  type: "string",
13682
15271
  format: "emoji",
@@ -14249,8 +15838,8 @@ function _check2(fn, params) {
14249
15838
  function describe$1(description) {
14250
15839
  const ch = new $ZodCheck2({ check: "describe" });
14251
15840
  ch._zod.onattach = [(inst) => {
14252
- const existing = globalRegistry2.get(inst) ?? {};
14253
- globalRegistry2.add(inst, {
15841
+ const existing = globalRegistry$1.get(inst) ?? {};
15842
+ globalRegistry$1.add(inst, {
14254
15843
  ...existing,
14255
15844
  description
14256
15845
  });
@@ -14261,8 +15850,8 @@ function describe$1(description) {
14261
15850
  function meta$1(metadata) {
14262
15851
  const ch = new $ZodCheck2({ check: "meta" });
14263
15852
  ch._zod.onattach = [(inst) => {
14264
- const existing = globalRegistry2.get(inst) ?? {};
14265
- globalRegistry2.add(inst, {
15853
+ const existing = globalRegistry$1.get(inst) ?? {};
15854
+ globalRegistry$1.add(inst, {
14266
15855
  ...existing,
14267
15856
  ...metadata
14268
15857
  });
@@ -14367,7 +15956,7 @@ function initializeContext2(params) {
14367
15956
  target = "draft-07";
14368
15957
  return {
14369
15958
  processors: params.processors ?? {},
14370
- metadataRegistry: params?.metadata ?? globalRegistry2,
15959
+ metadataRegistry: params?.metadata ?? globalRegistry$1,
14371
15960
  target,
14372
15961
  unrepresentable: params?.unrepresentable ?? "throw",
14373
15962
  override: params?.override ?? (() => {}),
@@ -14957,7 +16546,7 @@ function aggregateChecks2(schema) {
14957
16546
  addPattern2(agg, pattern);
14958
16547
  return agg;
14959
16548
  }
14960
- var formatMap = {
16549
+ var formatMap2 = {
14961
16550
  guid: "uuid",
14962
16551
  url: "uri",
14963
16552
  datetime: "date-time",
@@ -14965,7 +16554,7 @@ var formatMap = {
14965
16554
  regex: ""
14966
16555
  };
14967
16556
  var exactPatterns2 = /* @__PURE__ */ new Map([[base64Charset2, base64$1], [base64urlCharset2, base64url$1]]);
14968
- var exactPattern = (p) => exactPatterns2.get(p) ?? p;
16557
+ var exactPattern2 = (p) => exactPatterns2.get(p) ?? p;
14969
16558
  var stringProcessor2 = (schema, ctx, _json, _params) => {
14970
16559
  const json = _json;
14971
16560
  json.type = "string";
@@ -14975,7 +16564,7 @@ var stringProcessor2 = (schema, ctx, _json, _params) => {
14975
16564
  if (typeof maximum === "number")
14976
16565
  json.maxLength = maximum;
14977
16566
  if (format) {
14978
- json.format = formatMap[format] ?? format;
16567
+ json.format = formatMap2[format] ?? format;
14979
16568
  if (json.format === "")
14980
16569
  delete json.format;
14981
16570
  if (format === "time" || laxFormat)
@@ -14984,7 +16573,7 @@ var stringProcessor2 = (schema, ctx, _json, _params) => {
14984
16573
  if (contentEncoding)
14985
16574
  json.contentEncoding = contentEncoding;
14986
16575
  if (patterns && patterns.size > 0) {
14987
- const patternList = [...patterns].map(exactPattern);
16576
+ const patternList = [...patterns].map(exactPattern2);
14988
16577
  if (patternList.length === 1)
14989
16578
  json.pattern = patternList[0].source;
14990
16579
  else if (patternList.length > 1)
@@ -15401,7 +16990,7 @@ var recordProcessor2 = (schema, ctx, _json, params) => {
15401
16990
  });
15402
16991
  json.patternProperties = {};
15403
16992
  for (const pattern of patterns)
15404
- assignProp2(json.patternProperties, exactPattern(pattern).source, valueSchema);
16993
+ assignProp2(json.patternProperties, exactPattern2(pattern).source, valueSchema);
15405
16994
  } else {
15406
16995
  if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
15407
16996
  json.propertyNames = processSchema2(def.keyType, ctx, {
@@ -15607,7 +17196,7 @@ var initializer3 = (inst, issues) => {
15607
17196
  });
15608
17197
  };
15609
17198
  var ZodRealError2 = /* @__PURE__ */ $constructor2("ZodError", initializer3, undefined, { Parent: Error });
15610
- var parse3 = /* @__PURE__ */ _parse2(ZodRealError2);
17199
+ var parse4 = /* @__PURE__ */ _parse2(ZodRealError2);
15611
17200
  var parseAsync2 = /* @__PURE__ */ _parseAsync2(ZodRealError2);
15612
17201
  var safeParse2 = /* @__PURE__ */ _safeParse2(ZodRealError2);
15613
17202
  var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync2(ZodRealError2);
@@ -15622,15 +17211,15 @@ var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync2(ZodRealError2);
15622
17211
  var schemas_exports = /* @__PURE__ */ __exportAll({
15623
17212
  ZodAny: () => ZodAny,
15624
17213
  ZodArray: () => ZodArray2,
15625
- ZodBase64: () => ZodBase64,
15626
- ZodBase64URL: () => ZodBase64URL,
17214
+ ZodBase64: () => ZodBase642,
17215
+ ZodBase64URL: () => ZodBase64URL2,
15627
17216
  ZodBigInt: () => ZodBigInt,
15628
17217
  ZodBigIntFormat: () => ZodBigIntFormat,
15629
- ZodBoolean: () => ZodBoolean2,
15630
- ZodCIDRv4: () => ZodCIDRv4,
15631
- ZodCIDRv6: () => ZodCIDRv6,
15632
- ZodCUID: () => ZodCUID,
15633
- ZodCUID2: () => ZodCUID2,
17218
+ ZodBoolean: () => ZodBoolean,
17219
+ ZodCIDRv4: () => ZodCIDRv42,
17220
+ ZodCIDRv6: () => ZodCIDRv62,
17221
+ ZodCUID: () => ZodCUID3,
17222
+ ZodCUID2: () => ZodCUID22,
15634
17223
  ZodCatch: () => ZodCatch2,
15635
17224
  ZodCodec: () => ZodCodec,
15636
17225
  ZodCreditCard: () => ZodCreditCard,
@@ -15639,31 +17228,31 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
15639
17228
  ZodDate: () => ZodDate,
15640
17229
  ZodDefault: () => ZodDefault2,
15641
17230
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
15642
- ZodE164: () => ZodE164,
15643
- ZodEmail: () => ZodEmail,
15644
- ZodEmoji: () => ZodEmoji,
17231
+ ZodE164: () => ZodE1642,
17232
+ ZodEmail: () => ZodEmail2,
17233
+ ZodEmoji: () => ZodEmoji2,
15645
17234
  ZodEnum: () => ZodEnum2,
15646
17235
  ZodExactOptional: () => ZodExactOptional2,
15647
17236
  ZodFile: () => ZodFile,
15648
17237
  ZodFunction: () => ZodFunction,
15649
- ZodGUID: () => ZodGUID,
17238
+ ZodGUID: () => ZodGUID2,
15650
17239
  ZodIBAN: () => ZodIBAN,
15651
- ZodIPv4: () => ZodIPv4,
15652
- ZodIPv6: () => ZodIPv6,
15653
- ZodISODate: () => ZodISODate,
15654
- ZodISODateTime: () => ZodISODateTime,
15655
- ZodISODuration: () => ZodISODuration,
15656
- ZodISOTime: () => ZodISOTime,
17240
+ ZodIPv4: () => ZodIPv42,
17241
+ ZodIPv6: () => ZodIPv62,
17242
+ ZodISODate: () => ZodISODate2,
17243
+ ZodISODateTime: () => ZodISODateTime2,
17244
+ ZodISODuration: () => ZodISODuration2,
17245
+ ZodISOTime: () => ZodISOTime2,
15657
17246
  ZodInstanceOf: () => ZodInstanceOf,
15658
17247
  ZodIntersection: () => ZodIntersection2,
15659
- ZodJWT: () => ZodJWT,
15660
- ZodKSUID: () => ZodKSUID,
17248
+ ZodJWT: () => ZodJWT2,
17249
+ ZodKSUID: () => ZodKSUID2,
15661
17250
  ZodLazy: () => ZodLazy,
15662
17251
  ZodLiteral: () => ZodLiteral2,
15663
17252
  ZodMAC: () => ZodMAC,
15664
17253
  ZodMap: () => ZodMap,
15665
17254
  ZodNaN: () => ZodNaN,
15666
- ZodNanoID: () => ZodNanoID,
17255
+ ZodNanoID: () => ZodNanoID2,
15667
17256
  ZodNever: () => ZodNever2,
15668
17257
  ZodNonOptional: () => ZodNonOptional2,
15669
17258
  ZodNull: () => ZodNull,
@@ -15679,24 +17268,24 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
15679
17268
  ZodReadonly: () => ZodReadonly2,
15680
17269
  ZodRecord: () => ZodRecord,
15681
17270
  ZodSet: () => ZodSet,
15682
- ZodString: () => ZodString,
15683
- ZodStringFormat: () => ZodStringFormat,
17271
+ ZodString: () => ZodString2,
17272
+ ZodStringFormat: () => ZodStringFormat2,
15684
17273
  ZodSuccess: () => ZodSuccess,
15685
17274
  ZodSymbol: () => ZodSymbol,
15686
17275
  ZodTemplateLiteral: () => ZodTemplateLiteral,
15687
17276
  ZodTransform: () => ZodTransform2,
15688
17277
  ZodTuple: () => ZodTuple2,
15689
17278
  ZodType: () => ZodType2,
15690
- ZodULID: () => ZodULID,
15691
- ZodURL: () => ZodURL,
15692
- ZodUUID: () => ZodUUID,
17279
+ ZodULID: () => ZodULID2,
17280
+ ZodURL: () => ZodURL2,
17281
+ ZodUUID: () => ZodUUID2,
15693
17282
  ZodUndefined: () => ZodUndefined,
15694
17283
  ZodUnion: () => ZodUnion2,
15695
17284
  ZodUnknown: () => ZodUnknown2,
15696
17285
  ZodVoid: () => ZodVoid,
15697
- ZodXID: () => ZodXID,
17286
+ ZodXID: () => ZodXID2,
15698
17287
  ZodXor: () => ZodXor,
15699
- _ZodString: () => _ZodString,
17288
+ _ZodString: () => _ZodString2,
15700
17289
  _default: () => _default2,
15701
17290
  _function: () => _function,
15702
17291
  any: () => any,
@@ -15773,7 +17362,7 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
15773
17362
  refine: () => refine2,
15774
17363
  set: () => set,
15775
17364
  strictObject: () => strictObject,
15776
- string: () => string2,
17365
+ string: () => string3,
15777
17366
  stringFormat: () => stringFormat,
15778
17367
  stringbool: () => stringbool,
15779
17368
  success: () => success,
@@ -15886,14 +17475,14 @@ var ZodType2 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => {
15886
17475
  },
15887
17476
  describe(description) {
15888
17477
  const cl = this.clone();
15889
- globalRegistry2.add(cl, { description });
17478
+ globalRegistry$1.add(cl, { description });
15890
17479
  return cl;
15891
17480
  },
15892
17481
  meta(...args) {
15893
17482
  if (args.length === 0)
15894
- return globalRegistry2.get(this);
17483
+ return globalRegistry$1.get(this);
15895
17484
  const cl = this.clone();
15896
- globalRegistry2.add(cl, args[0]);
17485
+ globalRegistry$1.add(cl, args[0]);
15897
17486
  return cl;
15898
17487
  },
15899
17488
  isOptional() {
@@ -15918,7 +17507,7 @@ var ZodType2 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => {
15918
17507
  own2(this, "~standard", value);
15919
17508
  },
15920
17509
  parse: function _parse(data, params) {
15921
- return parse3(this, data, params, { callee: _parse });
17510
+ return parse4(this, data, params, { callee: _parse });
15922
17511
  },
15923
17512
  parseAsync: async function _parseAsync(data, params) {
15924
17513
  return await parseAsync2(this, data, params, { callee: _parseAsync });
@@ -15969,13 +17558,13 @@ var ZodType2 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => {
15969
17558
  return createToJSONSchemaMethod2(this, {})(params);
15970
17559
  },
15971
17560
  get description() {
15972
- return globalRegistry2.get(this)?.description;
17561
+ return globalRegistry$1.get(this)?.description;
15973
17562
  },
15974
17563
  get _def() {
15975
17564
  return this._zod.def;
15976
17565
  }
15977
17566
  });
15978
- var _ZodString = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => {
17567
+ var _ZodString2 = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => {
15979
17568
  $ZodString2.init(inst, def);
15980
17569
  ZodType2.init(inst, def);
15981
17570
  inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor2(inst, ctx, json, params);
@@ -16030,285 +17619,285 @@ var _ZodString = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => {
16030
17619
  return this.check(/* @__PURE__ */ _slugify2());
16031
17620
  }
16032
17621
  }));
16033
- var ZodString = /* @__PURE__ */ $constructor2("ZodString", (inst, def) => {
17622
+ var ZodString2 = /* @__PURE__ */ $constructor2("ZodString", (inst, def) => {
16034
17623
  $ZodString2.init(inst, def);
16035
- _ZodString.init(inst, def);
17624
+ _ZodString2.init(inst, def);
16036
17625
  }, {
16037
17626
  email(params) {
16038
- return this.check(/* @__PURE__ */ _email2(ZodEmail, params));
17627
+ return this.check(/* @__PURE__ */ _email2(ZodEmail2, params));
16039
17628
  },
16040
17629
  url(params) {
16041
- return this.check(/* @__PURE__ */ _url2(ZodURL, params));
17630
+ return this.check(/* @__PURE__ */ _url2(ZodURL2, params));
16042
17631
  },
16043
17632
  jwt(params) {
16044
- return this.check(/* @__PURE__ */ _jwt2(ZodJWT, params));
17633
+ return this.check(/* @__PURE__ */ _jwt2(ZodJWT2, params));
16045
17634
  },
16046
17635
  emoji(params) {
16047
- return this.check(/* @__PURE__ */ _emoji2(ZodEmoji, params));
17636
+ return this.check(/* @__PURE__ */ _emoji3(ZodEmoji2, params));
16048
17637
  },
16049
17638
  guid(params) {
16050
- return this.check(/* @__PURE__ */ _guid2(ZodGUID, params));
17639
+ return this.check(/* @__PURE__ */ _guid2(ZodGUID2, params));
16051
17640
  },
16052
17641
  uuid(params) {
16053
- return this.check(/* @__PURE__ */ _uuid2(ZodUUID, params));
17642
+ return this.check(/* @__PURE__ */ _uuid2(ZodUUID2, params));
16054
17643
  },
16055
17644
  uuidv4(params) {
16056
- return this.check(/* @__PURE__ */ _uuidv42(ZodUUID, params));
17645
+ return this.check(/* @__PURE__ */ _uuidv42(ZodUUID2, params));
16057
17646
  },
16058
17647
  uuidv6(params) {
16059
- return this.check(/* @__PURE__ */ _uuidv62(ZodUUID, params));
17648
+ return this.check(/* @__PURE__ */ _uuidv62(ZodUUID2, params));
16060
17649
  },
16061
17650
  uuidv7(params) {
16062
- return this.check(/* @__PURE__ */ _uuidv72(ZodUUID, params));
17651
+ return this.check(/* @__PURE__ */ _uuidv72(ZodUUID2, params));
16063
17652
  },
16064
17653
  nanoid(params) {
16065
- return this.check(/* @__PURE__ */ _nanoid2(ZodNanoID, params));
17654
+ return this.check(/* @__PURE__ */ _nanoid2(ZodNanoID2, params));
16066
17655
  },
16067
17656
  cuid(params) {
16068
- return this.check(/* @__PURE__ */ _cuid3(ZodCUID, params));
17657
+ return this.check(/* @__PURE__ */ _cuid3(ZodCUID3, params));
16069
17658
  },
16070
17659
  cuid2(params) {
16071
- return this.check(/* @__PURE__ */ _cuid22(ZodCUID2, params));
17660
+ return this.check(/* @__PURE__ */ _cuid22(ZodCUID22, params));
16072
17661
  },
16073
17662
  ulid(params) {
16074
- return this.check(/* @__PURE__ */ _ulid2(ZodULID, params));
17663
+ return this.check(/* @__PURE__ */ _ulid2(ZodULID2, params));
16075
17664
  },
16076
17665
  base64(params) {
16077
- return this.check(/* @__PURE__ */ _base642(ZodBase64, params));
17666
+ return this.check(/* @__PURE__ */ _base642(ZodBase642, params));
16078
17667
  },
16079
17668
  base64url(params) {
16080
- return this.check(/* @__PURE__ */ _base64url2(ZodBase64URL, params));
17669
+ return this.check(/* @__PURE__ */ _base64url2(ZodBase64URL2, params));
16081
17670
  },
16082
17671
  xid(params) {
16083
- return this.check(/* @__PURE__ */ _xid2(ZodXID, params));
17672
+ return this.check(/* @__PURE__ */ _xid2(ZodXID2, params));
16084
17673
  },
16085
17674
  ksuid(params) {
16086
- return this.check(/* @__PURE__ */ _ksuid2(ZodKSUID, params));
17675
+ return this.check(/* @__PURE__ */ _ksuid2(ZodKSUID2, params));
16087
17676
  },
16088
17677
  ipv4(params) {
16089
- return this.check(/* @__PURE__ */ _ipv42(ZodIPv4, params));
17678
+ return this.check(/* @__PURE__ */ _ipv42(ZodIPv42, params));
16090
17679
  },
16091
17680
  ipv6(params) {
16092
- return this.check(/* @__PURE__ */ _ipv62(ZodIPv6, params));
17681
+ return this.check(/* @__PURE__ */ _ipv62(ZodIPv62, params));
16093
17682
  },
16094
17683
  cidrv4(params) {
16095
- return this.check(/* @__PURE__ */ _cidrv42(ZodCIDRv4, params));
17684
+ return this.check(/* @__PURE__ */ _cidrv42(ZodCIDRv42, params));
16096
17685
  },
16097
17686
  cidrv6(params) {
16098
- return this.check(/* @__PURE__ */ _cidrv62(ZodCIDRv6, params));
17687
+ return this.check(/* @__PURE__ */ _cidrv62(ZodCIDRv62, params));
16099
17688
  },
16100
17689
  e164(params) {
16101
- return this.check(/* @__PURE__ */ _e1642(ZodE164, params));
17690
+ return this.check(/* @__PURE__ */ _e1642(ZodE1642, params));
16102
17691
  },
16103
17692
  datetime(params) {
16104
- return this.check(/* @__PURE__ */ _isoDateTime2(ZodISODateTime, params));
17693
+ return this.check(/* @__PURE__ */ _isoDateTime2(ZodISODateTime2, params));
16105
17694
  },
16106
17695
  date(params) {
16107
- return this.check(/* @__PURE__ */ _isoDate2(ZodISODate, params));
17696
+ return this.check(/* @__PURE__ */ _isoDate2(ZodISODate2, params));
16108
17697
  },
16109
17698
  time(params) {
16110
- return this.check(/* @__PURE__ */ _isoTime2(ZodISOTime, params));
17699
+ return this.check(/* @__PURE__ */ _isoTime2(ZodISOTime2, params));
16111
17700
  },
16112
17701
  duration(params) {
16113
- return this.check(/* @__PURE__ */ _isoDuration2(ZodISODuration, params));
17702
+ return this.check(/* @__PURE__ */ _isoDuration2(ZodISODuration2, params));
16114
17703
  }
16115
17704
  });
16116
- function string2(params) {
16117
- return /* @__PURE__ */ _string2(ZodString, params);
17705
+ function string3(params) {
17706
+ return /* @__PURE__ */ _string2(ZodString2, params);
16118
17707
  }
16119
- var ZodStringFormat = /* @__PURE__ */ $constructor2("ZodStringFormat", (inst, def) => {
17708
+ var ZodStringFormat2 = /* @__PURE__ */ $constructor2("ZodStringFormat", (inst, def) => {
16120
17709
  $ZodStringFormat2.init(inst, def);
16121
- _ZodString.init(inst, def);
17710
+ _ZodString2.init(inst, def);
16122
17711
  });
16123
- var ZodISODateTime = /* @__PURE__ */ $constructor2("ZodISODateTime", (inst, def) => {
17712
+ var ZodISODateTime2 = /* @__PURE__ */ $constructor2("ZodISODateTime", (inst, def) => {
16124
17713
  $ZodISODateTime2.init(inst, def);
16125
- ZodStringFormat.init(inst, def);
17714
+ ZodStringFormat2.init(inst, def);
16126
17715
  });
16127
- var ZodISODate = /* @__PURE__ */ $constructor2("ZodISODate", (inst, def) => {
17716
+ var ZodISODate2 = /* @__PURE__ */ $constructor2("ZodISODate", (inst, def) => {
16128
17717
  $ZodISODate2.init(inst, def);
16129
- ZodStringFormat.init(inst, def);
17718
+ ZodStringFormat2.init(inst, def);
16130
17719
  });
16131
- var ZodISOTime = /* @__PURE__ */ $constructor2("ZodISOTime", (inst, def) => {
17720
+ var ZodISOTime2 = /* @__PURE__ */ $constructor2("ZodISOTime", (inst, def) => {
16132
17721
  $ZodISOTime2.init(inst, def);
16133
- ZodStringFormat.init(inst, def);
17722
+ ZodStringFormat2.init(inst, def);
16134
17723
  });
16135
- var ZodISODuration = /* @__PURE__ */ $constructor2("ZodISODuration", (inst, def) => {
17724
+ var ZodISODuration2 = /* @__PURE__ */ $constructor2("ZodISODuration", (inst, def) => {
16136
17725
  $ZodISODuration2.init(inst, def);
16137
- ZodStringFormat.init(inst, def);
17726
+ ZodStringFormat2.init(inst, def);
16138
17727
  });
16139
- var ZodEmail = /* @__PURE__ */ $constructor2("ZodEmail", (inst, def) => {
17728
+ var ZodEmail2 = /* @__PURE__ */ $constructor2("ZodEmail", (inst, def) => {
16140
17729
  $ZodEmail2.init(inst, def);
16141
- ZodStringFormat.init(inst, def);
17730
+ ZodStringFormat2.init(inst, def);
16142
17731
  });
16143
17732
  function email2(params) {
16144
- return /* @__PURE__ */ _email2(ZodEmail, params);
17733
+ return /* @__PURE__ */ _email2(ZodEmail2, params);
16145
17734
  }
16146
- var ZodGUID = /* @__PURE__ */ $constructor2("ZodGUID", (inst, def) => {
17735
+ var ZodGUID2 = /* @__PURE__ */ $constructor2("ZodGUID", (inst, def) => {
16147
17736
  $ZodGUID2.init(inst, def);
16148
- ZodStringFormat.init(inst, def);
17737
+ ZodStringFormat2.init(inst, def);
16149
17738
  });
16150
17739
  function guid2(params) {
16151
- return /* @__PURE__ */ _guid2(ZodGUID, params);
17740
+ return /* @__PURE__ */ _guid2(ZodGUID2, params);
16152
17741
  }
16153
- var ZodUUID = /* @__PURE__ */ $constructor2("ZodUUID", (inst, def) => {
17742
+ var ZodUUID2 = /* @__PURE__ */ $constructor2("ZodUUID", (inst, def) => {
16154
17743
  $ZodUUID2.init(inst, def);
16155
- ZodStringFormat.init(inst, def);
17744
+ ZodStringFormat2.init(inst, def);
16156
17745
  });
16157
17746
  function uuid2(params) {
16158
- return /* @__PURE__ */ _uuid2(ZodUUID, params);
17747
+ return /* @__PURE__ */ _uuid2(ZodUUID2, params);
16159
17748
  }
16160
17749
  function uuidv4(params) {
16161
- return /* @__PURE__ */ _uuidv42(ZodUUID, params);
17750
+ return /* @__PURE__ */ _uuidv42(ZodUUID2, params);
16162
17751
  }
16163
17752
  function uuidv6(params) {
16164
- return /* @__PURE__ */ _uuidv62(ZodUUID, params);
17753
+ return /* @__PURE__ */ _uuidv62(ZodUUID2, params);
16165
17754
  }
16166
17755
  function uuidv7(params) {
16167
- return /* @__PURE__ */ _uuidv72(ZodUUID, params);
17756
+ return /* @__PURE__ */ _uuidv72(ZodUUID2, params);
16168
17757
  }
16169
- var ZodURL = /* @__PURE__ */ $constructor2("ZodURL", (inst, def) => {
17758
+ var ZodURL2 = /* @__PURE__ */ $constructor2("ZodURL", (inst, def) => {
16170
17759
  $ZodURL2.init(inst, def);
16171
- ZodStringFormat.init(inst, def);
17760
+ ZodStringFormat2.init(inst, def);
16172
17761
  });
16173
17762
  function url(params) {
16174
- return /* @__PURE__ */ _url2(ZodURL, params);
17763
+ return /* @__PURE__ */ _url2(ZodURL2, params);
16175
17764
  }
16176
17765
  function httpUrl(params) {
16177
- return /* @__PURE__ */ _url2(ZodURL, {
17766
+ return /* @__PURE__ */ _url2(ZodURL2, {
16178
17767
  protocol: httpProtocol2,
16179
17768
  hostname: domain,
16180
17769
  ...normalizeParams2(params)
16181
17770
  });
16182
17771
  }
16183
- var ZodEmoji = /* @__PURE__ */ $constructor2("ZodEmoji", (inst, def) => {
17772
+ var ZodEmoji2 = /* @__PURE__ */ $constructor2("ZodEmoji", (inst, def) => {
16184
17773
  $ZodEmoji2.init(inst, def);
16185
- ZodStringFormat.init(inst, def);
17774
+ ZodStringFormat2.init(inst, def);
16186
17775
  });
16187
17776
  function emoji2(params) {
16188
- return /* @__PURE__ */ _emoji2(ZodEmoji, params);
17777
+ return /* @__PURE__ */ _emoji3(ZodEmoji2, params);
16189
17778
  }
16190
- var ZodNanoID = /* @__PURE__ */ $constructor2("ZodNanoID", (inst, def) => {
17779
+ var ZodNanoID2 = /* @__PURE__ */ $constructor2("ZodNanoID", (inst, def) => {
16191
17780
  $ZodNanoID2.init(inst, def);
16192
- ZodStringFormat.init(inst, def);
17781
+ ZodStringFormat2.init(inst, def);
16193
17782
  });
16194
17783
  function nanoid2(params) {
16195
- return /* @__PURE__ */ _nanoid2(ZodNanoID, params);
17784
+ return /* @__PURE__ */ _nanoid2(ZodNanoID2, params);
16196
17785
  }
16197
- var ZodCUID = /* @__PURE__ */ $constructor2("ZodCUID", (inst, def) => {
17786
+ var ZodCUID3 = /* @__PURE__ */ $constructor2("ZodCUID", (inst, def) => {
16198
17787
  $ZodCUID3.init(inst, def);
16199
- ZodStringFormat.init(inst, def);
17788
+ ZodStringFormat2.init(inst, def);
16200
17789
  });
16201
17790
  function cuid3(params) {
16202
- return /* @__PURE__ */ _cuid3(ZodCUID, params);
17791
+ return /* @__PURE__ */ _cuid3(ZodCUID3, params);
16203
17792
  }
16204
- var ZodCUID2 = /* @__PURE__ */ $constructor2("ZodCUID2", (inst, def) => {
17793
+ var ZodCUID22 = /* @__PURE__ */ $constructor2("ZodCUID2", (inst, def) => {
16205
17794
  $ZodCUID22.init(inst, def);
16206
- ZodStringFormat.init(inst, def);
17795
+ ZodStringFormat2.init(inst, def);
16207
17796
  });
16208
17797
  function cuid22(params) {
16209
- return /* @__PURE__ */ _cuid22(ZodCUID2, params);
17798
+ return /* @__PURE__ */ _cuid22(ZodCUID22, params);
16210
17799
  }
16211
- var ZodULID = /* @__PURE__ */ $constructor2("ZodULID", (inst, def) => {
17800
+ var ZodULID2 = /* @__PURE__ */ $constructor2("ZodULID", (inst, def) => {
16212
17801
  $ZodULID2.init(inst, def);
16213
- ZodStringFormat.init(inst, def);
17802
+ ZodStringFormat2.init(inst, def);
16214
17803
  });
16215
17804
  function ulid2(params) {
16216
- return /* @__PURE__ */ _ulid2(ZodULID, params);
17805
+ return /* @__PURE__ */ _ulid2(ZodULID2, params);
16217
17806
  }
16218
- var ZodXID = /* @__PURE__ */ $constructor2("ZodXID", (inst, def) => {
17807
+ var ZodXID2 = /* @__PURE__ */ $constructor2("ZodXID", (inst, def) => {
16219
17808
  $ZodXID2.init(inst, def);
16220
- ZodStringFormat.init(inst, def);
17809
+ ZodStringFormat2.init(inst, def);
16221
17810
  });
16222
17811
  function xid2(params) {
16223
- return /* @__PURE__ */ _xid2(ZodXID, params);
17812
+ return /* @__PURE__ */ _xid2(ZodXID2, params);
16224
17813
  }
16225
- var ZodKSUID = /* @__PURE__ */ $constructor2("ZodKSUID", (inst, def) => {
17814
+ var ZodKSUID2 = /* @__PURE__ */ $constructor2("ZodKSUID", (inst, def) => {
16226
17815
  $ZodKSUID2.init(inst, def);
16227
- ZodStringFormat.init(inst, def);
17816
+ ZodStringFormat2.init(inst, def);
16228
17817
  });
16229
17818
  function ksuid2(params) {
16230
- return /* @__PURE__ */ _ksuid2(ZodKSUID, params);
17819
+ return /* @__PURE__ */ _ksuid2(ZodKSUID2, params);
16231
17820
  }
16232
- var ZodIPv4 = /* @__PURE__ */ $constructor2("ZodIPv4", (inst, def) => {
17821
+ var ZodIPv42 = /* @__PURE__ */ $constructor2("ZodIPv4", (inst, def) => {
16233
17822
  $ZodIPv42.init(inst, def);
16234
- ZodStringFormat.init(inst, def);
17823
+ ZodStringFormat2.init(inst, def);
16235
17824
  });
16236
17825
  function ipv42(params) {
16237
- return /* @__PURE__ */ _ipv42(ZodIPv4, params);
17826
+ return /* @__PURE__ */ _ipv42(ZodIPv42, params);
16238
17827
  }
16239
17828
  var ZodMAC = /* @__PURE__ */ $constructor2("ZodMAC", (inst, def) => {
16240
17829
  $ZodMAC2.init(inst, def);
16241
- ZodStringFormat.init(inst, def);
17830
+ ZodStringFormat2.init(inst, def);
16242
17831
  });
16243
17832
  function mac2(params) {
16244
17833
  return /* @__PURE__ */ _mac2(ZodMAC, params);
16245
17834
  }
16246
- var ZodIPv6 = /* @__PURE__ */ $constructor2("ZodIPv6", (inst, def) => {
17835
+ var ZodIPv62 = /* @__PURE__ */ $constructor2("ZodIPv6", (inst, def) => {
16247
17836
  $ZodIPv62.init(inst, def);
16248
- ZodStringFormat.init(inst, def);
17837
+ ZodStringFormat2.init(inst, def);
16249
17838
  });
16250
17839
  function ipv62(params) {
16251
- return /* @__PURE__ */ _ipv62(ZodIPv6, params);
17840
+ return /* @__PURE__ */ _ipv62(ZodIPv62, params);
16252
17841
  }
16253
- var ZodCIDRv4 = /* @__PURE__ */ $constructor2("ZodCIDRv4", (inst, def) => {
17842
+ var ZodCIDRv42 = /* @__PURE__ */ $constructor2("ZodCIDRv4", (inst, def) => {
16254
17843
  $ZodCIDRv42.init(inst, def);
16255
- ZodStringFormat.init(inst, def);
17844
+ ZodStringFormat2.init(inst, def);
16256
17845
  });
16257
17846
  function cidrv42(params) {
16258
- return /* @__PURE__ */ _cidrv42(ZodCIDRv4, params);
17847
+ return /* @__PURE__ */ _cidrv42(ZodCIDRv42, params);
16259
17848
  }
16260
- var ZodCIDRv6 = /* @__PURE__ */ $constructor2("ZodCIDRv6", (inst, def) => {
17849
+ var ZodCIDRv62 = /* @__PURE__ */ $constructor2("ZodCIDRv6", (inst, def) => {
16261
17850
  $ZodCIDRv62.init(inst, def);
16262
- ZodStringFormat.init(inst, def);
17851
+ ZodStringFormat2.init(inst, def);
16263
17852
  });
16264
17853
  function cidrv62(params) {
16265
- return /* @__PURE__ */ _cidrv62(ZodCIDRv6, params);
17854
+ return /* @__PURE__ */ _cidrv62(ZodCIDRv62, params);
16266
17855
  }
16267
- var ZodBase64 = /* @__PURE__ */ $constructor2("ZodBase64", (inst, def) => {
17856
+ var ZodBase642 = /* @__PURE__ */ $constructor2("ZodBase64", (inst, def) => {
16268
17857
  $ZodBase642.init(inst, def);
16269
- ZodStringFormat.init(inst, def);
17858
+ ZodStringFormat2.init(inst, def);
16270
17859
  });
16271
17860
  function base642(params) {
16272
- return /* @__PURE__ */ _base642(ZodBase64, params);
17861
+ return /* @__PURE__ */ _base642(ZodBase642, params);
16273
17862
  }
16274
- var ZodBase64URL = /* @__PURE__ */ $constructor2("ZodBase64URL", (inst, def) => {
17863
+ var ZodBase64URL2 = /* @__PURE__ */ $constructor2("ZodBase64URL", (inst, def) => {
16275
17864
  $ZodBase64URL2.init(inst, def);
16276
- ZodStringFormat.init(inst, def);
17865
+ ZodStringFormat2.init(inst, def);
16277
17866
  });
16278
17867
  function base64url2(params) {
16279
- return /* @__PURE__ */ _base64url2(ZodBase64URL, params);
17868
+ return /* @__PURE__ */ _base64url2(ZodBase64URL2, params);
16280
17869
  }
16281
- var ZodE164 = /* @__PURE__ */ $constructor2("ZodE164", (inst, def) => {
17870
+ var ZodE1642 = /* @__PURE__ */ $constructor2("ZodE164", (inst, def) => {
16282
17871
  $ZodE1642.init(inst, def);
16283
- ZodStringFormat.init(inst, def);
17872
+ ZodStringFormat2.init(inst, def);
16284
17873
  });
16285
17874
  function e1642(params) {
16286
- return /* @__PURE__ */ _e1642(ZodE164, params);
17875
+ return /* @__PURE__ */ _e1642(ZodE1642, params);
16287
17876
  }
16288
17877
  var ZodCreditCard = /* @__PURE__ */ $constructor2("ZodCreditCard", (inst, def) => {
16289
17878
  $ZodCreditCard2.init(inst, def);
16290
- ZodStringFormat.init(inst, def);
17879
+ ZodStringFormat2.init(inst, def);
16291
17880
  });
16292
17881
  function creditCard2(params) {
16293
17882
  return /* @__PURE__ */ _creditCard2(ZodCreditCard, params);
16294
17883
  }
16295
17884
  var ZodIBAN = /* @__PURE__ */ $constructor2("ZodIBAN", (inst, def) => {
16296
17885
  $ZodIBAN2.init(inst, def);
16297
- ZodStringFormat.init(inst, def);
17886
+ ZodStringFormat2.init(inst, def);
16298
17887
  });
16299
17888
  function iban2(params) {
16300
17889
  return /* @__PURE__ */ _iban2(ZodIBAN, params);
16301
17890
  }
16302
- var ZodJWT = /* @__PURE__ */ $constructor2("ZodJWT", (inst, def) => {
17891
+ var ZodJWT2 = /* @__PURE__ */ $constructor2("ZodJWT", (inst, def) => {
16303
17892
  $ZodJWT2.init(inst, def);
16304
- ZodStringFormat.init(inst, def);
17893
+ ZodStringFormat2.init(inst, def);
16305
17894
  });
16306
17895
  function jwt(params) {
16307
- return /* @__PURE__ */ _jwt2(ZodJWT, params);
17896
+ return /* @__PURE__ */ _jwt2(ZodJWT2, params);
16308
17897
  }
16309
17898
  var ZodCustomStringFormat = /* @__PURE__ */ $constructor2("ZodCustomStringFormat", (inst, def) => {
16310
17899
  $ZodCustomStringFormat2.init(inst, def);
16311
- ZodStringFormat.init(inst, def);
17900
+ ZodStringFormat2.init(inst, def);
16312
17901
  });
16313
17902
  function stringFormat(format, fnOrRegex, _params = {}) {
16314
17903
  return /* @__PURE__ */ _stringFormat2(ZodCustomStringFormat, format, fnOrRegex, _params);
@@ -16417,13 +18006,13 @@ function int32(params) {
16417
18006
  function uint32(params) {
16418
18007
  return /* @__PURE__ */ _uint322(ZodNumberFormat2, params);
16419
18008
  }
16420
- var ZodBoolean2 = /* @__PURE__ */ $constructor2("ZodBoolean", (inst, def) => {
18009
+ var ZodBoolean = /* @__PURE__ */ $constructor2("ZodBoolean", (inst, def) => {
16421
18010
  $ZodBoolean2.init(inst, def);
16422
18011
  ZodType2.init(inst, def);
16423
18012
  inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor2(inst, ctx, json, params);
16424
18013
  });
16425
18014
  function boolean3(params) {
16426
- return /* @__PURE__ */ _boolean2(ZodBoolean2, params);
18015
+ return /* @__PURE__ */ _boolean2(ZodBoolean, params);
16427
18016
  }
16428
18017
  var ZodBigInt = /* @__PURE__ */ $constructor2("ZodBigInt", (inst, def) => {
16429
18018
  $ZodBigInt2.init(inst, def);
@@ -16761,7 +18350,7 @@ function record(keyType, valueType, params) {
16761
18350
  if (!valueType || !valueType._zod)
16762
18351
  return new ZodRecord({
16763
18352
  type: "record",
16764
- keyType: string2(),
18353
+ keyType: string3(),
16765
18354
  valueType: keyType,
16766
18355
  ...normalizeParams2(valueType)
16767
18356
  });
@@ -17212,18 +18801,18 @@ function _instanceof(cls, params = {}) {
17212
18801
  }
17213
18802
  var stringbool = (...args) => /* @__PURE__ */ _stringbool2({
17214
18803
  Codec: ZodCodec,
17215
- Boolean: ZodBoolean2,
17216
- String: ZodString
18804
+ Boolean: ZodBoolean,
18805
+ String: ZodString2
17217
18806
  }, ...args);
17218
18807
  function json(params) {
17219
18808
  const jsonSchema = lazy(() => {
17220
18809
  return union2([
17221
- string2(params),
18810
+ string3(params),
17222
18811
  number3(),
17223
18812
  boolean3(),
17224
18813
  _null3(),
17225
18814
  array2(jsonSchema),
17226
- record(string2(), jsonSchema)
18815
+ record(string3(), jsonSchema)
17227
18816
  ]);
17228
18817
  });
17229
18818
  return jsonSchema;
@@ -17241,6 +18830,14 @@ ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
17241
18830
  ...schemas_exports,
17242
18831
  ...checks_exports
17243
18832
  });
18833
+ var createMetaType = (type) => {
18834
+ return Object.assign((value) => {
18835
+ return {
18836
+ type,
18837
+ data: value ?? {}
18838
+ };
18839
+ }, type);
18840
+ };
17244
18841
  (/* @__PURE__ */ __commonJSMin((exports, module) => {
17245
18842
  const CHARS_GLOBAL_BACKSLASH_SUPPORTED_RX = /[\0\b\t\n\r\x1a"'\\]/g;
17246
18843
  const CHARS_ESCAPE_BACKSLASH_SUPPORTED_MAP = {
@@ -17277,6 +18874,45 @@ ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
17277
18874
  }
17278
18875
  module.exports = escapeString;
17279
18876
  }))();
18877
+ var isZodTypeExtends = (type, zodType) => {
18878
+ if (type instanceof zodType)
18879
+ return type;
18880
+ if (type.def.type === "union") {
18881
+ for (const option of type.def.options)
18882
+ if (isZodTypeExtends(option, zodType))
18883
+ return option;
18884
+ return false;
18885
+ }
18886
+ const rootType = type.def.innerType ?? type.def.in;
18887
+ if (rootType)
18888
+ return isZodTypeExtends(rootType, zodType);
18889
+ return false;
18890
+ };
18891
+ createMetaType({
18892
+ id: "foreignKey",
18893
+ check: (type) => {
18894
+ if (isZodTypeExtends(type, ZodString) || isZodTypeExtends(type, ZodNumber))
18895
+ return { success: true };
18896
+ return {
18897
+ success: false,
18898
+ message: "Foreign key must be a string or number"
18899
+ };
18900
+ }
18901
+ });
18902
+ createMetaType({
18903
+ id: "primaryKey",
18904
+ check: (type) => {
18905
+ if (isZodTypeExtends(type, ZodString) || isZodTypeExtends(type, ZodNumber))
18906
+ return { success: true };
18907
+ return {
18908
+ success: false,
18909
+ message: "Primary key must be a string or number"
18910
+ };
18911
+ }
18912
+ });
18913
+ createMetaType({ id: "updatedAt" });
18914
+ createMetaType({ id: "monotonicTimestamp" });
18915
+ createMetaType({ id: "backfill" });
17280
18916
  var ID_PREFIXES = {
17281
18917
  organisation: "org",
17282
18918
  project: "proj",
@@ -17418,6 +19054,19 @@ var deliverEvent = async (event, options) => {
17418
19054
  const baseDelay = delays[attempt - 1];
17419
19055
  const delayMs = isRetryable(result) && baseDelay !== undefined ? Math.max(baseDelay, Math.min(MAX_RETRY_AFTER_MS, (result.retryAfterSeconds ?? 0) * 1000)) : undefined;
17420
19056
  log(formatForwardLine(event, result, new Date, { attempt, attempts, delayMs }));
19057
+ options.onDelivery?.({
19058
+ type: "delivery",
19059
+ eventId: event.id,
19060
+ eventType: event.type,
19061
+ deliveryId,
19062
+ attempt,
19063
+ attempts,
19064
+ ok: result.ok,
19065
+ status: result.status ?? null,
19066
+ error: result.error ?? null,
19067
+ durationMs: result.durationMs,
19068
+ retryInMs: delayMs ?? null
19069
+ });
17421
19070
  if (delayMs === undefined || options.signal?.aborted)
17422
19071
  return result;
17423
19072
  await sleep2(delayMs, options.signal);
@@ -17509,20 +19158,25 @@ var DEVICE_POLL_INTERVAL_SECONDS = 5;
17509
19158
 
17510
19159
  // src/cli/login.ts
17511
19160
  var DEFAULT_API_URL = "https://api.calmlens.com/v1";
17512
- var credentialsPath = () => {
19161
+ var PROFILE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
19162
+ var credentialsPath = (profile) => {
19163
+ if (profile !== undefined && !PROFILE_PATTERN.test(profile)) {
19164
+ throw new Error(`"${profile}" isn't a profile name: use letters, digits, - and _, up to 64 characters.`);
19165
+ }
17513
19166
  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");
19167
+ return join(base, profile ? `credentials-${profile}.json` : "credentials.json");
17515
19168
  };
17516
- var readCredentials = async () => {
19169
+ var readCredentials = async (profile) => {
19170
+ const path = credentialsPath(profile);
17517
19171
  try {
17518
- const stored = JSON.parse(await readFile(credentialsPath(), "utf8"));
19172
+ const stored = JSON.parse(await readFile(path, "utf8"));
17519
19173
  return stored.apiKey && stored.projectId && stored.apiUrl ? stored : undefined;
17520
19174
  } catch {
17521
19175
  return;
17522
19176
  }
17523
19177
  };
17524
- var writeCredentials = async (credentials) => {
17525
- const path = credentialsPath();
19178
+ var writeCredentials = async (credentials, profile) => {
19179
+ const path = credentialsPath(profile);
17526
19180
  await mkdir(dirname(path), { recursive: true, mode: 448 });
17527
19181
  await writeFile(path, `${JSON.stringify(credentials, null, 2)}
17528
19182
  `, { mode: 384 });
@@ -17585,7 +19239,7 @@ var login = async (options) => {
17585
19239
  projectId: polled.body.project_id,
17586
19240
  apiUrl: options.apiUrl
17587
19241
  };
17588
- await writeCredentials(credentials);
19242
+ await writeCredentials(credentials, options.profile);
17589
19243
  return credentials;
17590
19244
  }
17591
19245
  if (polled.body.error === "authorization_pending")
@@ -17597,12 +19251,12 @@ var login = async (options) => {
17597
19251
  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
19252
  }
17599
19253
  };
17600
- var logout = async () => {
17601
- const stored = await readCredentials();
19254
+ var logout = async (profile) => {
19255
+ const stored = await readCredentials(profile);
17602
19256
  if (!stored)
17603
19257
  return "signed-out";
17604
19258
  const revoked = await post(oauthUrl(stored.apiUrl, "/oauth/revoke"), { token: stored.apiKey }).then((result) => result.ok).catch(() => false);
17605
- await rm(credentialsPath(), { force: true });
19259
+ await rm(credentialsPath(profile), { force: true });
17606
19260
  return revoked ? "revoked" : "forgotten";
17607
19261
  };
17608
19262
 
@@ -17610,11 +19264,11 @@ var logout = async () => {
17610
19264
  var HELP = `CalmLens CLI
17611
19265
 
17612
19266
  Usage:
17613
- calmlens login [--read-only] [--no-browser]
17614
- calmlens logout
19267
+ calmlens login [--read-only] [--no-browser] [--profile <name>]
19268
+ calmlens logout [--profile <name>]
17615
19269
  calmlens listen --forward-to <url> [options]
17616
19270
  calmlens trigger [sexual|violence|self-harm|harassment|hate|criminal-activity|clean] [options]
17617
- calmlens plan [--config <path>] [--prune]
19271
+ calmlens plan [--config <path>] [--prune] [--detailed-exitcode]
17618
19272
  calmlens apply [--config <path>] [--prune]
17619
19273
 
17620
19274
  Install it with \`brew install calmlens/sdks/calmlens\` (after
@@ -17657,7 +19311,14 @@ Options:
17657
19311
  --config <path> For plan and apply: the configuration file (default: calmlens.config.json)
17658
19312
  --prune For plan and apply: also delete upload presets, lenses and metadata
17659
19313
  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)
19314
+ --api-url <url> API base URL (default: $CALMLENS_BASE_URL or https://api.calmlens.com/v1)
19315
+ --profile <name> Use, or sign in to, a named login, so several projects can be signed in
19316
+ at once (default: $CALMLENS_PROFILE, else the default login)
19317
+ --json For listen, trigger, plan and apply: print JSON on stdout (listen: one
19318
+ line per delivery attempt) and messages on stderr
19319
+ --detailed-exitcode For plan: exit 0 with no changes, 2 with changes and 1 on an error
19320
+ --log-level <level> Log the CLI's API requests to stderr: off, info (retries and failures)
19321
+ or debug (every request) (default: $CALMLENS_LOG, else off)
17661
19322
  -v, --version Show the CLI version
17662
19323
  -h, --help Show this help
17663
19324
  `;
@@ -17667,6 +19328,15 @@ var fail = (message) => {
17667
19328
  `);
17668
19329
  process.exit(1);
17669
19330
  };
19331
+ var LOG_LEVELS2 = ["off", "info", "debug"];
19332
+ var stderrLogger = {
19333
+ debug: (message) => process.stderr.write(`${message}
19334
+ `),
19335
+ info: (message) => process.stderr.write(`${message}
19336
+ `)
19337
+ };
19338
+ var printJson = (value) => process.stdout.write(`${JSON.stringify(value)}
19339
+ `);
17670
19340
  var describeError = (error) => {
17671
19341
  if (error instanceof CalmLensError) {
17672
19342
  return `${error.message.replace(/^\[calmlens\] /, "")} (${error.code})`;
@@ -17690,6 +19360,10 @@ var main = async () => {
17690
19360
  config: { type: "string" },
17691
19361
  prune: { type: "boolean" },
17692
19362
  "no-browser": { type: "boolean" },
19363
+ profile: { type: "string" },
19364
+ json: { type: "boolean" },
19365
+ "detailed-exitcode": { type: "boolean" },
19366
+ "log-level": { type: "string" },
17693
19367
  help: { type: "boolean", short: "h" },
17694
19368
  version: { type: "boolean", short: "v" }
17695
19369
  }
@@ -17711,15 +19385,26 @@ var main = async () => {
17711
19385
  fail(`Couldn't read ${values["env-file"]}.`);
17712
19386
  }
17713
19387
  }
19388
+ const json = Boolean(values.json);
19389
+ const say = (text) => (json ? process.stderr : process.stdout).write(text);
19390
+ const profile = values.profile ?? (process.env.CALMLENS_PROFILE?.trim() || undefined);
19391
+ if (profile !== undefined && !PROFILE_PATTERN.test(profile)) {
19392
+ fail(`"${profile}" isn't a profile name: use letters, digits, - and _, up to 64 characters.`);
19393
+ }
19394
+ const logLevel = values["log-level"] ?? process.env.CALMLENS_LOG?.trim().toLowerCase();
19395
+ if (logLevel !== undefined && !LOG_LEVELS2.includes(logLevel)) {
19396
+ fail(`--log-level must be one of ${LOG_LEVELS2.join(", ")}.`);
19397
+ }
17714
19398
  if (command === "login") {
17715
19399
  try {
17716
19400
  const credentials = await login({
17717
- apiUrl: values["api-url"] ?? process.env.CALMLENS_API_URL ?? DEFAULT_API_URL,
19401
+ profile,
19402
+ apiUrl: values["api-url"] ?? process.env.CALMLENS_BASE_URL ?? DEFAULT_API_URL,
17718
19403
  readOnly: Boolean(values["read-only"]),
17719
19404
  openBrowser: !values["no-browser"],
17720
19405
  write: (text) => process.stdout.write(text)
17721
19406
  });
17722
- process.stdout.write(`Signed in to project ${credentials.projectId}. Saved to ${credentialsPath()}.
19407
+ process.stdout.write(`Signed in to project ${credentials.projectId}. Saved to ${credentialsPath(profile)}.
17723
19408
  `);
17724
19409
  } catch (error) {
17725
19410
  fail(`Sign-in failed: ${describeError(error)}`);
@@ -17727,7 +19412,7 @@ var main = async () => {
17727
19412
  return;
17728
19413
  }
17729
19414
  if (command === "logout") {
17730
- const result = await logout();
19415
+ const result = await logout(profile);
17731
19416
  process.stdout.write(result === "revoked" ? `Signed out and revoked the key.
17732
19417
  ` : result === "forgotten" ? `Signed out here, but CalmLens couldn't be reached: revoke the key in the portal under API keys.
17733
19418
  ` : `You're not signed in.
@@ -17736,17 +19421,22 @@ var main = async () => {
17736
19421
  }
17737
19422
  const explicitKey = values["api-key"] ?? process.env.CALMLENS_API_KEY;
17738
19423
  const explicitProject = values["project-id"] ?? process.env.CALMLENS_PROJECT_ID;
17739
- const stored = explicitKey || explicitProject ? undefined : await readCredentials();
19424
+ const stored = explicitKey || explicitProject ? undefined : await readCredentials(profile);
19425
+ if (profile !== undefined && !stored && !(explicitKey && explicitProject)) {
19426
+ fail(`No login for profile "${profile}". Run \`calmlens login --profile ${profile}\`.`);
19427
+ }
17740
19428
  const apiKey = explicitKey ?? stored?.apiKey;
17741
19429
  const projectId = explicitProject ?? stored?.projectId;
17742
19430
  if (!apiKey || !projectId) {
17743
19431
  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
19432
  }
17745
- const baseUrl = values["api-url"] ?? process.env.CALMLENS_API_URL ?? stored?.apiUrl;
19433
+ const baseUrl = values["api-url"] ?? process.env.CALMLENS_BASE_URL ?? stored?.apiUrl;
17746
19434
  const client = new CalmLensServerClient({
17747
19435
  apiKey,
17748
19436
  projectId,
17749
- ...baseUrl ? { baseUrl } : {}
19437
+ ...baseUrl ? { baseUrl } : {},
19438
+ logLevel: logLevel ?? "off",
19439
+ logger: stderrLogger
17750
19440
  });
17751
19441
  if (command === "listen") {
17752
19442
  const forwardTo = values["forward-to"];
@@ -17769,8 +19459,15 @@ var main = async () => {
17769
19459
  eventTypes,
17770
19460
  intervalMs: intervalSeconds * 1000,
17771
19461
  signal: controller.signal,
19462
+ ...json && {
19463
+ log: (line) => process.stderr.write(`${line}
19464
+ `),
19465
+ onDelivery: printJson
19466
+ },
17772
19467
  onReady: ({ unavailableTypes }) => {
17773
- process.stdout.write([
19468
+ if (json)
19469
+ printJson({ type: "ready", projectId, forwardTo, unavailableTypes });
19470
+ say([
17774
19471
  `Forwarding CalmLens events for project ${projectId} to ${forwardTo}`,
17775
19472
  configuredSecret ? "Signing with your CALMLENS_WEBHOOK_SECRET." : `Signing secret: ${secret}
17776
19473
  Set CALMLENS_WEBHOOK_SECRET to this value in your app, or pass --secret.`,
@@ -17808,7 +19505,10 @@ var main = async () => {
17808
19505
  name: `cli-trigger-${kind}`,
17809
19506
  content: { plainText: text, type: "text/plain" }
17810
19507
  });
17811
- process.stdout.write(`Created asset ${asset.id}: ${asset.classification.moderation.status}.
19508
+ if (json)
19509
+ printJson(asset);
19510
+ else
19511
+ process.stdout.write(`Created asset ${asset.id}: ${asset.classification.moderation.decision}.
17812
19512
  `);
17813
19513
  } catch (error) {
17814
19514
  fail(`Trigger failed: ${describeError(error)}`);
@@ -17827,13 +19527,19 @@ var main = async () => {
17827
19527
  const config = parseConfiguration(text, path);
17828
19528
  const state = await readConfigurationState(client, config);
17829
19529
  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}
19530
+ say(formatPlan(plan));
19531
+ const applying = command === "apply" && plan.changes.length > 0;
19532
+ if (applying) {
19533
+ await applyConfiguration(client, config, state, plan, (line) => say(`${line}
17833
19534
  `));
17834
- process.stdout.write(`Applied.
19535
+ say(`Applied.
17835
19536
  `);
17836
19537
  }
19538
+ if (json)
19539
+ printJson({ changes: plan.changes, unchanged: plan.unchanged, applied: applying });
19540
+ if (command === "plan" && values["detailed-exitcode"] && plan.changes.length) {
19541
+ process.exitCode = 2;
19542
+ }
17837
19543
  } catch (error) {
17838
19544
  if (error instanceof CalmLensError && error.code.endsWith("/revision-conflict"))
17839
19545
  fail(`${describeError(error)}