calmlens 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +13 -9
  2. package/bin/calmlens.js +1646 -706
  3. package/cjs/{BrowserUpload-CJ4Xc9bR.js → BrowserUpload-CeSwiMo5.js} +1 -1
  4. package/{esm/BrowserUpload-RkxV_Vv7.d.ts → cjs/BrowserUpload-D-NnAN7g.d.ts} +2 -2
  5. package/cjs/{CalmLensAppClient-LHMEQ-UZ.js → CalmLensAppClient-0UVCuNqW.js} +30 -10
  6. package/cjs/{CalmLensAppClient-B5gfOB6J.d.ts → CalmLensAppClient-gG16T2py.d.ts} +13 -3
  7. package/cjs/{CalmLensOptionKeys-BUj7v5AG.js → CalmLensOptionKeys-CYY6elxg.js} +242 -345
  8. package/cjs/{CalmLensServerClient-DCSbwIBs.d.ts → CalmLensServerClient-BHx3x_nZ.d.ts} +107 -49
  9. package/cjs/{CalmLensServerClient-BVOEUT_v.js → CalmLensServerClient-nfu6_YEW.js} +297 -92
  10. package/cjs/{CalmLensTypes-DpU-hXq2.d.ts → CalmLensTypes-CUB0YYVz.d.ts} +26601 -27354
  11. package/cjs/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  12. package/cjs/Core-C82YmjjX.d.ts +823 -0
  13. package/cjs/Core-Dc3cteU7.js +998 -0
  14. package/cjs/FileIcons-4qSX7DW2.d.ts +67 -0
  15. package/cjs/{ModerationContextLimits-FDpQmw_T.js → ModerationContextLimits-BxOmeSqq.js} +970 -278
  16. package/cjs/{ReactUpload-BvpW4hJi.js → ReactUpload-BK2O3dnK.js} +1 -1
  17. package/cjs/{ReactUpload-huIMnOJ4.d.ts → ReactUpload-DiiXfKvj.d.ts} +1 -1
  18. package/cjs/{TestTriggers-CMwMrbjy-K0YBzu2a.js → TestTriggers-BTyXtX0Q-ATuFDhLX.js} +343 -35
  19. package/{esm/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → cjs/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  20. package/cjs/{UploadController-D4qOZZc3.js → UploadController-DLyiLDTB.js} +34 -14
  21. package/cjs/{WebhookPayload-CQg8BBZQ.d.ts → WebhookPayload-BLT2y_Jy.d.ts} +93 -86
  22. package/cjs/app.d.ts +6 -7
  23. package/cjs/app.js +4 -3
  24. package/cjs/elements.d.ts +123 -22
  25. package/cjs/elements.js +553 -156
  26. package/cjs/file-icons.d.ts +2 -67
  27. package/cjs/index-CKRgjV16.d.ts +16 -0
  28. package/cjs/index.d.ts +5 -6
  29. package/cjs/index.js +3 -2
  30. package/cjs/react-native.d.ts +52 -11
  31. package/cjs/react-native.js +231 -99
  32. package/cjs/react.d.ts +42 -9
  33. package/cjs/react.js +381 -118
  34. package/cjs/server.d.ts +48 -7
  35. package/cjs/server.js +7 -3
  36. package/cjs/test-inputs.d.ts +2 -2
  37. package/cjs/test-inputs.js +13 -9
  38. package/cjs/testing.d.ts +29 -16
  39. package/cjs/testing.js +1511 -397
  40. package/cjs/ui-CTBUxnVp.d.ts +139 -0
  41. package/cjs/ui-CZ8exACq.js +1359 -0
  42. package/cjs/ui.d.ts +3 -2
  43. package/cjs/ui.js +45 -22
  44. package/cjs/vue.d.ts +802 -199
  45. package/cjs/vue.js +359 -127
  46. package/{cjs/BrowserUpload-RkxV_Vv7.d.ts → esm/BrowserUpload-D-NnAN7g.d.ts} +2 -2
  47. package/esm/{BrowserUpload-DpzS2bbj.js → BrowserUpload-i9OhCzMJ.js} +1 -1
  48. package/esm/{CalmLensAppClient-BjlvBweS.js → CalmLensAppClient-CK4_Py0c.js} +30 -10
  49. package/esm/{CalmLensAppClient-B5gfOB6J.d.ts → CalmLensAppClient-gG16T2py.d.ts} +13 -3
  50. package/esm/{CalmLensOptionKeys-BKez0Wiw.js → CalmLensOptionKeys-BGZlIsT2.js} +235 -338
  51. package/esm/{CalmLensServerClient-DCSbwIBs.d.ts → CalmLensServerClient-BHx3x_nZ.d.ts} +107 -49
  52. package/esm/{CalmLensServerClient-DemxbNMn.js → CalmLensServerClient-dAQUcDWb.js} +274 -93
  53. package/esm/{CalmLensTypes-DpU-hXq2.d.ts → CalmLensTypes-CUB0YYVz.d.ts} +26601 -27354
  54. package/esm/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  55. package/esm/Core-BxeIud_S.js +843 -0
  56. package/esm/Core-C82YmjjX.d.ts +823 -0
  57. package/esm/FileIcons-4qSX7DW2.d.ts +67 -0
  58. package/esm/{ModerationContextLimits-lLfmyLni.js → ModerationContextLimits-B6_RalCQ.js} +911 -261
  59. package/esm/{ReactUpload-huIMnOJ4.d.ts → ReactUpload-DiiXfKvj.d.ts} +1 -1
  60. package/esm/{ReactUpload-6klucehl.js → ReactUpload-DxwVqfX1.js} +1 -1
  61. package/esm/{TestTriggers-CMwMrbjy-bdowBBKw.js → TestTriggers-BTyXtX0Q-GRB9jQwo.js} +320 -36
  62. package/{cjs/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → esm/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  63. package/esm/{UploadController-UxP6gj7A.js → UploadController-D9Z-h00Q.js} +34 -14
  64. package/esm/{WebhookPayload-CQg8BBZQ.d.ts → WebhookPayload-BLT2y_Jy.d.ts} +93 -86
  65. package/esm/app.d.ts +6 -7
  66. package/esm/app.js +3 -3
  67. package/esm/elements.d.ts +123 -22
  68. package/esm/elements.js +497 -128
  69. package/esm/file-icons.d.ts +2 -67
  70. package/esm/index-CKRgjV16.d.ts +16 -0
  71. package/esm/index.d.ts +5 -6
  72. package/esm/index.js +1 -1
  73. package/esm/react-native.d.ts +52 -11
  74. package/esm/react-native.js +205 -75
  75. package/esm/react.d.ts +42 -9
  76. package/esm/react.js +327 -91
  77. package/esm/server.d.ts +48 -7
  78. package/esm/server.js +3 -3
  79. package/esm/styles.css +142 -22
  80. package/esm/svelte/AssetViewer.svelte +25 -0
  81. package/esm/svelte/CalmLensAsset.svelte +318 -0
  82. package/esm/svelte/CalmLensDocumentViewer.svelte +7 -0
  83. package/esm/svelte/CalmLensImageViewer.svelte +7 -0
  84. package/esm/svelte/CalmLensSpreadsheetViewer.svelte +7 -0
  85. package/esm/svelte/CalmLensTextViewer.svelte +7 -0
  86. package/esm/svelte/CalmLensWebsiteViewer.svelte +7 -0
  87. package/esm/svelte/index.d.ts +29 -6
  88. package/esm/svelte/index.js +7 -2
  89. package/esm/test-inputs.d.ts +2 -2
  90. package/esm/test-inputs.js +1 -1
  91. package/esm/testing.d.ts +29 -16
  92. package/esm/testing.js +1507 -393
  93. package/esm/ui-CTBUxnVp.d.ts +139 -0
  94. package/esm/ui-Cr7s6JHm.js +1258 -0
  95. package/esm/ui.d.ts +3 -2
  96. package/esm/ui.js +4 -3
  97. package/esm/vue.d.ts +802 -199
  98. package/esm/vue.js +308 -103
  99. package/package.json +3 -1
  100. package/cjs/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  101. package/cjs/index-BcDDQJF2.d.ts +0 -253
  102. package/cjs/ui-B23r8BvW.d.ts +0 -539
  103. package/cjs/ui-Dq-cm6Rx.js +0 -586
  104. package/esm/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  105. package/esm/index-BcDDQJF2.d.ts +0 -253
  106. package/esm/svelte/CalmLensMedia.svelte +0 -134
  107. package/esm/ui-B23r8BvW.d.ts +0 -539
  108. package/esm/ui-Bn29rfAi.js +0 -461
package/cjs/testing.js CHANGED
@@ -1,15 +1,15 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_TestTriggers_CMwMrbjy = require("./TestTriggers-CMwMrbjy-K0YBzu2a.js");
3
- const require_ModerationContextLimits = require("./ModerationContextLimits-FDpQmw_T.js");
4
- const require_CalmLensServerClient = require("./CalmLensServerClient-BVOEUT_v.js");
5
- const require_CalmLensOptionKeys = require("./CalmLensOptionKeys-BUj7v5AG.js");
2
+ const require_TestTriggers_BTyXtX0Q = require("./TestTriggers-BTyXtX0Q-ATuFDhLX.js");
3
+ const require_ModerationContextLimits = require("./ModerationContextLimits-BxOmeSqq.js");
4
+ const require_CalmLensServerClient = require("./CalmLensServerClient-nfu6_YEW.js");
5
+ const require_CalmLensOptionKeys = require("./CalmLensOptionKeys-CYY6elxg.js");
6
6
  const require_CryptoUtils_B_x8lMIx = require("./CryptoUtils-B_x8lMIx-YBW1-bvL.js");
7
- const require_CalmLensAppClient = require("./CalmLensAppClient-LHMEQ-UZ.js");
8
- const require_UploadController = require("./UploadController-D4qOZZc3.js");
7
+ const require_CalmLensAppClient = require("./CalmLensAppClient-0UVCuNqW.js");
8
+ const require_UploadController = require("./UploadController-DLyiLDTB.js");
9
9
  let zod = require("zod");
10
- zod = require_TestTriggers_CMwMrbjy.__toESM(zod, 1);
10
+ zod = require_TestTriggers_BTyXtX0Q.__toESM(zod, 1);
11
11
  // src/contract/MediaTestTriggers.js
12
- const MEDIA_TEST_SIGNALS = [...require_TestTriggers_CMwMrbjy.CLASSIFICATION_CATEGORIES, "violence.graphic"];
12
+ const MEDIA_TEST_SIGNALS = [...require_TestTriggers_BTyXtX0Q.CLASSIFICATION_CATEGORIES, "violence.graphic"];
13
13
  const HEX_WORDS = [
14
14
  "zero",
15
15
  "one",
@@ -31,9 +31,9 @@ const HEX_WORDS = [
31
31
  /** Read this aloud, or render it as large, high-contrast text in a video frame. */
32
32
  async function generateMediaTestCode(signal, testInputKey) {
33
33
  if (!MEDIA_TEST_SIGNALS.includes(signal)) throw new RangeError("Unsupported media test signal");
34
- return `Calm Lens test ${[...await require_TestTriggers_CMwMrbjy.getTestInputTag("media", signal, testInputKey)].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
34
+ return `Calm Lens test ${[...await require_TestTriggers_BTyXtX0Q.getTestInputTag("media", signal, testInputKey)].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
35
35
  }
36
- // src/contract/Ids-D2XfVlL6.js
36
+ // src/contract/Ids-BESMSxGb.js
37
37
  var __defProp = Object.defineProperty;
38
38
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
39
39
  var __exportAll = (all, no_symbols) => {
@@ -7909,6 +7909,7 @@ const ID_PREFIXES = {
7909
7909
  member: "mem",
7910
7910
  invitation: "inv",
7911
7911
  transfer: "xfer",
7912
+ assetBatch: "batch",
7912
7913
  supportTicket: "tkt",
7913
7914
  supportTicketMessage: "msg",
7914
7915
  humanReview: "rev",
@@ -7970,6 +7971,7 @@ const EXAMPLE_IDS = {
7970
7971
  mem: "mem_9Xm4Rk7Lq2Vt8Wb3Np5C",
7971
7972
  inv: "inv_3Qk8Xm2Rt9Lv4Wb7Np6C",
7972
7973
  xfer: "xfer_6Lq2Xm8Rk4Vt9Wb3Np7C",
7974
+ batch: "batch_5Rt8Xm3Lq9Vk2Wb7Np4C",
7973
7975
  tkt: "tkt_6Xm2Rk9Lq4Vt7Wb3Np8C",
7974
7976
  msg: "msg_2Rk7Xm4Lq9Vt3Wb8Np5C",
7975
7977
  rev: "rev_8Xm3Rk2Lq7Vt9Wb4Np6C",
@@ -7987,7 +7989,7 @@ const EXAMPLE_IDS = {
7987
7989
  * across the packages that build records from plain strings).
7988
7990
  */
7989
7991
  const idField = (prefix) => zod.string().regex(idPattern(prefix), { message: `Must be a valid ID: "${prefix}_" followed by 20 letters or digits` }).meta({ examples: [EXAMPLE_IDS[prefix]] });
7990
- // src/contract/Permissions-C2KeOlab.js
7992
+ // src/contract/Permissions-BqpmE0Qa.js
7991
7993
  const ACTION_SCHEMA = zod.enum([
7992
7994
  "assets:read",
7993
7995
  "assets:download",
@@ -8108,6 +8110,8 @@ const MOCK_QUALIFIERS = {
8108
8110
  "sexual-non-consensual",
8109
8111
  "sexual-intimate-image-abuse",
8110
8112
  "sexual-extreme",
8113
+ "sexual-strangulation",
8114
+ "sexual-incest",
8111
8115
  "sexual-minors",
8112
8116
  "sexual-solicitation",
8113
8117
  "sexual-paid",
@@ -8319,7 +8323,7 @@ var MockDecision = class {
8319
8323
  }
8320
8324
  /**
8321
8325
  * The report a decided asset gets, as the API sends it: every category (unflagged ones
8322
- * evaluated with score 0), policy-adjusted results and the automated action and
8326
+ * evaluated with score 0), policy-adjusted results and the automated status and
8323
8327
  * `flaggedCategories`. `undefined` for `pending` and `failed`.
8324
8328
  */
8325
8329
  report() {
@@ -8352,10 +8356,16 @@ var MockDecision = class {
8352
8356
  }])),
8353
8357
  explanationComplete: true,
8354
8358
  source: "policy",
8355
- automatedAction: STATUS_ACTION[status],
8359
+ rule: null,
8360
+ automatedStatus: status,
8356
8361
  regions: [],
8362
+ linkSafety: null,
8363
+ timeline: null,
8357
8364
  flaggedCategories: evaluated.filter(([, score]) => action(score) !== "allow").map(([category]) => category),
8358
- raw: { categories }
8365
+ raw: {
8366
+ categories,
8367
+ hashMatches: []
8368
+ }
8359
8369
  };
8360
8370
  }
8361
8371
  };
@@ -8363,17 +8373,395 @@ var MockDecision = class {
8363
8373
  const mockDecision = (status) => new MockDecision(status);
8364
8374
  /** The default `moderate`: queued work stays pending until `completeProcessing`, which allows it. */
8365
8375
  const defaultModerate = ({ trigger, queued }) => queued && trigger !== "complete" ? "pending" : "allowed";
8376
+ // src/testing/MockAssetFilters.ts
8377
+ /** The asset fields a list filter may name, each with the operators it accepts. */
8378
+ const MOCK_ASSET_FILTER_FIELDS = {
8379
+ id: {
8380
+ kind: "text",
8381
+ nullable: false,
8382
+ operators: [
8383
+ "==",
8384
+ "!=",
8385
+ ">",
8386
+ ">=",
8387
+ "<",
8388
+ "<=",
8389
+ "=in=",
8390
+ "=out="
8391
+ ]
8392
+ },
8393
+ parentId: {
8394
+ kind: "text",
8395
+ nullable: true,
8396
+ operators: [
8397
+ "==",
8398
+ "!=",
8399
+ ">",
8400
+ ">=",
8401
+ "<",
8402
+ "<=",
8403
+ "=in=",
8404
+ "=out="
8405
+ ]
8406
+ },
8407
+ folderId: {
8408
+ kind: "text",
8409
+ nullable: true,
8410
+ operators: [
8411
+ "==",
8412
+ "!=",
8413
+ ">",
8414
+ ">=",
8415
+ "<",
8416
+ "<=",
8417
+ "=in=",
8418
+ "=out="
8419
+ ]
8420
+ },
8421
+ uploadPresetId: {
8422
+ kind: "text",
8423
+ nullable: true,
8424
+ operators: [
8425
+ "==",
8426
+ "!=",
8427
+ ">",
8428
+ ">=",
8429
+ "<",
8430
+ "<=",
8431
+ "=in=",
8432
+ "=out="
8433
+ ]
8434
+ },
8435
+ createdAt: {
8436
+ kind: "number",
8437
+ nullable: false,
8438
+ operators: [
8439
+ "==",
8440
+ "!=",
8441
+ ">",
8442
+ ">=",
8443
+ "<",
8444
+ "<=",
8445
+ "=in=",
8446
+ "=out="
8447
+ ]
8448
+ },
8449
+ updatedAt: {
8450
+ kind: "number",
8451
+ nullable: false,
8452
+ operators: [
8453
+ "==",
8454
+ "!=",
8455
+ ">",
8456
+ ">=",
8457
+ "<",
8458
+ "<=",
8459
+ "=in=",
8460
+ "=out="
8461
+ ]
8462
+ },
8463
+ type: {
8464
+ kind: "text",
8465
+ nullable: false,
8466
+ operators: [
8467
+ "==",
8468
+ "!=",
8469
+ ">",
8470
+ ">=",
8471
+ "<",
8472
+ "<=",
8473
+ "=in=",
8474
+ "=out="
8475
+ ]
8476
+ },
8477
+ name: {
8478
+ kind: "text",
8479
+ nullable: false,
8480
+ operators: [
8481
+ "==",
8482
+ "!=",
8483
+ ">",
8484
+ ">=",
8485
+ "<",
8486
+ "<=",
8487
+ "=in=",
8488
+ "=out="
8489
+ ]
8490
+ },
8491
+ description: {
8492
+ kind: "text",
8493
+ nullable: true,
8494
+ operators: [
8495
+ "==",
8496
+ "!=",
8497
+ ">",
8498
+ ">=",
8499
+ "<",
8500
+ "<=",
8501
+ "=in=",
8502
+ "=out="
8503
+ ]
8504
+ },
8505
+ externalId: {
8506
+ kind: "text",
8507
+ nullable: true,
8508
+ operators: [
8509
+ "==",
8510
+ "!=",
8511
+ ">",
8512
+ ">=",
8513
+ "<",
8514
+ "<=",
8515
+ "=in=",
8516
+ "=out="
8517
+ ]
8518
+ },
8519
+ externalUrl: {
8520
+ kind: "text",
8521
+ nullable: true,
8522
+ operators: [
8523
+ "==",
8524
+ "!=",
8525
+ ">",
8526
+ ">=",
8527
+ "<",
8528
+ "<=",
8529
+ "=in=",
8530
+ "=out="
8531
+ ]
8532
+ },
8533
+ authorId: {
8534
+ kind: "text",
8535
+ nullable: true,
8536
+ operators: [
8537
+ "==",
8538
+ "!=",
8539
+ ">",
8540
+ ">=",
8541
+ "<",
8542
+ "<=",
8543
+ "=in=",
8544
+ "=out="
8545
+ ]
8546
+ },
8547
+ tags: {
8548
+ kind: "list",
8549
+ nullable: false,
8550
+ operators: ["=in=", "=out="]
8551
+ },
8552
+ visibility: {
8553
+ kind: "text",
8554
+ nullable: true,
8555
+ operators: [
8556
+ "==",
8557
+ "!=",
8558
+ ">",
8559
+ ">=",
8560
+ "<",
8561
+ "<=",
8562
+ "=in=",
8563
+ "=out="
8564
+ ]
8565
+ },
8566
+ "upload.status": {
8567
+ kind: "text",
8568
+ nullable: false,
8569
+ operators: [
8570
+ "==",
8571
+ "!=",
8572
+ ">",
8573
+ ">=",
8574
+ "<",
8575
+ "<=",
8576
+ "=in=",
8577
+ "=out="
8578
+ ]
8579
+ },
8580
+ "upload.updatedAt": {
8581
+ kind: "number",
8582
+ nullable: true,
8583
+ operators: [
8584
+ "==",
8585
+ "!=",
8586
+ ">",
8587
+ ">=",
8588
+ "<",
8589
+ "<=",
8590
+ "=in=",
8591
+ "=out="
8592
+ ]
8593
+ },
8594
+ "classification.status": {
8595
+ kind: "text",
8596
+ nullable: false,
8597
+ operators: [
8598
+ "==",
8599
+ "!=",
8600
+ ">",
8601
+ ">=",
8602
+ "<",
8603
+ "<=",
8604
+ "=in=",
8605
+ "=out="
8606
+ ]
8607
+ },
8608
+ "classification.updatedAt": {
8609
+ kind: "number",
8610
+ nullable: true,
8611
+ operators: [
8612
+ "==",
8613
+ "!=",
8614
+ ">",
8615
+ ">=",
8616
+ "<",
8617
+ "<=",
8618
+ "=in=",
8619
+ "=out="
8620
+ ]
8621
+ },
8622
+ "classification.completedAt": {
8623
+ kind: "number",
8624
+ nullable: true,
8625
+ operators: [
8626
+ "==",
8627
+ "!=",
8628
+ ">",
8629
+ ">=",
8630
+ "<",
8631
+ "<=",
8632
+ "=in=",
8633
+ "=out="
8634
+ ]
8635
+ },
8636
+ "classification.moderation.status": {
8637
+ kind: "text",
8638
+ nullable: false,
8639
+ operators: [
8640
+ "==",
8641
+ "!=",
8642
+ ">",
8643
+ ">=",
8644
+ "<",
8645
+ "<=",
8646
+ "=in=",
8647
+ "=out="
8648
+ ]
8649
+ },
8650
+ "content.status": {
8651
+ kind: "text",
8652
+ nullable: false,
8653
+ operators: [
8654
+ "==",
8655
+ "!=",
8656
+ ">",
8657
+ ">=",
8658
+ "<",
8659
+ "<=",
8660
+ "=in=",
8661
+ "=out="
8662
+ ]
8663
+ },
8664
+ "content.removalReason": {
8665
+ kind: "text",
8666
+ nullable: true,
8667
+ operators: [
8668
+ "==",
8669
+ "!=",
8670
+ ">",
8671
+ ">=",
8672
+ "<",
8673
+ "<=",
8674
+ "=in=",
8675
+ "=out="
8676
+ ]
8677
+ },
8678
+ "content.updatedAt": {
8679
+ kind: "number",
8680
+ nullable: true,
8681
+ operators: [
8682
+ "==",
8683
+ "!=",
8684
+ ">",
8685
+ ">=",
8686
+ "<",
8687
+ "<=",
8688
+ "=in=",
8689
+ "=out="
8690
+ ]
8691
+ },
8692
+ "content.format": {
8693
+ kind: "text",
8694
+ nullable: true,
8695
+ operators: [
8696
+ "==",
8697
+ "!=",
8698
+ ">",
8699
+ ">=",
8700
+ "<",
8701
+ "<=",
8702
+ "=in=",
8703
+ "=out="
8704
+ ]
8705
+ },
8706
+ "content.extension": {
8707
+ kind: "text",
8708
+ nullable: true,
8709
+ operators: [
8710
+ "==",
8711
+ "!=",
8712
+ ">",
8713
+ ">=",
8714
+ "<",
8715
+ "<=",
8716
+ "=in=",
8717
+ "=out="
8718
+ ]
8719
+ },
8720
+ "content.sizeInBytes": {
8721
+ kind: "number",
8722
+ nullable: true,
8723
+ operators: [
8724
+ "==",
8725
+ "!=",
8726
+ ">",
8727
+ ">=",
8728
+ "<",
8729
+ "<=",
8730
+ "=in=",
8731
+ "=out="
8732
+ ]
8733
+ }
8734
+ };
8366
8735
  // src/testing/MockUtils.ts
8736
+ /**
8737
+ * A `sort` query value as the API parses it (`sortQueryField` in shared/Page.ts): comma-separated
8738
+ * fields from `fields`, descending when prefixed with `-`, none repeated and at most `max`.
8739
+ * Undefined for a list that sends none; `undefined`'s default applies.
8740
+ */
8741
+ const parseSort = (value, fields, max, fail) => {
8742
+ if (value === null) return void 0;
8743
+ const sort = [];
8744
+ for (const part of value.split(",").map((item) => item.trim())) {
8745
+ const field = part.startsWith("-") ? part.slice(1) : part;
8746
+ if (!/^-?[A-Za-z][A-Za-z0-9.]*$/.test(part) || !fields.includes(field)) throw fail();
8747
+ if (sort.some((rule) => rule.field === field)) throw fail();
8748
+ sort.push({
8749
+ field,
8750
+ direction: part.startsWith("-") ? "desc" : "asc"
8751
+ });
8752
+ }
8753
+ if (sort.length > max) throw fail();
8754
+ return sort;
8755
+ };
8367
8756
  const toBase64Utf8 = (value) => btoa(Array.from(new TextEncoder().encode(value), (byte) => String.fromCharCode(byte)).join(""));
8368
8757
  const fromBase64Utf8 = (value) => new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(atob(value), (char) => char.charCodeAt(0)));
8369
8758
  /**
8370
8759
  * One keyset page like the API's (packages/shared-backend/src/CursorPagination.ts): ordered by
8371
- * `ordering` (newest first by default) with an `id` tie-breaker added, starting after the
8372
- * cursor's values. The cursor is tied to `scope` (the filter, folder or parent) and the
8373
- * ordering, so it only continues the query it came from. `name` and `id` are compared by code
8374
- * point, like the database.
8760
+ * `sort` (newest first by default) with an `id` tie-breaker added, starting after the cursor's
8761
+ * values. The cursor is tied to `scope` (the filter, folder or parent) and the sort, so it only
8762
+ * continues the query it came from. `name` and `id` are compared by code point, like the database.
8375
8763
  */
8376
- const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOrdering = [{
8764
+ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultSort = [{
8377
8765
  field: "createdAt",
8378
8766
  direction: "desc"
8379
8767
  }] }) => {
@@ -8381,7 +8769,7 @@ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOr
8381
8769
  if (typeof pageSize !== "number" || !Number.isFinite(pageSize) || pageSize < 1) throw fail("validation/too-small", "pageSize");
8382
8770
  if (pageSize > 100) throw fail("validation/too-big", "pageSize");
8383
8771
  if (!Number.isInteger(pageSize)) throw require_ModerationContextLimits.invalidArgument("Invalid page size");
8384
- const ordering = query.ordering?.length ? [...query.ordering] : [...defaultOrdering];
8772
+ const ordering = query.sort?.length ? [...query.sort] : [...defaultSort];
8385
8773
  if (!ordering.some(({ field }) => field === "id")) ordering.push({
8386
8774
  field: "id",
8387
8775
  direction: ordering[0].direction
@@ -8395,7 +8783,7 @@ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOr
8395
8783
  values = parsed?.values;
8396
8784
  if (parsed?.scope !== signature || !Array.isArray(values) || values.length !== ordering.length || values.some((value, i) => STRING_FIELDS.has(ordering[i].field) ? typeof value !== "string" : typeof value !== "number" || !Number.isFinite(value))) throw new Error();
8397
8785
  } catch {
8398
- throw fail("validation/invalid-cursor");
8786
+ throw fail("cursor/invalid");
8399
8787
  }
8400
8788
  remaining = remaining.filter((item) => {
8401
8789
  for (const [i, rule] of ordering.entries()) {
@@ -8410,9 +8798,7 @@ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOr
8410
8798
  const last = pageItems.at(-1);
8411
8799
  return {
8412
8800
  items: pageItems,
8413
- pageSize,
8414
8801
  hasMore,
8415
- ordering,
8416
8802
  nextCursor: hasMore && last ? toBase64Utf8(JSON.stringify({
8417
8803
  scope: signature,
8418
8804
  values: ordering.map(({ field }) => last[field])
@@ -8428,7 +8814,7 @@ const compareValues = (left, right) => {
8428
8814
  const [a, b] = [String(left), String(right)];
8429
8815
  return a < b ? -1 : a > b ? 1 : 0;
8430
8816
  };
8431
- /** Sorts like the API's `ordering`; without one, newest first. */
8817
+ /** Sorts like the API's `sort`; without one, newest first. */
8432
8818
  const orderItems = (items, ordering) => {
8433
8819
  const rules = ordering?.length ? ordering : [{
8434
8820
  field: "createdAt",
@@ -8442,90 +8828,196 @@ const orderItems = (items, ordering) => {
8442
8828
  return 0;
8443
8829
  });
8444
8830
  };
8445
- const COMPARISON = /^([A-Za-z][\w.]*)(==|!=|=in=|=out=|>=|<=|=gt=|=ge=|=lt=|=le=|>|<)(.+)$/;
8446
- const parseFilterValue = (raw) => {
8447
- const value = raw.trim();
8448
- if (/^".*"$/.test(value) || /^'.*'$/.test(value)) return value.slice(1, -1);
8449
- if (value === "null") return null;
8450
- if (value === "true") return true;
8451
- if (value === "false") return false;
8452
- if (value !== "" && !Number.isNaN(Number(value))) return Number(value);
8453
- return value;
8831
+ /** Thrown for a filter the API refuses with `filter/invalid`. */
8832
+ var MockInvalidFilter = class extends Error {};
8833
+ /** The characters that end an unquoted word, as in @rsql/parser. */
8834
+ const RESERVED = "\"'();,=!~<> \n \r";
8835
+ const LOGIC_WORDS = ["and", "or"];
8836
+ /** Splits a filter into tokens like @rsql/parser's lexer. */
8837
+ const tokenize = (filter) => {
8838
+ const tokens = [];
8839
+ let i = 0;
8840
+ while (i < filter.length) {
8841
+ const char = filter[i];
8842
+ if (" \n \r".includes(char)) i++;
8843
+ else if (char === "\"" || char === "'") {
8844
+ let text = "";
8845
+ let j = i + 1;
8846
+ for (; j < filter.length && filter[j] !== char; j++) {
8847
+ if (filter[j] === "\\" && j + 1 < filter.length) j++;
8848
+ text += filter[j];
8849
+ }
8850
+ if (j >= filter.length) throw new MockInvalidFilter();
8851
+ tokens.push({
8852
+ kind: "quoted",
8853
+ text
8854
+ });
8855
+ i = j + 1;
8856
+ } else if (char === "(" || char === ")") {
8857
+ tokens.push({
8858
+ kind: "paren",
8859
+ text: char
8860
+ });
8861
+ i++;
8862
+ } else if (char === ";" || char === ",") {
8863
+ tokens.push({
8864
+ kind: "logic",
8865
+ text: char === ";" ? "and" : "or"
8866
+ });
8867
+ i++;
8868
+ } else if ("=!~<>".includes(char)) {
8869
+ const operator = /^(==|!=|<=|>=|<|>|=[a-z]*=)/.exec(filter.slice(i))?.[0];
8870
+ if (!operator) throw new MockInvalidFilter();
8871
+ tokens.push({
8872
+ kind: "operator",
8873
+ text: operator
8874
+ });
8875
+ i += operator.length;
8876
+ } else {
8877
+ const word = LOGIC_WORDS.find((logic) => filter.startsWith(`${logic} `, i));
8878
+ if (word) {
8879
+ tokens.push({
8880
+ kind: "logic",
8881
+ text: word
8882
+ });
8883
+ i += word.length;
8884
+ continue;
8885
+ }
8886
+ let j = i + 1;
8887
+ while (j < filter.length && !RESERVED.includes(filter[j])) j++;
8888
+ tokens.push({
8889
+ kind: "word",
8890
+ text: filter.slice(i, j)
8891
+ });
8892
+ i = j;
8893
+ }
8894
+ }
8895
+ return tokens;
8896
+ };
8897
+ /**
8898
+ * A field's value as the API reads it (zodbase/rsql): `null` is a missing value only on a
8899
+ * nullable field, and a number field's value must be a finite number.
8900
+ */
8901
+ const readFilterValue = (field, text) => {
8902
+ const { kind, nullable } = MOCK_ASSET_FILTER_FIELDS[field];
8903
+ if (text === "null" && nullable) return null;
8904
+ if (kind !== "number") return text;
8905
+ const number = Number(text);
8906
+ if (text === "" || !Number.isFinite(number)) throw new MockInvalidFilter();
8907
+ return number;
8908
+ };
8909
+ /** Parses a filter: `;` (and) binds tighter than `,` (or), and parentheses group. */
8910
+ const parseFilter = (filter) => {
8911
+ const tokens = tokenize(filter);
8912
+ let position = 0;
8913
+ const peek = () => tokens[position];
8914
+ const next = () => {
8915
+ const token = tokens[position++];
8916
+ if (!token) throw new MockInvalidFilter();
8917
+ return token;
8918
+ };
8919
+ const value = () => {
8920
+ const token = next();
8921
+ if (token.kind !== "word" && token.kind !== "quoted") throw new MockInvalidFilter();
8922
+ return token.text;
8923
+ };
8924
+ const term = () => {
8925
+ const token = next();
8926
+ if (token.kind === "paren" && token.text === "(") {
8927
+ const node = alternatives();
8928
+ if (next().text !== ")") throw new MockInvalidFilter();
8929
+ return node;
8930
+ }
8931
+ if (token.kind !== "word" || !Object.hasOwn(MOCK_ASSET_FILTER_FIELDS, token.text)) throw new MockInvalidFilter();
8932
+ const field = token.text;
8933
+ const operator = next();
8934
+ if (operator.kind !== "operator" || !MOCK_ASSET_FILTER_FIELDS[field].operators.includes(operator.text)) throw new MockInvalidFilter();
8935
+ let texts;
8936
+ if (peek()?.kind === "paren" && peek()?.text === "(") {
8937
+ next();
8938
+ texts = [value()];
8939
+ while (peek()?.kind === "logic" && peek()?.text === "or") {
8940
+ next();
8941
+ texts.push(value());
8942
+ }
8943
+ if (next().text !== ")") throw new MockInvalidFilter();
8944
+ } else texts = [value()];
8945
+ if (texts.length > 1 && operator.text !== "=in=" && operator.text !== "=out=") throw new MockInvalidFilter();
8946
+ return {
8947
+ type: "comparison",
8948
+ field,
8949
+ operator: operator.text,
8950
+ values: texts.map((text) => readFilterValue(field, text))
8951
+ };
8952
+ };
8953
+ const conjunction = () => {
8954
+ const nodes = [term()];
8955
+ while (peek()?.kind === "logic" && peek()?.text === "and") {
8956
+ next();
8957
+ nodes.push(term());
8958
+ }
8959
+ return nodes.length === 1 ? nodes[0] : {
8960
+ type: "and",
8961
+ nodes
8962
+ };
8963
+ };
8964
+ const alternatives = () => {
8965
+ const nodes = [conjunction()];
8966
+ while (peek()?.kind === "logic" && peek()?.text === "or") {
8967
+ next();
8968
+ nodes.push(conjunction());
8969
+ }
8970
+ return nodes.length === 1 ? nodes[0] : {
8971
+ type: "or",
8972
+ nodes
8973
+ };
8974
+ };
8975
+ const node = alternatives();
8976
+ if (position !== tokens.length) throw new MockInvalidFilter();
8977
+ return node;
8454
8978
  };
8455
8979
  const readField = (item, path) => path.split(".").reduce((value, key) => value && typeof value === "object" ? value[key] : void 0, item);
8456
- const unsupportedFilter = (expression) => require_ModerationContextLimits.invalidArgument(`MockCalmLensServerClient cannot evaluate the filter "${expression}". It supports ==, !=, <, <=, >, >=, =in= and =out=, joined by ; (and) or , (or) and grouped with parentheses.`);
8457
- const matchesComparison = (item, comparison) => {
8458
- const match = COMPARISON.exec(comparison.trim());
8459
- if (!match) throw unsupportedFilter(comparison);
8460
- const [, field, operator, rawValue] = match;
8461
- const actual = readField(item, field);
8462
- const isList = operator === "=in=" || operator === "=out=";
8463
- if (isList && !/^\(.*\)$/.test(rawValue.trim())) throw unsupportedFilter(comparison);
8464
- const values = isList ? rawValue.trim().slice(1, -1).split(",").map(parseFilterValue) : [parseFilterValue(rawValue)];
8465
- const equals = (expected) => Array.isArray(actual) ? actual.includes(expected) : expected === null ? actual === null || actual === void 0 : actual === expected;
8980
+ /** `*` matches any run of characters, regardless of case; every other character itself. */
8981
+ const wildcard = (pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "isu");
8982
+ /** Compares like SQL: a missing value never matches, except `== null`. */
8983
+ const matchesComparison = (item, { field, operator, values }) => {
8984
+ const actual = readField(item, field) ?? null;
8985
+ const [value] = values;
8986
+ if (actual === null && MOCK_ASSET_FILTER_FIELDS[field].kind === "list") return operator === "=out=";
8987
+ if (actual === null) return operator === "==" && value === null;
8988
+ if (operator === "!=" && value === null) return true;
8989
+ const actuals = Array.isArray(actual) ? actual : [actual];
8990
+ const equals = (expected) => actuals.some((each) => each === expected);
8991
+ if ((operator === "==" || operator === "!=") && typeof value === "string" && value.includes("*")) {
8992
+ const pattern = wildcard(value);
8993
+ const matched = actuals.some((each) => typeof each === "string" && pattern.test(each));
8994
+ return operator === "==" ? matched : !matched;
8995
+ }
8466
8996
  switch (operator) {
8467
- case "==": return equals(values[0]);
8468
- case "!=": return !equals(values[0]);
8997
+ case "==": return equals(value);
8998
+ case "!=": return !equals(value);
8469
8999
  case "=in=": return values.some(equals);
8470
- case "=out=": return !values.some(equals);
8471
- case ">":
8472
- case "=gt=": return compareValues(actual, values[0]) > 0;
8473
- case ">=":
8474
- case "=ge=": return compareValues(actual, values[0]) >= 0;
8475
- case "<":
8476
- case "=lt=": return compareValues(actual, values[0]) < 0;
8477
- default: return compareValues(actual, values[0]) <= 0;
8478
- }
8479
- };
8480
- /** Splits on `separator` outside quotes and parentheses. */
8481
- const splitTopLevel = (text, separator) => {
8482
- const parts = [];
8483
- let depth = 0;
8484
- let quote = null;
8485
- let current = "";
8486
- for (const char of text) {
8487
- if (quote) {
8488
- if (char === quote) quote = null;
8489
- } else if (char === "\"" || char === "'") quote = char;
8490
- else if (char === "(") depth++;
8491
- else if (char === ")") depth--;
8492
- else if (char === separator && depth === 0) {
8493
- parts.push(current);
8494
- current = "";
8495
- continue;
8496
- }
8497
- current += char;
8498
- }
8499
- parts.push(current);
8500
- return parts;
8501
- };
8502
- /** The expression inside `( … )` when the parentheses enclose all of `text`, else undefined. */
8503
- const unwrapGroup = (text) => {
8504
- if (!text.startsWith("(") || !text.endsWith(")")) return void 0;
8505
- let depth = 0;
8506
- let quote = null;
8507
- for (const [index, char] of [...text].entries()) if (quote) {
8508
- if (char === quote) quote = null;
8509
- } else if (char === "\"" || char === "'") quote = char;
8510
- else if (char === "(") depth++;
8511
- else if (char === ")" && --depth === 0) return index === text.length - 1 ? text.slice(1, -1) : void 0;
8512
- };
8513
- /** Evaluates `,` (or) of `;` (and) terms, where a term is a comparison or a `( … )` group. */
8514
- const matchesExpression = (item, expression) => splitTopLevel(expression, ",").some((alternative) => splitTopLevel(alternative, ";").every((term) => {
8515
- const trimmed = term.trim();
8516
- if (!trimmed) throw unsupportedFilter(expression);
8517
- const group = unwrapGroup(trimmed);
8518
- return group === void 0 ? matchesComparison(item, trimmed) : matchesExpression(item, group);
8519
- }));
9000
+ case "=out=": return !values.includes(null) && !values.some(equals);
9001
+ }
9002
+ if (value === null) return false;
9003
+ const order = compareValues(actual, value);
9004
+ switch (operator) {
9005
+ case ">": return order > 0;
9006
+ case ">=": return order >= 0;
9007
+ case "<": return order < 0;
9008
+ default: return order <= 0;
9009
+ }
9010
+ };
9011
+ const matchesNode = (item, node) => node.type === "comparison" ? matchesComparison(item, node) : node.type === "and" ? node.nodes.every((child) => matchesNode(item, child)) : node.nodes.some((child) => matchesNode(item, child));
8520
9012
  /**
8521
- * Applies an RSQL `filter` like the API: comparisons joined by `;` (and), which binds tighter
8522
- * than `,` (or), and grouped with parentheses. Anything it can't evaluate throws instead of
8523
- * returning wrong results.
9013
+ * Applies an RSQL `filter` like the API (zodbase/rsql with MOCK_ASSET_FILTER_FIELDS): only the
9014
+ * listed fields, each with its own operators, `;` (and) binding tighter than `,` (or), and parentheses. Throws
9015
+ * `MockInvalidFilter` for any filter the API refuses with `filter/invalid`.
8524
9016
  */
8525
9017
  const filterAssets = (items, filter) => {
8526
9018
  if (!filter) return items;
8527
- if (items.length === 0) matchesExpression({}, filter);
8528
- return items.filter((item) => matchesExpression(item, filter));
9019
+ const node = parseFilter(filter);
9020
+ return items.filter((item) => matchesNode(item, node));
8529
9021
  };
8530
9022
  const MAX_SEARCH_TOKENS = 8;
8531
9023
  /** The keyword fields the API searches, in the order it reports matches. */
@@ -8586,15 +9078,100 @@ const REVIEW_DECISIONS = [
8586
9078
  "blocked",
8587
9079
  "purged"
8588
9080
  ];
9081
+ /**
9082
+ * A client method, named like its path on the client. A request is recorded under the first
9083
+ * method that sends it; `callsTo` and `failNextRequest` also match the others (see
9084
+ * `MockCalmLensCall`).
9085
+ */
9086
+ const MOCK_OPERATIONS = [
9087
+ "assets.list",
9088
+ "assets.iterate",
9089
+ "assets.search",
9090
+ "assets.retrieve",
9091
+ "assets.waitForDecision",
9092
+ "assets.update",
9093
+ "assets.listChildren",
9094
+ "assets.iterateChildren",
9095
+ "assets.listTimeline",
9096
+ "assets.iterateTimeline",
9097
+ "assets.create",
9098
+ "assets.classify",
9099
+ "assets.uploadPart",
9100
+ "assets.move",
9101
+ "assets.retry",
9102
+ "assets.explain",
9103
+ "assets.decide",
9104
+ "assets.removeContent",
9105
+ "assets.delete",
9106
+ "assets.batch",
9107
+ "text.classify",
9108
+ "cdn.serve",
9109
+ "cdn.getAssetInfo",
9110
+ "cdn.signAssetUrl",
9111
+ "events.list",
9112
+ "events.pages",
9113
+ "folders.list",
9114
+ "folders.iterate",
9115
+ "folders.retrieve",
9116
+ "folders.create",
9117
+ "folders.update",
9118
+ "folders.delete",
9119
+ "folders.move",
9120
+ "hashLists.list",
9121
+ "hashLists.iterate",
9122
+ "hashLists.retrieve",
9123
+ "hashLists.create",
9124
+ "hashLists.update",
9125
+ "hashLists.delete",
9126
+ "hashLists.listEntries",
9127
+ "hashLists.iterateEntries",
9128
+ "hashLists.addEntry",
9129
+ "hashLists.removeEntry",
9130
+ "policies.list",
9131
+ "policies.iterate",
9132
+ "policies.retrieve",
9133
+ "policies.create",
9134
+ "policies.update",
9135
+ "policies.reset",
9136
+ "policies.upgrade",
9137
+ "policies.setAutomaticUpdates",
9138
+ "policies.delete",
9139
+ "policies.retrieveAssigned",
9140
+ "policies.assign",
9141
+ "lenses.list",
9142
+ "lenses.iterate",
9143
+ "lenses.create",
9144
+ "lenses.retrieve",
9145
+ "lenses.update",
9146
+ "lenses.delete",
9147
+ "ensureLens",
9148
+ "ensureLenses"
9149
+ ];
8589
9150
  const MAX_PAGE_SIZE = 100;
8590
9151
  const MAX_DECISION_NOTE_LENGTH = 1499;
8591
9152
  /** How the API names a reviewer acting through an unnamed API key. */
8592
9153
  const API_KEY_REVIEWER_NAME = "An API key";
8593
- const MAX_SEARCH_LIMIT = 20;
9154
+ /** The actor of events the mock's API key causes: mock keys have no ID. */
9155
+ const MOCK_API_KEY_ACTOR = {
9156
+ type: "api-key",
9157
+ id: null
9158
+ };
9159
+ /** The actor of a reviewer's decision through the `decide` test hook. */
9160
+ const MOCK_REVIEWER_ACTOR = {
9161
+ type: "user",
9162
+ id: null
9163
+ };
9164
+ const AUTOMATED_ACTOR = {
9165
+ type: "automated",
9166
+ id: null
9167
+ };
9168
+ /** An event type's shape (`resource.action`), as the mock checks `types` without the catalog. */
9169
+ const EVENT_TYPE_PATTERN = /^[a-z][a-z-]*\.[a-z][a-z-]*$/;
9170
+ const MAX_SEARCH_PAGE_SIZE = 20;
8594
9171
  const MAX_SEARCH_QUERY_LENGTH = 200;
8595
9172
  /**
8596
- * The ThumbHash the mock gives every classified image, standing in for one computed from its
8597
- * pixels. The `placeholder` resource serves it as a PNG, like the CDN.
9173
+ * The ThumbHash the mock gives every processed asset's preview, standing in for one computed from
9174
+ * its pixels. The `placeholder` resource serves it as a PNG, like the CDN.
8598
9175
  */
8599
9176
  const MOCK_THUMBHASH = "1QcSHQRnh493V4dIh4eXh1h4kJUI";
8600
9177
  /** Like the API: 1 to 255 printable ASCII characters, once HTTP has trimmed the header value. */
@@ -8618,10 +9195,19 @@ const toEventAsset = (asset) => ({
8618
9195
  upload: { status: asset.upload.status },
8619
9196
  classification: {
8620
9197
  status: asset.classification.status,
9198
+ testInput: asset.classification.testInput,
8621
9199
  moderation: { status: asset.classification.moderation.status }
8622
9200
  },
8623
9201
  content: { status: asset.content.status }
8624
9202
  });
9203
+ /** The moderation status each `asset.<status>` event announces. */
9204
+ const ANNOUNCED_STATUS = {
9205
+ "asset.allowed": "allowed",
9206
+ "asset.limited": "limited",
9207
+ "asset.age-restricted": "age-restricted",
9208
+ "asset.blocked": "blocked",
9209
+ "asset.purged": "purged"
9210
+ };
8625
9211
  /** A `moderate` answer or `completeProcessing` decision as a checked `MockDecision`. */
8626
9212
  const toDecision = (value) => {
8627
9213
  if (value instanceof MockDecision) return value;
@@ -8634,12 +9220,116 @@ const assetNameFact = (asset) => ({
8634
9220
  value: asset.name,
8635
9221
  url: `https://calmlens.com/go/asset/${asset.id}`
8636
9222
  });
8637
- /** Removing content removes the placeholder and average colour with it. */
8638
- const withoutPlaceholder = (image) => image ? {
8639
- ...image,
8640
- thumbhash: null,
8641
- averageColor: null
8642
- } : image;
9223
+ /** The page the mock serves at `/embed`, standing in for the CDN's embed page. */
9224
+ const MOCK_EMBED_HTML = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>Embed</title></head><body></body></html>";
9225
+ /** A ThumbHash as the PNG the placeholder resource serves. */
9226
+ const mockPlaceholderPng = (thumbhash) => Uint8Array.from(atob(require_UploadController.placeholderHashToDataURL(thumbhash).split(",", 2)[1]), (char) => char.charCodeAt(0));
9227
+ /** Removing or withholding content removes its rendered file and preview, as the API does. */
9228
+ const NO_RENDERING = {
9229
+ rendered: null,
9230
+ preview: null,
9231
+ hls: null
9232
+ };
9233
+ /** The size of the waveform the API makes as an audio asset's preview. */
9234
+ const WAVEFORM_SIZE = {
9235
+ width: 1200,
9236
+ height: 300
9237
+ };
9238
+ /** Audio and video formats browsers play as uploaded, so the API serves them as stored (Asset.ts). */
9239
+ const BROWSER_SAFE_MEDIA_FORMATS = [
9240
+ "video/mp4",
9241
+ "audio/mpeg",
9242
+ "audio/aac",
9243
+ "audio/mp4",
9244
+ "audio/x-m4a",
9245
+ "audio/ogg"
9246
+ ];
9247
+ /** Spreadsheets, which have no rendered file or preview (Asset.ts). */
9248
+ const SPREADSHEET_MIME_TYPES = [
9249
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
9250
+ "application/vnd.ms-excel.sheet.macroenabled.12",
9251
+ "application/vnd.ms-excel",
9252
+ "application/vnd.oasis.opendocument.spreadsheet"
9253
+ ];
9254
+ /** Whether browsers play an audio or video upload's format as it is, so it is served as stored. */
9255
+ const isBrowserSafeMediaFormat = (format) => BROWSER_SAFE_MEDIA_FORMATS.includes(require_ModerationContextLimits.normalizeUploadMimeType(format ?? ""));
9256
+ /**
9257
+ * The rendered file and preview the API reports for an asset with its content held (Asset.ts,
9258
+ * getAssetRendered and getAssetPreview). Once uploaded, an image renders as itself with a preview
9259
+ * that has no ThumbHash yet, and a PDF and browser-safe audio and video render as uploaded. Once
9260
+ * processed, a website renders as its screenshot; a document or presentation as a PDF, with its
9261
+ * first page as the preview; video and audio as a browser-safe file (MP4 or M4A unless browsers
9262
+ * play the upload), audio with a waveform preview and video with no poster; and every preview has
9263
+ * its ThumbHash. Text, spreadsheets and other files have neither. The mock decodes nothing, so
9264
+ * sizes are unknown, audio has no peaks, and audio and video never get an HLS stream.
9265
+ */
9266
+ const mockRendering = (asset, processed) => {
9267
+ const format = asset.content.format;
9268
+ const mimeType = require_ModerationContextLimits.normalizeUploadMimeType(format ?? "");
9269
+ const browserSafe = isBrowserSafeMediaFormat(format);
9270
+ const preview = (size) => ({
9271
+ ...size,
9272
+ thumbhash: processed ? MOCK_THUMBHASH : null,
9273
+ averageColor: processed ? "#7f7f7f" : null
9274
+ });
9275
+ const unsized = {
9276
+ width: null,
9277
+ height: null
9278
+ };
9279
+ const rendersOnUpload = asset.type === "image" || mimeType === "application/pdf" || (asset.type === "video" || asset.type === "audio") && browserSafe;
9280
+ if (!processed && !rendersOnUpload) return NO_RENDERING;
9281
+ switch (asset.type) {
9282
+ case "image": return {
9283
+ rendered: {
9284
+ kind: "image",
9285
+ format: format ?? "image/png",
9286
+ ...unsized
9287
+ },
9288
+ preview: preview(unsized),
9289
+ hls: null
9290
+ };
9291
+ case "website": return {
9292
+ rendered: {
9293
+ kind: "image",
9294
+ format: "image/png",
9295
+ ...unsized
9296
+ },
9297
+ preview: preview(unsized),
9298
+ hls: null
9299
+ };
9300
+ case "multimedia-document":
9301
+ if (SPREADSHEET_MIME_TYPES.includes(mimeType)) return NO_RENDERING;
9302
+ return {
9303
+ rendered: {
9304
+ kind: "pdf",
9305
+ format: "application/pdf",
9306
+ ...unsized
9307
+ },
9308
+ preview: processed ? preview(unsized) : null,
9309
+ hls: null
9310
+ };
9311
+ case "video": return {
9312
+ rendered: {
9313
+ kind: "video",
9314
+ format: browserSafe ? format : "video/mp4",
9315
+ ...unsized
9316
+ },
9317
+ preview: null,
9318
+ hls: null
9319
+ };
9320
+ case "audio": return {
9321
+ rendered: {
9322
+ kind: "audio",
9323
+ format: browserSafe ? format : "audio/mp4",
9324
+ ...unsized,
9325
+ ...processed && { peaks: [] }
9326
+ },
9327
+ preview: processed ? preview(WAVEFORM_SIZE) : null,
9328
+ hls: null
9329
+ };
9330
+ default: return NO_RENDERING;
9331
+ }
9332
+ };
8643
9333
  /** An asset's type from its content type, or `website` for a URL. */
8644
9334
  const inferAssetType = (contentType) => {
8645
9335
  if (contentType === void 0) return "website";
@@ -8661,8 +9351,52 @@ var ApiFailure = class {
8661
9351
  }
8662
9352
  };
8663
9353
  const fail = (code, { message, details } = {}) => new ApiFailure(require_ModerationContextLimits.API_ERROR_DEFINITIONS[code].status, code, message ?? require_ModerationContextLimits.API_ERROR_DEFINITIONS[code].message, details);
8664
- /** A request the API's schema refuses: `validation/<zod issue>` with HTTP 400 and the field. */
8665
- const invalidField = (code, path) => new ApiFailure(400, code, `Invalid ${path}`, { path });
9354
+ /**
9355
+ * A request the API's schema refuses: `validation/invalid-request` with HTTP 400, listing the field
9356
+ * and its issue code (such as `validation/too-big`) in `details.issues`.
9357
+ */
9358
+ /**
9359
+ * The mock's grant, the asset segment of a URL `signAssetUrl` signs: `sig_` and the hex of
9360
+ * `{assetId}.{1|0}.{expiresAt}`, its asset, original access and expiry. Every SDK's mock writes it
9361
+ * the same way. It is readable, not signed, as the mock has no secret to keep.
9362
+ */
9363
+ const encodeMockGrant = (grant) => `sig_${[...new TextEncoder().encode(`${grant.assetId}.${grant.original ? 1 : 0}.${grant.expiresAt}`)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
9364
+ /** Reads a mock grant, or `undefined` for a segment the mock didn't sign. */
9365
+ const decodeMockGrant = (segment) => {
9366
+ const hex = segment.slice(4);
9367
+ if (!/^(?:[0-9a-f]{2})+$/.test(hex)) return void 0;
9368
+ let text;
9369
+ try {
9370
+ text = new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(hex.match(/../g), (pair) => Number.parseInt(pair, 16)));
9371
+ } catch {
9372
+ return;
9373
+ }
9374
+ const match = /^(.+)\.([01])\.(\d+)$/s.exec(text);
9375
+ if (!match) return void 0;
9376
+ return {
9377
+ assetId: match[1],
9378
+ original: match[2] === "1",
9379
+ expiresAt: Number(match[3])
9380
+ };
9381
+ };
9382
+ const invalidField = (code, path) => new ApiFailure(400, require_ModerationContextLimits.API_ERROR_CODES.INVALID_REQUEST, `Invalid ${path}`, { issues: [{
9383
+ path,
9384
+ message: `Invalid ${path}`,
9385
+ code
9386
+ }] });
9387
+ /**
9388
+ * Refuses `metadata` the API's schema refuses (METADATA_ITEM_SCHEMA): it is `null` or a list of
9389
+ * `{ id, value }` objects with a string `id` and any JSON `value`.
9390
+ */
9391
+ const checkMetadata = (metadata) => {
9392
+ if (metadata === void 0 || metadata === null) return;
9393
+ if (!Array.isArray(metadata)) throw invalidField("validation/invalid-type", "metadata");
9394
+ metadata.forEach((item, index) => {
9395
+ if (typeof item !== "object" || item === null || Array.isArray(item)) throw invalidField("validation/invalid-type", `metadata.${index}`);
9396
+ if (typeof item.id !== "string") throw invalidField("validation/invalid-type", `metadata.${index}.id`);
9397
+ if (item.value === void 0) throw invalidField("validation/invalid-value", `metadata.${index}.value`);
9398
+ });
9399
+ };
8666
9400
  /** The built-in presets the mock knows, by display name. */
8667
9401
  const MOCK_PRESET_NAMES = {
8668
9402
  "general-community": "General",
@@ -8670,35 +9404,65 @@ const MOCK_PRESET_NAMES = {
8670
9404
  "education-support": "Learning and support",
8671
9405
  "wholesome-community": "Teen-safe"
8672
9406
  };
9407
+ /**
9408
+ * The settings of the mock's presets: every category with its default action (`allow` for
9409
+ * personal information and profanity, `block` otherwise) and no rules. The mock holds no built-in
9410
+ * preset settings, and uploads are never decided by a policy.
9411
+ */
9412
+ const mockPresetSettings = () => ({ categorySettings: Object.fromEntries(require_TestTriggers_BTyXtX0Q.CLASSIFICATION_CATEGORIES.map((category) => [category, {
9413
+ action: category === "personal-information" || category === "profanity" ? "allow" : "block",
9414
+ allowances: [],
9415
+ restrictions: []
9416
+ }])) });
9417
+ /**
9418
+ * Refuses settings the API refuses (MODERATION_POLICY_SETTINGS_SCHEMA): every category, each with
9419
+ * an `action` and its `allowances` and `restrictions` lists.
9420
+ */
9421
+ const checkPolicySettings = (settings) => {
9422
+ const categories = settings?.categorySettings;
9423
+ if (!categories || typeof categories !== "object") throw invalidField("validation/invalid-type", "settings.categorySettings");
9424
+ for (const category of require_TestTriggers_BTyXtX0Q.CLASSIFICATION_CATEGORIES) {
9425
+ const value = categories[category];
9426
+ if (!value || typeof value !== "object") throw invalidField("validation/invalid-type", `settings.categorySettings.${category}`);
9427
+ for (const key of ["allowances", "restrictions"]) if (!Array.isArray(value[key])) throw invalidField("validation/invalid-type", `settings.categorySettings.${category}.${key}`);
9428
+ if (typeof value.action !== "string") throw invalidField("validation/invalid-value", `settings.categorySettings.${category}.action`);
9429
+ }
9430
+ for (const key of Object.keys(categories)) if (!require_TestTriggers_BTyXtX0Q.CLASSIFICATION_CATEGORIES.includes(key)) throw invalidField("validation/unknown-field", `settings.categorySettings.${key}`);
9431
+ };
8673
9432
  /** The client methods that send a request, the one it is recorded under first. */
8674
9433
  const operationsOf = (request) => {
8675
9434
  const { method, segments, query, cdn } = request;
8676
- if (cdn) return ["cdn.serve"];
9435
+ if (cdn) return segments[3] === "info" ? ["cdn.getAssetInfo"] : ["cdn.serve"];
8677
9436
  const [root] = segments;
8678
9437
  if (root === "projects") {
8679
9438
  switch (segments.slice(2).join("/")) {
8680
9439
  case "events": return ["events.list", "events.pages"];
8681
- case "lenses": return ["ensureLenses", "ensureLens"];
8682
- case "folders": return method === "GET" ? ["folders.list"] : ["folders.create"];
8683
- case "hash-lists": return method === "GET" ? ["hashLists.list"] : ["hashLists.create"];
8684
- case "policies": return method === "GET" ? ["policies.list"] : ["policies.create"];
8685
- case "policy": return ["policies.assign"];
9440
+ case "lenses": return method === "GET" ? ["lenses.list", "lenses.iterate"] : method === "POST" ? ["lenses.create"] : ["ensureLenses", "ensureLens"];
9441
+ case "folders": return method === "GET" ? ["folders.list", "folders.iterate"] : ["folders.create"];
9442
+ case "hash-lists": return method === "GET" ? ["hashLists.list", "hashLists.iterate"] : ["hashLists.create"];
9443
+ case "policy": return method === "GET" ? ["policies.retrieveAssigned"] : ["policies.assign"];
8686
9444
  case "assets/search": return ["assets.search"];
8687
9445
  case "assets/batch": return ["assets.batch"];
9446
+ case "signed-asset-urls": return ["cdn.signAssetUrl"];
8688
9447
  case "assets":
8689
9448
  if (method === "GET") return ["assets.list", "assets.iterate"];
8690
- if (query.get("queue") === "true") return ["assets.create"];
9449
+ if (query.get("wait") === "false") return ["assets.create"];
8691
9450
  return isTextUpload(request) ? ["assets.classify", "text.classify"] : ["assets.classify"];
8692
9451
  }
8693
- if (segments[2] === "policies" && segments[3] !== void 0) {
8694
- if (segments[4] === "preset") return ["policies.applyPreset"];
8695
- if (segments[4] === "automatic-updates") return ["policies.setAutomaticUpdates"];
8696
- return method === "GET" ? ["policies.retrieve"] : method === "PATCH" ? ["policies.update"] : ["policies.delete"];
8697
- }
9452
+ if (segments[2] === "assets" && segments[4] === "timeline" && segments.length === 5) return ["assets.listTimeline", "assets.iterateTimeline"];
8698
9453
  return [];
8699
9454
  }
9455
+ if (root === "policies") {
9456
+ const [, policyId, policyAction] = segments;
9457
+ if (policyId === void 0) return method === "GET" ? ["policies.list", "policies.iterate"] : ["policies.create"];
9458
+ if (policyAction === "reset") return ["policies.reset"];
9459
+ if (policyAction === "upgrade") return ["policies.upgrade"];
9460
+ if (policyAction === "automatic-updates") return ["policies.setAutomaticUpdates"];
9461
+ return method === "GET" ? ["policies.retrieve"] : method === "PATCH" ? ["policies.update"] : ["policies.delete"];
9462
+ }
9463
+ if (root === "lenses" && segments[1] !== void 0) return method === "GET" ? ["lenses.retrieve"] : method === "PATCH" ? ["lenses.update"] : ["lenses.delete"];
8700
9464
  if (root === "upload-presets") {
8701
- if (segments[3] === void 0) return [query.get("queue") === "true" ? "assets.create" : "assets.classify"];
9465
+ if (segments[3] === void 0) return [query.get("wait") === "false" ? "assets.create" : "assets.classify"];
8702
9466
  return segments[4] === "part" ? ["assets.uploadPart"] : ["assets.retrieve"];
8703
9467
  }
8704
9468
  const id = segments[1];
@@ -8708,16 +9472,15 @@ const operationsOf = (request) => {
8708
9472
  return method === "GET" ? ["folders.retrieve"] : method === "PATCH" ? ["folders.update"] : ["folders.delete"];
8709
9473
  }
8710
9474
  if (root === "hash-lists" && id !== void 0) {
8711
- if (action === "entries") return method === "GET" ? ["hashLists.listEntries"] : ["hashLists.addEntry"];
9475
+ if (action === "entries") return method === "GET" ? ["hashLists.listEntries", "hashLists.iterateEntries"] : ["hashLists.addEntry"];
8712
9476
  return method === "GET" ? ["hashLists.retrieve"] : method === "PATCH" ? ["hashLists.update"] : ["hashLists.delete"];
8713
9477
  }
8714
9478
  if (root === "hash-list-entries" && id !== void 0) return ["hashLists.removeEntry"];
8715
9479
  if (root !== "assets" || id === void 0) return [];
8716
9480
  switch (action) {
8717
9481
  case void 0: return method === "GET" ? ["assets.retrieve", "assets.waitForDecision"] : method === "PATCH" ? ["assets.update"] : ["assets.delete"];
8718
- case "content": return ["assets.deleteContent"];
9482
+ case "content": return ["assets.removeContent"];
8719
9483
  case "children": return ["assets.listChildren", "assets.iterateChildren"];
8720
- case "signed-url": return ["assets.createSignedUrl"];
8721
9484
  case "part": return ["assets.uploadPart"];
8722
9485
  case "move": return ["assets.move"];
8723
9486
  case "retry": return ["assets.retry"];
@@ -8755,8 +9518,12 @@ const createMonotonicClock = () => {
8755
9518
  var MockCalmLensApi = class {
8756
9519
  constructor(options) {
8757
9520
  this.calls = [];
9521
+ this.cdnBaseUrl = "";
8758
9522
  this.lenses = /* @__PURE__ */ new Map();
8759
9523
  this.eventFeed = [];
9524
+ this.assetEventSequences = /* @__PURE__ */ new Map();
9525
+ this.processingOptions = /* @__PURE__ */ new Map();
9526
+ this.pendingReruns = /* @__PURE__ */ new Set();
8760
9527
  this.openUploads = /* @__PURE__ */ new Map();
8761
9528
  this.idempotentResults = /* @__PURE__ */ new Map();
8762
9529
  this.pendingFailures = [];
@@ -8765,7 +9532,7 @@ var MockCalmLensApi = class {
8765
9532
  this.policies = /* @__PURE__ */ new Map();
8766
9533
  this.hashLists = /* @__PURE__ */ new Map();
8767
9534
  this.hashListEntries = /* @__PURE__ */ new Map();
8768
- this.pageFailure = (code, path) => code === "validation/invalid-cursor" ? fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR) : invalidField(code, path ?? "pageSize");
9535
+ this.pageFailure = (code, path) => code === "cursor/invalid" ? fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR) : invalidField(code, path ?? "pageSize");
8769
9536
  this.options = options;
8770
9537
  this.projectId = options.projectId;
8771
9538
  this.apiKey = options.apiKey;
@@ -8777,6 +9544,8 @@ var MockCalmLensApi = class {
8777
9544
  }
8778
9545
  /** Queues a failure for the next request, or the next one `operation` sends. */
8779
9546
  failNextRequest(failure, options = {}) {
9547
+ if (options.operation !== void 0 && !MOCK_OPERATIONS.includes(options.operation)) throw require_ModerationContextLimits.invalidArgument(`${options.operation} is not a client method that sends requests`);
9548
+ if (!(typeof failure === "string" && failure in require_ModerationContextLimits.API_ERROR_DEFINITIONS) && (options.details !== void 0 || options.retryAfter !== void 0)) throw require_ModerationContextLimits.invalidArgument("details and retryAfter apply only to an API error code");
8780
9549
  if (options.retryAfter !== void 0 && !(Number.isInteger(options.retryAfter) && options.retryAfter >= 0)) throw require_ModerationContextLimits.invalidArgument("retryAfter must be a whole number of seconds");
8781
9550
  this.pendingFailures.push({
8782
9551
  failure,
@@ -8793,10 +9562,14 @@ var MockCalmLensApi = class {
8793
9562
  */
8794
9563
  async enqueueEvent(input) {
8795
9564
  const asset = input.asset === void 0 && input.assetId ? await this.databaseStorage.getAsset(input.assetId) : void 0;
8796
- return this.pushEvent(asset ? {
9565
+ if (!asset) return this.pushEvent(input);
9566
+ const snapshot = toEventAsset(asset);
9567
+ const announced = ANNOUNCED_STATUS[input.type];
9568
+ if (announced) snapshot.classification.moderation.status = announced;
9569
+ return this.pushEvent({
8797
9570
  ...input,
8798
- asset: toEventAsset(asset)
8799
- } : input);
9571
+ asset: snapshot
9572
+ });
8800
9573
  }
8801
9574
  /** Adds an event to the feed, filling the fields the API always sets. */
8802
9575
  pushEvent(input) {
@@ -8809,10 +9582,14 @@ var MockCalmLensApi = class {
8809
9582
  description: null,
8810
9583
  assetId: null,
8811
9584
  asset: null,
9585
+ actor: MOCK_API_KEY_ACTOR,
8812
9586
  facts: [],
8813
9587
  createdAt: now,
8814
9588
  ...input
8815
9589
  };
9590
+ const sequence = event.assetId ? (this.assetEventSequences.get(event.assetId) ?? 0) + 1 : null;
9591
+ if (event.assetId && sequence !== null) this.assetEventSequences.set(event.assetId, sequence);
9592
+ event.assetSequence = sequence;
8816
9593
  this.eventFeed.push(event);
8817
9594
  return event;
8818
9595
  }
@@ -8839,15 +9616,17 @@ var MockCalmLensApi = class {
8839
9616
  } catch (failure) {
8840
9617
  throw this.toError(failure);
8841
9618
  }
8842
- if (asset.classification.status !== "processing") throw require_ModerationContextLimits.invalidArgument(`asset ${assetId} isn't processing`);
9619
+ const rerun = this.pendingReruns.has(asset.id);
9620
+ if (!rerun && asset.classification.status !== "processing") throw require_ModerationContextLimits.invalidArgument(`asset ${assetId} isn't processing`);
8843
9621
  const settled = decision === void 0 ? void 0 : toDecision(decision);
8844
- return structuredClone(await this.moderateStored(asset, "complete", settled));
9622
+ if (!rerun) return structuredClone(await this.moderateStored(asset, "complete", settled));
9623
+ return structuredClone(await this.settleRerun(asset, settled ?? await this.decisionFor(asset, "complete", true)));
8845
9624
  }
8846
9625
  /**
8847
9626
  * `POST /assets/:assetId/decision`, like the API: an asset still uploading or processing can't
8848
9627
  * be decided, one pending moderation can only be blocked or purged, a decision must change the
8849
- * status and purged content can only be blocked. Mock API keys have no name, so the reviewer is
8850
- * "An API key".
9628
+ * status and purged content can only be blocked. The review is the API key's, and mock API keys
9629
+ * have no ID or name, so its ID is `null` and the event names the reviewer "An API key".
8851
9630
  */
8852
9631
  async decideAsset(assetId, body) {
8853
9632
  const { decision, note: rawNote } = body;
@@ -8864,43 +9643,38 @@ var MockCalmLensApi = class {
8864
9643
  if (decision !== "purged" && decision !== "blocked" && status === "pending") throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_DECISION_NOT_ALLOWED);
8865
9644
  if (status === decision) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_DECISION_UNCHANGED);
8866
9645
  if (decision !== "purged" && decision !== "blocked" && status === "purged") throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_CONTENT_PURGED);
8867
- return this.recordDecision(asset, decision, {
8868
- note,
8869
- reviewerName: API_KEY_REVIEWER_NAME
8870
- });
9646
+ return this.recordDecision(asset, decision, { note });
8871
9647
  }
8872
9648
  /**
8873
9649
  * Sets the reviewer's decision: the moderation status, a manual review and the
8874
- * `asset.<status>` event (after `asset.content-removed` when purging). The test hook records no
8875
- * reviewer or note; the API's handler records both.
9650
+ * `asset.<status>` event (after `asset.content-removed` when purging). Either way the review is
9651
+ * the mock API key's; the test hook records no note, the API's handler records it.
8876
9652
  */
8877
9653
  async recordDecision(asset, decision, review) {
9654
+ this.pendingReruns.delete(asset.id);
8878
9655
  const decided = await this.applyOutcome(asset, decision, "requested");
8879
9656
  const now = this.now();
8880
9657
  decided.classification.moderation.manualReviews = [...decided.classification.moderation.manualReviews ?? [], {
8881
9658
  id: this.createId("rev"),
8882
9659
  decision,
8883
9660
  note: review?.note ?? null,
8884
- ...review && {
8885
- reviewerName: review.reviewerName,
8886
- reviewerEmail: null
9661
+ decidedBy: {
9662
+ type: "api-key",
9663
+ id: null
8887
9664
  },
8888
9665
  reviewedAt: now,
8889
- appliedToAsset: true
9666
+ applied: true
8890
9667
  }];
8891
9668
  const stored = await this.databaseStorage.updateAsset(decided);
8892
- if (decision === "purged") this.recordLifecycleEvent("asset.content-removed", stored);
9669
+ if (decision === "purged") this.recordLifecycleEvent("asset.content-removed", stored, { actor: review ? MOCK_API_KEY_ACTOR : MOCK_REVIEWER_ACTOR });
8893
9670
  this.pushEvent({
8894
9671
  type: `asset.${decision}`,
8895
9672
  severity: decision === "allowed" || decision === "limited" ? "low" : "high",
8896
9673
  title: `asset.${decision}`,
8897
9674
  assetId: stored.id,
8898
9675
  asset: toEventAsset(stored),
9676
+ actor: review ? MOCK_API_KEY_ACTOR : MOCK_REVIEWER_ACTOR,
8899
9677
  facts: [
8900
- {
8901
- key: "decided-by",
8902
- value: "reviewer"
8903
- },
8904
9678
  {
8905
9679
  key: "asset-type",
8906
9680
  value: stored.type
@@ -8911,11 +9685,8 @@ var MockCalmLensApi = class {
8911
9685
  url: `https://calmlens.com/go/asset/${stored.id}`
8912
9686
  },
8913
9687
  ...review ? [{
8914
- key: "reviewer-user-id",
8915
- value: null
8916
- }, {
8917
9688
  key: "reviewer-name",
8918
- value: review.reviewerName
9689
+ value: API_KEY_REVIEWER_NAME
8919
9690
  }] : [],
8920
9691
  {
8921
9692
  key: "note",
@@ -8943,6 +9714,7 @@ var MockCalmLensApi = class {
8943
9714
  async handle(input, init, endpoints, session) {
8944
9715
  if (init?.signal?.aborted) throw init.signal.reason;
8945
9716
  const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
9717
+ this.cdnBaseUrl = endpoints.cdnBaseUrl;
8946
9718
  const cdn = url.startsWith(`${endpoints.cdnBaseUrl}/`);
8947
9719
  const base = cdn ? endpoints.cdnBaseUrl : endpoints.baseUrl;
8948
9720
  if (!url.startsWith(`${base}/`)) throw new TypeError(`MockCalmLensServerClient does not serve ${url}`);
@@ -8955,6 +9727,7 @@ var MockCalmLensApi = class {
8955
9727
  method: (init?.method ?? "GET").toUpperCase(),
8956
9728
  url,
8957
9729
  segments: path.split("/").filter(Boolean).map(decodeSegment),
9730
+ rawSegments: path.split("/").filter(Boolean),
8958
9731
  query: new URLSearchParams(queryIndex === -1 ? "" : relative.slice(queryIndex + 1)),
8959
9732
  headers,
8960
9733
  bytes,
@@ -9091,25 +9864,39 @@ var MockCalmLensApi = class {
9091
9864
  case "GET assets": return [200, await this.listAssets(request.query)];
9092
9865
  case "GET assets/search": return [200, await this.searchAssets(request.query)];
9093
9866
  case "POST assets/batch": return [202, await this.batch(this.json(request))];
9867
+ case "POST signed-asset-urls": return [200, await this.signAssetUrl(this.json(request))];
9094
9868
  case "GET events": return [200, this.listEvents(request.query)];
9095
9869
  case "GET folders": return [200, await this.listFolders(request.query)];
9096
9870
  case "POST folders": return [201, await this.createFolder(this.json(request))];
9097
9871
  case "GET hash-lists": return [200, this.listHashLists(request.query)];
9098
9872
  case "POST hash-lists": return [201, this.createHashList(this.json(request))];
9099
9873
  case "PUT lenses": return [200, this.ensureLenses(this.json(request))];
9100
- case "GET policies": return [200, this.listPolicies()];
9101
- case "POST policies": return [201, this.createPolicy(this.json(request))];
9874
+ case "GET lenses": return [200, this.listLenses(request.query)];
9875
+ case "POST lenses": return [201, this.createLens(this.json(request))];
9876
+ case "GET policy": return [200, this.toPolicy(this.findPolicy(this.ensurePolicies()))];
9102
9877
  case "PUT policy": return [200, this.assignPolicy(this.json(request))];
9103
9878
  }
9104
- const [, , collection, policyId, policyAction, ...more] = segments;
9105
- if (collection === "policies" && policyId !== void 0 && more.length === 0) switch (`${method} ${policyAction ?? ""}`) {
9106
- case "GET ": return [200, this.toPolicy(this.findPolicy(policyId))];
9107
- case "PATCH ": return [200, this.updatePolicy(policyId, this.json(request))];
9108
- case "DELETE ": return [200, this.deletePolicy(policyId)];
9109
- case "POST preset": return [200, this.applyPolicyPreset(policyId, this.json(request))];
9110
- case "PUT automatic-updates": return [200, this.setPolicyAutomaticUpdates(policyId, this.json(request))];
9879
+ const [, , collection, itemId, itemAction, ...more] = segments;
9880
+ if (collection === "assets" && itemId !== void 0 && itemAction === "timeline" && more.length === 0 && method === "GET") return [200, await this.listTimeline(itemId, request.query)];
9881
+ }
9882
+ if (root === "policies" && rest.length === 0) {
9883
+ if (id === void 0) {
9884
+ if (method === "GET") return [200, this.listPolicies(request.query)];
9885
+ if (method === "POST") return [201, this.createPolicy(this.json(request))];
9886
+ } else switch (`${method} ${action ?? ""}`) {
9887
+ case "GET ": return [200, this.toPolicy(this.findPolicy(id))];
9888
+ case "PATCH ": return [200, this.updatePolicy(id, this.json(request))];
9889
+ case "DELETE ": return [200, this.deletePolicy(id)];
9890
+ case "POST reset": return [200, this.restorePolicy(id, "reset", this.json(request))];
9891
+ case "POST upgrade": return [200, this.restorePolicy(id, "upgrade", this.json(request))];
9892
+ case "PUT automatic-updates": return [200, this.setPolicyAutomaticUpdates(id, this.json(request))];
9111
9893
  }
9112
9894
  }
9895
+ if (root === "lenses" && id !== void 0 && action === void 0) switch (method) {
9896
+ case "GET": return [200, this.findLens(id)];
9897
+ case "PATCH": return [200, this.updateLens(id, this.json(request))];
9898
+ case "DELETE": return [200, this.deleteLens(id)];
9899
+ }
9113
9900
  if (root === "upload-presets" && id !== void 0 && action === "assets") return [200, await this.presetRoute(request, id, rest, session)];
9114
9901
  if (root === "assets" && id !== void 0 && rest.length === 0) switch (`${method} ${action ?? ""}`) {
9115
9902
  case "GET ": return [200, await this.findOwnAsset(id)];
@@ -9117,7 +9904,6 @@ var MockCalmLensApi = class {
9117
9904
  case "DELETE ": return [200, await this.deleteAsset(id)];
9118
9905
  case "GET children": return [200, await this.listChildren(id, request.query)];
9119
9906
  case "POST part": return [200, await this.uploadPart(id, request)];
9120
- case "POST signed-url": return [200, await this.createSignedUrl(id, this.json(request))];
9121
9907
  case "POST move": return [200, await this.moveAsset(id, this.json(request))];
9122
9908
  case "POST retry": return [200, await this.retryAsset(id)];
9123
9909
  case "POST explain": return [200, await this.explainAsset(id, this.json(request))];
@@ -9143,21 +9929,23 @@ var MockCalmLensApi = class {
9143
9929
  }
9144
9930
  throw fail(require_ModerationContextLimits.API_ERROR_CODES.ROUTE_NOT_FOUND, { message: `No route for ${method} /${segments.join("/")}` });
9145
9931
  }
9932
+ /** The project's policy, after creating the organisation's own General policy on first use. */
9146
9933
  ensurePolicies() {
9147
- if (this.projectPolicyId) return;
9934
+ if (this.projectPolicyId) return this.projectPolicyId;
9148
9935
  const now = this.now();
9149
9936
  const general = this.newPolicy({
9150
9937
  name: MOCK_PRESET_NAMES["general-community"],
9151
- settings: { categorySettings: {} },
9152
- automaticUpdates: true,
9938
+ settings: mockPresetSettings(),
9939
+ followsPreset: true,
9153
9940
  preset: {
9154
9941
  id: "general-community",
9155
9942
  version: 1,
9156
- projectId: this.projectId
9943
+ own: true
9157
9944
  },
9158
9945
  createdAt: now
9159
9946
  });
9160
9947
  this.projectPolicyId = general.id;
9948
+ return general.id;
9161
9949
  }
9162
9950
  newPolicy(values) {
9163
9951
  const policy = {
@@ -9166,7 +9954,7 @@ var MockCalmLensApi = class {
9166
9954
  description: values.description ?? "",
9167
9955
  settings: values.settings,
9168
9956
  revision: 1,
9169
- automaticUpdates: values.automaticUpdates ?? false,
9957
+ followsPreset: values.followsPreset ?? false,
9170
9958
  preset: values.preset ?? null,
9171
9959
  baseline: structuredClone(values.settings),
9172
9960
  createdAt: values.createdAt,
@@ -9176,12 +9964,14 @@ var MockCalmLensApi = class {
9176
9964
  return policy;
9177
9965
  }
9178
9966
  toPolicy(policy) {
9179
- const { baseline: _baseline, preset, ...rest } = policy;
9967
+ const { baseline: _baseline, preset, followsPreset, ...rest } = policy;
9180
9968
  return {
9181
9969
  ...structuredClone(rest),
9182
9970
  preset: preset && {
9183
- ...preset,
9184
- latestVersion: 1
9971
+ id: preset.id,
9972
+ version: preset.version,
9973
+ latestVersion: 1,
9974
+ mode: preset.own ? followsPreset ? "live" : "pinned" : "copy"
9185
9975
  },
9186
9976
  projectIds: policy.id === this.projectPolicyId ? [this.projectId] : []
9187
9977
  };
@@ -9192,26 +9982,32 @@ var MockCalmLensApi = class {
9192
9982
  if (!policy) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_NOT_FOUND);
9193
9983
  return policy;
9194
9984
  }
9195
- listPolicies() {
9985
+ /** A page of the organisation's policies, oldest first unless `sort` says otherwise. */
9986
+ listPolicies(query) {
9196
9987
  this.ensurePolicies();
9197
- return {
9198
- policies: [...this.policies.values()].map((policy) => this.toPolicy(policy)),
9199
- projectPolicyId: this.projectPolicyId
9200
- };
9988
+ return createPage([...this.policies.values()].map((policy) => this.toPolicy(policy)), this.pageQuery(query), {
9989
+ scope: `policies:${this.projectId}`,
9990
+ fail: this.pageFailure,
9991
+ defaultSort: [{
9992
+ field: "createdAt",
9993
+ direction: "asc"
9994
+ }]
9995
+ });
9201
9996
  }
9202
9997
  createPolicy(body) {
9203
9998
  this.ensurePolicies();
9204
9999
  const { name, description, settings, presetId } = body;
9205
10000
  const preset = typeof presetId === "string" ? presetId : void 0;
9206
10001
  if (settings === void 0 === (preset === void 0) || preset !== void 0 && !(preset in MOCK_PRESET_NAMES) || preset === void 0 && (typeof name !== "string" || !name.trim())) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_VALUE, { message: "Send settings with a name, or presetId" });
10002
+ if (!preset) checkPolicySettings(settings);
9207
10003
  const policy = this.newPolicy({
9208
10004
  name: typeof name === "string" && name.trim() ? name.trim() : MOCK_PRESET_NAMES[preset],
9209
10005
  ...typeof description === "string" ? { description } : {},
9210
- settings: preset ? { categorySettings: {} } : settings,
10006
+ settings: preset ? mockPresetSettings() : settings,
9211
10007
  ...preset ? { preset: {
9212
10008
  id: preset,
9213
10009
  version: 1,
9214
- projectId: null
10010
+ own: false
9215
10011
  } } : {},
9216
10012
  createdAt: this.now()
9217
10013
  });
@@ -9231,28 +10027,30 @@ var MockCalmLensApi = class {
9231
10027
  }
9232
10028
  updatePolicy(policyId, body) {
9233
10029
  const policy = this.findPolicy(policyId);
10030
+ if (body.settings !== void 0) checkPolicySettings(body.settings);
9234
10031
  return this.savePolicy(policy, body.revision, {
9235
10032
  ...typeof body.name === "string" ? { name: body.name.trim() } : {},
9236
10033
  ...typeof body.description === "string" ? { description: body.description } : {},
9237
10034
  ...body.settings !== void 0 ? { settings: body.settings } : {},
9238
- automaticUpdates: false
10035
+ followsPreset: false
9239
10036
  });
9240
10037
  }
9241
- applyPolicyPreset(policyId, body) {
10038
+ /** Resets a `pinned` or `copy` policy to its preset release, or upgrades it to the latest. */
10039
+ restorePolicy(policyId, operation, body) {
9242
10040
  const policy = this.findPolicy(policyId);
9243
- if (!policy.preset || policy.automaticUpdates) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_NO_PRESET);
10041
+ if (!policy.preset || policy.followsPreset) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_NO_PRESET);
9244
10042
  if (body.presetVersion !== policy.preset.version) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_PRESET_VERSION_CONFLICT);
9245
- if (body.operation === "update") throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_PRESET_UPDATE_UNAVAILABLE);
10043
+ if (operation === "upgrade") throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_PRESET_UPDATE_UNAVAILABLE);
9246
10044
  return this.savePolicy(policy, body.revision, { settings: structuredClone(policy.baseline) });
9247
10045
  }
9248
10046
  setPolicyAutomaticUpdates(policyId, body) {
9249
10047
  const policy = this.findPolicy(policyId);
9250
10048
  const enabled = body.enabled === true;
9251
- if (policy.preset?.projectId !== this.projectId || policy.automaticUpdates === enabled) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_AUTOMATIC_UPDATES_UNAVAILABLE);
10049
+ if (!policy.preset?.own || policy.followsPreset === enabled) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_AUTOMATIC_UPDATES_UNAVAILABLE);
9252
10050
  if (body.revision !== policy.revision) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_REVISION_CONFLICT);
9253
10051
  if (body.presetVersion !== 1) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_PRESET_VERSION_CONFLICT);
9254
10052
  return this.savePolicy(policy, body.revision, {
9255
- automaticUpdates: enabled,
10053
+ followsPreset: enabled,
9256
10054
  ...enabled ? {
9257
10055
  name: MOCK_PRESET_NAMES[policy.preset.id],
9258
10056
  description: "",
@@ -9317,26 +10115,10 @@ var MockCalmLensApi = class {
9317
10115
  }
9318
10116
  listHashListEntries(hashListId, query) {
9319
10117
  this.findHashList(hashListId);
9320
- const pageSize = this.integer(query, "pageSize", 50);
9321
- const entries = [...this.hashListEntries.values()].filter((entry) => entry.hashListId === hashListId).reverse();
9322
- const cursor = query.get("cursor");
9323
- const start = cursor ? Number(atob(cursor)) : 0;
9324
- if (!Number.isInteger(start) || start < 0) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR);
9325
- const items = entries.slice(start, start + pageSize);
9326
- const hasMore = start + pageSize < entries.length;
9327
- return {
9328
- items,
9329
- hasMore,
9330
- nextCursor: hasMore ? btoa(String(start + pageSize)) : null,
9331
- pageSize,
9332
- ordering: [{
9333
- field: "createdAt",
9334
- direction: "desc"
9335
- }, {
9336
- field: "id",
9337
- direction: "desc"
9338
- }]
9339
- };
10118
+ return createPage([...this.hashListEntries.values()].filter((entry) => entry.hashListId === hashListId), this.pageQuery(query), {
10119
+ scope: `hash-list-entries:${hashListId}`,
10120
+ fail: this.pageFailure
10121
+ });
9340
10122
  }
9341
10123
  async addHashListEntry(hashListId, body) {
9342
10124
  const list = this.findHashList(hashListId);
@@ -9345,10 +10127,10 @@ var MockCalmLensApi = class {
9345
10127
  const assetId = typeof body.assetId === "string" ? body.assetId : void 0;
9346
10128
  if (hash === void 0 === (assetId === void 0)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Send either hash or assetId" });
9347
10129
  if (assetId) {
9348
- const image = (await this.findOwnAsset(assetId)).content.image;
9349
- if (!image?.perceptualHash) throw fail(require_ModerationContextLimits.API_ERROR_CODES.HASH_LIST_ASSET_NOT_HASHED);
9350
- hash = image.perceptualHash;
9351
- quality = image.perceptualHashQuality ?? null;
10130
+ const { content } = await this.findOwnAsset(assetId);
10131
+ if (!content.perceptualHash) throw fail(require_ModerationContextLimits.API_ERROR_CODES.HASH_LIST_ASSET_NOT_HASHED);
10132
+ hash = content.perceptualHash;
10133
+ quality = content.perceptualHashQuality ?? null;
9352
10134
  }
9353
10135
  if (!/^[0-9a-f]{64}$/.test(hash)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Use a PDQ hash of 64 hexadecimal characters" });
9354
10136
  const existing = [...this.hashListEntries.values()].find((entry) => entry.hashListId === list.id && entry.hash === hash);
@@ -9360,7 +10142,7 @@ var MockCalmLensApi = class {
9360
10142
  hash,
9361
10143
  quality,
9362
10144
  label: typeof body.label === "string" ? body.label : null,
9363
- sourceAssetId: assetId ?? null,
10145
+ assetId: assetId ?? null,
9364
10146
  createdAt: this.now()
9365
10147
  };
9366
10148
  this.hashListEntries.set(entry.id, entry);
@@ -9373,7 +10155,7 @@ var MockCalmLensApi = class {
9373
10155
  const body = JSON.parse(new TextDecoder().decode(request.bytes));
9374
10156
  return body && typeof body === "object" ? body : {};
9375
10157
  } catch {
9376
- throw new ApiFailure(400, "validation/invalid-json", "Invalid JSON body");
10158
+ throw invalidField("validation/invalid-type", "");
9377
10159
  }
9378
10160
  }
9379
10161
  /** A whole number from the query, or `fallback` when absent; other values fail like zod. */
@@ -9385,26 +10167,22 @@ var MockCalmLensApi = class {
9385
10167
  if (!Number.isInteger(value)) throw invalidField("validation/invalid-type", name);
9386
10168
  return value;
9387
10169
  }
9388
- /** `ordering[i][field]` and `ordering[i][direction]` pairs, as qs parses them. */
9389
- ordering(query) {
9390
- const ordering = [];
9391
- for (const [key, value] of query) {
9392
- const match = /^ordering\[(\d+)\]\[(field|direction)\]$/.exec(key);
9393
- if (!match) continue;
9394
- const index = Number(match[1]);
9395
- ordering[index] = {
9396
- ...ordering[index],
9397
- [match[2]]: value
9398
- };
9399
- }
9400
- return ordering.filter(Boolean);
10170
+ /** The list's `sort`, from `fields`, as the API's `sortQueryField` reads it. */
10171
+ sort(query, fields, max) {
10172
+ return parseSort(query.get("sort"), fields, max, () => invalidField("validation/invalid-value", "sort"));
9401
10173
  }
10174
+ /**
10175
+ * A cursor list's query, checked like CURSOR_PAGE_QUERY_SCHEMA before anything else: `pageSize`
10176
+ * from 1 to 100, and a `sort` of at most two fields from `createdAt` and `id`.
10177
+ */
9402
10178
  pageQuery(query) {
9403
- const ordering = this.ordering(query);
10179
+ const pageSize = this.integer(query, "pageSize", 50);
10180
+ if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
10181
+ if (pageSize > 100) throw invalidField("validation/too-big", "pageSize");
9404
10182
  return {
9405
- pageSize: this.integer(query, "pageSize", 50),
10183
+ pageSize,
9406
10184
  cursor: query.get("cursor") ?? void 0,
9407
- ordering: ordering.length ? ordering : void 0
10185
+ sort: this.sort(query, ["createdAt", "id"], 2)
9408
10186
  };
9409
10187
  }
9410
10188
  async findOwnAsset(assetId) {
@@ -9414,16 +10192,16 @@ var MockCalmLensApi = class {
9414
10192
  }
9415
10193
  async listAssets(query) {
9416
10194
  let assets = await this.databaseStorage.listAssets(this.projectId);
9417
- const folderId = query.get("folderId");
9418
- if (folderId !== null) assets = assets.filter((asset) => (asset.folderId ?? null) === folderId);
10195
+ const page = this.pageQuery(query);
9419
10196
  const filter = query.get("filter") ?? void 0;
9420
- assets = filterAssets(assets, filter);
9421
- return createPage(assets, this.pageQuery(query), {
9422
- scope: JSON.stringify([
9423
- this.projectId,
9424
- filter ?? null,
9425
- folderId
9426
- ]),
10197
+ try {
10198
+ assets = filterAssets(assets, filter);
10199
+ } catch (error) {
10200
+ if (error instanceof MockInvalidFilter) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_FILTER);
10201
+ throw error;
10202
+ }
10203
+ return createPage(assets, page, {
10204
+ scope: JSON.stringify([this.projectId, filter ?? null]),
9427
10205
  fail: this.pageFailure
9428
10206
  });
9429
10207
  }
@@ -9436,12 +10214,12 @@ var MockCalmLensApi = class {
9436
10214
  const query = (params.get("query") ?? "").trim();
9437
10215
  if (!query) throw invalidField("validation/too-small", "query");
9438
10216
  if (query.length > MAX_SEARCH_QUERY_LENGTH) throw invalidField("validation/too-big", "query");
9439
- const limit = this.integer(params, "limit", 10);
9440
- if (limit < 1) throw invalidField("validation/too-small", "limit");
9441
- if (limit > MAX_SEARCH_LIMIT) throw invalidField("validation/too-big", "limit");
10217
+ const pageSize = this.integer(params, "pageSize", 10);
10218
+ if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
10219
+ if (pageSize > MAX_SEARCH_PAGE_SIZE) throw invalidField("validation/too-big", "pageSize");
9442
10220
  return {
9443
10221
  query,
9444
- items: searchAssets(await this.databaseStorage.listAssets(this.projectId), query, limit),
10222
+ items: searchAssets(await this.databaseStorage.listAssets(this.projectId), query, pageSize),
9445
10223
  semanticStatus: "disabled"
9446
10224
  };
9447
10225
  }
@@ -9453,7 +10231,27 @@ var MockCalmLensApi = class {
9453
10231
  fail: this.pageFailure
9454
10232
  });
9455
10233
  }
10234
+ /**
10235
+ * An asset's findings timeline, as the API lists it (publicGetAssetTimeline.ts): refused while a
10236
+ * safety hold is on. The mock analyses no audio or video, so it keeps no segments: every
10237
+ * timeline is empty, and no cursor continues one.
10238
+ */
10239
+ async listTimeline(assetId, query) {
10240
+ const asset = await this.findOwnAsset(assetId);
10241
+ const pageSize = this.integer(query, "pageSize", 50);
10242
+ if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
10243
+ if (pageSize > 100) throw invalidField("validation/too-big", "pageSize");
10244
+ if (asset.content.safetyHold) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_HELD, { details: { hold: "safety" } });
10245
+ if (query.get("cursor") !== null) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR);
10246
+ return {
10247
+ items: [],
10248
+ nextCursor: null,
10249
+ hasMore: false
10250
+ };
10251
+ }
9456
10252
  async updateAsset(assetId, body) {
10253
+ checkMetadata(body.metadata);
10254
+ if (body.name === null) throw invalidField("validation/invalid-type", "name");
9457
10255
  const asset = await this.findOwnAsset(assetId);
9458
10256
  if (body.externalId) {
9459
10257
  if ((await this.databaseStorage.listAssets(this.projectId)).some((other) => other.id !== asset.id && other.externalId === body.externalId)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.DUPLICATE_EXTERNAL_ID);
@@ -9480,14 +10278,46 @@ var MockCalmLensApi = class {
9480
10278
  updatedAt: this.now()
9481
10279
  });
9482
10280
  }
9483
- async createSignedUrl(assetId, body) {
9484
- const asset = await this.findOwnAsset(assetId);
9485
- const expiresInSeconds = body.expiresInSeconds ?? 900;
9486
- const resource = body.resource ?? "rendered";
9487
- const selector = (body.lens ? `&lens=${encodeURIComponent(String(body.lens))}` : "") + (body.transform ? `&transform=${encodeURIComponent(String(body.transform))}` : "");
10281
+ /**
10282
+ * Signs an asset URL like the API (`POST /projects/:projectId/signed-asset-urls`): a grant to one
10283
+ * asset, by ID or external ID, until it expires, serving the original only when asked. The mock's
10284
+ * grant is readable (its asset, original access and expiry), unlike the CDN's, and only the
10285
+ * mock's CDN accepts it.
10286
+ */
10287
+ async signAssetUrl(body) {
10288
+ for (const key of [
10289
+ "assetId",
10290
+ "externalId",
10291
+ "expiresIn",
10292
+ "original"
10293
+ ]) if (body[key] === null) throw invalidField("validation/invalid-type", key);
10294
+ const { assetId, externalId } = body;
10295
+ if (assetId === void 0 === (externalId === void 0)) throw new ApiFailure(400, require_ModerationContextLimits.API_ERROR_CODES.INVALID_REQUEST, "Send either assetId or externalId", { issues: [{
10296
+ path: "",
10297
+ message: "Send either assetId or externalId",
10298
+ code: "custom"
10299
+ }] });
10300
+ const expiresIn = body.expiresIn ?? 900;
10301
+ if (typeof expiresIn !== "number" || !Number.isInteger(expiresIn)) throw invalidField("validation/invalid-type", "expiresIn");
10302
+ if (expiresIn < 1) throw invalidField("validation/too-small", "expiresIn");
10303
+ if (expiresIn > 86400) throw invalidField("validation/too-big", "expiresIn");
10304
+ const original = body.original ?? false;
10305
+ if (typeof original !== "boolean") throw invalidField("validation/invalid-type", "original");
10306
+ let asset;
10307
+ if (externalId !== void 0) {
10308
+ asset = (await this.databaseStorage.listAssets(this.projectId)).find((candidate) => candidate.externalId === externalId);
10309
+ if (!asset) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_NOT_FOUND);
10310
+ } else asset = await this.findOwnAsset(String(assetId));
10311
+ if (asset.content.safetyHold) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_HELD);
10312
+ const expiresAt = this.now() + expiresIn * 1e3;
10313
+ const grant = encodeMockGrant({
10314
+ assetId: asset.id,
10315
+ original,
10316
+ expiresAt
10317
+ });
9488
10318
  return {
9489
- url: `${this.options.signedUrlBaseUrl}/assets/${asset.id}/${resource}?expiresInSeconds=${expiresInSeconds}${selector}`,
9490
- expiresAt: this.now() + expiresInSeconds * 1e3
10319
+ url: `${this.cdnBaseUrl}/assets/${encodeURIComponent(this.projectId)}/${grant}`,
10320
+ expiresAt
9491
10321
  };
9492
10322
  }
9493
10323
  async retryAsset(assetId) {
@@ -9517,8 +10347,27 @@ var MockCalmLensApi = class {
9517
10347
  }
9518
10348
  if (asset.classification.moderation.manualReviews.length) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_REVIEWED);
9519
10349
  if (asset.content.status === "removed") throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_CONTENT_UNAVAILABLE);
9520
- const rerun = await this.databaseStorage.updateAsset(await this.applyOutcome(asset, "pending"));
9521
- return this.moderateStored(rerun, "rerun");
10350
+ this.pushEvent({
10351
+ type: "asset.rerun-requested",
10352
+ actor: MOCK_API_KEY_ACTOR,
10353
+ severity: "low",
10354
+ assetId: asset.id,
10355
+ asset: toEventAsset(asset),
10356
+ facts: [
10357
+ assetNameFact(asset),
10358
+ {
10359
+ key: "asset-type",
10360
+ value: asset.type
10361
+ },
10362
+ {
10363
+ key: "moderation-status",
10364
+ value: asset.classification.moderation.status
10365
+ }
10366
+ ]
10367
+ });
10368
+ const response = structuredClone(asset);
10369
+ await this.settleRerun(asset, await this.decisionFor(asset, "rerun", true));
10370
+ return response;
9522
10371
  }
9523
10372
  /**
9524
10373
  * Checks every asset like the API (an ID that is not an asset ID is
@@ -9526,7 +10375,8 @@ var MockCalmLensApi = class {
9526
10375
  * one `asset/not-found`, and either refuses the whole batch), then applies the operation at
9527
10376
  * once instead of in the background: `delete` deletes each asset with its stored child
9528
10377
  * assets and records `asset.deleted` with the asset as it was; `remove-content` removes
9529
- * the content like `deleteContent`. Mock assets carry no safety holds, so none is skipped.
10378
+ * the content like `removeContent`. Each event carries the batch's `batch-id` fact. Mock assets
10379
+ * carry no safety holds, so none is skipped.
9530
10380
  */
9531
10381
  async batch(body) {
9532
10382
  const assetIds = Array.isArray(body.assetIds) ? body.assetIds : [];
@@ -9539,26 +10389,31 @@ var MockCalmLensApi = class {
9539
10389
  });
9540
10390
  const assets = [];
9541
10391
  for (const assetId of new Set(assetIds)) assets.push(await this.findOwnAsset(assetId));
10392
+ const batchId = this.createId("batch");
9542
10393
  for (const asset of assets) if (operation === "delete") {
9543
10394
  await this.deleteAssetTree(asset);
9544
- this.recordLifecycleEvent("asset.deleted", asset);
9545
- } else await this.removeContent(asset);
9546
- return { queued: true };
10395
+ this.recordLifecycleEvent("asset.deleted", asset, { batchId });
10396
+ } else await this.removeContent(asset, batchId);
10397
+ return {
10398
+ batchId,
10399
+ status: "queued",
10400
+ assetCount: assets.length
10401
+ };
9547
10402
  }
9548
10403
  /**
9549
10404
  * Removes an asset's content like the API: the record and report stay; stored content,
9550
10405
  * extracted text and the placeholder go. Content already removed keeps its reason, and an
9551
10406
  * `asset.content-removed` event is recorded either way.
9552
10407
  */
9553
- async removeContent(asset) {
10408
+ async removeContent(asset, batchId) {
9554
10409
  await this.imageStorage.deleteContent(asset.id);
9555
10410
  let removed = asset;
9556
10411
  if (asset.content.status === "removed") {
9557
- if (asset.content.image?.thumbhash) removed = await this.databaseStorage.updateAsset({
10412
+ if (asset.content.rendered || asset.content.preview) removed = await this.databaseStorage.updateAsset({
9558
10413
  ...asset,
9559
10414
  content: {
9560
10415
  ...asset.content,
9561
- image: withoutPlaceholder(asset.content.image)
10416
+ ...NO_RENDERING
9562
10417
  }
9563
10418
  });
9564
10419
  } else {
@@ -9572,13 +10427,13 @@ var MockCalmLensApi = class {
9572
10427
  removalReason: "requested",
9573
10428
  updatedAt: now,
9574
10429
  extractedText: null,
9575
- fileMetadata: null,
9576
- image: withoutPlaceholder(asset.content.image)
10430
+ metadata: null,
10431
+ ...NO_RENDERING
9577
10432
  },
9578
10433
  updatedAt: now
9579
10434
  });
9580
10435
  }
9581
- this.recordLifecycleEvent("asset.content-removed", removed);
10436
+ this.recordLifecycleEvent("asset.content-removed", removed, { batchId });
9582
10437
  return removed;
9583
10438
  }
9584
10439
  /** Deletes an asset, its stored child assets and their content. */
@@ -9600,7 +10455,11 @@ var MockCalmLensApi = class {
9600
10455
  /** The upload fields of `POST .../assets`: raw uploads carry them in the query. */
9601
10456
  uploadFields(request) {
9602
10457
  const upload = request.headers.get("x-calmlens-upload");
9603
- if (upload !== "content" && upload !== "part") return this.json(request);
10458
+ if (upload !== "content" && upload !== "part") {
10459
+ const body = this.json(request);
10460
+ checkMetadata(body.metadata);
10461
+ return body;
10462
+ }
9604
10463
  const { query } = request;
9605
10464
  const text = (name) => query.get(name) ?? void 0;
9606
10465
  const parsed = (name) => {
@@ -9609,16 +10468,18 @@ var MockCalmLensApi = class {
9609
10468
  try {
9610
10469
  return JSON.parse(raw);
9611
10470
  } catch {
9612
- throw invalidField("validation/invalid-json", name);
10471
+ throw invalidField("validation/invalid-value", name);
9613
10472
  }
9614
10473
  };
9615
10474
  const total = query.get("totalSizeInBytes");
10475
+ checkMetadata(parsed("metadata"));
9616
10476
  return {
9617
10477
  name: query.get("name") ?? "",
9618
10478
  description: text("description"),
9619
10479
  processingOptions: parsed("processingOptions"),
9620
10480
  visibility: text("visibility"),
9621
10481
  metadata: parsed("metadata"),
10482
+ tags: parsed("tags"),
9622
10483
  authorId: text("authorId"),
9623
10484
  context: parsed("context"),
9624
10485
  externalId: text("externalId"),
@@ -9635,22 +10496,25 @@ var MockCalmLensApi = class {
9635
10496
  };
9636
10497
  }
9637
10498
  async createAsset(request) {
9638
- return this.storeAsset(this.uploadFields(request), request.query.get("queue") === "true");
10499
+ return this.storeAsset(this.uploadFields(request), request.query.get("wait") === "false");
9639
10500
  }
9640
10501
  async storeAsset(fields, queue) {
9641
10502
  if (!fields.name) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Asset name is required" });
9642
10503
  const { contentType, part } = fields;
9643
10504
  const bytes = fields.bytes ?? /* @__PURE__ */ new Uint8Array(0);
9644
- if (contentType !== void 0 && require_ModerationContextLimits.isRejectedUploadMimeType(contentType)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_MIME_TYPE, {
10505
+ if (contentType !== void 0 && !require_ModerationContextLimits.isAcceptedUploadMimeType(contentType)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, {
9645
10506
  message: require_ModerationContextLimits.getRejectedUploadMimeTypeError(contentType),
9646
- details: { mimeType: contentType }
10507
+ details: {
10508
+ mimeType: contentType,
10509
+ source: "calmlens"
10510
+ }
9647
10511
  });
9648
10512
  const type = inferAssetType(fields.url === void 0 ? contentType ?? "" : void 0);
9649
10513
  if (part) {
9650
10514
  if (part.partNumber > 1) throw fail(require_ModerationContextLimits.API_ERROR_CODES.USE_UPLOAD_PART);
9651
10515
  const partSize = bytes.byteLength;
9652
10516
  const sizeError = (part.totalSizeInBytes === void 0 ? void 0 : this.multipartImageSizeError(type, part.totalSizeInBytes)) ?? (part.isFinal ? this.multipartTotalSizeError(part.totalSizeInBytes, partSize, true) ?? this.multipartImageSizeError(type, partSize) : void 0);
9653
- if (sizeError) throw fail(sizeError);
10517
+ if (sizeError) throw this.sizeFailure(sizeError);
9654
10518
  const validation = require_CalmLensOptionKeys.validateAssetPayload({ uint8Array: bytes }, {
9655
10519
  multipart: true,
9656
10520
  isFinal: part.isFinal
@@ -9670,6 +10534,7 @@ var MockCalmLensApi = class {
9670
10534
  const isOpenUpload = part !== void 0 && !part.isFinal;
9671
10535
  const processingOptions = fields.processingOptions ?? { keepContentAfterProcessing: false };
9672
10536
  const keepContent = processingOptions.keepContentAfterProcessing === true;
10537
+ this.processingOptions.set(id, processingOptions);
9673
10538
  const hasContent = fields.url === void 0;
9674
10539
  const contextItems = require_ModerationContextLimits.selectModerationContextItems(fields.context?.items ?? []);
9675
10540
  const asset = {
@@ -9685,11 +10550,10 @@ var MockCalmLensApi = class {
9685
10550
  externalId: fields.externalId ?? null,
9686
10551
  externalUrl: fields.url ?? fields.externalUrl ?? null,
9687
10552
  type,
9688
- metadata: fields.metadata ?? null,
10553
+ metadata: fields.metadata ?? [],
9689
10554
  authorId: fields.authorId ?? null,
9690
10555
  context: contextItems.length ? { items: contextItems } : null,
9691
- tags: null,
9692
- processingOptions,
10556
+ tags: fields.tags ?? [],
9693
10557
  visibility: fields.visibility ?? "private",
9694
10558
  content: {
9695
10559
  status: keepContent ? "stored" : "temporary",
@@ -9700,9 +10564,15 @@ var MockCalmLensApi = class {
9700
10564
  extension: null,
9701
10565
  sizeInBytes: hasContent ? bytes.byteLength : null,
9702
10566
  checksums: null,
9703
- image: null,
10567
+ width: null,
10568
+ height: null,
10569
+ durationSeconds: null,
10570
+ pageCount: null,
10571
+ perceptualHash: null,
10572
+ perceptualHashQuality: null,
10573
+ metadata: null,
9704
10574
  extractedText: null,
9705
- fileMetadata: null
10575
+ ...NO_RENDERING
9706
10576
  },
9707
10577
  upload: {
9708
10578
  status: isOpenUpload ? "uploading" : "completed",
@@ -9710,16 +10580,27 @@ var MockCalmLensApi = class {
9710
10580
  partsReceived: isOpenUpload ? part.partNumber : null
9711
10581
  },
9712
10582
  classification: {
9713
- status: isOpenUpload ? "pending" : "processing",
10583
+ status: isOpenUpload ? "queued" : "processing",
9714
10584
  failureReason: null,
9715
10585
  updatedAt: now,
9716
10586
  completedAt: null,
10587
+ progress: null,
10588
+ testInput: false,
9717
10589
  moderation: {
9718
10590
  status: "pending",
9719
10591
  manualReviews: [],
10592
+ automatedStatus: null,
10593
+ source: null,
10594
+ rule: null,
10595
+ explanationComplete: null,
10596
+ categories: null,
9720
10597
  flaggedCategories: [],
9721
- regions: []
9722
- }
10598
+ regions: [],
10599
+ raw: null,
10600
+ timeline: null
10601
+ },
10602
+ ocr: null,
10603
+ linkDetection: null
9723
10604
  }
9724
10605
  };
9725
10606
  if (part) {
@@ -9738,6 +10619,10 @@ var MockCalmLensApi = class {
9738
10619
  type: contentType ?? ""
9739
10620
  });
9740
10621
  if (isOpenUpload) return this.databaseStorage.createAsset(asset);
10622
+ if (hasContent) asset.content = {
10623
+ ...asset.content,
10624
+ ...mockRendering(asset, false)
10625
+ };
9741
10626
  const decision = await this.decisionFor(asset, "upload", queue, hasContent ? bytes : null);
9742
10627
  const stored = await this.databaseStorage.createAsset(decision.status === "pending" ? asset : await this.decided(asset, decision));
9743
10628
  this.recordUploaded(asset);
@@ -9762,7 +10647,7 @@ var MockCalmLensApi = class {
9762
10647
  const received = (asset.content.sizeInBytes ?? 0) + bytes.byteLength;
9763
10648
  const upload = this.openUploads.get(assetId);
9764
10649
  const sizeError = this.multipartImageSizeError(asset.type, received) ?? this.multipartTotalSizeError(upload?.totalSizeInBytes, received, isFinal);
9765
- if (sizeError) throw fail(sizeError);
10650
+ if (sizeError) throw this.sizeFailure(sizeError);
9766
10651
  const validation = require_CalmLensOptionKeys.validateAssetPayload({ uint8Array: bytes }, {
9767
10652
  multipart: true,
9768
10653
  isFinal
@@ -9773,8 +10658,8 @@ var MockCalmLensApi = class {
9773
10658
  partNumber,
9774
10659
  isFinal
9775
10660
  });
9776
- const queueOverride = query.get("queue");
9777
- const queue = queueOverride === null ? upload?.queue ?? false : queueOverride === "true";
10661
+ const waitOverride = query.get("wait");
10662
+ const queue = waitOverride === null ? upload?.queue ?? false : waitOverride === "false";
9778
10663
  if (isFinal) this.openUploads.delete(assetId);
9779
10664
  const now = this.now();
9780
10665
  const next = {
@@ -9801,7 +10686,14 @@ var MockCalmLensApi = class {
9801
10686
  /** Like the API: image uploads in parts total at most 20 MiB, at any size below that. */
9802
10687
  multipartImageSizeError(type, sizeInBytes) {
9803
10688
  if (type !== "image") return void 0;
9804
- if (sizeInBytes > require_ModerationContextLimits.MAX_IMAGE_UPLOAD_BYTES) return require_ModerationContextLimits.API_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE;
10689
+ if (sizeInBytes > require_ModerationContextLimits.MAX_IMAGE_UPLOAD_BYTES) return require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_TOO_LARGE;
10690
+ }
10691
+ /** The failure for a size error code, with the limit `upload/too-large` carries. */
10692
+ sizeFailure(code) {
10693
+ return fail(code, code === require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_TOO_LARGE ? { details: {
10694
+ limitBytes: require_ModerationContextLimits.MAX_IMAGE_UPLOAD_BYTES,
10695
+ source: "plan"
10696
+ } } : {});
9805
10697
  }
9806
10698
  /** Like the API: the parts may not overshoot a declared total, and must reach it at the end. */
9807
10699
  multipartTotalSizeError(totalSizeInBytes, receivedSizeInBytes, isFinal) {
@@ -9830,9 +10722,37 @@ var MockCalmLensApi = class {
9830
10722
  queued
9831
10723
  }));
9832
10724
  }
9833
- /** `asset` decided as `decision` says, with its report. */
9834
- decided(asset, decision) {
9835
- return this.applyOutcome(asset, decision.status, "policy", decision.report());
10725
+ /**
10726
+ * `asset` decided as `decision` says, with its report. Like the API for an image with nobody in
10727
+ * it, a decided image reports the person and face detection its upload turned on.
10728
+ */
10729
+ async decided(asset, decision) {
10730
+ const next = await this.applyOutcome(asset, decision.status, "policy", decision.report());
10731
+ const features = this.processingOptions.get(asset.id)?.features;
10732
+ if (next.classification.status !== "completed" || asset.type !== "image") return next;
10733
+ return {
10734
+ ...next,
10735
+ classification: {
10736
+ ...next.classification,
10737
+ ...features?.ocr?.enabled === true && { ocr: {
10738
+ status: "evaluated",
10739
+ textRegions: []
10740
+ } },
10741
+ ...features?.linkDetection?.enabled !== false && { linkDetection: {
10742
+ status: "evaluated",
10743
+ qrCodes: [],
10744
+ links: []
10745
+ } },
10746
+ ...features?.personDetection?.enabled === true && { personDetection: {
10747
+ status: "evaluated",
10748
+ people: []
10749
+ } },
10750
+ ...features?.faceDetection?.enabled === true && { faceDetection: {
10751
+ status: "evaluated",
10752
+ faces: []
10753
+ } }
10754
+ }
10755
+ };
9836
10756
  }
9837
10757
  /**
9838
10758
  * Stores a processing asset's `decision` and records its events; a `pending` decision leaves it
@@ -9844,6 +10764,20 @@ var MockCalmLensApi = class {
9844
10764
  this.recordProcessingEvents(stored, decision);
9845
10765
  return stored;
9846
10766
  }
10767
+ /**
10768
+ * Applies a re-run's `decision` to a decided asset like the pipeline: a `pending` decision stays
10769
+ * queued for `completeProcessing`, a `failed` one keeps the asset's decision, and any other
10770
+ * replaces it with the pipeline's events.
10771
+ */
10772
+ async settleRerun(asset, decision) {
10773
+ this.pendingReruns.delete(asset.id);
10774
+ if (decision.status === "pending") {
10775
+ this.pendingReruns.add(asset.id);
10776
+ return asset;
10777
+ }
10778
+ if (decision.status === "failed") return asset;
10779
+ return this.settle(asset, decision);
10780
+ }
9847
10781
  /** Asks `moderate` (unless `decision` is given) and settles a processing asset. */
9848
10782
  async moderateStored(asset, trigger, decision) {
9849
10783
  return this.settle(asset, decision ?? await this.decisionFor(asset, trigger, true));
@@ -9877,7 +10811,8 @@ var MockCalmLensApi = class {
9877
10811
  if (decision.status === "pending") return;
9878
10812
  const event = {
9879
10813
  assetId: asset.id,
9880
- asset: toEventAsset(asset)
10814
+ asset: toEventAsset(asset),
10815
+ actor: AUTOMATED_ACTOR
9881
10816
  };
9882
10817
  if (decision.status === "failed") {
9883
10818
  this.pushEvent({
@@ -9928,10 +10863,6 @@ var MockCalmLensApi = class {
9928
10863
  type: `asset.${decision.status}`,
9929
10864
  severity: decision.status === "allowed" || decision.status === "limited" ? "low" : "high",
9930
10865
  facts: [
9931
- {
9932
- key: "decided-by",
9933
- value: "automated"
9934
- },
9935
10866
  {
9936
10867
  key: "flagged-categories",
9937
10868
  value: flaggedCategories
@@ -9947,8 +10878,8 @@ var MockCalmLensApi = class {
9947
10878
  /**
9948
10879
  * Moves an asset to `outcome` like the pipeline would: a decision finishes processing, `purged`
9949
10880
  * deletes the content (with `purgeReason`, `policy` for the pipeline), and finished processing
9950
- * removes content kept only temporarily (`keepContentAfterProcessing` off). A classified image
9951
- * gets a ThumbHash for its placeholder, which goes with purged content.
10881
+ * removes content kept only temporarily (`keepContentAfterProcessing` off). A decided asset gets
10882
+ * its rendered file and preview (with a ThumbHash for its placeholder), which go with its content.
9952
10883
  */
9953
10884
  async applyOutcome(asset, outcome, purgeReason = "policy", report) {
9954
10885
  const now = this.now();
@@ -9957,15 +10888,7 @@ var MockCalmLensApi = class {
9957
10888
  const purge = outcome === "purged" && asset.content.status !== "removed";
9958
10889
  const removeContent = purge || classificationStatus === "completed" && asset.content.status === "temporary";
9959
10890
  if (removeContent) await this.imageStorage.deleteContent(asset.id);
9960
- const image = decided && asset.type === "image" && asset.content.status !== "removed" && !purge ? {
9961
- width: null,
9962
- height: null,
9963
- perceptualHash: null,
9964
- perceptualHashQuality: null,
9965
- ...asset.content.image,
9966
- thumbhash: MOCK_THUMBHASH,
9967
- averageColor: asset.content.image?.averageColor ?? "#7f7f7f"
9968
- } : outcome === "purged" ? withoutPlaceholder(asset.content.image) : asset.content.image;
10891
+ const rendering = asset.content.status !== "removed" && !purge && !asset.content.safetyHold ? mockRendering(asset, decided) : NO_RENDERING;
9969
10892
  return {
9970
10893
  ...asset,
9971
10894
  updatedAt: now,
@@ -9976,11 +10899,11 @@ var MockCalmLensApi = class {
9976
10899
  removalReason: purge ? purgeReason : "retention",
9977
10900
  updatedAt: now,
9978
10901
  extractedText: null,
9979
- fileMetadata: null,
9980
- image: withoutPlaceholder(image)
10902
+ metadata: null,
10903
+ ...NO_RENDERING
9981
10904
  } : {
9982
10905
  ...asset.content,
9983
- image
10906
+ ...rendering
9984
10907
  },
9985
10908
  upload: {
9986
10909
  ...asset.upload,
@@ -10002,20 +10925,29 @@ var MockCalmLensApi = class {
10002
10925
  };
10003
10926
  }
10004
10927
  /** Adds an `asset.deleted`, `asset.content-removed` or `asset.retried` event, like the API. */
10005
- recordLifecycleEvent(type, asset) {
10928
+ recordLifecycleEvent(type, asset, options = {}) {
10929
+ const { batchId, actor = MOCK_API_KEY_ACTOR } = options;
10006
10930
  this.pushEvent({
10007
10931
  type,
10932
+ actor,
10008
10933
  severity: "low",
10009
10934
  assetId: asset.id,
10010
10935
  asset: toEventAsset(asset),
10011
- facts: [{
10012
- key: "asset-name",
10013
- value: asset.name,
10014
- ...type === "asset.deleted" ? {} : { url: `https://calmlens.com/go/asset/${asset.id}` }
10015
- }, {
10016
- key: "asset-type",
10017
- value: asset.type
10018
- }]
10936
+ facts: [
10937
+ {
10938
+ key: "asset-name",
10939
+ value: asset.name,
10940
+ ...type === "asset.deleted" ? {} : { url: `https://calmlens.com/go/asset/${asset.id}` }
10941
+ },
10942
+ {
10943
+ key: "asset-type",
10944
+ value: asset.type
10945
+ },
10946
+ ...batchId ? [{
10947
+ key: "batch-id",
10948
+ value: batchId
10949
+ }] : []
10950
+ ]
10019
10951
  });
10020
10952
  }
10021
10953
  /**
@@ -10030,7 +10962,15 @@ var MockCalmLensApi = class {
10030
10962
  name: asset.name,
10031
10963
  uploadPresetId,
10032
10964
  createdAt: asset.createdAt,
10033
- ...preset.showDecisions !== false && { status: asset.classification.moderation.status }
10965
+ upload: {
10966
+ status: asset.upload.status,
10967
+ partsReceived: asset.upload.partsReceived
10968
+ },
10969
+ classification: {
10970
+ status: asset.classification.status,
10971
+ failureReason: asset.classification.failureReason,
10972
+ ...preset.showDecisions !== false && { moderation: { status: asset.classification.moderation.status } }
10973
+ }
10034
10974
  });
10035
10975
  const [assetId, action] = rest;
10036
10976
  if (assetId !== void 0) {
@@ -10044,19 +10984,32 @@ var MockCalmLensApi = class {
10044
10984
  const fields = this.uploadFields(request);
10045
10985
  const token = request.headers.get("authorization");
10046
10986
  if (preset.requireToken && !token) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_TOKEN_REQUIRED);
10987
+ const tokenExternalId = token ? require_CalmLensServerClient.decodeUploadToken(token.replace(/^Bearer /, ""))?.claims.x : void 0;
10988
+ if (fields.externalId && fields.externalId !== tokenExternalId) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field: "externalId" } });
10989
+ for (const field of [
10990
+ "metadata",
10991
+ "tags",
10992
+ "authorId",
10993
+ "context",
10994
+ "processingOptions"
10995
+ ]) if (fields[field] !== void 0 && fields[field] !== null) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field } });
10047
10996
  if (preset.allowedContentTypes && !require_UploadController.isFileAccepted({
10048
10997
  name: fields.name,
10049
10998
  type: fields.contentType ?? ""
10050
- }, preset.allowedContentTypes.join(","))) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_CONTENT_TYPE_NOT_ALLOWED);
10999
+ }, preset.allowedContentTypes.join(","))) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, { details: { source: "preset" } });
10051
11000
  const size = fields.part?.totalSizeInBytes ?? fields.bytes?.byteLength;
10052
- if (preset.maxFileSizeInBytes !== void 0 && size !== void 0 && size > preset.maxFileSizeInBytes) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_TOO_LARGE);
11001
+ if (preset.maxFileSizeInBytes !== void 0 && size !== void 0 && size > preset.maxFileSizeInBytes) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_TOO_LARGE, { details: {
11002
+ limitBytes: preset.maxFileSizeInBytes,
11003
+ source: "preset"
11004
+ } });
10053
11005
  const asset = await this.storeAsset({
10054
11006
  ...fields,
11007
+ externalId: tokenExternalId,
10055
11008
  uploadPresetId,
10056
11009
  visibility: preset.visibility ?? "public",
10057
11010
  folderId: preset.folderId ?? void 0,
10058
11011
  processingOptions: { keepContentAfterProcessing: preset.keepContentAfterProcessing ?? true }
10059
- }, request.query.get("queue") === "true");
11012
+ }, request.query.get("wait") === "false");
10060
11013
  session.uploads.add(asset.id);
10061
11014
  return toUploaded(asset);
10062
11015
  }
@@ -10069,22 +11022,33 @@ var MockCalmLensApi = class {
10069
11022
  const pageSize = this.integer(query, "pageSize", 50);
10070
11023
  if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
10071
11024
  if (pageSize > MAX_PAGE_SIZE) throw invalidField("validation/too-big", "pageSize");
11025
+ const typesValue = query.get("types");
11026
+ const types = typesValue === null ? [] : typesValue.split(",");
11027
+ if (typesValue !== null && (types.length === 0 || types.some((type) => !EVENT_TYPE_PATTERN.test(type)))) throw invalidField("validation/invalid-value", "types");
11028
+ const assetId = query.get("assetId");
11029
+ if (assetId !== null && !isId(assetId, "asset")) throw invalidField("validation/invalid-format", "assetId");
11030
+ const filter = btoa(JSON.stringify([[...new Set(types)].sort(), assetId]));
11031
+ const matches = (event) => (!types.length || types.includes(event.type)) && (assetId === null || event.assetId === assetId);
10072
11032
  const cursor = query.get("cursor");
10073
11033
  if (!cursor) return {
10074
11034
  items: [],
10075
- nextCursor: `mock_${this.eventFeed.length}`,
11035
+ nextCursor: `mock_${this.eventFeed.length}~${filter}`,
10076
11036
  hasMore: false,
10077
11037
  excludedTypes: []
10078
11038
  };
10079
- const match = /^mock_(\d+)$/.exec(cursor);
10080
- const position = match ? Number(match[1]) : NaN;
11039
+ const match = /^mock_(\d+)~(.*)$/.exec(cursor);
11040
+ const position = match && match[2] === filter ? Number(match[1]) : NaN;
10081
11041
  if (!Number.isSafeInteger(position) || position > this.eventFeed.length) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR);
10082
- const items = this.eventFeed.slice(position, position + pageSize);
10083
- const next = position + items.length;
11042
+ const items = [];
11043
+ let next = position;
11044
+ while (next < this.eventFeed.length && items.length < pageSize) {
11045
+ const event = this.eventFeed[next++];
11046
+ if (matches(event)) items.push(event);
11047
+ }
10084
11048
  return {
10085
11049
  items,
10086
- nextCursor: `mock_${next}`,
10087
- hasMore: next < this.eventFeed.length,
11050
+ nextCursor: `mock_${next}~${filter}`,
11051
+ hasMore: this.eventFeed.slice(next).some(matches),
10088
11052
  excludedTypes: []
10089
11053
  };
10090
11054
  }
@@ -10096,12 +11060,12 @@ var MockCalmLensApi = class {
10096
11060
  const all = await this.databaseStorage.listFolders?.(this.projectId) ?? [];
10097
11061
  const parentId = query.get("parentId");
10098
11062
  const search = query.get("search")?.trim() || null;
10099
- const ordering = this.folderOrdering(query);
11063
+ const sort = this.sort(query, ["name", "createdAt"], 1);
10100
11064
  const matching = all.filter((folder) => (folder.parentId ?? null) === parentId && (!search || folder.name.toLowerCase().includes(search.toLowerCase())));
10101
11065
  const page = createPage(matching, {
10102
11066
  cursor: query.get("cursor") ?? void 0,
10103
11067
  pageSize: this.integer(query, "pageSize", 50),
10104
- ordering
11068
+ sort
10105
11069
  }, {
10106
11070
  scope: JSON.stringify([
10107
11071
  this.projectId,
@@ -10109,7 +11073,7 @@ var MockCalmLensApi = class {
10109
11073
  search
10110
11074
  ]),
10111
11075
  fail: this.pageFailure,
10112
- defaultOrdering: [{
11076
+ defaultSort: [{
10113
11077
  field: "name",
10114
11078
  direction: "asc"
10115
11079
  }]
@@ -10125,21 +11089,9 @@ var MockCalmLensApi = class {
10125
11089
  items: folders,
10126
11090
  ancestors: all.filter((folder) => ids.has(folder.id) && !folders.some((item) => item.id === folder.id)),
10127
11091
  nextCursor: page.nextCursor,
10128
- pageSize: page.pageSize,
10129
- hasMore: page.hasMore,
10130
- ordering: page.ordering
11092
+ hasMore: page.hasMore
10131
11093
  };
10132
11094
  }
10133
- /** The folder list's `ordering`: at most one rule, by `name` or `createdAt`. */
10134
- folderOrdering(query) {
10135
- const ordering = this.ordering(query);
10136
- if (ordering.length > 1) throw invalidField("validation/too-big", "ordering");
10137
- for (const [index, rule] of ordering.entries()) {
10138
- if (rule.field !== "name" && rule.field !== "createdAt") throw invalidField("validation/invalid-value", `ordering.${index}.field`);
10139
- if (rule.direction !== "asc" && rule.direction !== "desc") throw invalidField("validation/invalid-value", `ordering.${index}.direction`);
10140
- }
10141
- return ordering;
10142
- }
10143
11095
  async createFolder(body) {
10144
11096
  const name = body.name;
10145
11097
  if (typeof name !== "string" || !name) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Folder name is required" });
@@ -10210,7 +11162,7 @@ var MockCalmLensApi = class {
10210
11162
  async assertUniqueFolderName(name, parentId, excludeFolderId) {
10211
11163
  if ((await this.databaseStorage.listFolders?.(this.projectId) ?? []).find((folder) => folder.id !== excludeFolderId && (folder.parentId ?? null) === parentId && folder.name === name)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.DUPLICATE_FOLDER_NAME, { message: `A folder named "${name}" already exists in this location.` });
10212
11164
  }
10213
- /** Saves each lens in order, like the API: new ones, or changes with a greater version. */
11165
+ /** Saves each lens in order, like the API: new ones, or a changed definition. */
10214
11166
  ensureLenses(body) {
10215
11167
  const lenses = Array.isArray(body.lenses) ? body.lenses : [];
10216
11168
  if (lenses.length === 0) throw invalidField("validation/too-small", "lenses");
@@ -10218,50 +11170,124 @@ var MockCalmLensApi = class {
10218
11170
  }
10219
11171
  ensureLens(options) {
10220
11172
  const existing = this.lenses.get(options.identifier);
10221
- if (!existing) {
10222
- const now = this.now();
10223
- const lens = {
10224
- id: this.createId("lens"),
10225
- projectId: this.projectId,
10226
- ...options,
10227
- createdAt: now,
10228
- updatedAt: now
10229
- };
10230
- this.lenses.set(lens.identifier, lens);
10231
- return lens;
10232
- }
10233
- if (existing.name === options.name && (existing.description ?? null) === (options.description ?? null) && existing.type === options.type && existing.active === options.active && require_CalmLensServerClient.stringifyJsonCanonical(existing.transform ?? null) === require_CalmLensServerClient.stringifyJsonCanonical(options.transform ?? null) && existing.version === options.version) return existing;
10234
- if (options.version > existing.version) {
10235
- const lens = {
10236
- ...existing,
10237
- ...options,
10238
- updatedAt: this.now()
10239
- };
10240
- this.lenses.set(lens.identifier, lens);
10241
- return lens;
10242
- }
10243
- throw fail(require_ModerationContextLimits.API_ERROR_CODES.LENS_VERSION_CONFLICT, { details: {
10244
- currentVersion: existing.version,
10245
- minimumVersion: existing.version + 1,
10246
- requestedVersion: options.version
10247
- } });
11173
+ if (!existing) return this.saveNewLens(options);
11174
+ if (existing.name === options.name && (existing.description ?? null) === (options.description ?? null) && existing.type === options.type && existing.active === options.active && require_CalmLensServerClient.stringifyJsonCanonical(existing.transform ?? null) === require_CalmLensServerClient.stringifyJsonCanonical(options.transform ?? null)) return existing;
11175
+ const lens = {
11176
+ ...existing,
11177
+ ...options,
11178
+ updatedAt: this.now()
11179
+ };
11180
+ this.lenses.set(lens.identifier, lens);
11181
+ return lens;
11182
+ }
11183
+ saveNewLens(options) {
11184
+ const now = this.now();
11185
+ const lens = {
11186
+ id: this.createId("lens"),
11187
+ projectId: this.projectId,
11188
+ ...options,
11189
+ createdAt: now,
11190
+ updatedAt: now
11191
+ };
11192
+ this.lenses.set(lens.identifier, lens);
11193
+ return lens;
11194
+ }
11195
+ /** A page of the project's lenses, newest first unless `sort` says otherwise. */
11196
+ listLenses(query) {
11197
+ return createPage([...this.lenses.values()], this.pageQuery(query), {
11198
+ scope: `lenses:${this.projectId}`,
11199
+ fail: this.pageFailure
11200
+ });
11201
+ }
11202
+ createLens(body) {
11203
+ const definition = body;
11204
+ if (typeof definition.identifier !== "string" || !definition.identifier) throw invalidField("validation/invalid-type", "identifier");
11205
+ if (this.lenses.has(definition.identifier)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.LENS_IDENTIFIER_TAKEN, { details: { identifier: definition.identifier } });
11206
+ return this.saveNewLens(definition);
11207
+ }
11208
+ findLens(lensId) {
11209
+ const lens = [...this.lenses.values()].find((candidate) => candidate.id === lensId);
11210
+ if (!lens) throw fail(require_ModerationContextLimits.API_ERROR_CODES.LENS_NOT_FOUND);
11211
+ return lens;
11212
+ }
11213
+ updateLens(lensId, body) {
11214
+ const lens = this.findLens(lensId);
11215
+ const { identifier: _identifier, ...changes } = body;
11216
+ return this.ensureLens({
11217
+ ...lens,
11218
+ ...changes
11219
+ });
11220
+ }
11221
+ deleteLens(lensId) {
11222
+ this.lenses.delete(this.findLens(lensId).identifier);
11223
+ return {};
10248
11224
  }
10249
11225
  /**
10250
- * Serves stored content like the CDN (`/assets/:projectId/:asset/:resource`): `200` with
11226
+ * Serves an asset's resources like the CDN (`/assets/:projectId/:asset/:resource`): `200` with
10251
11227
  * `Content-Type`, `Content-Length`, `Cache-Control`, `Cache-Tag`, the CDN's protection headers
10252
- * and, for images, `ETag` and `Expires`; or a JSON error body with `404`/`403`. A
10253
- * `placeholder` is the asset's ThumbHash as a PNG.
11228
+ * and, for still images, `ETag` and `Expires`; or a JSON error body with `400`, `403` or `404`.
11229
+ * `original` is the upload; `rendered` the image, PDF, video or audio file `content.rendered`
11230
+ * describes; `preview` the still `content.preview` describes; and `placeholder` its ThumbHash as a
11231
+ * PNG. The mock converts nothing: an upload stands in for its rendered file, an image for its own
11232
+ * preview, and the placeholder PNG for a screenshot, page, poster or waveform.
10254
11233
  */
10255
11234
  async serveCdn(request) {
10256
11235
  const { url, segments, query } = request;
10257
- const [root, projectId, assetIdentifier, resource] = segments;
11236
+ const [root, projectId, , resource] = segments;
11237
+ const assetSegment = request.rawSegments[2] ?? "";
11238
+ const selectorPath = request.rawSegments.slice(4);
10258
11239
  const notFound = () => this.jsonResponse(404, {
10259
11240
  code: "asset/not-found",
10260
11241
  message: "Asset not found"
10261
11242
  }, url);
10262
- if (root !== "assets" || projectId !== this.projectId || !assetIdentifier) return notFound();
10263
- const asset = (await this.databaseStorage.listAssets(this.projectId)).find((asset) => asset.id === assetIdentifier || asset.externalId === assetIdentifier);
11243
+ const noRenderedVersion = () => this.jsonResponse(404, {
11244
+ code: "asset/no-rendered-version",
11245
+ message: "This asset has no such resource"
11246
+ }, url);
11247
+ const invalidTransform = () => this.jsonResponse(400, {
11248
+ code: "transform/invalid",
11249
+ message: "Invalid transform selector"
11250
+ }, url);
11251
+ const isHls = resource === "hls";
11252
+ let selector;
11253
+ try {
11254
+ selector = require_ModerationContextLimits.parseTransformSelector(isHls ? "" : selectorPath.join("/"));
11255
+ } catch {
11256
+ return invalidTransform();
11257
+ }
11258
+ const hasSelector = Boolean(selector.lens || selector.options);
11259
+ if ((resource === "original" || resource === "embed" || resource === "info") && hasSelector) return invalidTransform();
11260
+ if (root !== "assets" || projectId !== this.projectId || !assetSegment) return notFound();
11261
+ const assets = await this.databaseStorage.listAssets(this.projectId);
11262
+ let grant;
11263
+ let asset;
11264
+ if (assetSegment.startsWith("sig_")) {
11265
+ grant = decodeMockGrant(assetSegment);
11266
+ if (!grant) return this.jsonResponse(403, {
11267
+ code: "signed-url/invalid",
11268
+ message: "The signed asset URL's grant is invalid"
11269
+ }, url);
11270
+ if (grant.expiresAt <= this.now()) return this.jsonResponse(403, {
11271
+ code: "signed-url/expired",
11272
+ message: "The signed URL has expired"
11273
+ }, url);
11274
+ const grantedId = grant.assetId;
11275
+ asset = assets.find((candidate) => candidate.id === grantedId);
11276
+ } else if (assetSegment.startsWith("ext:")) {
11277
+ let externalId;
11278
+ try {
11279
+ externalId = decodeURIComponent(assetSegment.slice(4));
11280
+ } catch {}
11281
+ asset = externalId ? assets.find((candidate) => candidate.externalId === externalId) : void 0;
11282
+ } else {
11283
+ const assetId = decodeSegment(assetSegment);
11284
+ asset = assets.find((candidate) => candidate.id === assetId);
11285
+ }
10264
11286
  if (!asset) return notFound();
11287
+ if (resource === "original" && grant && !grant.original) return this.jsonResponse(403, {
11288
+ code: "signed-url/original-not-granted",
11289
+ message: "This signed asset URL doesn't grant the original file"
11290
+ }, url);
10265
11291
  const notAvailable = () => this.jsonResponse(403, {
10266
11292
  code: "asset/not-available",
10267
11293
  message: "Asset is not available"
@@ -10271,11 +11297,13 @@ var MockCalmLensApi = class {
10271
11297
  const canDownload = () => permits(grants, "assets:download", asset.folderId ?? null, folders);
10272
11298
  const status = asset.classification.moderation.status;
10273
11299
  const isHead = request.method === "HEAD";
11300
+ const { rendered, preview } = asset.content;
11301
+ if (resource === "info") return this.serveInfo(request, asset, Boolean(grant) || canDownload());
11302
+ if (asset.content.safetyHold) return notAvailable();
10274
11303
  if (resource === "placeholder") {
10275
- const thumbhash = asset.content.image?.thumbhash;
11304
+ const thumbhash = preview?.thumbhash;
10276
11305
  if (!thumbhash || status === "purged") return notAvailable();
10277
- const png = Uint8Array.from(atob(require_UploadController.placeholderHashToDataURL(thumbhash).split(",", 2)[1]), (char) => char.charCodeAt(0));
10278
- return this.cdnResponse(isHead, png, url, {
11306
+ return this.cdnResponse(isHead, mockPlaceholderPng(thumbhash), url, {
10279
11307
  "Content-Type": "image/png",
10280
11308
  "Cache-Control": "public, max-age=3600",
10281
11309
  "Cache-Tag": `asset-${asset.id}`,
@@ -10283,33 +11311,59 @@ var MockCalmLensApi = class {
10283
11311
  });
10284
11312
  }
10285
11313
  const storedContent = await this.imageStorage.getContent(asset.id);
10286
- if (asset.upload.status === "uploading" || status === "purged" || status === "blocked" || asset.classification.status === "failed" || asset.content.status === "removed" || !storedContent) return notAvailable();
11314
+ if (asset.upload.status === "uploading" || status === "purged" || status === "blocked" || asset.classification.status === "failed" || asset.content.status === "removed" || resource === "original" && !storedContent) return notAvailable();
10287
11315
  let claims = {};
10288
11316
  try {
10289
11317
  claims = JSON.parse(query.get("viewerClaims") ?? request.headers.get("X-CalmLens-Viewer-Claims") ?? "{}");
10290
11318
  } catch {
10291
- return this.jsonResponse(400, { code: "viewer/invalid-claims" }, url);
11319
+ return this.jsonResponse(400, { code: "viewer-claims/invalid" }, url);
10292
11320
  }
10293
11321
  if (status === "age-restricted" && claims.ageConfirmed !== true) return this.jsonResponse(403, { code: "viewer/age-confirmation-required" }, url);
10294
11322
  const isPrivate = asset.visibility !== "public";
10295
- if (isPrivate && !canDownload()) return this.jsonResponse(403, {
10296
- code: "asset/api-key-missing-permission",
11323
+ if (isPrivate && !grant && !canDownload()) return this.jsonResponse(403, {
11324
+ code: "auth/permission-denied",
10297
11325
  message: "This API key needs assets:download permission for this asset’s folder."
10298
11326
  }, url);
10299
- const parts = [...storedContent.parts.entries()].sort(([left], [right]) => left - right).map(([, value]) => value);
10300
- const bytes = new Uint8Array(parts.reduce((sum, value) => sum + value.byteLength, 0));
10301
- let offset = 0;
10302
- for (const part of parts) {
10303
- bytes.set(part, offset);
10304
- offset += part.byteLength;
10305
- }
10306
- const contentType = storedContent.type ?? "application/octet-stream";
10307
- const isImage = asset.type === "image";
11327
+ if (resource === "embed") return this.cdnResponse(isHead, new TextEncoder().encode(MOCK_EMBED_HTML), url, {
11328
+ "Content-Type": "text/html; charset=utf-8",
11329
+ "Cache-Control": Object.keys(claims).length ? "private, no-store" : `${isPrivate ? "private" : "public"}, max-age=3600`,
11330
+ "Cache-Tag": `asset-${asset.id}`,
11331
+ "X-Content-Type-Options": "nosniff"
11332
+ });
11333
+ if (resource === "rendered" && !rendered || resource === "preview" && !preview) return noRenderedVersion();
11334
+ if (isHls && !asset.content.hls) return noRenderedVersion();
11335
+ const stillImage = resource === "preview" || resource === "rendered" && rendered?.kind === "image";
11336
+ if (!stillImage && hasSelector) return invalidTransform();
11337
+ if (selector.options) {
11338
+ const { unknownKeys, invalidKeys } = require_ModerationContextLimits.checkTransformOptions(selector.options);
11339
+ if (unknownKeys.length || invalidKeys.length) return this.jsonResponse(400, {
11340
+ code: "transform-options/invalid",
11341
+ message: `Invalid transform options: ${[...unknownKeys, ...invalidKeys].join(", ")}`
11342
+ }, url);
11343
+ }
11344
+ const servesUpload = resource === "original" || resource === "rendered" && rendered?.kind !== "image" || asset.type === "image";
11345
+ let bytes;
11346
+ let contentType;
11347
+ if (servesUpload) {
11348
+ if (!storedContent) return notAvailable();
11349
+ const parts = [...storedContent.parts.entries()].sort(([left], [right]) => left - right).map(([, value]) => value);
11350
+ bytes = new Uint8Array(parts.reduce((sum, value) => sum + value.byteLength, 0));
11351
+ let offset = 0;
11352
+ for (const part of parts) {
11353
+ bytes.set(part, offset);
11354
+ offset += part.byteLength;
11355
+ }
11356
+ contentType = resource === "rendered" && rendered ? rendered.format : storedContent.type ?? "application/octet-stream";
11357
+ } else {
11358
+ bytes = mockPlaceholderPng(preview?.thumbhash ?? MOCK_THUMBHASH);
11359
+ contentType = "image/png";
11360
+ }
11361
+ const immutable = stillImage || resource === "original" && asset.type === "image";
10308
11362
  return this.cdnResponse(isHead, bytes, url, {
10309
11363
  "Content-Type": contentType,
10310
- "Cache-Control": Object.keys(claims).length ? "private, no-store" : `${isPrivate ? "private" : "public"}, ${isImage ? "max-age=31536000, immutable" : "max-age=3600"}`,
11364
+ "Cache-Control": Object.keys(claims).length ? "private, no-store" : `${isPrivate ? "private" : "public"}, ${immutable ? "max-age=31536000, immutable" : "max-age=3600"}`,
10311
11365
  "Cache-Tag": `asset-${asset.id}`,
10312
- ...isImage ? {
11366
+ ...immutable ? {
10313
11367
  ETag: `"${asset.id}"`,
10314
11368
  Expires: new Date(this.now() + 31536e6).toUTCString()
10315
11369
  } : {},
@@ -10318,6 +11372,51 @@ var MockCalmLensApi = class {
10318
11372
  ...isActiveContentType(contentType) ? { "Content-Disposition": "attachment" } : {}
10319
11373
  });
10320
11374
  }
11375
+ /**
11376
+ * The display info at `/info`, like the CDN's (AssetInfo.ts): the allowlisted fields and whether
11377
+ * the viewer the claims describe can see the content, decided as the other resources decide it.
11378
+ * A private asset's needs a grant or an API key with `assets:download`.
11379
+ */
11380
+ serveInfo(request, asset, authorised) {
11381
+ const { url, query } = request;
11382
+ const isPrivate = asset.visibility !== "public";
11383
+ if (isPrivate && !authorised) return this.jsonResponse(404, {
11384
+ code: "asset/not-available",
11385
+ message: "Asset is not available"
11386
+ }, url);
11387
+ let claims = {};
11388
+ try {
11389
+ claims = JSON.parse(query.get("viewerClaims") ?? request.headers.get("X-CalmLens-Viewer-Claims") ?? "{}");
11390
+ } catch {
11391
+ return this.jsonResponse(400, { code: "viewer-claims/invalid" }, url);
11392
+ }
11393
+ const status = asset.classification.moderation.status;
11394
+ const availability = asset.content.safetyHold || asset.upload.status === "uploading" || status === "blocked" || status === "purged" || asset.classification.status === "failed" || asset.content.status === "removed" ? "unavailable" : status === "age-restricted" && claims.ageConfirmed !== true ? "age-restricted" : "available";
11395
+ const { content } = asset;
11396
+ const info = {
11397
+ id: asset.id,
11398
+ projectId: asset.projectId,
11399
+ type: asset.type,
11400
+ externalUrl: asset.externalUrl ?? null,
11401
+ content: {
11402
+ format: content.format,
11403
+ width: content.width,
11404
+ height: content.height,
11405
+ durationSeconds: content.durationSeconds,
11406
+ pageCount: content.pageCount,
11407
+ rendered: content.rendered,
11408
+ preview: content.preview,
11409
+ hls: content.hls
11410
+ },
11411
+ availability
11412
+ };
11413
+ const bytes = new TextEncoder().encode(JSON.stringify(info));
11414
+ return this.cdnResponse(request.method === "HEAD", bytes, url, {
11415
+ "Content-Type": "application/json",
11416
+ "Cache-Control": `${isPrivate ? "private" : "public"}, max-age=60`,
11417
+ "Cache-Tag": `asset-${asset.id}`
11418
+ });
11419
+ }
10321
11420
  cdnResponse(isHead, bytes, url, headers) {
10322
11421
  return this.response(200, isHead ? null : bytes, url, {
10323
11422
  ...headers,
@@ -10404,7 +11503,6 @@ var InMemoryMockDatabaseStorage = class {
10404
11503
  this.folders.delete(folderId);
10405
11504
  }
10406
11505
  };
10407
- // src/testing/MockCalmLensServerClient.ts
10408
11506
  const apis = /* @__PURE__ */ new WeakMap();
10409
11507
  /** The in-memory API a mock server client runs against, for `MockCalmLensAppClient`. */
10410
11508
  const getMockApi = (client) => {
@@ -10420,7 +11518,7 @@ const mockClientOptions = (api, endpoints, session) => {
10420
11518
  const fetch = api.createFetch(endpoints, session);
10421
11519
  const hooks = {
10422
11520
  sleep: async (ms, signal) => {
10423
- await require_CalmLensOptionKeys.sleep(0, signal);
11521
+ await require_ModerationContextLimits.sleep(0, signal);
10424
11522
  api.waitedMs += ms;
10425
11523
  },
10426
11524
  now: () => api.waitedMs,
@@ -10446,13 +11544,18 @@ const mockClientOptions = (api, endpoints, session) => {
10446
11544
  */
10447
11545
  var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLensServerClient {
10448
11546
  #api;
11547
+ #fetch;
10449
11548
  #projectId;
10450
11549
  /**
10451
11550
  * Accepts the same options as `CalmLensServerClient` (validated the same way), plus
10452
11551
  * `mockOptions`. `maxRetries` defaults to 0, so a failed request fails once; retry backoff and
10453
11552
  * `assets.waitForDecision` take no real time.
10454
11553
  */
10455
- constructor(options) {
11554
+ constructor(input) {
11555
+ const options = {
11556
+ ...input,
11557
+ projectId: input.projectId ?? "project-1"
11558
+ };
10456
11559
  require_ModerationContextLimits.validateServerClientOptions(options);
10457
11560
  const { mockOptions = {}, ...clientOptions } = options;
10458
11561
  const api = new MockCalmLensApi({
@@ -10463,8 +11566,7 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
10463
11566
  imageStorage: mockOptions.imageStorage ?? new InMemoryMockImageStorage(),
10464
11567
  createId: mockOptions.createId ?? newId,
10465
11568
  now: mockOptions.now ?? createMonotonicClock(),
10466
- moderate: mockOptions.moderate ?? defaultModerate,
10467
- signedUrlBaseUrl: mockOptions.signedUrlBaseUrl ?? "mock://calmlens"
11569
+ moderate: mockOptions.moderate ?? defaultModerate
10468
11570
  });
10469
11571
  let endpoints;
10470
11572
  super({
@@ -10479,6 +11581,7 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
10479
11581
  cdnBaseUrl
10480
11582
  };
10481
11583
  this.#api = api;
11584
+ this.#fetch = api.createFetch(() => endpoints);
10482
11585
  this.#projectId = options.projectId;
10483
11586
  this.databaseStorage = api.databaseStorage;
10484
11587
  this.imageStorage = api.imageStorage;
@@ -10503,6 +11606,14 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
10503
11606
  callsTo(operation) {
10504
11607
  return this.#api.calls.filter(({ operations }) => operations.includes(operation)).map(({ call }) => call);
10505
11608
  }
11609
+ /**
11610
+ * Fetches a URL of the mock's CDN as a browser would, without the API key: a signed asset URL
11611
+ * from `cdn.signAssetUrl` (with a resource appended), or a public one from `cdn.getAssetUrl`.
11612
+ * The request is recorded like any other.
11613
+ */
11614
+ fetchCdn(url, init) {
11615
+ return this.#fetch(url, init);
11616
+ }
10506
11617
  /** Forgets the requests recorded so far, so `calls` lists only later ones. */
10507
11618
  clearCalls() {
10508
11619
  this.#api.calls.length = 0;
@@ -10535,7 +11646,7 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
10535
11646
  * Applies a reviewer's decision to a stored asset, as the portal or API would: the moderation
10536
11647
  * status changes (`purged` also removes the content, with reason `requested` and an
10537
11648
  * `asset.content-removed` event), the review joins `manualReviews`, and an `asset.<decision>`
10538
- * event with a `decided-by: reviewer` fact joins the events feed. Rejects with
11649
+ * event whose `actor` is a `user` joins the events feed. Rejects with
10539
11650
  * `asset/not-found` for an unknown asset. It sends no request.
10540
11651
  */
10541
11652
  decide(assetId, decision) {
@@ -10546,15 +11657,17 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
10546
11657
  * else what `mockOptions.moderate` returns for the `complete` trigger (`allowed` by default).
10547
11658
  * The asset gets the decision's report, and `asset.classified` and the automated
10548
11659
  * `asset.<status>` (or `asset.failed`) join the events feed. No review is recorded, so the
10549
- * asset can still be moderated again. Rejects with `asset/not-found` for an unknown asset and
10550
- * `sdk/invalid-argument` for one that isn't processing. It sends no request.
11660
+ * asset can still be moderated again. A decided asset whose re-run (`assets.explain` with
11661
+ * `rerun: true`) is still pending gets the decision in place of its old one, unless it is
11662
+ * `pending` or `failed`. Rejects with `asset/not-found` for an unknown asset and
11663
+ * `sdk/invalid-argument` for one that isn't processing or awaiting a pending re-run. It sends
11664
+ * no request.
10551
11665
  */
10552
11666
  completeProcessing(assetId, decision) {
10553
11667
  return this.#api.completeProcessing(assetId, decision);
10554
11668
  }
10555
11669
  };
10556
11670
  // src/testing/MockCalmLensAppClient.ts
10557
- const MOCK_PROJECT_ID = "proj_0000000000000000c1a5";
10558
11671
  /**
10559
11672
  * The real `CalmLensAppClient`, answered by the in-memory API of a `MockCalmLensServerClient`.
10560
11673
  * The API applies `mockOptions.preset` to this client's uploads like CalmLens applies an upload
@@ -10577,7 +11690,6 @@ var MockCalmLensAppClient = class extends require_CalmLensAppClient.CalmLensAppC
10577
11690
  folderId: null,
10578
11691
  includeSubfolders: true
10579
11692
  }]),
10580
- projectId: MOCK_PROJECT_ID,
10581
11693
  mockOptions: { moderate: mockOptions.moderate }
10582
11694
  });
10583
11695
  let endpoints;
@@ -10610,11 +11722,13 @@ var MockCalmLensAppClient = class extends require_CalmLensAppClient.CalmLensAppC
10610
11722
  const toWebhookEventPayload = (event) => ({
10611
11723
  id: event.id,
10612
11724
  projectId: event.projectId,
11725
+ actor: event.actor,
10613
11726
  type: event.type,
10614
11727
  severity: event.severity,
10615
11728
  title: event.title,
10616
11729
  description: event.description ?? null,
10617
11730
  assetId: event.assetId ?? null,
11731
+ assetSequence: event.assetSequence ?? null,
10618
11732
  asset: event.asset ?? null,
10619
11733
  facts: event.facts,
10620
11734
  createdAt: event.createdAt