calmlens 0.28.2 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/bin/calmlens.js +151 -123
  2. package/cjs/{BrowserUpload-DmKNP0Vy.js → BrowserUpload-CcSQI7Kf.js} +1 -1
  3. package/cjs/{BrowserUpload-CRbCsX7a.d.ts → BrowserUpload-CeGsM9h1.d.ts} +2 -2
  4. package/cjs/{CalmLensAppClient-Bl9VU7S2.js → CalmLensAppClient-BPILD5mg.js} +11 -17
  5. package/cjs/{CalmLensAppClient-B3u6BlP5.d.ts → CalmLensAppClient-D-BD_Ny1.d.ts} +7 -1
  6. package/cjs/{CalmLensOptionKeys-DolSy6qV.js → CalmLensConnection-Wfxn25LT.js} +660 -643
  7. package/cjs/{CalmLensServerClient-B8ntjNL3.d.ts → CalmLensServerClient-BYN_N0lt.d.ts} +33 -2
  8. package/cjs/{CalmLensServerClient-DA-sB9ru.js → CalmLensServerClient-C_42j_i4.js} +72 -41
  9. package/cjs/{CalmLensTypes-CtO4Dieu.d.ts → CalmLensTypes-C2blKgTu.d.ts} +51 -75
  10. package/{esm/Core-BJaLU71Q.d.ts → cjs/Core-CNmoxDCW.d.ts} +2 -2
  11. package/cjs/{Core-RSm9Xcse.js → Core-CfdovxKJ.js} +2 -2
  12. package/cjs/{ModerationContextLimits-51OdOFof.js → ModerationContextLimits-DXlPrt4K.js} +24 -13
  13. package/cjs/{ReactUpload-DQYHaJSZ.js → ReactUpload-CzsQwVKM.js} +1 -1
  14. package/cjs/{ReactUpload-BGUkcMpg.d.ts → ReactUpload-kqEe6gcN.d.ts} +1 -1
  15. package/cjs/{UploadController-C6Gt-YQA.js → UploadController-D_Y5wktq.js} +2 -2
  16. package/cjs/{WebhookPayload-DZadhbAJ.d.ts → WebhookPayload-DZWlnvcY.d.ts} +3 -2
  17. package/cjs/app.d.ts +5 -5
  18. package/cjs/app.js +2 -2
  19. package/cjs/elements.d.ts +4 -4
  20. package/cjs/elements.js +4 -4
  21. package/cjs/{index-DQUZYLVY.d.ts → index-Dl2qwS8L.d.ts} +2 -2
  22. package/cjs/index.d.ts +4 -4
  23. package/cjs/index.js +1 -1
  24. package/cjs/react-native.d.ts +2 -2
  25. package/cjs/react-native.js +4 -4
  26. package/cjs/react.d.ts +4 -4
  27. package/cjs/react.js +5 -5
  28. package/cjs/server.d.ts +5 -5
  29. package/cjs/server.js +2 -2
  30. package/cjs/testing.d.ts +46 -12
  31. package/cjs/testing.js +405 -88
  32. package/cjs/{ui-BGywTQ2M.d.ts → ui-BtmJC-f9.d.ts} +2 -2
  33. package/cjs/{ui-Ntkv4inL.js → ui-CkOexkAO.js} +2 -2
  34. package/cjs/ui.d.ts +2 -2
  35. package/cjs/ui.js +3 -3
  36. package/cjs/vue.d.ts +5 -5
  37. package/cjs/vue.js +4 -4
  38. package/esm/{BrowserUpload-CRbCsX7a.d.ts → BrowserUpload-CeGsM9h1.d.ts} +2 -2
  39. package/esm/{BrowserUpload-CvUgnS8I.js → BrowserUpload-DJ2euKyv.js} +1 -1
  40. package/esm/{CalmLensAppClient-ktB4Vfbk.js → CalmLensAppClient-CCT5Em2S.js} +3 -9
  41. package/esm/{CalmLensAppClient-B3u6BlP5.d.ts → CalmLensAppClient-D-BD_Ny1.d.ts} +7 -1
  42. package/esm/{CalmLensOptionKeys-DCO58tKr.js → CalmLensConnection-CfBXkam-.js} +661 -644
  43. package/esm/{CalmLensServerClient-B8ntjNL3.d.ts → CalmLensServerClient-BYN_N0lt.d.ts} +33 -2
  44. package/esm/{CalmLensServerClient-D02L8AUH.js → CalmLensServerClient-e6gVcMxy.js} +58 -27
  45. package/esm/{CalmLensTypes-CtO4Dieu.d.ts → CalmLensTypes-C2blKgTu.d.ts} +51 -75
  46. package/{cjs/Core-BJaLU71Q.d.ts → esm/Core-CNmoxDCW.d.ts} +2 -2
  47. package/esm/{Core-22KeL-HD.js → Core-CojlqrKH.js} +2 -2
  48. package/esm/{ModerationContextLimits-BFfngsVu.js → ModerationContextLimits-Abu_L1Df.js} +24 -13
  49. package/esm/{ReactUpload-CFGawuk6.js → ReactUpload-CDrA7hRn.js} +1 -1
  50. package/esm/{ReactUpload-BGUkcMpg.d.ts → ReactUpload-kqEe6gcN.d.ts} +1 -1
  51. package/esm/{UploadController-CLEvEwzd.js → UploadController-BubUXclM.js} +2 -2
  52. package/esm/{WebhookPayload-DZadhbAJ.d.ts → WebhookPayload-DZWlnvcY.d.ts} +3 -2
  53. package/esm/app.d.ts +5 -5
  54. package/esm/app.js +2 -2
  55. package/esm/elements.d.ts +4 -4
  56. package/esm/elements.js +4 -4
  57. package/esm/{index-DQUZYLVY.d.ts → index-Dl2qwS8L.d.ts} +2 -2
  58. package/esm/index.d.ts +4 -4
  59. package/esm/index.js +1 -1
  60. package/esm/react-native.d.ts +2 -2
  61. package/esm/react-native.js +4 -4
  62. package/esm/react.d.ts +4 -4
  63. package/esm/react.js +5 -5
  64. package/esm/server.d.ts +5 -5
  65. package/esm/server.js +2 -2
  66. package/esm/testing.d.ts +46 -12
  67. package/esm/testing.js +398 -82
  68. package/esm/{ui-C9u03xc3.js → ui--AzgLLVf.js} +2 -2
  69. package/esm/{ui-BGywTQ2M.d.ts → ui-BtmJC-f9.d.ts} +2 -2
  70. package/esm/ui.d.ts +2 -2
  71. package/esm/ui.js +3 -3
  72. package/esm/vue.d.ts +5 -5
  73. package/esm/vue.js +4 -4
  74. package/package.json +1 -1
package/cjs/testing.js CHANGED
@@ -1,11 +1,11 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_TestTriggers_uL2Ec8Vt = require("./TestTriggers-uL2Ec8Vt-cPmmKvYd.js");
3
- const require_ModerationContextLimits = require("./ModerationContextLimits-51OdOFof.js");
4
- const require_CalmLensServerClient = require("./CalmLensServerClient-DA-sB9ru.js");
5
- const require_CalmLensOptionKeys = require("./CalmLensOptionKeys-DolSy6qV.js");
3
+ const require_ModerationContextLimits = require("./ModerationContextLimits-DXlPrt4K.js");
4
+ const require_CalmLensServerClient = require("./CalmLensServerClient-C_42j_i4.js");
5
+ const require_CalmLensConnection = require("./CalmLensConnection-Wfxn25LT.js");
6
6
  const require_CryptoUtils_BLCa_oZe = require("./CryptoUtils-BLCa-oZe-leCkr1ko.js");
