calmlens 0.28.1 → 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.
- package/bin/calmlens.js +151 -123
- package/cjs/{BrowserUpload-DLoi5qVj.js → BrowserUpload-CcSQI7Kf.js} +1 -1
- package/cjs/{BrowserUpload-CRbCsX7a.d.ts → BrowserUpload-CeGsM9h1.d.ts} +2 -2
- package/cjs/{CalmLensAppClient-C--UAnoz.js → CalmLensAppClient-BPILD5mg.js} +11 -17
- package/cjs/{CalmLensAppClient-B3u6BlP5.d.ts → CalmLensAppClient-D-BD_Ny1.d.ts} +7 -1
- package/cjs/{CalmLensOptionKeys-BxrJ47zd.js → CalmLensConnection-Wfxn25LT.js} +660 -643
- package/cjs/{CalmLensServerClient-B8ntjNL3.d.ts → CalmLensServerClient-BYN_N0lt.d.ts} +33 -2
- package/cjs/{CalmLensServerClient-CPbCEJMK.js → CalmLensServerClient-C_42j_i4.js} +72 -41
- package/cjs/{CalmLensTypes-CtO4Dieu.d.ts → CalmLensTypes-C2blKgTu.d.ts} +51 -75
- package/{esm/Core-BJaLU71Q.d.ts → cjs/Core-CNmoxDCW.d.ts} +2 -2
- package/cjs/{Core-CB0-p-ro.js → Core-CfdovxKJ.js} +2 -2
- package/cjs/{ModerationContextLimits-CuL1TOuf.js → ModerationContextLimits-DXlPrt4K.js} +24 -13
- package/cjs/{ReactUpload-3QgzpdMu.js → ReactUpload-CzsQwVKM.js} +1 -1
- package/{esm/ReactUpload-BGUkcMpg.d.ts → cjs/ReactUpload-kqEe6gcN.d.ts} +1 -1
- package/cjs/{UploadController-BSZnq84V.js → UploadController-D_Y5wktq.js} +2 -2
- package/{esm/WebhookPayload-DZadhbAJ.d.ts → cjs/WebhookPayload-DZWlnvcY.d.ts} +3 -2
- package/cjs/app.d.ts +5 -5
- package/cjs/app.js +2 -2
- package/cjs/elements.d.ts +4 -4
- package/cjs/elements.js +4 -4
- package/cjs/{index-DQUZYLVY.d.ts → index-Dl2qwS8L.d.ts} +2 -2
- package/cjs/index.d.ts +4 -4
- package/cjs/index.js +1 -1
- package/cjs/react-native.d.ts +2 -2
- package/cjs/react-native.js +4 -4
- package/cjs/react.d.ts +4 -4
- package/cjs/react.js +5 -5
- package/cjs/server.d.ts +5 -5
- package/cjs/server.js +2 -2
- package/cjs/testing.d.ts +54 -26
- package/cjs/testing.js +413 -93
- package/cjs/{ui-BGywTQ2M.d.ts → ui-BtmJC-f9.d.ts} +2 -2
- package/cjs/{ui-CkQQm3Qw.js → ui-CkOexkAO.js} +2 -2
- package/cjs/ui.d.ts +2 -2
- package/cjs/ui.js +3 -3
- package/cjs/vue.d.ts +5 -5
- package/cjs/vue.js +4 -4
- package/esm/{BrowserUpload-CRbCsX7a.d.ts → BrowserUpload-CeGsM9h1.d.ts} +2 -2
- package/esm/{BrowserUpload-BKrrHzoh.js → BrowserUpload-DJ2euKyv.js} +1 -1
- package/esm/{CalmLensAppClient-D_SprSKl.js → CalmLensAppClient-CCT5Em2S.js} +3 -9
- package/esm/{CalmLensAppClient-B3u6BlP5.d.ts → CalmLensAppClient-D-BD_Ny1.d.ts} +7 -1
- package/esm/{CalmLensOptionKeys-B6an7neE.js → CalmLensConnection-CfBXkam-.js} +661 -644
- package/esm/{CalmLensServerClient-B8ntjNL3.d.ts → CalmLensServerClient-BYN_N0lt.d.ts} +33 -2
- package/esm/{CalmLensServerClient-BY45aX5Q.js → CalmLensServerClient-e6gVcMxy.js} +58 -27
- package/esm/{CalmLensTypes-CtO4Dieu.d.ts → CalmLensTypes-C2blKgTu.d.ts} +51 -75
- package/{cjs/Core-BJaLU71Q.d.ts → esm/Core-CNmoxDCW.d.ts} +2 -2
- package/esm/{Core-dzPyrg_G.js → Core-CojlqrKH.js} +2 -2
- package/esm/{ModerationContextLimits-IH2zX1wg.js → ModerationContextLimits-Abu_L1Df.js} +24 -13
- package/esm/{ReactUpload-4DeUbua_.js → ReactUpload-CDrA7hRn.js} +1 -1
- package/{cjs/ReactUpload-BGUkcMpg.d.ts → esm/ReactUpload-kqEe6gcN.d.ts} +1 -1
- package/esm/{UploadController-DKjI8S2K.js → UploadController-BubUXclM.js} +2 -2
- package/{cjs/WebhookPayload-DZadhbAJ.d.ts → esm/WebhookPayload-DZWlnvcY.d.ts} +3 -2
- package/esm/app.d.ts +5 -5
- package/esm/app.js +2 -2
- package/esm/elements.d.ts +4 -4
- package/esm/elements.js +4 -4
- package/esm/{index-DQUZYLVY.d.ts → index-Dl2qwS8L.d.ts} +2 -2
- package/esm/index.d.ts +4 -4
- package/esm/index.js +1 -1
- package/esm/react-native.d.ts +2 -2
- package/esm/react-native.js +4 -4
- package/esm/react.d.ts +4 -4
- package/esm/react.js +5 -5
- package/esm/server.d.ts +5 -5
- package/esm/server.js +2 -2
- package/esm/testing.d.ts +54 -26
- package/esm/testing.js +406 -87
- package/esm/{ui-BovDqg9n.js → ui--AzgLLVf.js} +2 -2
- package/esm/{ui-BGywTQ2M.d.ts → ui-BtmJC-f9.d.ts} +2 -2
- package/esm/ui.d.ts +2 -2
- package/esm/ui.js +3 -3
- package/esm/vue.d.ts +5 -5
- package/esm/vue.js +4 -4
- package/package.json +1 -1
package/esm/testing.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { A as MAX_IMAGE_UPLOAD_BYTES, D as validateServerClientOptions, F as sleep, M as getRejectedUploadMimeTypeError, N as normalizeUploadMimeType, Q as CalmLensError, T as validateAppClientOptions, _ as isAcceptedUploadMimeType, b as randomUuid, dt as invalidConfig, ft as API_ERROR_CODES, h as checkTransformOptions, i as ASSET_RESOURCE_PATHS, lt as SDK_ERROR_CODES, pt as API_ERROR_DEFINITIONS, r as selectModerationContextItems, ut as invalidArgument, v as parseTransformSelector } from "./ModerationContextLimits-
|
|
2
|
-
import { a as WEBHOOK_TIMESTAMP_HEADER, f as signUploadTokenWithApiKey, m as stringifyJsonCanonical, n as WEBHOOK_DELIVERY_HEADER, p as decodeUploadToken, r as WEBHOOK_SIGNATURE_HEADER, t as CalmLensServerClient } from "./CalmLensServerClient-
|
|
3
|
-
import { _ as validateAssetPayload,
|
|
1
|
+
import { A as MAX_IMAGE_UPLOAD_BYTES, D as validateServerClientOptions, F as sleep, M as getRejectedUploadMimeTypeError, N as normalizeUploadMimeType, Q as CalmLensError, T as validateAppClientOptions, _ as isAcceptedUploadMimeType, b as randomUuid, dt as invalidConfig, ft as API_ERROR_CODES, h as checkTransformOptions, i as ASSET_RESOURCE_PATHS, lt as SDK_ERROR_CODES, pt as API_ERROR_DEFINITIONS, r as selectModerationContextItems, ut as invalidArgument, v as parseTransformSelector } from "./ModerationContextLimits-Abu_L1Df.js";
|
|
2
|
+
import { a as WEBHOOK_TIMESTAMP_HEADER, f as signUploadTokenWithApiKey, m as stringifyJsonCanonical, n as WEBHOOK_DELIVERY_HEADER, p as decodeUploadToken, r as WEBHOOK_SIGNATURE_HEADER, t as CalmLensServerClient } from "./CalmLensServerClient-e6gVcMxy.js";
|
|
3
|
+
import { _ as validateAssetPayload, g as assetToData, h as assetDataToUint8Array, n as MOCK_HOOKS } from "./CalmLensConnection-CfBXkam-.js";
|
|
4
4
|
import { t as hmacSha256Hex } from "./CryptoUtils-BLCa-oZe-DKr3LmN6.js";
|
|
5
|
-
import { t as CalmLensAppClient } from "./CalmLensAppClient-
|
|
6
|
-
import { o as placeholderHashToDataURL, r as isFileAccepted } from "./UploadController-
|
|
5
|
+
import { t as CalmLensAppClient } from "./CalmLensAppClient-CCT5Em2S.js";
|
|
6
|
+
import { o as placeholderHashToDataURL, r as isFileAccepted } from "./UploadController-BubUXclM.js";
|
|
7
7
|
import { d as getTestInputTag, h as CLASSIFICATION_CATEGORIES, m as lazySchema } from "./TestTriggers-uL2Ec8Vt-DYbTEJWm.js";
|
|
8
8
|
import * as zod from "zod";
|
|
9
9
|
// src/contract/MediaTestTriggers.js
|
|
@@ -8137,6 +8137,11 @@ const getMockApiKeyGrants = (apiKey) => {
|
|
|
8137
8137
|
return [];
|
|
8138
8138
|
}
|
|
8139
8139
|
};
|
|
8140
|
+
/**
|
|
8141
|
+
* The ID of every mock API key, as the `id` of the `actor` and `decidedBy` its requests record,
|
|
8142
|
+
* where CalmLens gives your key's own ID.
|
|
8143
|
+
*/
|
|
8144
|
+
const MOCK_API_KEY_ID = "key_mock0000000000000000";
|
|
8140
8145
|
// src/testing/MockClassification.ts
|
|
8141
8146
|
/** The parent categories, in the API's order. */
|
|
8142
8147
|
const MOCK_CATEGORIES = [
|
|
@@ -9265,6 +9270,7 @@ const MOCK_OPERATIONS = [
|
|
|
9265
9270
|
"assets.list",
|
|
9266
9271
|
"assets.search",
|
|
9267
9272
|
"assets.retrieve",
|
|
9273
|
+
"assets.retrieveByExternalId",
|
|
9268
9274
|
"assets.waitForDecision",
|
|
9269
9275
|
"assets.update",
|
|
9270
9276
|
"assets.listChildren",
|
|
@@ -9275,6 +9281,7 @@ const MOCK_OPERATIONS = [
|
|
|
9275
9281
|
"assets.move",
|
|
9276
9282
|
"assets.retry",
|
|
9277
9283
|
"assets.decide",
|
|
9284
|
+
"assets.requestReview",
|
|
9278
9285
|
"assets.removeContent",
|
|
9279
9286
|
"assets.delete",
|
|
9280
9287
|
"assets.batch",
|
|
@@ -9283,6 +9290,7 @@ const MOCK_OPERATIONS = [
|
|
|
9283
9290
|
"cdn.getAssetInfo",
|
|
9284
9291
|
"cdn.signAssetUrl",
|
|
9285
9292
|
"events.list",
|
|
9293
|
+
"events.retrieveAsset",
|
|
9286
9294
|
"folders.list",
|
|
9287
9295
|
"folders.retrieve",
|
|
9288
9296
|
"folders.create",
|
|
@@ -9323,14 +9331,36 @@ const MOCK_OPERATIONS = [
|
|
|
9323
9331
|
"metadataFields.ensure",
|
|
9324
9332
|
"metadataFields.delete"
|
|
9325
9333
|
];
|
|
9334
|
+
/** The keys a `MockUploadPreset` takes; `checkMockUploadPreset` refuses any other. */
|
|
9335
|
+
const MOCK_UPLOAD_PRESET_KEYS = [
|
|
9336
|
+
"access",
|
|
9337
|
+
"allowedContentTypes",
|
|
9338
|
+
"maxSizeInBytes",
|
|
9339
|
+
"revealDecision",
|
|
9340
|
+
"visibility",
|
|
9341
|
+
"folderId",
|
|
9342
|
+
"processingOptions"
|
|
9343
|
+
];
|
|
9344
|
+
/**
|
|
9345
|
+
* Throws `sdk/invalid-argument` naming each key a mock upload preset doesn't take, such as a
|
|
9346
|
+
* misspelt or renamed one, instead of silently ignoring it.
|
|
9347
|
+
*/
|
|
9348
|
+
const checkMockUploadPreset = (preset) => {
|
|
9349
|
+
const unknown = Object.keys(preset).filter((key) => !MOCK_UPLOAD_PRESET_KEYS.includes(key));
|
|
9350
|
+
if (unknown.length) throw invalidArgument(`Unknown mockOptions.preset key${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")}`, { options: unknown });
|
|
9351
|
+
};
|
|
9326
9352
|
const MAX_PAGE_SIZE = 100;
|
|
9353
|
+
/** Entries with a lower PDQ quality never match (HashList.ts, HASH_MATCH_MIN_QUALITY). */
|
|
9354
|
+
const HASH_MATCH_MIN_QUALITY = 50;
|
|
9355
|
+
/** The most hash matches an asset records (HashList.ts). */
|
|
9356
|
+
const MAX_RECORDED_HASH_MATCHES = 10;
|
|
9327
9357
|
const MAX_DECISION_NOTE_LENGTH = 1499;
|
|
9328
9358
|
/** How the API names a reviewer acting through an unnamed API key. */
|
|
9329
9359
|
const API_KEY_REVIEWER_NAME = "An API key";
|
|
9330
|
-
/** The actor of events the mock's API key causes
|
|
9360
|
+
/** The actor of events and reviews the mock's API key causes. */
|
|
9331
9361
|
const MOCK_API_KEY_ACTOR = {
|
|
9332
9362
|
type: "api-key",
|
|
9333
|
-
id:
|
|
9363
|
+
id: MOCK_API_KEY_ID
|
|
9334
9364
|
};
|
|
9335
9365
|
/** The actor of a reviewer's decision through the `decide` test hook. */
|
|
9336
9366
|
const MOCK_REVIEWER_ACTOR = {
|
|
@@ -9363,27 +9393,8 @@ const isActiveContentType = (type) => {
|
|
|
9363
9393
|
"text/xml"
|
|
9364
9394
|
].includes(normalized) || normalized.endsWith("+xml")));
|
|
9365
9395
|
};
|
|
9366
|
-
/**
|
|
9367
|
-
const
|
|
9368
|
-
id: asset.id,
|
|
9369
|
-
externalId: asset.externalId ?? null,
|
|
9370
|
-
uploadPresetId: asset.uploadPresetId ?? null,
|
|
9371
|
-
upload: { status: asset.upload.status },
|
|
9372
|
-
classification: {
|
|
9373
|
-
status: asset.classification.status,
|
|
9374
|
-
testInput: asset.classification.testInput,
|
|
9375
|
-
moderation: { decision: asset.classification.moderation.decision }
|
|
9376
|
-
},
|
|
9377
|
-
content: { status: asset.content.status }
|
|
9378
|
-
});
|
|
9379
|
-
/** The moderation status each `asset.<status>` event announces. */
|
|
9380
|
-
const ANNOUNCED_STATUS = {
|
|
9381
|
-
"asset.allowed": "allowed",
|
|
9382
|
-
"asset.limited": "limited",
|
|
9383
|
-
"asset.age-restricted": "age-restricted",
|
|
9384
|
-
"asset.blocked": "blocked",
|
|
9385
|
-
"asset.purged": "purged"
|
|
9386
|
-
};
|
|
9396
|
+
/** Whether a value in a response body is an asset: its ID is an asset ID and it has its states. */
|
|
9397
|
+
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;
|
|
9387
9398
|
/** A `moderate` answer or `completeProcessing` decision as a checked `MockDecision`. */
|
|
9388
9399
|
const toDecision = (value) => {
|
|
9389
9400
|
if (value instanceof MockDecision) return value;
|
|
@@ -9525,7 +9536,8 @@ const urlAssetType = (url) => {
|
|
|
9525
9536
|
};
|
|
9526
9537
|
/** An asset's type from its content type. */
|
|
9527
9538
|
const inferAssetType = (contentType) => {
|
|
9528
|
-
const type = contentType.toLowerCase();
|
|
9539
|
+
const type = contentType.toLowerCase().split(";", 1)[0].trim();
|
|
9540
|
+
if (type === "text/html" || type === "application/xhtml+xml") return "website";
|
|
9529
9541
|
if (type.startsWith("image/")) return "image";
|
|
9530
9542
|
if (type.startsWith("video/")) return "video";
|
|
9531
9543
|
if (type.startsWith("audio/")) return "audio";
|
|
@@ -9542,6 +9554,11 @@ var ApiFailure = class {
|
|
|
9542
9554
|
this.details = details;
|
|
9543
9555
|
}
|
|
9544
9556
|
};
|
|
9557
|
+
/**
|
|
9558
|
+
* `asset/duplicate-external-id`, naming the stored asset that holds the external ID in
|
|
9559
|
+
* `details.assetId`, like the API.
|
|
9560
|
+
*/
|
|
9561
|
+
const duplicateExternalId = (holder) => fail(API_ERROR_CODES.DUPLICATE_EXTERNAL_ID, { details: { assetId: holder.id } });
|
|
9545
9562
|
const fail = (code, { message, details } = {}) => new ApiFailure(API_ERROR_DEFINITIONS[code].status, code, message ?? API_ERROR_DEFINITIONS[code].message, details);
|
|
9546
9563
|
/**
|
|
9547
9564
|
* A request the API's schema refuses: `validation/invalid-request` with HTTP 400, listing the field
|
|
@@ -9712,6 +9729,7 @@ const operationsOf = (request) => {
|
|
|
9712
9729
|
if (query.get("wait") === "false") return ["assets.create"];
|
|
9713
9730
|
return isTextUpload(request) ? ["text.classify"] : ["assets.classify"];
|
|
9714
9731
|
}
|
|
9732
|
+
if (segments[2] === "assets" && segments[3] === "by-external-id" && segments.length === 5) return ["assets.retrieveByExternalId"];
|
|
9715
9733
|
if (segments[2] === "assets" && segments[4] === "timeline" && segments.length === 5) return ["assets.listTimeline"];
|
|
9716
9734
|
if (segments[2] === "metadata-fields" && segments.length === 4) return ["metadataFields.delete"];
|
|
9717
9735
|
return [];
|
|
@@ -9743,16 +9761,34 @@ const operationsOf = (request) => {
|
|
|
9743
9761
|
if (root === "hash-list-entries" && id !== void 0) return ["hashLists.removeEntry"];
|
|
9744
9762
|
if (root !== "assets" || id === void 0) return [];
|
|
9745
9763
|
switch (action) {
|
|
9746
|
-
case void 0: return method === "GET" ? [
|
|
9764
|
+
case void 0: return method === "GET" ? [
|
|
9765
|
+
"assets.retrieve",
|
|
9766
|
+
"assets.waitForDecision",
|
|
9767
|
+
"events.retrieveAsset"
|
|
9768
|
+
] : method === "PATCH" ? ["assets.update"] : ["assets.delete"];
|
|
9747
9769
|
case "content": return ["assets.removeContent"];
|
|
9748
9770
|
case "children": return ["assets.listChildren"];
|
|
9749
9771
|
case "part": return ["assets.uploadPart"];
|
|
9750
9772
|
case "move": return ["assets.move"];
|
|
9751
9773
|
case "retry": return ["assets.retry"];
|
|
9752
9774
|
case "decision": return ["assets.decide"];
|
|
9775
|
+
case "review-requests": return ["assets.requestReview"];
|
|
9753
9776
|
}
|
|
9754
9777
|
return [];
|
|
9755
9778
|
};
|
|
9779
|
+
/**
|
|
9780
|
+
* The methods whose requests the API runs under an `Idempotency-Key` (`idempotent` in its request
|
|
9781
|
+
* definitions): a retry with the same key replays the first response. Others ignore the header.
|
|
9782
|
+
*/
|
|
9783
|
+
const IDEMPOTENT_OPERATIONS = [
|
|
9784
|
+
"assets.create",
|
|
9785
|
+
"assets.classify",
|
|
9786
|
+
"text.classify",
|
|
9787
|
+
"assets.uploadPart",
|
|
9788
|
+
"assets.decide",
|
|
9789
|
+
"assets.requestReview",
|
|
9790
|
+
"hashLists.addEntry"
|
|
9791
|
+
];
|
|
9756
9792
|
/** A plain-text upload: the SDKs send text as a JSON body with `content.plainText`. */
|
|
9757
9793
|
const isTextUpload = (request) => {
|
|
9758
9794
|
if (request.headers.get("x-calmlens-upload")) return false;
|
|
@@ -9798,9 +9834,15 @@ var MockCalmLensApi = class {
|
|
|
9798
9834
|
this.openUploads = /* @__PURE__ */ new Map();
|
|
9799
9835
|
this.idempotentResults = /* @__PURE__ */ new Map();
|
|
9800
9836
|
this.pendingFailures = [];
|
|
9837
|
+
this.servedUrls = /* @__PURE__ */ new Map();
|
|
9838
|
+
this.pendingReviews = /* @__PURE__ */ new Map();
|
|
9801
9839
|
this.requestCount = 0;
|
|
9802
9840
|
this.useTimers = false;
|
|
9803
9841
|
this.waitedMs = 0;
|
|
9842
|
+
this.publishAssets = (_key, value) => isStoredAsset(value) ? {
|
|
9843
|
+
...value,
|
|
9844
|
+
eventSequence: this.eventSequenceOf(value.id)
|
|
9845
|
+
} : value;
|
|
9804
9846
|
this.policies = /* @__PURE__ */ new Map();
|
|
9805
9847
|
this.hashLists = /* @__PURE__ */ new Map();
|
|
9806
9848
|
this.hashListEntries = /* @__PURE__ */ new Map();
|
|
@@ -9818,14 +9860,43 @@ var MockCalmLensApi = class {
|
|
|
9818
9860
|
this.createId = options.createId;
|
|
9819
9861
|
this.now = options.now;
|
|
9820
9862
|
}
|
|
9821
|
-
/**
|
|
9863
|
+
/**
|
|
9864
|
+
* Queues a failure for the next request, or the next one `operation` sends, or for that many
|
|
9865
|
+
* with `times`; `failRequests` passes `Infinity`, which fails every one until `clearFailures`.
|
|
9866
|
+
*/
|
|
9822
9867
|
failNextRequest(failure, options = {}) {
|
|
9868
|
+
const { times = 1, ...rest } = options;
|
|
9869
|
+
if (times !== Number.POSITIVE_INFINITY && !(Number.isSafeInteger(times) && times >= 1)) throw invalidArgument("times must be a positive whole number");
|
|
9823
9870
|
if (options.operation !== void 0 && !MOCK_OPERATIONS.includes(options.operation)) throw invalidArgument(`${options.operation} is not a client method that sends requests`);
|
|
9824
9871
|
if (!(typeof failure === "string" && failure in API_ERROR_DEFINITIONS) && (options.details !== void 0 || options.retryAfter !== void 0)) throw invalidArgument("details and retryAfter apply only to an API error code");
|
|
9825
9872
|
if (options.retryAfter !== void 0 && !(Number.isInteger(options.retryAfter) && options.retryAfter >= 0)) throw invalidArgument("retryAfter must be a whole number of seconds");
|
|
9826
9873
|
this.pendingFailures.push({
|
|
9827
9874
|
failure,
|
|
9828
|
-
|
|
9875
|
+
remaining: times,
|
|
9876
|
+
...rest
|
|
9877
|
+
});
|
|
9878
|
+
}
|
|
9879
|
+
/** Drops every queued failure, so requests reach the API again. */
|
|
9880
|
+
clearFailures() {
|
|
9881
|
+
this.pendingFailures.length = 0;
|
|
9882
|
+
}
|
|
9883
|
+
/**
|
|
9884
|
+
* Makes a URL answer with `content` and its `type` when a URL upload fetches it, as a site
|
|
9885
|
+
* would. Registering a URL again replaces its content.
|
|
9886
|
+
*/
|
|
9887
|
+
serveUrl(url, { content, type }) {
|
|
9888
|
+
let key;
|
|
9889
|
+
try {
|
|
9890
|
+
key = new URL(url).href;
|
|
9891
|
+
} catch {
|
|
9892
|
+
throw invalidArgument("url must be an absolute URL");
|
|
9893
|
+
}
|
|
9894
|
+
if (typeof type !== "string" || !type.trim()) throw invalidArgument("type must be a content type, such as image/png");
|
|
9895
|
+
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;
|
|
9896
|
+
if (!bytes) throw invalidArgument("content must be bytes or a string");
|
|
9897
|
+
this.servedUrls.set(key, {
|
|
9898
|
+
bytes,
|
|
9899
|
+
type: type.trim()
|
|
9829
9900
|
});
|
|
9830
9901
|
}
|
|
9831
9902
|
/** A `fetch` that answers a client's requests from memory; app clients pass their session. */
|
|
@@ -9837,15 +9908,7 @@ var MockCalmLensApi = class {
|
|
|
9837
9908
|
* the stored event.
|
|
9838
9909
|
*/
|
|
9839
9910
|
async enqueueEvent(input) {
|
|
9840
|
-
|
|
9841
|
-
if (!asset) return this.pushEvent(input);
|
|
9842
|
-
const snapshot = toEventAsset(asset);
|
|
9843
|
-
const announced = ANNOUNCED_STATUS[input.type];
|
|
9844
|
-
if (announced) snapshot.classification.moderation.decision = announced;
|
|
9845
|
-
return this.pushEvent({
|
|
9846
|
-
...input,
|
|
9847
|
-
asset: snapshot
|
|
9848
|
-
});
|
|
9911
|
+
return this.pushEvent(input);
|
|
9849
9912
|
}
|
|
9850
9913
|
/** Adds an event to the feed, filling the fields the API always sets. */
|
|
9851
9914
|
pushEvent(input) {
|
|
@@ -9857,7 +9920,6 @@ var MockCalmLensApi = class {
|
|
|
9857
9920
|
title: input.type,
|
|
9858
9921
|
description: null,
|
|
9859
9922
|
assetId: null,
|
|
9860
|
-
asset: null,
|
|
9861
9923
|
actor: MOCK_API_KEY_ACTOR,
|
|
9862
9924
|
facts: [],
|
|
9863
9925
|
createdAt: now,
|
|
@@ -9869,6 +9931,22 @@ var MockCalmLensApi = class {
|
|
|
9869
9931
|
this.eventFeed.push(event);
|
|
9870
9932
|
return event;
|
|
9871
9933
|
}
|
|
9934
|
+
/** The `assetSequence` of the latest event about an asset, or 0 before its first. */
|
|
9935
|
+
eventSequenceOf(assetId) {
|
|
9936
|
+
return this.assetEventSequences.get(assetId) ?? 0;
|
|
9937
|
+
}
|
|
9938
|
+
/**
|
|
9939
|
+
* A copy of a stored asset as the API returns it, with its `eventSequence` as it is now. The
|
|
9940
|
+
* mock keeps each asset's sequence itself rather than in `databaseStorage`, whose
|
|
9941
|
+
* implementations needn't know about it, so every asset leaving the mock passes through here
|
|
9942
|
+
* or `publishAssets`.
|
|
9943
|
+
*/
|
|
9944
|
+
toPublished(asset) {
|
|
9945
|
+
return {
|
|
9946
|
+
...structuredClone(asset),
|
|
9947
|
+
eventSequence: this.eventSequenceOf(asset.id)
|
|
9948
|
+
};
|
|
9949
|
+
}
|
|
9872
9950
|
/** Applies a reviewer's decision to a stored asset (see `MockCalmLensServerClient.decide`). */
|
|
9873
9951
|
async decide(assetId, decision) {
|
|
9874
9952
|
if (!REVIEW_DECISIONS.includes(decision)) throw invalidArgument(`decision must be one of ${REVIEW_DECISIONS.join(", ")}`);
|
|
@@ -9878,7 +9956,7 @@ var MockCalmLensApi = class {
|
|
|
9878
9956
|
} catch (failure) {
|
|
9879
9957
|
throw this.toError(failure);
|
|
9880
9958
|
}
|
|
9881
|
-
return
|
|
9959
|
+
return this.toPublished(await this.recordDecision(asset, decision));
|
|
9882
9960
|
}
|
|
9883
9961
|
/**
|
|
9884
9962
|
* Finishes processing a pending asset as the pipeline would (see
|
|
@@ -9894,13 +9972,13 @@ var MockCalmLensApi = class {
|
|
|
9894
9972
|
}
|
|
9895
9973
|
if (asset.classification.status !== "processing") throw invalidArgument(`asset ${assetId} isn't processing`);
|
|
9896
9974
|
const settled = decision === void 0 ? void 0 : toDecision(decision);
|
|
9897
|
-
return
|
|
9975
|
+
return this.toPublished(await this.moderateStored(asset, "complete", settled));
|
|
9898
9976
|
}
|
|
9899
9977
|
/**
|
|
9900
9978
|
* `POST /assets/:assetId/decision`, like the API: an asset still uploading or processing can't
|
|
9901
9979
|
* be decided, one pending moderation can only be blocked or purged, a decision must change the
|
|
9902
|
-
* status and purged content can only be blocked. The review is the API key's,
|
|
9903
|
-
* have no
|
|
9980
|
+
* status and purged content can only be blocked. The review is the API key's (`MOCK_API_KEY_ID`),
|
|
9981
|
+
* and mock API keys have no name, so the event names the reviewer "An API key".
|
|
9904
9982
|
*/
|
|
9905
9983
|
async decideAsset(assetId, body) {
|
|
9906
9984
|
const { decision, note: rawNote } = body;
|
|
@@ -9932,10 +10010,7 @@ var MockCalmLensApi = class {
|
|
|
9932
10010
|
id: this.createId("rev"),
|
|
9933
10011
|
decision,
|
|
9934
10012
|
note: review?.note ?? null,
|
|
9935
|
-
decidedBy:
|
|
9936
|
-
type: "api-key",
|
|
9937
|
-
id: null
|
|
9938
|
-
},
|
|
10013
|
+
decidedBy: MOCK_API_KEY_ACTOR,
|
|
9939
10014
|
reviewedAt: now,
|
|
9940
10015
|
applied: true
|
|
9941
10016
|
}];
|
|
@@ -9946,7 +10021,6 @@ var MockCalmLensApi = class {
|
|
|
9946
10021
|
severity: decision === "allowed" || decision === "limited" ? "low" : "high",
|
|
9947
10022
|
title: `asset.${decision}`,
|
|
9948
10023
|
assetId: stored.id,
|
|
9949
|
-
asset: toEventAsset(stored),
|
|
9950
10024
|
actor: review ? MOCK_API_KEY_ACTOR : MOCK_REVIEWER_ACTOR,
|
|
9951
10025
|
facts: [
|
|
9952
10026
|
{
|
|
@@ -10024,7 +10098,9 @@ var MockCalmLensApi = class {
|
|
|
10024
10098
|
});
|
|
10025
10099
|
const index = this.pendingFailures.findIndex((pending) => pending.operation === void 0 || operations.includes(pending.operation));
|
|
10026
10100
|
if (index !== -1) {
|
|
10027
|
-
const
|
|
10101
|
+
const pending = this.pendingFailures[index];
|
|
10102
|
+
const { failure, details, retryAfter } = pending;
|
|
10103
|
+
if (--pending.remaining <= 0) this.pendingFailures.splice(index, 1);
|
|
10028
10104
|
if (typeof failure === "string" && failure in API_ERROR_DEFINITIONS) return this.answered(call, this.failureResponse(fail(failure, { details }), url, retryAfter));
|
|
10029
10105
|
throw this.toFailureError(failure);
|
|
10030
10106
|
}
|
|
@@ -10101,7 +10177,7 @@ var MockCalmLensApi = class {
|
|
|
10101
10177
|
async answer(request, operation, session) {
|
|
10102
10178
|
const { url, headers } = request;
|
|
10103
10179
|
if (!(request.segments[0] === "upload-presets") && headers.get("x-api-key") !== this.apiKey) return this.failureResponse(fail(API_ERROR_CODES.INVALID_API_KEY), url);
|
|
10104
|
-
const key = headers.get("idempotency-key")?.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
|
|
10180
|
+
const key = operation && IDEMPOTENT_OPERATIONS.includes(operation) ? headers.get("idempotency-key")?.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "") : void 0;
|
|
10105
10181
|
const upload = headers.get("x-calmlens-upload");
|
|
10106
10182
|
const contentType = headers.get("content-type");
|
|
10107
10183
|
const isForm = !!upload && /^multipart\/form-data\b/i.test(contentType ?? "");
|
|
@@ -10137,7 +10213,7 @@ var MockCalmLensApi = class {
|
|
|
10137
10213
|
throw failure;
|
|
10138
10214
|
}
|
|
10139
10215
|
const [status, body] = answer;
|
|
10140
|
-
const json = JSON.stringify(body ?? {});
|
|
10216
|
+
const json = JSON.stringify(body ?? {}, this.publishAssets);
|
|
10141
10217
|
const finalStatus = operation ? SUCCESS_STATUS[operation] ?? status : status;
|
|
10142
10218
|
if (key !== void 0) this.idempotentResults.set(key, {
|
|
10143
10219
|
fingerprint,
|
|
@@ -10175,6 +10251,7 @@ var MockCalmLensApi = class {
|
|
|
10175
10251
|
case "PUT metadata-fields": return [200, this.ensureMetadataFields(this.json(request))];
|
|
10176
10252
|
}
|
|
10177
10253
|
const [, , collection, itemId, itemAction, ...more] = segments;
|
|
10254
|
+
if (collection === "assets" && itemId === "by-external-id" && itemAction !== void 0 && more.length === 0 && method === "GET") return [200, await this.findByExternalId(itemAction)];
|
|
10178
10255
|
if (collection === "metadata-fields" && itemId !== void 0 && itemAction === void 0) {
|
|
10179
10256
|
if (method === "DELETE") return [200, this.deleteMetadataField(itemId, request.query)];
|
|
10180
10257
|
}
|
|
@@ -10211,6 +10288,7 @@ var MockCalmLensApi = class {
|
|
|
10211
10288
|
case "POST move": return [200, await this.moveAsset(id, this.json(request))];
|
|
10212
10289
|
case "POST retry": return [200, await this.retryAsset(id)];
|
|
10213
10290
|
case "POST decision": return [200, await this.decideAsset(id, this.json(request))];
|
|
10291
|
+
case "POST review-requests": return this.requestReview(id, this.json(request));
|
|
10214
10292
|
case "DELETE content": return [200, await this.removeContent(await this.findOwnAsset(id))];
|
|
10215
10293
|
}
|
|
10216
10294
|
if (root === "folders" && id !== void 0 && rest.length === 0) switch (`${method} ${action ?? ""}`) {
|
|
@@ -10493,6 +10571,115 @@ var MockCalmLensApi = class {
|
|
|
10493
10571
|
if (!asset || asset.projectId !== this.projectId) throw fail(API_ERROR_CODES.ASSET_NOT_FOUND);
|
|
10494
10572
|
return asset;
|
|
10495
10573
|
}
|
|
10574
|
+
/** `GET /projects/:projectId/assets/by-external-id/:externalId`: the asset with that external ID. */
|
|
10575
|
+
async findByExternalId(externalId) {
|
|
10576
|
+
const asset = (await this.databaseStorage.listAssets(this.projectId)).find((candidate) => candidate.externalId === externalId);
|
|
10577
|
+
if (!asset) throw fail(API_ERROR_CODES.ASSET_NOT_FOUND);
|
|
10578
|
+
return asset;
|
|
10579
|
+
}
|
|
10580
|
+
/**
|
|
10581
|
+
* The review the queue holds for an asset, or undefined when none is waiting. A review a
|
|
10582
|
+
* decision left waiting (`pendingReview`) gets its ID the first time it is read.
|
|
10583
|
+
*/
|
|
10584
|
+
pendingReviewOf(asset) {
|
|
10585
|
+
const pending = asset.classification.moderation.pendingReview;
|
|
10586
|
+
if (!pending) {
|
|
10587
|
+
this.pendingReviews.delete(asset.id);
|
|
10588
|
+
return;
|
|
10589
|
+
}
|
|
10590
|
+
let review = this.pendingReviews.get(asset.id);
|
|
10591
|
+
if (!review) {
|
|
10592
|
+
review = {
|
|
10593
|
+
id: this.createId("rev"),
|
|
10594
|
+
assetId: asset.id,
|
|
10595
|
+
reason: pending.reason,
|
|
10596
|
+
status: "pending",
|
|
10597
|
+
note: null,
|
|
10598
|
+
createdAt: pending.requestedAt
|
|
10599
|
+
};
|
|
10600
|
+
this.pendingReviews.set(asset.id, review);
|
|
10601
|
+
}
|
|
10602
|
+
return review;
|
|
10603
|
+
}
|
|
10604
|
+
/**
|
|
10605
|
+
* `POST /assets/:assetId/review-requests`, like the API (publicPostAssetReviewRequest.ts and
|
|
10606
|
+
* getReportRefusal): a held asset is `asset/held`; a child asset, an asset not yet decided, and
|
|
10607
|
+
* a purged one or one whose content is gone are `asset/not-reviewable` with that `reason`. A
|
|
10608
|
+
* review already waiting is returned unchanged with 200; otherwise a `reported` review joins
|
|
10609
|
+
* the queue with 201, the asset's `pendingReview` is set and `asset.review-requested` is
|
|
10610
|
+
* recorded with the API key as its actor.
|
|
10611
|
+
*/
|
|
10612
|
+
async requestReview(assetId, body) {
|
|
10613
|
+
const { note: rawNote } = body;
|
|
10614
|
+
if (rawNote !== void 0 && typeof rawNote !== "string") throw invalidField("validation/invalid-type", "note");
|
|
10615
|
+
const note = rawNote?.trim();
|
|
10616
|
+
if (note !== void 0 && !note) throw invalidField("validation/too-small", "note");
|
|
10617
|
+
if (note && note.length > MAX_DECISION_NOTE_LENGTH) throw invalidField("validation/too-big", "note");
|
|
10618
|
+
const asset = await this.findOwnAsset(assetId);
|
|
10619
|
+
if (asset.content.safetyHold) throw fail(API_ERROR_CODES.ASSET_HELD, { details: { hold: "safety" } });
|
|
10620
|
+
const decision = asset.classification.moderation.decision;
|
|
10621
|
+
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;
|
|
10622
|
+
if (reason) throw fail(API_ERROR_CODES.ASSET_NOT_REVIEWABLE, { details: { reason } });
|
|
10623
|
+
const waiting = this.pendingReviewOf(asset);
|
|
10624
|
+
if (waiting) return [200, waiting];
|
|
10625
|
+
const now = this.now();
|
|
10626
|
+
const review = {
|
|
10627
|
+
id: this.createId("rev"),
|
|
10628
|
+
assetId: asset.id,
|
|
10629
|
+
reason: "reported",
|
|
10630
|
+
status: "pending",
|
|
10631
|
+
note: note ?? null,
|
|
10632
|
+
createdAt: now
|
|
10633
|
+
};
|
|
10634
|
+
this.pendingReviews.set(asset.id, review);
|
|
10635
|
+
const stored = await this.databaseStorage.updateAsset({
|
|
10636
|
+
...asset,
|
|
10637
|
+
classification: {
|
|
10638
|
+
...asset.classification,
|
|
10639
|
+
moderation: {
|
|
10640
|
+
...asset.classification.moderation,
|
|
10641
|
+
pendingReview: {
|
|
10642
|
+
requestedAt: now,
|
|
10643
|
+
reason: "reported",
|
|
10644
|
+
uncertainCategories: []
|
|
10645
|
+
}
|
|
10646
|
+
}
|
|
10647
|
+
}
|
|
10648
|
+
});
|
|
10649
|
+
this.pushEvent({
|
|
10650
|
+
type: "asset.review-requested",
|
|
10651
|
+
severity: "low",
|
|
10652
|
+
assetId: stored.id,
|
|
10653
|
+
facts: [
|
|
10654
|
+
assetNameFact(stored),
|
|
10655
|
+
{
|
|
10656
|
+
key: "asset-type",
|
|
10657
|
+
value: stored.type
|
|
10658
|
+
},
|
|
10659
|
+
{
|
|
10660
|
+
key: "review-id",
|
|
10661
|
+
value: review.id
|
|
10662
|
+
},
|
|
10663
|
+
{
|
|
10664
|
+
key: "automated-status",
|
|
10665
|
+
value: decision
|
|
10666
|
+
},
|
|
10667
|
+
{
|
|
10668
|
+
key: "review-reason",
|
|
10669
|
+
value: "reported"
|
|
10670
|
+
},
|
|
10671
|
+
{
|
|
10672
|
+
key: "uncertain-categories",
|
|
10673
|
+
value: []
|
|
10674
|
+
},
|
|
10675
|
+
...review.note ? [{
|
|
10676
|
+
key: "note",
|
|
10677
|
+
value: review.note
|
|
10678
|
+
}] : []
|
|
10679
|
+
]
|
|
10680
|
+
});
|
|
10681
|
+
return [201, review];
|
|
10682
|
+
}
|
|
10496
10683
|
async listAssets(query) {
|
|
10497
10684
|
let assets = await this.databaseStorage.listAssets(this.projectId);
|
|
10498
10685
|
const page = this.pageQuery(query);
|
|
@@ -10557,7 +10744,8 @@ var MockCalmLensApi = class {
|
|
|
10557
10744
|
if (body.name === null) throw invalidField("validation/invalid-type", "name");
|
|
10558
10745
|
const asset = await this.findOwnAsset(assetId);
|
|
10559
10746
|
if (body.externalId) {
|
|
10560
|
-
|
|
10747
|
+
const holder = (await this.databaseStorage.listAssets(this.projectId)).find((other) => other.id !== asset.id && other.externalId === body.externalId);
|
|
10748
|
+
if (holder) throw duplicateExternalId(holder);
|
|
10561
10749
|
}
|
|
10562
10750
|
return this.databaseStorage.updateAsset({
|
|
10563
10751
|
...asset,
|
|
@@ -10810,8 +10998,11 @@ var MockCalmLensApi = class {
|
|
|
10810
10998
|
}
|
|
10811
10999
|
async storeAsset(fields, queue) {
|
|
10812
11000
|
if (!fields.name) throw fail(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Asset name is required" });
|
|
10813
|
-
const
|
|
10814
|
-
const
|
|
11001
|
+
const served = fields.url === void 0 ? void 0 : this.servedContent(fields.url);
|
|
11002
|
+
const fetched = served && inferAssetType(served.type) !== "website" ? served : void 0;
|
|
11003
|
+
const { part } = fields;
|
|
11004
|
+
const contentType = fetched ? fetched.type : fields.contentType;
|
|
11005
|
+
const bytes = fetched?.bytes ?? fields.bytes ?? /* @__PURE__ */ new Uint8Array(0);
|
|
10815
11006
|
if (contentType !== void 0 && !isAcceptedUploadMimeType(contentType)) throw fail(API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, {
|
|
10816
11007
|
message: getRejectedUploadMimeTypeError(contentType),
|
|
10817
11008
|
details: {
|
|
@@ -10819,7 +11010,7 @@ var MockCalmLensApi = class {
|
|
|
10819
11010
|
source: "calmlens"
|
|
10820
11011
|
}
|
|
10821
11012
|
});
|
|
10822
|
-
const type = fields.url === void 0 ? inferAssetType(contentType ?? "") : urlAssetType(fields.url);
|
|
11013
|
+
const type = served ? inferAssetType(served.type) : fields.url === void 0 ? inferAssetType(contentType ?? "") : urlAssetType(fields.url);
|
|
10823
11014
|
if (part) {
|
|
10824
11015
|
if (part.partNumber > 1) throw fail(API_ERROR_CODES.USE_UPLOAD_PART);
|
|
10825
11016
|
const partSize = bytes.byteLength;
|
|
@@ -10837,7 +11028,8 @@ var MockCalmLensApi = class {
|
|
|
10837
11028
|
}
|
|
10838
11029
|
if (fields.folderId) await this.findOwnFolder(fields.folderId);
|
|
10839
11030
|
if (fields.externalId) {
|
|
10840
|
-
|
|
11031
|
+
const holder = (await this.databaseStorage.listAssets(this.projectId)).find((asset) => asset.externalId === fields.externalId);
|
|
11032
|
+
if (holder) throw duplicateExternalId(holder);
|
|
10841
11033
|
}
|
|
10842
11034
|
const id = this.createId("asset");
|
|
10843
11035
|
const now = this.now();
|
|
@@ -10848,7 +11040,7 @@ var MockCalmLensApi = class {
|
|
|
10848
11040
|
};
|
|
10849
11041
|
const keepContent = processingOptions.retainContent === true;
|
|
10850
11042
|
this.processingOptions.set(id, processingOptions);
|
|
10851
|
-
const hasContent = fields.url === void 0;
|
|
11043
|
+
const hasContent = fields.url === void 0 || fetched !== void 0;
|
|
10852
11044
|
const contextItems = selectModerationContextItems(fields.context?.items ?? []);
|
|
10853
11045
|
const asset = {
|
|
10854
11046
|
id,
|
|
@@ -10869,6 +11061,7 @@ var MockCalmLensApi = class {
|
|
|
10869
11061
|
context: contextItems.length ? { items: contextItems } : null,
|
|
10870
11062
|
tags: fields.tags ?? [],
|
|
10871
11063
|
visibility: fields.visibility ?? "private",
|
|
11064
|
+
eventSequence: 0,
|
|
10872
11065
|
content: {
|
|
10873
11066
|
status: keepContent ? "stored" : "temporary",
|
|
10874
11067
|
removalReason: null,
|
|
@@ -11019,22 +11212,90 @@ var MockCalmLensApi = class {
|
|
|
11019
11212
|
return receivedSizeInBytes > totalSizeInBytes || isFinal && receivedSizeInBytes !== totalSizeInBytes ? API_ERROR_CODES.UPLOAD_SIZE_MISMATCH : void 0;
|
|
11020
11213
|
}
|
|
11021
11214
|
/**
|
|
11215
|
+
* The content a URL upload fetches from a URL `serveUrl` registered, or undefined: then the
|
|
11216
|
+
* mock fetches nothing, and the URL's path's extension types it.
|
|
11217
|
+
*/
|
|
11218
|
+
servedContent(url) {
|
|
11219
|
+
let key;
|
|
11220
|
+
try {
|
|
11221
|
+
key = new URL(url).href;
|
|
11222
|
+
} catch {
|
|
11223
|
+
return;
|
|
11224
|
+
}
|
|
11225
|
+
const served = this.servedUrls.get(key);
|
|
11226
|
+
return served && {
|
|
11227
|
+
bytes: served.bytes.slice(),
|
|
11228
|
+
type: served.type
|
|
11229
|
+
};
|
|
11230
|
+
}
|
|
11231
|
+
/** An asset's stored content, its parts in order, or `null` once it is removed. */
|
|
11232
|
+
async storedBytes(asset) {
|
|
11233
|
+
if (asset.content.status === "removed") return null;
|
|
11234
|
+
const stored = await this.imageStorage.getContent(asset.id);
|
|
11235
|
+
if (!stored) return null;
|
|
11236
|
+
const parts = [...stored.parts].sort(([a], [b]) => a - b).map(([, part]) => part);
|
|
11237
|
+
return new Uint8Array(await new Blob(parts).arrayBuffer());
|
|
11238
|
+
}
|
|
11239
|
+
/**
|
|
11240
|
+
* A decided image with its hash and the project's hash list matches, as the API records them
|
|
11241
|
+
* (AssetClassification.ts, Project.ts and HashList.ts). The mock computes no PDQ hash: an
|
|
11242
|
+
* image's `content.perceptualHash` is the SHA-256 of its bytes in lowercase hex, with quality
|
|
11243
|
+
* 100, so an entry matches an image whose bytes equal those it was taken from, at distance 0.
|
|
11244
|
+
* Entries below quality 50 never match. Each match takes its list's action, blocking matches
|
|
11245
|
+
* first; a block raises an allowed, limited or age-restricted decision to `blocked`, with
|
|
11246
|
+
* `source: "hash-list"`, and a flag only records the match.
|
|
11247
|
+
*/
|
|
11248
|
+
async withHashMatches(asset, bytes) {
|
|
11249
|
+
const hash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
11250
|
+
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) => ({
|
|
11251
|
+
source: "hash-list",
|
|
11252
|
+
hashListId: entry.hashListId,
|
|
11253
|
+
hashListEntryId: entry.id,
|
|
11254
|
+
distance: 0,
|
|
11255
|
+
action: this.hashLists.get(entry.hashListId).action
|
|
11256
|
+
})).sort((a, b) => Number(b.action === "block") - Number(a.action === "block")).slice(0, MAX_RECORDED_HASH_MATCHES);
|
|
11257
|
+
const hashed = {
|
|
11258
|
+
...asset,
|
|
11259
|
+
content: {
|
|
11260
|
+
...asset.content,
|
|
11261
|
+
perceptualHash: hash,
|
|
11262
|
+
perceptualHashQuality: 100
|
|
11263
|
+
}
|
|
11264
|
+
};
|
|
11265
|
+
if (!matches.length) return hashed;
|
|
11266
|
+
const { moderation } = asset.classification;
|
|
11267
|
+
const raised = matches.some((match) => match.action === "block") && (moderation.decision === "allowed" || moderation.decision === "limited" || moderation.decision === "age-restricted");
|
|
11268
|
+
return {
|
|
11269
|
+
...hashed,
|
|
11270
|
+
classification: {
|
|
11271
|
+
...asset.classification,
|
|
11272
|
+
moderation: {
|
|
11273
|
+
...moderation,
|
|
11274
|
+
...raised && {
|
|
11275
|
+
decision: "blocked",
|
|
11276
|
+
automatedStatus: "blocked",
|
|
11277
|
+
source: "hash-list"
|
|
11278
|
+
},
|
|
11279
|
+
raw: {
|
|
11280
|
+
...moderation.raw,
|
|
11281
|
+
hashMatches: matches
|
|
11282
|
+
}
|
|
11283
|
+
}
|
|
11284
|
+
}
|
|
11285
|
+
};
|
|
11286
|
+
}
|
|
11287
|
+
/**
|
|
11022
11288
|
* Asks `moderate` how to decide `asset`, with its content: `bytes` when the caller has them,
|
|
11023
11289
|
* otherwise the stored parts in order (none once the content is removed).
|
|
11024
11290
|
*/
|
|
11025
11291
|
async decisionFor(asset, trigger, queued, bytes) {
|
|
11026
|
-
|
|
11027
|
-
if (data === void 0) {
|
|
11028
|
-
const stored = asset.content.status === "removed" ? void 0 : await this.imageStorage.getContent(asset.id);
|
|
11029
|
-
const parts = stored ? [...stored.parts].sort(([a], [b]) => a - b).map(([, part]) => part) : [];
|
|
11030
|
-
data = stored ? new Uint8Array(await new Blob(parts).arrayBuffer()) : null;
|
|
11031
|
-
}
|
|
11292
|
+
const data = bytes === void 0 ? await this.storedBytes(asset) : bytes;
|
|
11032
11293
|
const content = {
|
|
11033
11294
|
bytes: data,
|
|
11034
11295
|
text: data && asset.type === "plaintext-document" ? new TextDecoder().decode(data) : null
|
|
11035
11296
|
};
|
|
11036
11297
|
return toDecision(await this.options.moderate({
|
|
11037
|
-
asset:
|
|
11298
|
+
asset: this.toPublished(asset),
|
|
11038
11299
|
content,
|
|
11039
11300
|
trigger,
|
|
11040
11301
|
queued
|
|
@@ -11045,9 +11306,11 @@ var MockCalmLensApi = class {
|
|
|
11045
11306
|
* it, a decided image reports the person and face detection its upload turned on.
|
|
11046
11307
|
*/
|
|
11047
11308
|
async decided(asset, decision) {
|
|
11048
|
-
const
|
|
11309
|
+
const image = asset.type === "image" ? await this.storedBytes(asset) : null;
|
|
11310
|
+
const outcome = await this.applyOutcome(asset, decision.status, "policy", decision.report(this.now()));
|
|
11049
11311
|
const features = this.processingOptions.get(asset.id)?.features;
|
|
11050
|
-
if (
|
|
11312
|
+
if (outcome.classification.status !== "completed" || asset.type !== "image") return outcome;
|
|
11313
|
+
const next = image ? await this.withHashMatches(outcome, image) : outcome;
|
|
11051
11314
|
const ocr = features?.ocr?.enabled === true ? decision.ocrFindings : void 0;
|
|
11052
11315
|
const ages = features?.faceDetection?.ageEstimation === true;
|
|
11053
11316
|
return {
|
|
@@ -11106,7 +11369,6 @@ var MockCalmLensApi = class {
|
|
|
11106
11369
|
type: "asset.uploaded",
|
|
11107
11370
|
severity: "low",
|
|
11108
11371
|
assetId: asset.id,
|
|
11109
|
-
asset: toEventAsset(asset),
|
|
11110
11372
|
facts: [
|
|
11111
11373
|
{
|
|
11112
11374
|
key: "asset-type",
|
|
@@ -11129,7 +11391,6 @@ var MockCalmLensApi = class {
|
|
|
11129
11391
|
if (decision.status === "pending") return;
|
|
11130
11392
|
const event = {
|
|
11131
11393
|
assetId: asset.id,
|
|
11132
|
-
asset: toEventAsset(asset),
|
|
11133
11394
|
actor: AUTOMATED_ACTOR
|
|
11134
11395
|
};
|
|
11135
11396
|
if (decision.status === "failed") {
|
|
@@ -11156,6 +11417,7 @@ var MockCalmLensApi = class {
|
|
|
11156
11417
|
return;
|
|
11157
11418
|
}
|
|
11158
11419
|
const flaggedCategories = decision.report()?.flaggedCategories ?? [];
|
|
11420
|
+
const status = asset.classification.moderation.decision ?? decision.status;
|
|
11159
11421
|
this.pushEvent({
|
|
11160
11422
|
...event,
|
|
11161
11423
|
type: "asset.classified",
|
|
@@ -11167,7 +11429,7 @@ var MockCalmLensApi = class {
|
|
|
11167
11429
|
},
|
|
11168
11430
|
{
|
|
11169
11431
|
key: "moderation-status",
|
|
11170
|
-
value:
|
|
11432
|
+
value: status
|
|
11171
11433
|
},
|
|
11172
11434
|
{
|
|
11173
11435
|
key: "asset-type",
|
|
@@ -11178,8 +11440,8 @@ var MockCalmLensApi = class {
|
|
|
11178
11440
|
});
|
|
11179
11441
|
this.pushEvent({
|
|
11180
11442
|
...event,
|
|
11181
|
-
type: `asset.${
|
|
11182
|
-
severity:
|
|
11443
|
+
type: `asset.${status}`,
|
|
11444
|
+
severity: status === "allowed" || status === "limited" ? "low" : "high",
|
|
11183
11445
|
facts: [
|
|
11184
11446
|
{
|
|
11185
11447
|
key: "flagged-categories",
|
|
@@ -11192,6 +11454,36 @@ var MockCalmLensApi = class {
|
|
|
11192
11454
|
assetNameFact(asset)
|
|
11193
11455
|
]
|
|
11194
11456
|
});
|
|
11457
|
+
const match = asset.classification.moderation.raw?.hashMatches?.[0];
|
|
11458
|
+
if (match) this.pushEvent({
|
|
11459
|
+
...event,
|
|
11460
|
+
type: "asset.hash-matched",
|
|
11461
|
+
severity: "high",
|
|
11462
|
+
facts: [
|
|
11463
|
+
{
|
|
11464
|
+
key: "hash-list-id",
|
|
11465
|
+
value: match.hashListId
|
|
11466
|
+
},
|
|
11467
|
+
{
|
|
11468
|
+
key: "hash-list-name",
|
|
11469
|
+
value: this.hashLists.get(match.hashListId)?.name ?? "",
|
|
11470
|
+
url: `https://calmlens.com/go/hash-list/${encodeURIComponent(match.hashListId)}`
|
|
11471
|
+
},
|
|
11472
|
+
{
|
|
11473
|
+
key: "distance",
|
|
11474
|
+
value: match.distance
|
|
11475
|
+
},
|
|
11476
|
+
{
|
|
11477
|
+
key: "match-action",
|
|
11478
|
+
value: match.action
|
|
11479
|
+
},
|
|
11480
|
+
{
|
|
11481
|
+
key: "asset-type",
|
|
11482
|
+
value: asset.type
|
|
11483
|
+
},
|
|
11484
|
+
assetNameFact(asset)
|
|
11485
|
+
]
|
|
11486
|
+
});
|
|
11195
11487
|
}
|
|
11196
11488
|
/**
|
|
11197
11489
|
* Moves an asset to `outcome` like the pipeline would: a decision finishes processing, `purged`
|
|
@@ -11250,7 +11542,6 @@ var MockCalmLensApi = class {
|
|
|
11250
11542
|
actor,
|
|
11251
11543
|
severity: "low",
|
|
11252
11544
|
assetId: asset.id,
|
|
11253
|
-
asset: toEventAsset(asset),
|
|
11254
11545
|
facts: [
|
|
11255
11546
|
{
|
|
11256
11547
|
key: "asset-name",
|
|
@@ -11287,7 +11578,7 @@ var MockCalmLensApi = class {
|
|
|
11287
11578
|
classification: {
|
|
11288
11579
|
status: asset.classification.status,
|
|
11289
11580
|
failureReason: asset.classification.failureReason,
|
|
11290
|
-
...preset.
|
|
11581
|
+
...preset.revealDecision !== false && { moderation: { decision: asset.classification.moderation.decision } }
|
|
11291
11582
|
}
|
|
11292
11583
|
});
|
|
11293
11584
|
const [assetId, action] = rest;
|
|
@@ -11301,7 +11592,7 @@ var MockCalmLensApi = class {
|
|
|
11301
11592
|
if (request.method !== "POST") throw new ApiFailure(404, "not-found", "No such route");
|
|
11302
11593
|
const fields = this.uploadFields(request);
|
|
11303
11594
|
const token = request.headers.get("authorization");
|
|
11304
|
-
if (preset.
|
|
11595
|
+
if (preset.access === "token" && !token) throw fail(API_ERROR_CODES.UPLOAD_PRESET_TOKEN_REQUIRED);
|
|
11305
11596
|
const tokenExternalId = token ? decodeUploadToken(token.replace(/^Bearer /, ""))?.claims.x : void 0;
|
|
11306
11597
|
if (fields.externalId && fields.externalId !== tokenExternalId) throw fail(API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field: "externalId" } });
|
|
11307
11598
|
for (const field of [
|
|
@@ -11320,8 +11611,8 @@ var MockCalmLensApi = class {
|
|
|
11320
11611
|
allowedContentTypes: preset.allowedContentTypes
|
|
11321
11612
|
} });
|
|
11322
11613
|
const size = fields.part?.totalSizeInBytes ?? fields.bytes?.byteLength;
|
|
11323
|
-
if (preset.
|
|
11324
|
-
limitBytes: preset.
|
|
11614
|
+
if (preset.maxSizeInBytes != null && size !== void 0 && size > preset.maxSizeInBytes) throw fail(API_ERROR_CODES.UPLOAD_TOO_LARGE, { details: {
|
|
11615
|
+
limitBytes: preset.maxSizeInBytes,
|
|
11325
11616
|
source: "preset"
|
|
11326
11617
|
} });
|
|
11327
11618
|
const asset = await this.storeAsset({
|
|
@@ -11330,7 +11621,10 @@ var MockCalmLensApi = class {
|
|
|
11330
11621
|
uploadPresetId,
|
|
11331
11622
|
visibility: preset.visibility ?? "public",
|
|
11332
11623
|
folderId: preset.folderId ?? void 0,
|
|
11333
|
-
processingOptions: {
|
|
11624
|
+
processingOptions: {
|
|
11625
|
+
...preset.processingOptions?.features && { features: preset.processingOptions.features },
|
|
11626
|
+
retainContent: preset.processingOptions?.retainContent ?? true
|
|
11627
|
+
}
|
|
11334
11628
|
}, request.query.get("wait") === "false");
|
|
11335
11629
|
session.uploads.add(asset.id);
|
|
11336
11630
|
return toUploaded(asset);
|
|
@@ -11763,12 +12057,11 @@ var MockCalmLensApi = class {
|
|
|
11763
12057
|
if (asset.content.safetyHold) return notAvailable();
|
|
11764
12058
|
if (resource === "placeholder") {
|
|
11765
12059
|
if (asset.visibility !== "public" && !grant && !canDownload()) return notFound();
|
|
11766
|
-
if (status === "blocked" && !grant && !canDownload()) return notAvailable();
|
|
11767
12060
|
const thumbhash = preview?.thumbhash;
|
|
11768
12061
|
if (!thumbhash || status === "purged") return notAvailable();
|
|
11769
12062
|
return this.cdnResponse(isHead, mockPlaceholderPng(thumbhash), url, {
|
|
11770
12063
|
"Content-Type": "image/png",
|
|
11771
|
-
"Cache-Control": asset.visibility !== "public"
|
|
12064
|
+
"Cache-Control": asset.visibility !== "public" ? "private, no-store" : "public, no-cache",
|
|
11772
12065
|
"Cache-Tag": `asset-${asset.id}`,
|
|
11773
12066
|
ETag: `"${thumbhash}"`
|
|
11774
12067
|
});
|
|
@@ -12086,14 +12379,40 @@ var MockCalmLensServerClient = class extends CalmLensServerClient {
|
|
|
12086
12379
|
}
|
|
12087
12380
|
/**
|
|
12088
12381
|
* Makes the next request (or the next one `operation` sends) fail instead of reaching the
|
|
12089
|
-
* in-memory API. Each queued failure fails
|
|
12090
|
-
*
|
|
12091
|
-
*
|
|
12382
|
+
* in-memory API, or the next `times` of them. Each queued failure fails that many requests, so
|
|
12383
|
+
* a retry takes it again until it is used up, then the next queued failure or the API. A
|
|
12384
|
+
* request takes the oldest queued failure that matches it. An API error code answers with that
|
|
12385
|
+
* error and its HTTP status, with `details` and a `Retry-After` of `retryAfter` seconds when
|
|
12386
|
+
* given.
|
|
12092
12387
|
*/
|
|
12093
12388
|
failNextRequest(failure = "transport-error", options = {}) {
|
|
12094
12389
|
this.#api.failNextRequest(failure, options);
|
|
12095
12390
|
}
|
|
12096
12391
|
/**
|
|
12392
|
+
* Makes every request (or every one `operation` sends) fail as `failNextRequest` would, until
|
|
12393
|
+
* `clearFailures`. Queued after other failures, it fails the requests they don't.
|
|
12394
|
+
*/
|
|
12395
|
+
failRequests(failure = "transport-error", options = {}) {
|
|
12396
|
+
if (options && "times" in options) throw invalidArgument("failRequests fails every request: use failNextRequest for times");
|
|
12397
|
+
this.#api.failNextRequest(failure, {
|
|
12398
|
+
...options,
|
|
12399
|
+
times: Number.POSITIVE_INFINITY
|
|
12400
|
+
});
|
|
12401
|
+
}
|
|
12402
|
+
/** Drops every failure `failNextRequest` and `failRequests` queued. */
|
|
12403
|
+
clearFailures() {
|
|
12404
|
+
this.#api.clearFailures();
|
|
12405
|
+
}
|
|
12406
|
+
/**
|
|
12407
|
+
* Makes `url` answer with `content` (bytes, or text as UTF-8) and `type` when a URL upload
|
|
12408
|
+
* fetches it. The upload then stores that content and is typed by `type`, as an upload of the
|
|
12409
|
+
* bytes would be: `image/png` is an image, and `text/html` a website. A URL not served this way
|
|
12410
|
+
* is typed by its path's extension, and has no content.
|
|
12411
|
+
*/
|
|
12412
|
+
serveUrl(url, content) {
|
|
12413
|
+
this.#api.serveUrl(url, content);
|
|
12414
|
+
}
|
|
12415
|
+
/**
|
|
12097
12416
|
* Changes the grants of the mock's API key, as editing the key in the portal would: later
|
|
12098
12417
|
* requests, such as `cdn.serve`, use them. The key itself stays the same, so idempotency keys
|
|
12099
12418
|
* it used still replay.
|
|
@@ -12143,6 +12462,7 @@ var MockCalmLensAppClient = class extends CalmLensAppClient {
|
|
|
12143
12462
|
constructor(options) {
|
|
12144
12463
|
validateAppClientOptions(options);
|
|
12145
12464
|
const { mockOptions = {}, ...clientOptions } = options;
|
|
12465
|
+
if (mockOptions.preset) checkMockUploadPreset(mockOptions.preset);
|
|
12146
12466
|
const server = mockOptions.server ?? new MockCalmLensServerClient({
|
|
12147
12467
|
apiKey: createMockApiKey([{
|
|
12148
12468
|
actions: [
|
|
@@ -12192,7 +12512,6 @@ const toWebhookEventPayload = (event) => ({
|
|
|
12192
12512
|
description: event.description ?? null,
|
|
12193
12513
|
assetId: event.assetId ?? null,
|
|
12194
12514
|
assetSequence: event.assetSequence ?? null,
|
|
12195
|
-
asset: event.asset ?? null,
|
|
12196
12515
|
facts: event.facts,
|
|
12197
12516
|
createdAt: event.createdAt
|
|
12198
12517
|
});
|
|
@@ -12208,4 +12527,4 @@ const createWebhookHeaders = async (options) => {
|
|
|
12208
12527
|
[WEBHOOK_SIGNATURE_HEADER]: await createWebhookSignatureHeader(options.secret, timestamp, options.body)
|
|
12209
12528
|
};
|
|
12210
12529
|
};
|
|
12211
|
-
export { InMemoryMockDatabaseStorage, InMemoryMockImageStorage, MEDIA_TEST_SIGNALS, MOCK_API_KEY_PREFIX, MockCalmLensAppClient, MockCalmLensServerClient, MockDecision, createMockApiKey, createWebhookHeaders, createWebhookSignatureHeader, generateMediaTestCode, mockDecision, signUploadTokenWithApiKey as signUploadToken, toWebhookEventPayload };
|
|
12530
|
+
export { InMemoryMockDatabaseStorage, InMemoryMockImageStorage, MEDIA_TEST_SIGNALS, MOCK_API_KEY_ID, MOCK_API_KEY_PREFIX, MockCalmLensAppClient, MockCalmLensServerClient, MockDecision, createMockApiKey, createWebhookHeaders, createWebhookSignatureHeader, generateMediaTestCode, mockDecision, signUploadTokenWithApiKey as signUploadToken, toWebhookEventPayload };
|