7
- const require_CalmLensAppClient = require("./CalmLensAppClient-Bl9VU7S2.js");
8
- const require_UploadController = require("./UploadController-C6Gt-YQA.js");
7
+ const require_CalmLensAppClient = require("./CalmLensAppClient-BPILD5mg.js");
8
+ const require_UploadController = require("./UploadController-D_Y5wktq.js");
9
9
  let zod = require("zod");
10
10
  zod = require_TestTriggers_uL2Ec8Vt.__toESM(zod, 1);
11
11
  // src/contract/MediaTestTriggers.js
@@ -8139,6 +8139,11 @@ const getMockApiKeyGrants = (apiKey) => {
8139
8139
  return [];
8140
8140
  }
8141
8141
  };
8142
+ /**
8143
+ * The ID of every mock API key, as the `id` of the `actor` and `decidedBy` its requests record,
8144
+ * where CalmLens gives your key's own ID.
8145
+ */
8146
+ const MOCK_API_KEY_ID = "key_mock0000000000000000";
8142
8147
  // src/testing/MockClassification.ts
8143
8148
  /** The parent categories, in the API's order. */
8144
8149
  const MOCK_CATEGORIES = [
@@ -9267,6 +9272,7 @@ const MOCK_OPERATIONS = [
9267
9272
  "assets.list",
9268
9273
  "assets.search",
9269
9274
  "assets.retrieve",
9275
+ "assets.retrieveByExternalId",
9270
9276
  "assets.waitForDecision",
9271
9277
  "assets.update",
9272
9278
  "assets.listChildren",
@@ -9277,6 +9283,7 @@ const MOCK_OPERATIONS = [
9277
9283
  "assets.move",
9278
9284
  "assets.retry",
9279
9285
  "assets.decide",
9286
+ "assets.requestReview",
9280
9287
  "assets.removeContent",
9281
9288
  "assets.delete",
9282
9289
  "assets.batch",
@@ -9285,6 +9292,7 @@ const MOCK_OPERATIONS = [
9285
9292
  "cdn.getAssetInfo",
9286
9293
  "cdn.signAssetUrl",
9287
9294
  "events.list",
9295
+ "events.retrieveAsset",
9288
9296
  "folders.list",
9289
9297
  "folders.retrieve",
9290
9298
  "folders.create",
@@ -9325,14 +9333,36 @@ const MOCK_OPERATIONS = [
9325
9333
  "metadataFields.ensure",
9326
9334
  "metadataFields.delete"
9327
9335
  ];
9336
+ /** The keys a `MockUploadPreset` takes; `checkMockUploadPreset` refuses any other. */
9337
+ const MOCK_UPLOAD_PRESET_KEYS = [
9338
+ "access",
9339
+ "allowedContentTypes",
9340
+ "maxSizeInBytes",
9341
+ "revealDecision",
9342
+ "visibility",
9343
+ "folderId",
9344
+ "processingOptions"
9345
+ ];
9346
+ /**
9347
+ * Throws `sdk/invalid-argument` naming each key a mock upload preset doesn't take, such as a
9348
+ * misspelt or renamed one, instead of silently ignoring it.
9349
+ */
9350
+ const checkMockUploadPreset = (preset) => {
9351
+ const unknown = Object.keys(preset).filter((key) => !MOCK_UPLOAD_PRESET_KEYS.includes(key));
9352
+ if (unknown.length) throw require_ModerationContextLimits.invalidArgument(`Unknown mockOptions.preset key${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")}`, { options: unknown });
9353
+ };
9328
9354
  const MAX_PAGE_SIZE = 100;
9355
+ /** Entries with a lower PDQ quality never match (HashList.ts, HASH_MATCH_MIN_QUALITY). */
9356
+ const HASH_MATCH_MIN_QUALITY = 50;
9357
+ /** The most hash matches an asset records (HashList.ts). */
9358
+ const MAX_RECORDED_HASH_MATCHES = 10;
9329
9359
  const MAX_DECISION_NOTE_LENGTH = 1499;
9330
9360
  /** How the API names a reviewer acting through an unnamed API key. */
9331
9361
  const API_KEY_REVIEWER_NAME = "An API key";
9332
- /** The actor of events the mock's API key causes: mock keys have no ID. */
9362
+ /** The actor of events and reviews the mock's API key causes. */
9333
9363
  const MOCK_API_KEY_ACTOR = {
9334
9364
  type: "api-key",
9335
- id: null
9365
+ id: MOCK_API_KEY_ID
9336
9366
  };
9337
9367
  /** The actor of a reviewer's decision through the `decide` test hook. */
9338
9368
  const MOCK_REVIEWER_ACTOR = {
@@ -9365,27 +9395,8 @@ const isActiveContentType = (type) => {
9365
9395
  "text/xml"
9366
9396
  ].includes(normalized) || normalized.endsWith("+xml")));
9367
9397
  };
9368
- /** The asset snapshot events carry (getEventAsset in the API). */
9369
- const toEventAsset = (asset) => ({
9370
- id: asset.id,
9371
- externalId: asset.externalId ?? null,
9372
- uploadPresetId: asset.uploadPresetId ?? null,
9373
- upload: { status: asset.upload.status },
9374
- classification: {
9375
- status: asset.classification.status,
9376
- testInput: asset.classification.testInput,
9377
- moderation: { decision: asset.classification.moderation.decision }
9378
- },
9379
- content: { status: asset.content.status }
9380
- });
9381
- /** The moderation status each `asset.<status>` event announces. */
9382
- const ANNOUNCED_STATUS = {
9383
- "asset.allowed": "allowed",
9384
- "asset.limited": "limited",
9385
- "asset.age-restricted": "age-restricted",
9386
- "asset.blocked": "blocked",
9387
- "asset.purged": "purged"
9388
- };
9398
+ /** Whether a value in a response body is an asset: its ID is an asset ID and it has its states. */
9399
+ const isStoredAsset = (value) => typeof value === "object" && value !== null && typeof value.id === "string" && isId(value.id, "asset") && "upload" in value && "classification" in value && "content" in value;
9389
9400
  /** A `moderate` answer or `completeProcessing` decision as a checked `MockDecision`. */
9390
9401
  const toDecision = (value) => {
9391
9402
  if (value instanceof MockDecision) return value;
@@ -9527,7 +9538,8 @@ const urlAssetType = (url) => {
9527
9538
  };
9528
9539
  /** An asset's type from its content type. */
9529
9540
  const inferAssetType = (contentType) => {
9530
- const type = contentType.toLowerCase();
9541
+ const type = contentType.toLowerCase().split(";", 1)[0].trim();
9542
+ if (type === "text/html" || type === "application/xhtml+xml") return "website";
9531
9543
  if (type.startsWith("image/")) return "image";
9532
9544
  if (type.startsWith("video/")) return "video";
9533
9545
  if (type.startsWith("audio/")) return "audio";
@@ -9544,6 +9556,11 @@ var ApiFailure = class {
9544
9556
  this.details = details;
9545
9557
  }
9546
9558
  };
9559
+ /**
9560
+ * `asset/duplicate-external-id`, naming the stored asset that holds the external ID in
9561
+ * `details.assetId`, like the API.
9562
+ */
9563
+ const duplicateExternalId = (holder) => fail(require_ModerationContextLimits.API_ERROR_CODES.DUPLICATE_EXTERNAL_ID, { details: { assetId: holder.id } });
9547
9564
  const fail = (code, { message, details } = {}) => new ApiFailure(require_ModerationContextLimits.API_ERROR_DEFINITIONS[code].status, code, message ?? require_ModerationContextLimits.API_ERROR_DEFINITIONS[code].message, details);
9548
9565
  /**
9549
9566
  * A request the API's schema refuses: `validation/invalid-request` with HTTP 400, listing the field
@@ -9714,6 +9731,7 @@ const operationsOf = (request) => {
9714
9731
  if (query.get("wait") === "false") return ["assets.create"];
9715
9732
  return isTextUpload(request) ? ["text.classify"] : ["assets.classify"];
9716
9733
  }
9734
+ if (segments[2] === "assets" && segments[3] === "by-external-id" && segments.length === 5) return ["assets.retrieveByExternalId"];
9717
9735
  if (segments[2] === "assets" && segments[4] === "timeline" && segments.length === 5) return ["assets.listTimeline"];
9718
9736
  if (segments[2] === "metadata-fields" && segments.length === 4) return ["metadataFields.delete"];
9719
9737
  return [];
@@ -9745,16 +9763,34 @@ const operationsOf = (request) => {
9745
9763
  if (root === "hash-list-entries" && id !== void 0) return ["hashLists.removeEntry"];
9746
9764
  if (root !== "assets" || id === void 0) return [];
9747
9765
  switch (action) {
9748
- case void 0: return method === "GET" ? ["assets.retrieve", "assets.waitForDecision"] : method === "PATCH" ? ["assets.update"] : ["assets.delete"];
9766
+ case void 0: return method === "GET" ? [
9767
+ "assets.retrieve",
9768
+ "assets.waitForDecision",
9769
+ "events.retrieveAsset"
9770
+ ] : method === "PATCH" ? ["assets.update"] : ["assets.delete"];
9749
9771
  case "content": return ["assets.removeContent"];
9750
9772
  case "children": return ["assets.listChildren"];
9751
9773
  case "part": return ["assets.uploadPart"];
9752
9774
  case "move": return ["assets.move"];
9753
9775
  case "retry": return ["assets.retry"];
9754
9776
  case "decision": return ["assets.decide"];
9777
+ case "review-requests": return ["assets.requestReview"];
9755
9778
  }
9756
9779
  return [];
9757
9780
  };
9781
+ /**
9782
+ * The methods whose requests the API runs under an `Idempotency-Key` (`idempotent` in its request
9783
+ * definitions): a retry with the same key replays the first response. Others ignore the header.
9784
+ */
9785
+ const IDEMPOTENT_OPERATIONS = [
9786
+ "assets.create",
9787
+ "assets.classify",
9788
+ "text.classify",
9789
+ "assets.uploadPart",
9790
+ "assets.decide",
9791
+ "assets.requestReview",
9792
+ "hashLists.addEntry"
9793
+ ];
9758
9794
  /** A plain-text upload: the SDKs send text as a JSON body with `content.plainText`. */
9759
9795
  const isTextUpload = (request) => {
9760
9796
  if (request.headers.get("x-calmlens-upload")) return false;
@@ -9800,9 +9836,15 @@ var MockCalmLensApi = class {
9800
9836
  this.openUploads = /* @__PURE__ */ new Map();
9801
9837
  this.idempotentResults = /* @__PURE__ */ new Map();
9802
9838
  this.pendingFailures = [];
9839
+ this.servedUrls = /* @__PURE__ */ new Map();
9840
+ this.pendingReviews = /* @__PURE__ */ new Map();
9803
9841
  this.requestCount = 0;
9804
9842
  this.useTimers = false;
9805
9843
  this.waitedMs = 0;
9844
+ this.publishAssets = (_key, value) => isStoredAsset(value) ? {
9845
+ ...value,
9846
+ eventSequence: this.eventSequenceOf(value.id)
9847
+ } : value;
9806
9848
  this.policies = /* @__PURE__ */ new Map();
9807
9849
  this.hashLists = /* @__PURE__ */ new Map();
9808
9850
  this.hashListEntries = /* @__PURE__ */ new Map();
@@ -9820,14 +9862,43 @@ var MockCalmLensApi = class {
9820
9862
  this.createId = options.createId;
9821
9863
  this.now = options.now;
9822
9864
  }
9823
- /** Queues a failure for the next request, or the next one `operation` sends. */
9865
+ /**
9866
+ * Queues a failure for the next request, or the next one `operation` sends, or for that many
9867
+ * with `times`; `failRequests` passes `Infinity`, which fails every one until `clearFailures`.
9868
+ */
9824
9869
  failNextRequest(failure, options = {}) {
9870
+ const { times = 1, ...rest } = options;
9871
+ if (times !== Number.POSITIVE_INFINITY && !(Number.isSafeInteger(times) && times >= 1)) throw require_ModerationContextLimits.invalidArgument("times must be a positive whole number");
9825
9872
  if (options.operation !== void 0 && !MOCK_OPERATIONS.includes(options.operation)) throw require_ModerationContextLimits.invalidArgument(`${options.operation} is not a client method that sends requests`);
9826
9873
  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");
9827
9874
  if (options.retryAfter !== void 0 && !(Number.isInteger(options.retryAfter) && options.retryAfter >= 0)) throw require_ModerationContextLimits.invalidArgument("retryAfter must be a whole number of seconds");
9828
9875
  this.pendingFailures.push({
9829
9876
  failure,
9830
- ...options
9877
+ remaining: times,
9878
+ ...rest
9879
+ });
9880
+ }
9881
+ /** Drops every queued failure, so requests reach the API again. */
9882
+ clearFailures() {
9883
+ this.pendingFailures.length = 0;
9884
+ }
9885
+ /**
9886
+ * Makes a URL answer with `content` and its `type` when a URL upload fetches it, as a site
9887
+ * would. Registering a URL again replaces its content.
9888
+ */
9889
+ serveUrl(url, { content, type }) {
9890
+ let key;
9891
+ try {
9892
+ key = new URL(url).href;
9893
+ } catch {
9894
+ throw require_ModerationContextLimits.invalidArgument("url must be an absolute URL");
9895
+ }
9896
+ if (typeof type !== "string" || !type.trim()) throw require_ModerationContextLimits.invalidArgument("type must be a content type, such as image/png");
9897
+ const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content instanceof ArrayBuffer ? new Uint8Array(content.slice(0)) : content instanceof Uint8Array ? new Uint8Array(content) : void 0;
9898
+ if (!bytes) throw require_ModerationContextLimits.invalidArgument("content must be bytes or a string");
9899
+ this.servedUrls.set(key, {
9900
+ bytes,
9901
+ type: type.trim()
9831
9902
  });
9832
9903
  }
9833
9904
  /** A `fetch` that answers a client's requests from memory; app clients pass their session. */
@@ -9839,15 +9910,7 @@ var MockCalmLensApi = class {
9839
9910
  * the stored event.
9840
9911
  */
9841
9912
  async enqueueEvent(input) {
9842
- const asset = input.asset === void 0 && input.assetId ? await this.databaseStorage.getAsset(input.assetId) : void 0;
9843
- if (!asset) return this.pushEvent(input);
9844
- const snapshot = toEventAsset(asset);
9845
- const announced = ANNOUNCED_STATUS[input.type];
9846
- if (announced) snapshot.classification.moderation.decision = announced;
9847
- return this.pushEvent({
9848
- ...input,
9849
- asset: snapshot
9850
- });
9913
+ return this.pushEvent(input);
9851
9914
  }
9852
9915
  /** Adds an event to the feed, filling the fields the API always sets. */
9853
9916
  pushEvent(input) {
@@ -9859,7 +9922,6 @@ var MockCalmLensApi = class {
9859
9922
  title: input.type,
9860
9923
  description: null,
9861
9924
  assetId: null,
9862
- asset: null,
9863
9925
  actor: MOCK_API_KEY_ACTOR,
9864
9926
  facts: [],
9865
9927
  createdAt: now,
@@ -9871,6 +9933,22 @@ var MockCalmLensApi = class {
9871
9933
  this.eventFeed.push(event);
9872
9934
  return event;
9873
9935
  }
9936
+ /** The `assetSequence` of the latest event about an asset, or 0 before its first. */
9937
+ eventSequenceOf(assetId) {
9938
+ return this.assetEventSequences.get(assetId) ?? 0;
9939
+ }
9940
+ /**
9941
+ * A copy of a stored asset as the API returns it, with its `eventSequence` as it is now. The
9942
+ * mock keeps each asset's sequence itself rather than in `databaseStorage`, whose
9943
+ * implementations needn't know about it, so every asset leaving the mock passes through here
9944
+ * or `publishAssets`.
9945
+ */
9946
+ toPublished(asset) {
9947
+ return {
9948
+ ...structuredClone(asset),
9949
+ eventSequence: this.eventSequenceOf(asset.id)
9950
+ };
9951
+ }
9874
9952
  /** Applies a reviewer's decision to a stored asset (see `MockCalmLensServerClient.decide`). */
9875
9953
  async decide(assetId, decision) {
9876
9954
  if (!REVIEW_DECISIONS.includes(decision)) throw require_ModerationContextLimits.invalidArgument(`decision must be one of ${REVIEW_DECISIONS.join(", ")}`);
@@ -9880,7 +9958,7 @@ var MockCalmLensApi = class {
9880
9958
  } catch (failure) {
9881
9959
  throw this.toError(failure);
9882
9960
  }
9883
- return structuredClone(await this.recordDecision(asset, decision));
9961
+ return this.toPublished(await this.recordDecision(asset, decision));
9884
9962
  }
9885
9963
  /**
9886
9964
  * Finishes processing a pending asset as the pipeline would (see
@@ -9896,13 +9974,13 @@ var MockCalmLensApi = class {
9896
9974
  }
9897
9975
  if (asset.classification.status !== "processing") throw require_ModerationContextLimits.invalidArgument(`asset ${assetId} isn't processing`);
9898
9976
  const settled = decision === void 0 ? void 0 : toDecision(decision);
9899
- return structuredClone(await this.moderateStored(asset, "complete", settled));
9977
+ return this.toPublished(await this.moderateStored(asset, "complete", settled));
9900
9978
  }
9901
9979
  /**
9902
9980
  * `POST /assets/:assetId/decision`, like the API: an asset still uploading or processing can't
9903
9981
  * be decided, one pending moderation can only be blocked or purged, a decision must change the
9904
- * status and purged content can only be blocked. The review is the API key's, and mock API keys
9905
- * have no ID or name, so its ID is `null` and the event names the reviewer "An API key".
9982
+ * status and purged content can only be blocked. The review is the API key's (`MOCK_API_KEY_ID`),
9983
+ * and mock API keys have no name, so the event names the reviewer "An API key".
9906
9984
  */
9907
9985
  async decideAsset(assetId, body) {
9908
9986
  const { decision, note: rawNote } = body;
@@ -9934,10 +10012,7 @@ var MockCalmLensApi = class {
9934
10012
  id: this.createId("rev"),
9935
10013
  decision,
9936
10014
  note: review?.note ?? null,
9937
- decidedBy: {
9938
- type: "api-key",
9939
- id: null
9940
- },
10015
+ decidedBy: MOCK_API_KEY_ACTOR,
9941
10016
  reviewedAt: now,
9942
10017
  applied: true
9943
10018
  }];
@@ -9948,7 +10023,6 @@ var MockCalmLensApi = class {
9948
10023
  severity: decision === "allowed" || decision === "limited" ? "low" : "high",
9949
10024
  title: `asset.${decision}`,
9950
10025
  assetId: stored.id,
9951
- asset: toEventAsset(stored),
9952
10026
  actor: review ? MOCK_API_KEY_ACTOR : MOCK_REVIEWER_ACTOR,
9953
10027
  facts: [
9954
10028
  {
@@ -10026,7 +10100,9 @@ var MockCalmLensApi = class {
10026
10100
  });
10027
10101
  const index = this.pendingFailures.findIndex((pending) => pending.operation === void 0 || operations.includes(pending.operation));
10028
10102
  if (index !== -1) {
10029
- const [{ failure, details, retryAfter }] = this.pendingFailures.splice(index, 1);
10103
+ const pending = this.pendingFailures[index];
10104
+ const { failure, details, retryAfter } = pending;
10105
+ if (--pending.remaining <= 0) this.pendingFailures.splice(index, 1);
10030
10106
  if (typeof failure === "string" && failure in require_ModerationContextLimits.API_ERROR_DEFINITIONS) return this.answered(call, this.failureResponse(fail(failure, { details }), url, retryAfter));
10031
10107
  throw this.toFailureError(failure);
10032
10108
  }
@@ -10103,7 +10179,7 @@ var MockCalmLensApi = class {
10103
10179
  async answer(request, operation, session) {
10104
10180
  const { url, headers } = request;
10105
10181
  if (!(request.segments[0] === "upload-presets") && headers.get("x-api-key") !== this.apiKey) return this.failureResponse(fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_API_KEY), url);
10106
- const key = headers.get("idempotency-key")?.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
10182
+ const key = operation && IDEMPOTENT_OPERATIONS.includes(operation) ? headers.get("idempotency-key")?.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "") : void 0;
10107
10183
  const upload = headers.get("x-calmlens-upload");
10108
10184
  const contentType = headers.get("content-type");
10109
10185
  const isForm = !!upload && /^multipart\/form-data\b/i.test(contentType ?? "");
@@ -10139,7 +10215,7 @@ var MockCalmLensApi = class {
10139
10215
  throw failure;
10140
10216
  }
10141
10217
  const [status, body] = answer;
10142
- const json = JSON.stringify(body ?? {});
10218
+ const json = JSON.stringify(body ?? {}, this.publishAssets);
10143
10219
  const finalStatus = operation ? SUCCESS_STATUS[operation] ?? status : status;
10144
10220
  if (key !== void 0) this.idempotentResults.set(key, {
10145
10221
  fingerprint,
@@ -10177,6 +10253,7 @@ var MockCalmLensApi = class {
10177
10253
  case "PUT metadata-fields": return [200, this.ensureMetadataFields(this.json(request))];
10178
10254
  }
10179
10255
  const [, , collection, itemId, itemAction, ...more] = segments;
10256
+ if (collection === "assets" && itemId === "by-external-id" && itemAction !== void 0 && more.length === 0 && method === "GET") return [200, await this.findByExternalId(itemAction)];
10180
10257
  if (collection === "metadata-fields" && itemId !== void 0 && itemAction === void 0) {
10181
10258
  if (method === "DELETE") return [200, this.deleteMetadataField(itemId, request.query)];
10182
10259
  }
@@ -10213,6 +10290,7 @@ var MockCalmLensApi = class {
10213
10290
  case "POST move": return [200, await this.moveAsset(id, this.json(request))];
10214
10291
  case "POST retry": return [200, await this.retryAsset(id)];
10215
10292
  case "POST decision": return [200, await this.decideAsset(id, this.json(request))];
10293
+ case "POST review-requests": return this.requestReview(id, this.json(request));
10216
10294
  case "DELETE content": return [200, await this.removeContent(await this.findOwnAsset(id))];
10217
10295
  }
10218
10296
  if (root === "folders" && id !== void 0 && rest.length === 0) switch (`${method} ${action ?? ""}`) {
@@ -10495,6 +10573,115 @@ var MockCalmLensApi = class {
10495
10573
  if (!asset || asset.projectId !== this.projectId) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_NOT_FOUND);
10496
10574
  return asset;
10497
10575
  }
10576
+ /** `GET /projects/:projectId/assets/by-external-id/:externalId`: the asset with that external ID. */
10577
+ async findByExternalId(externalId) {
10578
+ const asset = (await this.databaseStorage.listAssets(this.projectId)).find((candidate) => candidate.externalId === externalId);
10579
+ if (!asset) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_NOT_FOUND);
10580
+ return asset;
10581
+ }
10582
+ /**
10583
+ * The review the queue holds for an asset, or undefined when none is waiting. A review a
10584
+ * decision left waiting (`pendingReview`) gets its ID the first time it is read.
10585
+ */
10586
+ pendingReviewOf(asset) {
10587
+ const pending = asset.classification.moderation.pendingReview;
10588
+ if (!pending) {
10589
+ this.pendingReviews.delete(asset.id);
10590
+ return;
10591
+ }
10592
+ let review = this.pendingReviews.get(asset.id);
10593
+ if (!review) {
10594
+ review = {
10595
+ id: this.createId("rev"),
10596
+ assetId: asset.id,
10597
+ reason: pending.reason,
10598
+ status: "pending",
10599
+ note: null,
10600
+ createdAt: pending.requestedAt
10601
+ };
10602
+ this.pendingReviews.set(asset.id, review);
10603
+ }
10604
+ return review;
10605
+ }
10606
+ /**
10607
+ * `POST /assets/:assetId/review-requests`, like the API (publicPostAssetReviewRequest.ts and
10608
+ * getReportRefusal): a held asset is `asset/held`; a child asset, an asset not yet decided, and
10609
+ * a purged one or one whose content is gone are `asset/not-reviewable` with that `reason`. A
10610
+ * review already waiting is returned unchanged with 200; otherwise a `reported` review joins
10611
+ * the queue with 201, the asset's `pendingReview` is set and `asset.review-requested` is
10612
+ * recorded with the API key as its actor.
10613
+ */
10614
+ async requestReview(assetId, body) {
10615
+ const { note: rawNote } = body;
10616
+ if (rawNote !== void 0 && typeof rawNote !== "string") throw invalidField("validation/invalid-type", "note");
10617
+ const note = rawNote?.trim();
10618
+ if (note !== void 0 && !note) throw invalidField("validation/too-small", "note");
10619
+ if (note && note.length > MAX_DECISION_NOTE_LENGTH) throw invalidField("validation/too-big", "note");
10620
+ const asset = await this.findOwnAsset(assetId);
10621
+ if (asset.content.safetyHold) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_HELD, { details: { hold: "safety" } });
10622
+ const decision = asset.classification.moderation.decision;
10623
+ const reason = asset.parentId ? "child-asset" : asset.upload.status === "uploading" || asset.classification.status !== "completed" || decision === null ? "not-moderated" : decision === "purged" || asset.content.status === "removed" ? "content-unavailable" : void 0;
10624
+ if (reason) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_NOT_REVIEWABLE, { details: { reason } });
10625
+ const waiting = this.pendingReviewOf(asset);
10626
+ if (waiting) return [200, waiting];
10627
+ const now = this.now();
10628
+ const review = {
10629
+ id: this.createId("rev"),
10630
+ assetId: asset.id,
10631
+ reason: "reported",
10632
+ status: "pending",
10633
+ note: note ?? null,
10634
+ createdAt: now
10635
+ };
10636
+ this.pendingReviews.set(asset.id, review);
10637
+ const stored = await this.databaseStorage.updateAsset({
10638
+ ...asset,
10639
+ classification: {
10640
+ ...asset.classification,
10641
+ moderation: {
10642
+ ...asset.classification.moderation,
10643
+ pendingReview: {
10644
+ requestedAt: now,
10645
+ reason: "reported",
10646
+ uncertainCategories: []
10647
+ }
10648
+ }
10649
+ }
10650
+ });
10651
+ this.pushEvent({
10652
+ type: "asset.review-requested",
10653
+ severity: "low",
10654
+ assetId: stored.id,
10655
+ facts: [
10656
+ assetNameFact(stored),
10657
+ {
10658
+ key: "asset-type",
10659
+ value: stored.type
10660
+ },
10661
+ {
10662
+ key: "review-id",
10663
+ value: review.id
10664
+ },
10665
+ {
10666
+ key: "automated-status",
10667
+ value: decision
10668
+ },
10669
+ {
10670
+ key: "review-reason",
10671
+ value: "reported"
10672
+ },
10673
+ {
10674
+ key: "uncertain-categories",
10675
+ value: []
10676
+ },
10677
+ ...review.note ? [{
10678
+ key: "note",
10679
+ value: review.note
10680
+ }] : []
10681
+ ]
10682
+ });
10683
+ return [201, review];
10684
+ }
10498
10685
  async listAssets(query) {
10499
10686
  let assets = await this.databaseStorage.listAssets(this.projectId);
10500
10687
  const page = this.pageQuery(query);
@@ -10559,7 +10746,8 @@ var MockCalmLensApi = class {
10559
10746
  if (body.name === null) throw invalidField("validation/invalid-type", "name");
10560
10747
  const asset = await this.findOwnAsset(assetId);
10561
10748
  if (body.externalId) {
10562
- 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);
10749
+ const holder = (await this.databaseStorage.listAssets(this.projectId)).find((other) => other.id !== asset.id && other.externalId === body.externalId);
10750
+ if (holder) throw duplicateExternalId(holder);
10563
10751
  }
10564
10752
  return this.databaseStorage.updateAsset({
10565
10753
  ...asset,
@@ -10812,8 +11000,11 @@ var MockCalmLensApi = class {
10812
11000
  }
10813
11001
  async storeAsset(fields, queue) {
10814
11002
  if (!fields.name) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Asset name is required" });
10815
- const { contentType, part } = fields;
10816
- const bytes = fields.bytes ?? /* @__PURE__ */ new Uint8Array(0);
11003
+ const served = fields.url === void 0 ? void 0 : this.servedContent(fields.url);
11004
+ const fetched = served && inferAssetType(served.type) !== "website" ? served : void 0;
11005
+ const { part } = fields;
11006
+ const contentType = fetched ? fetched.type : fields.contentType;
11007
+ const bytes = fetched?.bytes ?? fields.bytes ?? /* @__PURE__ */ new Uint8Array(0);
10817
11008
  if (contentType !== void 0 && !require_ModerationContextLimits.isAcceptedUploadMimeType(contentType)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, {
10818
11009
  message: require_ModerationContextLimits.getRejectedUploadMimeTypeError(contentType),
10819
11010
  details: {
@@ -10821,13 +11012,13 @@ var MockCalmLensApi = class {
10821
11012
  source: "calmlens"
10822
11013
  }
10823
11014
  });
10824
- const type = fields.url === void 0 ? inferAssetType(contentType ?? "") : urlAssetType(fields.url);
11015
+ const type = served ? inferAssetType(served.type) : fields.url === void 0 ? inferAssetType(contentType ?? "") : urlAssetType(fields.url);
10825
11016
  if (part) {
10826
11017
  if (part.partNumber > 1) throw fail(require_ModerationContextLimits.API_ERROR_CODES.USE_UPLOAD_PART);
10827
11018
  const partSize = bytes.byteLength;
10828
11019
  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);
10829
11020
  if (sizeError) throw this.sizeFailure(sizeError);
10830
- const validation = require_CalmLensOptionKeys.validateAssetPayload({ uint8Array: bytes }, {
11021
+ const validation = require_CalmLensConnection.validateAssetPayload({ uint8Array: bytes }, {
10831
11022
  multipart: true,
10832
11023
  isFinal: part.isFinal
10833
11024
  });
@@ -10839,7 +11030,8 @@ var MockCalmLensApi = class {
10839
11030
  }
10840
11031
  if (fields.folderId) await this.findOwnFolder(fields.folderId);
10841
11032
  if (fields.externalId) {
10842
- if ((await this.databaseStorage.listAssets(this.projectId)).some((asset) => asset.externalId === fields.externalId)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.DUPLICATE_EXTERNAL_ID);
11033
+ const holder = (await this.databaseStorage.listAssets(this.projectId)).find((asset) => asset.externalId === fields.externalId);
11034
+ if (holder) throw duplicateExternalId(holder);
10843
11035
  }
10844
11036
  const id = this.createId("asset");
10845
11037
  const now = this.now();
@@ -10850,7 +11042,7 @@ var MockCalmLensApi = class {
10850
11042
  };
10851
11043
  const keepContent = processingOptions.retainContent === true;
10852
11044
  this.processingOptions.set(id, processingOptions);
10853
- const hasContent = fields.url === void 0;
11045
+ const hasContent = fields.url === void 0 || fetched !== void 0;
10854
11046
  const contextItems = require_ModerationContextLimits.selectModerationContextItems(fields.context?.items ?? []);
10855
11047
  const asset = {
10856
11048
  id,
@@ -10871,6 +11063,7 @@ var MockCalmLensApi = class {
10871
11063
  context: contextItems.length ? { items: contextItems } : null,
10872
11064
  tags: fields.tags ?? [],
10873
11065
  visibility: fields.visibility ?? "private",
11066
+ eventSequence: 0,
10874
11067
  content: {
10875
11068
  status: keepContent ? "stored" : "temporary",
10876
11069
  removalReason: null,
@@ -10968,7 +11161,7 @@ var MockCalmLensApi = class {
10968
11161
  const upload = this.openUploads.get(assetId);
10969
11162
  const sizeError = this.multipartImageSizeError(asset.type, received) ?? this.multipartTotalSizeError(upload?.totalSizeInBytes, received, isFinal);
10970
11163
  if (sizeError) throw this.sizeFailure(sizeError);
10971
- const validation = require_CalmLensOptionKeys.validateAssetPayload({ uint8Array: bytes }, {
11164
+ const validation = require_CalmLensConnection.validateAssetPayload({ uint8Array: bytes }, {
10972
11165
  multipart: true,
10973
11166
  isFinal
10974
11167
  });
@@ -11021,22 +11214,90 @@ var MockCalmLensApi = class {
11021
11214
  return receivedSizeInBytes > totalSizeInBytes || isFinal && receivedSizeInBytes !== totalSizeInBytes ? require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_SIZE_MISMATCH : void 0;
11022
11215
  }
11023
11216
  /**
11217
+ * The content a URL upload fetches from a URL `serveUrl` registered, or undefined: then the
11218
+ * mock fetches nothing, and the URL's path's extension types it.
11219
+ */
11220
+ servedContent(url) {
11221
+ let key;
11222
+ try {
11223
+ key = new URL(url).href;
11224
+ } catch {
11225
+ return;
11226
+ }
11227
+ const served = this.servedUrls.get(key);
11228
+ return served && {
11229
+ bytes: served.bytes.slice(),
11230
+ type: served.type
11231
+ };
11232
+ }
11233
+ /** An asset's stored content, its parts in order, or `null` once it is removed. */
11234
+ async storedBytes(asset) {
11235
+ if (asset.content.status === "removed") return null;
11236
+ const stored = await this.imageStorage.getContent(asset.id);
11237
+ if (!stored) return null;
11238
+ const parts = [...stored.parts].sort(([a], [b]) => a - b).map(([, part]) => part);
11239
+ return new Uint8Array(await new Blob(parts).arrayBuffer());
11240
+ }
11241
+ /**
11242
+ * A decided image with its hash and the project's hash list matches, as the API records them
11243
+ * (AssetClassification.ts, Project.ts and HashList.ts). The mock computes no PDQ hash: an
11244
+ * image's `content.perceptualHash` is the SHA-256 of its bytes in lowercase hex, with quality
11245
+ * 100, so an entry matches an image whose bytes equal those it was taken from, at distance 0.
11246
+ * Entries below quality 50 never match. Each match takes its list's action, blocking matches
11247
+ * first; a block raises an allowed, limited or age-restricted decision to `blocked`, with
11248
+ * `source: "hash-list"`, and a flag only records the match.
11249
+ */
11250
+ async withHashMatches(asset, bytes) {
11251
+ const hash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
11252
+ const matches = [...this.hashListEntries.values()].filter((entry) => entry.hash === hash && (entry.quality === null || entry.quality >= HASH_MATCH_MIN_QUALITY) && this.hashLists.has(entry.hashListId)).map((entry) => ({
11253
+ source: "hash-list",
11254
+ hashListId: entry.hashListId,
11255
+ hashListEntryId: entry.id,
11256
+ distance: 0,
11257
+ action: this.hashLists.get(entry.hashListId).action
11258
+ })).sort((a, b) => Number(b.action === "block") - Number(a.action === "block")).slice(0, MAX_RECORDED_HASH_MATCHES);
11259
+ const hashed = {
11260
+ ...asset,
11261
+ content: {
11262
+ ...asset.content,
11263
+ perceptualHash: hash,
11264
+ perceptualHashQuality: 100
11265
+ }
11266
+ };
11267
+ if (!matches.length) return hashed;
11268
+ const { moderation } = asset.classification;
11269
+ const raised = matches.some((match) => match.action === "block") && (moderation.decision === "allowed" || moderation.decision === "limited" || moderation.decision === "age-restricted");
11270
+ return {
11271
+ ...hashed,
11272
+ classification: {
11273
+ ...asset.classification,
11274
+ moderation: {
11275
+ ...moderation,
11276
+ ...raised && {
11277
+ decision: "blocked",
11278
+ automatedStatus: "blocked",
11279
+ source: "hash-list"
11280
+ },
11281
+ raw: {
11282
+ ...moderation.raw,
11283
+ hashMatches: matches
11284
+ }
11285
+ }
11286
+ }
11287
+ };
11288
+ }
11289
+ /**
11024
11290
  * Asks `moderate` how to decide `asset`, with its content: `bytes` when the caller has them,
11025
11291
  * otherwise the stored parts in order (none once the content is removed).
11026
11292
  */
11027
11293
  async decisionFor(asset, trigger, queued, bytes) {
11028
- let data = bytes;
11029
- if (data === void 0) {
11030
- const stored = asset.content.status === "removed" ? void 0 : await this.imageStorage.getContent(asset.id);
11031
- const parts = stored ? [...stored.parts].sort(([a], [b]) => a - b).map(([, part]) => part) : [];
11032
- data = stored ? new Uint8Array(await new Blob(parts).arrayBuffer()) : null;
11033
- }
11294
+ const data = bytes === void 0 ? await this.storedBytes(asset) : bytes;
11034
11295
  const content = {
11035
11296
  bytes: data,
11036
11297
  text: data && asset.type === "plaintext-document" ? new TextDecoder().decode(data) : null
11037
11298
  };
11038
11299
  return toDecision(await this.options.moderate({
11039
- asset: structuredClone(asset),
11300
+ asset: this.toPublished(asset),
11040
11301
  content,
11041
11302
  trigger,
11042
11303
  queued
@@ -11047,9 +11308,11 @@ var MockCalmLensApi = class {
11047
11308
  * it, a decided image reports the person and face detection its upload turned on.
11048
11309
  */
11049
11310
  async decided(asset, decision) {
11050
- const next = await this.applyOutcome(asset, decision.status, "policy", decision.report(this.now()));
11311
+ const image = asset.type === "image" ? await this.storedBytes(asset) : null;
11312
+ const outcome = await this.applyOutcome(asset, decision.status, "policy", decision.report(this.now()));
11051
11313
  const features = this.processingOptions.get(asset.id)?.features;
11052
- if (next.classification.status !== "completed" || asset.type !== "image") return next;
11314
+ if (outcome.classification.status !== "completed" || asset.type !== "image") return outcome;
11315
+ const next = image ? await this.withHashMatches(outcome, image) : outcome;
11053
11316
  const ocr = features?.ocr?.enabled === true ? decision.ocrFindings : void 0;
11054
11317
  const ages = features?.faceDetection?.ageEstimation === true;
11055
11318
  return {
@@ -11108,7 +11371,6 @@ var MockCalmLensApi = class {
11108
11371
  type: "asset.uploaded",
11109
11372
  severity: "low",
11110
11373
  assetId: asset.id,
11111
- asset: toEventAsset(asset),
11112
11374
  facts: [
11113
11375
  {
11114
11376
  key: "asset-type",
@@ -11131,7 +11393,6 @@ var MockCalmLensApi = class {
11131
11393
  if (decision.status === "pending") return;
11132
11394
  const event = {
11133
11395
  assetId: asset.id,
11134
- asset: toEventAsset(asset),
11135
11396
  actor: AUTOMATED_ACTOR
11136
11397
  };
11137
11398
  if (decision.status === "failed") {
@@ -11158,6 +11419,7 @@ var MockCalmLensApi = class {
11158
11419
  return;
11159
11420
  }
11160
11421
  const flaggedCategories = decision.report()?.flaggedCategories ?? [];
11422
+ const status = asset.classification.moderation.decision ?? decision.status;
11161
11423
  this.pushEvent({
11162
11424
  ...event,
11163
11425
  type: "asset.classified",
@@ -11169,7 +11431,7 @@ var MockCalmLensApi = class {
11169
11431
  },
11170
11432
  {
11171
11433
  key: "moderation-status",
11172
- value: decision.status
11434
+ value: status
11173
11435
  },
11174
11436
  {
11175
11437
  key: "asset-type",
@@ -11180,8 +11442,8 @@ var MockCalmLensApi = class {
11180
11442
  });
11181
11443
  this.pushEvent({
11182
11444
  ...event,
11183
- type: `asset.${decision.status}`,
11184
- severity: decision.status === "allowed" || decision.status === "limited" ? "low" : "high",
11445
+ type: `asset.${status}`,
11446
+ severity: status === "allowed" || status === "limited" ? "low" : "high",
11185
11447
  facts: [
11186
11448
  {
11187
11449
  key: "flagged-categories",
@@ -11194,6 +11456,36 @@ var MockCalmLensApi = class {
11194
11456
  assetNameFact(asset)
11195
11457
  ]
11196
11458
  });
11459
+ const match = asset.classification.moderation.raw?.hashMatches?.[0];
11460
+ if (match) this.pushEvent({
11461
+ ...event,
11462
+ type: "asset.hash-matched",
11463
+ severity: "high",
11464
+ facts: [
11465
+ {
11466
+ key: "hash-list-id",
11467
+ value: match.hashListId
11468
+ },
11469
+ {
11470
+ key: "hash-list-name",
11471
+ value: this.hashLists.get(match.hashListId)?.name ?? "",
11472
+ url: `https://calmlens.com/go/hash-list/${encodeURIComponent(match.hashListId)}`
11473
+ },
11474
+ {
11475
+ key: "distance",
11476
+ value: match.distance
11477
+ },
11478
+ {
11479
+ key: "match-action",
11480
+ value: match.action
11481
+ },
11482
+ {
11483
+ key: "asset-type",
11484
+ value: asset.type
11485
+ },
11486
+ assetNameFact(asset)
11487
+ ]
11488
+ });
11197
11489
  }
11198
11490
  /**
11199
11491
  * Moves an asset to `outcome` like the pipeline would: a decision finishes processing, `purged`
@@ -11252,7 +11544,6 @@ var MockCalmLensApi = class {
11252
11544
  actor,
11253
11545
  severity: "low",
11254
11546
  assetId: asset.id,
11255
- asset: toEventAsset(asset),
11256
11547
  facts: [
11257
11548
  {
11258
11549
  key: "asset-name",
@@ -11768,12 +12059,11 @@ var MockCalmLensApi = class {
11768
12059
  if (asset.content.safetyHold) return notAvailable();
11769
12060
  if (resource === "placeholder") {
11770
12061
  if (asset.visibility !== "public" && !grant && !canDownload()) return notFound();
11771
- if (status === "blocked" && !grant && !canDownload()) return notAvailable();
11772
12062
  const thumbhash = preview?.thumbhash;
11773
12063
  if (!thumbhash || status === "purged") return notAvailable();
11774
12064
  return this.cdnResponse(isHead, mockPlaceholderPng(thumbhash), url, {
11775
12065
  "Content-Type": "image/png",
11776
- "Cache-Control": asset.visibility !== "public" || status === "blocked" ? "private, no-store" : "public, no-cache",
12066
+ "Cache-Control": asset.visibility !== "public" ? "private, no-store" : "public, no-cache",
11777
12067
  "Cache-Tag": `asset-${asset.id}`,
11778
12068
  ETag: `"${thumbhash}"`
11779
12069
  });
@@ -11900,9 +12190,9 @@ var InMemoryMockImageStorage = class {
11900
12190
  this.content = /* @__PURE__ */ new Map();
11901
12191
  }
11902
12192
  async putContent(assetId, content) {
11903
- const validation = require_CalmLensOptionKeys.validateAssetPayload(content);
12193
+ const validation = require_CalmLensConnection.validateAssetPayload(content);
11904
12194
  if (!validation.ok) throw new Error(validation.error);
11905
- const bytes = await require_CalmLensOptionKeys.assetDataToUint8Array(require_CalmLensOptionKeys.assetToData(content));
12195
+ const bytes = await require_CalmLensConnection.assetDataToUint8Array(require_CalmLensConnection.assetToData(content));
11906
12196
  this.content.set(assetId, {
11907
12197
  assetId,
11908
12198
  parts: /* @__PURE__ */ new Map([[1, bytes]]),
@@ -11910,12 +12200,12 @@ var InMemoryMockImageStorage = class {
11910
12200
  });
11911
12201
  }
11912
12202
  async putPart(assetId, part) {
11913
- const validation = require_CalmLensOptionKeys.validateAssetPayload(part, {
12203
+ const validation = require_CalmLensConnection.validateAssetPayload(part, {
11914
12204
  multipart: true,
11915
12205
  isFinal: part.isFinal
11916
12206
  });
11917
12207
  if (!validation.ok) throw new Error(validation.error);
11918
- const bytes = await require_CalmLensOptionKeys.assetDataToUint8Array(require_CalmLensOptionKeys.assetToData(part));
12208
+ const bytes = await require_CalmLensConnection.assetDataToUint8Array(require_CalmLensConnection.assetToData(part));
11919
12209
  const existing = this.content.get(assetId) ?? {
11920
12210
  assetId,
11921
12211
  parts: /* @__PURE__ */ new Map(),
@@ -12003,7 +12293,7 @@ const mockClientOptions = (api, endpoints, session) => {
12003
12293
  fetch,
12004
12294
  uploadFetch: fetch,
12005
12295
  cdnFetch: fetch,
12006
- [require_CalmLensOptionKeys.MOCK_HOOKS]: hooks
12296
+ [require_CalmLensConnection.MOCK_HOOKS]: hooks
12007
12297
  };
12008
12298
  };
12009
12299
  /**
@@ -12091,14 +12381,40 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
12091
12381
  }
12092
12382
  /**
12093
12383
  * Makes the next request (or the next one `operation` sends) fail instead of reaching the
12094
- * in-memory API. Each queued failure fails one request, so a retry takes the next queued
12095
- * failure or reaches the API. An API error code answers with that error and its HTTP status,
12096
- * with `details` and a `Retry-After` of `retryAfter` seconds when given.
12384
+ * in-memory API, or the next `times` of them. Each queued failure fails that many requests, so
12385
+ * a retry takes it again until it is used up, then the next queued failure or the API. A
12386
+ * request takes the oldest queued failure that matches it. An API error code answers with that
12387
+ * error and its HTTP status, with `details` and a `Retry-After` of `retryAfter` seconds when
12388
+ * given.
12097
12389
  */
12098
12390
  failNextRequest(failure = "transport-error", options = {}) {
12099
12391
  this.#api.failNextRequest(failure, options);
12100
12392
  }
12101
12393
  /**
12394
+ * Makes every request (or every one `operation` sends) fail as `failNextRequest` would, until
12395
+ * `clearFailures`. Queued after other failures, it fails the requests they don't.
12396
+ */
12397
+ failRequests(failure = "transport-error", options = {}) {
12398
+ if (options && "times" in options) throw require_ModerationContextLimits.invalidArgument("failRequests fails every request: use failNextRequest for times");
12399
+ this.#api.failNextRequest(failure, {
12400
+ ...options,
12401
+ times: Number.POSITIVE_INFINITY
12402
+ });
12403
+ }
12404
+ /** Drops every failure `failNextRequest` and `failRequests` queued. */
12405
+ clearFailures() {
12406
+ this.#api.clearFailures();
12407
+ }
12408
+ /**
12409
+ * Makes `url` answer with `content` (bytes, or text as UTF-8) and `type` when a URL upload
12410
+ * fetches it. The upload then stores that content and is typed by `type`, as an upload of the
12411
+ * bytes would be: `image/png` is an image, and `text/html` a website. A URL not served this way
12412
+ * is typed by its path's extension, and has no content.
12413
+ */
12414
+ serveUrl(url, content) {
12415
+ this.#api.serveUrl(url, content);
12416
+ }
12417
+ /**
12102
12418
  * Changes the grants of the mock's API key, as editing the key in the portal would: later
12103
12419
  * requests, such as `cdn.serve`, use them. The key itself stays the same, so idempotency keys
12104
12420
  * it used still replay.
@@ -12148,6 +12464,7 @@ var MockCalmLensAppClient = class extends require_CalmLensAppClient.CalmLensAppC
12148
12464
  constructor(options) {
12149
12465
  require_ModerationContextLimits.validateAppClientOptions(options);
12150
12466
  const { mockOptions = {}, ...clientOptions } = options;
12467
+ if (mockOptions.preset) checkMockUploadPreset(mockOptions.preset);
12151
12468
  const server = mockOptions.server ?? new MockCalmLensServerClient({
12152
12469
  apiKey: createMockApiKey([{
12153
12470
  actions: [
@@ -12197,7 +12514,6 @@ const toWebhookEventPayload = (event) => ({
12197
12514
  description: event.description ?? null,
12198
12515
  assetId: event.assetId ?? null,
12199
12516
  assetSequence: event.assetSequence ?? null,
12200
- asset: event.asset ?? null,
12201
12517
  facts: event.facts,
12202
12518
  createdAt: event.createdAt
12203
12519
  });
@@ -12216,6 +12532,7 @@ const createWebhookHeaders = async (options) => {
12216
12532
  exports.InMemoryMockDatabaseStorage = InMemoryMockDatabaseStorage;
12217
12533
  exports.InMemoryMockImageStorage = InMemoryMockImageStorage;
12218
12534
  exports.MEDIA_TEST_SIGNALS = MEDIA_TEST_SIGNALS;
12535
+ exports.MOCK_API_KEY_ID = MOCK_API_KEY_ID;
12219
12536
  exports.MOCK_API_KEY_PREFIX = MOCK_API_KEY_PREFIX;
12220
12537
  exports.MockCalmLensAppClient = MockCalmLensAppClient;
12221
12538
  exports.MockCalmLensServerClient = MockCalmLensServerClient;