calmlens 0.20.0 → 0.22.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/README.md +15 -10
- package/bin/calmlens.js +1848 -679
- package/cjs/{BrowserUpload-C07aL9Vq.d.ts → BrowserUpload-BWjZ9ntu.d.ts} +2 -2
- package/cjs/{BrowserUpload-CjSHjx3C.js → BrowserUpload-Bwlib4Zc.js} +1 -1
- package/cjs/{CalmLensAppClient-DDLojj0P.d.ts → CalmLensAppClient-BaW3ddUR.d.ts} +13 -3
- package/cjs/{CalmLensAppClient-NaCxOVlM.js → CalmLensAppClient-DUYMo9PZ.js} +30 -10
- package/cjs/{CalmLensOptionKeys-p2QK687A.js → CalmLensOptionKeys-YvgV995V.js} +318 -374
- package/cjs/{CalmLensServerClient-BDzTthxE.js → CalmLensServerClient-3N-gdsxC.js} +346 -89
- package/cjs/CalmLensServerClient-BKzn8zmp.d.ts +353 -0
- package/cjs/{CalmLensTypes-COJbOuiv.d.ts → CalmLensTypes-BDKwThbO.d.ts} +26993 -27187
- package/cjs/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
- package/cjs/Core-C33pkBmf.d.ts +826 -0
- package/cjs/Core-Cm5Z1oJ9.js +1001 -0
- package/cjs/FileIcons-4qSX7DW2.d.ts +67 -0
- package/cjs/{ModerationContextLimits-2nIv7Zh3.js → ModerationContextLimits-ud1xpZRK.js} +727 -268
- package/cjs/{ReactUpload-BdTRCTGA.js → ReactUpload-DQ0BYISX.js} +1 -1
- package/cjs/{ReactUpload-CRJNPB5T.d.ts → ReactUpload-DhF8mm51.d.ts} +1 -1
- package/{esm/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → cjs/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
- package/cjs/{TestTriggers-DbhsNPdg-DjvVuc2h.js → TestTriggers-D29T_R0M-D6Bu-Mln.js} +355 -47
- package/cjs/{UploadController-MLVs97Zt.js → UploadController-l8fZM2qT.js} +34 -14
- package/{esm/WebhookPayload-DkukERKE.d.ts → cjs/WebhookPayload-Dt6DttS0.d.ts} +120 -86
- package/cjs/app.d.ts +6 -7
- package/cjs/app.js +4 -3
- package/cjs/elements.d.ts +123 -22
- package/cjs/elements.js +553 -156
- package/cjs/file-icons.d.ts +2 -67
- package/cjs/index-Bde1wjiw.d.ts +16 -0
- package/cjs/index.d.ts +5 -6
- package/cjs/index.js +3 -2
- package/cjs/react-native.d.ts +52 -11
- package/cjs/react-native.js +231 -99
- package/cjs/react.d.ts +42 -9
- package/cjs/react.js +381 -118
- package/cjs/server.d.ts +48 -7
- package/cjs/server.js +7 -3
- package/cjs/test-inputs.d.ts +2 -2
- package/cjs/test-inputs.js +13 -9
- package/cjs/testing.d.ts +29 -15
- package/cjs/testing.js +1722 -433
- package/cjs/ui-BRA4HQ8r.js +1359 -0
- package/cjs/ui-YQuvbidU.d.ts +139 -0
- package/cjs/ui.d.ts +3 -2
- package/cjs/ui.js +45 -22
- package/cjs/vue.d.ts +802 -199
- package/cjs/vue.js +359 -127
- package/esm/{BrowserUpload-C07aL9Vq.d.ts → BrowserUpload-BWjZ9ntu.d.ts} +2 -2
- package/esm/{BrowserUpload-CAVkRotw.js → BrowserUpload-GRZVB0G_.js} +1 -1
- package/esm/{CalmLensAppClient-PQ9VBvlW.js → CalmLensAppClient-B5QIJ6KS.js} +30 -10
- package/esm/{CalmLensAppClient-DDLojj0P.d.ts → CalmLensAppClient-BaW3ddUR.d.ts} +13 -3
- package/esm/{CalmLensOptionKeys-Do2mPP6w.js → CalmLensOptionKeys-BG7Qrh8-.js} +317 -367
- package/esm/CalmLensServerClient-BKzn8zmp.d.ts +353 -0
- package/esm/{CalmLensServerClient-C_H5aAsV.js → CalmLensServerClient-bRUAebi-.js} +323 -90
- package/esm/{CalmLensTypes-COJbOuiv.d.ts → CalmLensTypes-BDKwThbO.d.ts} +26993 -27187
- package/esm/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
- package/esm/Core-BvQe4moS.js +846 -0
- package/esm/Core-C33pkBmf.d.ts +826 -0
- package/esm/FileIcons-4qSX7DW2.d.ts +67 -0
- package/esm/{ModerationContextLimits-Chw-AzgL.js → ModerationContextLimits-CrxSnVZ3.js} +682 -253
- package/esm/{ReactUpload-CMmL0R5Q.js → ReactUpload-BMO8saxT.js} +1 -1
- package/esm/{ReactUpload-CRJNPB5T.d.ts → ReactUpload-DhF8mm51.d.ts} +1 -1
- package/{cjs/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → esm/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
- package/esm/{TestTriggers-DbhsNPdg-CUdrv8Nm.js → TestTriggers-D29T_R0M-Ztc74ucs.js} +332 -48
- package/esm/{UploadController-BJZghJpg.js → UploadController-DnJrWiE4.js} +34 -14
- package/{cjs/WebhookPayload-DkukERKE.d.ts → esm/WebhookPayload-Dt6DttS0.d.ts} +120 -86
- package/esm/app.d.ts +6 -7
- package/esm/app.js +3 -3
- package/esm/elements.d.ts +123 -22
- package/esm/elements.js +497 -128
- package/esm/file-icons.d.ts +2 -67
- package/esm/index-Bde1wjiw.d.ts +16 -0
- package/esm/index.d.ts +5 -6
- package/esm/index.js +1 -1
- package/esm/react-native.d.ts +52 -11
- package/esm/react-native.js +205 -75
- package/esm/react.d.ts +42 -9
- package/esm/react.js +327 -91
- package/esm/server.d.ts +48 -7
- package/esm/server.js +3 -3
- package/esm/styles.css +142 -22
- package/esm/svelte/AssetViewer.svelte +25 -0
- package/esm/svelte/CalmLensAsset.svelte +318 -0
- package/esm/svelte/CalmLensDocumentViewer.svelte +7 -0
- package/esm/svelte/CalmLensImageViewer.svelte +7 -0
- package/esm/svelte/CalmLensSpreadsheetViewer.svelte +7 -0
- package/esm/svelte/CalmLensTextViewer.svelte +7 -0
- package/esm/svelte/CalmLensWebsiteViewer.svelte +7 -0
- package/esm/svelte/index.d.ts +29 -6
- package/esm/svelte/index.js +7 -2
- package/esm/test-inputs.d.ts +2 -2
- package/esm/test-inputs.js +1 -1
- package/esm/testing.d.ts +29 -15
- package/esm/testing.js +1718 -429
- package/esm/ui-YQuvbidU.d.ts +139 -0
- package/esm/ui-heryDd6g.js +1258 -0
- package/esm/ui.d.ts +3 -2
- package/esm/ui.js +4 -3
- package/esm/vue.d.ts +802 -199
- package/esm/vue.js +308 -103
- package/package.json +4 -2
- package/cjs/CalmLensServerClient-C-jsjn8m.d.ts +0 -259
- package/cjs/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
- package/cjs/index-DxbJ_Xaa.d.ts +0 -253
- package/cjs/ui-BSqPGKrZ.d.ts +0 -539
- package/cjs/ui-CX1z2pD9.js +0 -586
- package/esm/CalmLensServerClient-C-jsjn8m.d.ts +0 -259
- package/esm/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
- package/esm/index-DxbJ_Xaa.d.ts +0 -253
- package/esm/svelte/CalmLensMedia.svelte +0 -134
- package/esm/ui-BSqPGKrZ.d.ts +0 -539
- package/esm/ui-CXH7xJpb.js +0 -461
package/cjs/testing.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
3
|
-
const require_ModerationContextLimits = require("./ModerationContextLimits-
|
|
4
|
-
const require_CalmLensServerClient = require("./CalmLensServerClient-
|
|
5
|
-
const require_CalmLensOptionKeys = require("./CalmLensOptionKeys-
|
|
2
|
+
const require_TestTriggers_D29T_R0M = require("./TestTriggers-D29T_R0M-D6Bu-Mln.js");
|
|
3
|
+
const require_ModerationContextLimits = require("./ModerationContextLimits-ud1xpZRK.js");
|
|
4
|
+
const require_CalmLensServerClient = require("./CalmLensServerClient-3N-gdsxC.js");
|
|
5
|
+
const require_CalmLensOptionKeys = require("./CalmLensOptionKeys-YvgV995V.js");
|
|
6
6
|
const require_CryptoUtils_B_x8lMIx = require("./CryptoUtils-B_x8lMIx-YBW1-bvL.js");
|
|
7
|
-
const require_CalmLensAppClient = require("./CalmLensAppClient-
|
|
8
|
-
const require_UploadController = require("./UploadController-
|
|
7
|
+
const require_CalmLensAppClient = require("./CalmLensAppClient-DUYMo9PZ.js");
|
|
8
|
+
const require_UploadController = require("./UploadController-l8fZM2qT.js");
|
|
9
9
|
let zod = require("zod");
|
|
10
|
-
zod =
|
|
10
|
+
zod = require_TestTriggers_D29T_R0M.__toESM(zod, 1);
|
|
11
11
|
// src/contract/MediaTestTriggers.js
|
|
12
|
-
const MEDIA_TEST_SIGNALS = [...
|
|
12
|
+
const MEDIA_TEST_SIGNALS = [...require_TestTriggers_D29T_R0M.CLASSIFICATION_CATEGORIES, "violence.graphic"];
|
|
13
13
|
const HEX_WORDS = [
|
|
14
14
|
"zero",
|
|
15
15
|
"one",
|
|
@@ -31,9 +31,9 @@ const HEX_WORDS = [
|
|
|
31
31
|
/** Read this aloud, or render it as large, high-contrast text in a video frame. */
|
|
32
32
|
async function generateMediaTestCode(signal, testInputKey) {
|
|
33
33
|
if (!MEDIA_TEST_SIGNALS.includes(signal)) throw new RangeError("Unsupported media test signal");
|
|
34
|
-
return `Calm Lens test ${[...await
|
|
34
|
+
return `Calm Lens test ${[...await require_TestTriggers_D29T_R0M.getTestInputTag("media", signal, testInputKey)].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
|
|
35
35
|
}
|
|
36
|
-
// src/contract/Ids-
|
|
36
|
+
// src/contract/Ids-BESMSxGb.js
|
|
37
37
|
var __defProp = Object.defineProperty;
|
|
38
38
|
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
|
|
39
39
|
var __exportAll = (all, no_symbols) => {
|
|
@@ -7909,6 +7909,7 @@ const ID_PREFIXES = {
|
|
|
7909
7909
|
member: "mem",
|
|
7910
7910
|
invitation: "inv",
|
|
7911
7911
|
transfer: "xfer",
|
|
7912
|
+
assetBatch: "batch",
|
|
7912
7913
|
supportTicket: "tkt",
|
|
7913
7914
|
supportTicketMessage: "msg",
|
|
7914
7915
|
humanReview: "rev",
|
|
@@ -7970,6 +7971,7 @@ const EXAMPLE_IDS = {
|
|
|
7970
7971
|
mem: "mem_9Xm4Rk7Lq2Vt8Wb3Np5C",
|
|
7971
7972
|
inv: "inv_3Qk8Xm2Rt9Lv4Wb7Np6C",
|
|
7972
7973
|
xfer: "xfer_6Lq2Xm8Rk4Vt9Wb3Np7C",
|
|
7974
|
+
batch: "batch_5Rt8Xm3Lq9Vk2Wb7Np4C",
|
|
7973
7975
|
tkt: "tkt_6Xm2Rk9Lq4Vt7Wb3Np8C",
|
|
7974
7976
|
msg: "msg_2Rk7Xm4Lq9Vt3Wb8Np5C",
|
|
7975
7977
|
rev: "rev_8Xm3Rk2Lq7Vt9Wb4Np6C",
|
|
@@ -7987,7 +7989,7 @@ const EXAMPLE_IDS = {
|
|
|
7987
7989
|
* across the packages that build records from plain strings).
|
|
7988
7990
|
*/
|
|
7989
7991
|
const idField = (prefix) => zod.string().regex(idPattern(prefix), { message: `Must be a valid ID: "${prefix}_" followed by 20 letters or digits` }).meta({ examples: [EXAMPLE_IDS[prefix]] });
|
|
7990
|
-
// src/contract/Permissions-
|
|
7992
|
+
// src/contract/Permissions-DPNlE8m-.js
|
|
7991
7993
|
const ACTION_SCHEMA = zod.enum([
|
|
7992
7994
|
"assets:read",
|
|
7993
7995
|
"assets:download",
|
|
@@ -8044,10 +8046,13 @@ const GRANT_SCHEMA = zod.object({
|
|
|
8044
8046
|
const GRANTS_SCHEMA = zod.array(GRANT_SCHEMA).max(100);
|
|
8045
8047
|
zod.enum([
|
|
8046
8048
|
"admin",
|
|
8049
|
+
"configurator",
|
|
8047
8050
|
"editor",
|
|
8048
8051
|
"viewer",
|
|
8049
8052
|
"custom"
|
|
8050
8053
|
]);
|
|
8054
|
+
[...ACTION_SCHEMA.options.filter((a) => !isProjectAction(a))];
|
|
8055
|
+
[...ACTION_SCHEMA.options.filter((a) => !isProjectAction(a))];
|
|
8051
8056
|
const permits = (grants, action, folderId, folders) => grants.some((grant) => {
|
|
8052
8057
|
if (![action, ...actionsImplying(action)].some((held) => grant.actions.includes(held))) return false;
|
|
8053
8058
|
if (grant.folderId === null) return true;
|
|
@@ -8108,6 +8113,8 @@ const MOCK_QUALIFIERS = {
|
|
|
8108
8113
|
"sexual-non-consensual",
|
|
8109
8114
|
"sexual-intimate-image-abuse",
|
|
8110
8115
|
"sexual-extreme",
|
|
8116
|
+
"sexual-strangulation",
|
|
8117
|
+
"sexual-incest",
|
|
8111
8118
|
"sexual-minors",
|
|
8112
8119
|
"sexual-solicitation",
|
|
8113
8120
|
"sexual-paid",
|
|
@@ -8319,7 +8326,7 @@ var MockDecision = class {
|
|
|
8319
8326
|
}
|
|
8320
8327
|
/**
|
|
8321
8328
|
* The report a decided asset gets, as the API sends it: every category (unflagged ones
|
|
8322
|
-
* evaluated with score 0), policy-adjusted results and the automated
|
|
8329
|
+
* evaluated with score 0), policy-adjusted results and the automated status and
|
|
8323
8330
|
* `flaggedCategories`. `undefined` for `pending` and `failed`.
|
|
8324
8331
|
*/
|
|
8325
8332
|
report() {
|
|
@@ -8351,11 +8358,19 @@ var MockDecision = class {
|
|
|
8351
8358
|
action: action(score)
|
|
8352
8359
|
}])),
|
|
8353
8360
|
explanationComplete: true,
|
|
8361
|
+
policy: null,
|
|
8362
|
+
pendingReview: null,
|
|
8354
8363
|
source: "policy",
|
|
8355
|
-
|
|
8364
|
+
rule: null,
|
|
8365
|
+
automatedStatus: status,
|
|
8356
8366
|
regions: [],
|
|
8367
|
+
linkSafety: null,
|
|
8368
|
+
timeline: null,
|
|
8357
8369
|
flaggedCategories: evaluated.filter(([, score]) => action(score) !== "allow").map(([category]) => category),
|
|
8358
|
-
raw: {
|
|
8370
|
+
raw: {
|
|
8371
|
+
categories,
|
|
8372
|
+
hashMatches: []
|
|
8373
|
+
}
|
|
8359
8374
|
};
|
|
8360
8375
|
}
|
|
8361
8376
|
};
|
|
@@ -8363,17 +8378,395 @@ var MockDecision = class {
|
|
|
8363
8378
|
const mockDecision = (status) => new MockDecision(status);
|
|
8364
8379
|
/** The default `moderate`: queued work stays pending until `completeProcessing`, which allows it. */
|
|
8365
8380
|
const defaultModerate = ({ trigger, queued }) => queued && trigger !== "complete" ? "pending" : "allowed";
|
|
8381
|
+
// src/testing/MockAssetFilters.ts
|
|
8382
|
+
/** The asset fields a list filter may name, each with the operators it accepts. */
|
|
8383
|
+
const MOCK_ASSET_FILTER_FIELDS = {
|
|
8384
|
+
id: {
|
|
8385
|
+
kind: "text",
|
|
8386
|
+
nullable: false,
|
|
8387
|
+
operators: [
|
|
8388
|
+
"==",
|
|
8389
|
+
"!=",
|
|
8390
|
+
">",
|
|
8391
|
+
">=",
|
|
8392
|
+
"<",
|
|
8393
|
+
"<=",
|
|
8394
|
+
"=in=",
|
|
8395
|
+
"=out="
|
|
8396
|
+
]
|
|
8397
|
+
},
|
|
8398
|
+
parentId: {
|
|
8399
|
+
kind: "text",
|
|
8400
|
+
nullable: true,
|
|
8401
|
+
operators: [
|
|
8402
|
+
"==",
|
|
8403
|
+
"!=",
|
|
8404
|
+
">",
|
|
8405
|
+
">=",
|
|
8406
|
+
"<",
|
|
8407
|
+
"<=",
|
|
8408
|
+
"=in=",
|
|
8409
|
+
"=out="
|
|
8410
|
+
]
|
|
8411
|
+
},
|
|
8412
|
+
folderId: {
|
|
8413
|
+
kind: "text",
|
|
8414
|
+
nullable: true,
|
|
8415
|
+
operators: [
|
|
8416
|
+
"==",
|
|
8417
|
+
"!=",
|
|
8418
|
+
">",
|
|
8419
|
+
">=",
|
|
8420
|
+
"<",
|
|
8421
|
+
"<=",
|
|
8422
|
+
"=in=",
|
|
8423
|
+
"=out="
|
|
8424
|
+
]
|
|
8425
|
+
},
|
|
8426
|
+
uploadPresetId: {
|
|
8427
|
+
kind: "text",
|
|
8428
|
+
nullable: true,
|
|
8429
|
+
operators: [
|
|
8430
|
+
"==",
|
|
8431
|
+
"!=",
|
|
8432
|
+
">",
|
|
8433
|
+
">=",
|
|
8434
|
+
"<",
|
|
8435
|
+
"<=",
|
|
8436
|
+
"=in=",
|
|
8437
|
+
"=out="
|
|
8438
|
+
]
|
|
8439
|
+
},
|
|
8440
|
+
createdAt: {
|
|
8441
|
+
kind: "number",
|
|
8442
|
+
nullable: false,
|
|
8443
|
+
operators: [
|
|
8444
|
+
"==",
|
|
8445
|
+
"!=",
|
|
8446
|
+
">",
|
|
8447
|
+
">=",
|
|
8448
|
+
"<",
|
|
8449
|
+
"<=",
|
|
8450
|
+
"=in=",
|
|
8451
|
+
"=out="
|
|
8452
|
+
]
|
|
8453
|
+
},
|
|
8454
|
+
updatedAt: {
|
|
8455
|
+
kind: "number",
|
|
8456
|
+
nullable: false,
|
|
8457
|
+
operators: [
|
|
8458
|
+
"==",
|
|
8459
|
+
"!=",
|
|
8460
|
+
">",
|
|
8461
|
+
">=",
|
|
8462
|
+
"<",
|
|
8463
|
+
"<=",
|
|
8464
|
+
"=in=",
|
|
8465
|
+
"=out="
|
|
8466
|
+
]
|
|
8467
|
+
},
|
|
8468
|
+
type: {
|
|
8469
|
+
kind: "text",
|
|
8470
|
+
nullable: false,
|
|
8471
|
+
operators: [
|
|
8472
|
+
"==",
|
|
8473
|
+
"!=",
|
|
8474
|
+
">",
|
|
8475
|
+
">=",
|
|
8476
|
+
"<",
|
|
8477
|
+
"<=",
|
|
8478
|
+
"=in=",
|
|
8479
|
+
"=out="
|
|
8480
|
+
]
|
|
8481
|
+
},
|
|
8482
|
+
name: {
|
|
8483
|
+
kind: "text",
|
|
8484
|
+
nullable: false,
|
|
8485
|
+
operators: [
|
|
8486
|
+
"==",
|
|
8487
|
+
"!=",
|
|
8488
|
+
">",
|
|
8489
|
+
">=",
|
|
8490
|
+
"<",
|
|
8491
|
+
"<=",
|
|
8492
|
+
"=in=",
|
|
8493
|
+
"=out="
|
|
8494
|
+
]
|
|
8495
|
+
},
|
|
8496
|
+
description: {
|
|
8497
|
+
kind: "text",
|
|
8498
|
+
nullable: true,
|
|
8499
|
+
operators: [
|
|
8500
|
+
"==",
|
|
8501
|
+
"!=",
|
|
8502
|
+
">",
|
|
8503
|
+
">=",
|
|
8504
|
+
"<",
|
|
8505
|
+
"<=",
|
|
8506
|
+
"=in=",
|
|
8507
|
+
"=out="
|
|
8508
|
+
]
|
|
8509
|
+
},
|
|
8510
|
+
externalId: {
|
|
8511
|
+
kind: "text",
|
|
8512
|
+
nullable: true,
|
|
8513
|
+
operators: [
|
|
8514
|
+
"==",
|
|
8515
|
+
"!=",
|
|
8516
|
+
">",
|
|
8517
|
+
">=",
|
|
8518
|
+
"<",
|
|
8519
|
+
"<=",
|
|
8520
|
+
"=in=",
|
|
8521
|
+
"=out="
|
|
8522
|
+
]
|
|
8523
|
+
},
|
|
8524
|
+
externalUrl: {
|
|
8525
|
+
kind: "text",
|
|
8526
|
+
nullable: true,
|
|
8527
|
+
operators: [
|
|
8528
|
+
"==",
|
|
8529
|
+
"!=",
|
|
8530
|
+
">",
|
|
8531
|
+
">=",
|
|
8532
|
+
"<",
|
|
8533
|
+
"<=",
|
|
8534
|
+
"=in=",
|
|
8535
|
+
"=out="
|
|
8536
|
+
]
|
|
8537
|
+
},
|
|
8538
|
+
authorId: {
|
|
8539
|
+
kind: "text",
|
|
8540
|
+
nullable: true,
|
|
8541
|
+
operators: [
|
|
8542
|
+
"==",
|
|
8543
|
+
"!=",
|
|
8544
|
+
">",
|
|
8545
|
+
">=",
|
|
8546
|
+
"<",
|
|
8547
|
+
"<=",
|
|
8548
|
+
"=in=",
|
|
8549
|
+
"=out="
|
|
8550
|
+
]
|
|
8551
|
+
},
|
|
8552
|
+
tags: {
|
|
8553
|
+
kind: "list",
|
|
8554
|
+
nullable: false,
|
|
8555
|
+
operators: ["=in=", "=out="]
|
|
8556
|
+
},
|
|
8557
|
+
visibility: {
|
|
8558
|
+
kind: "text",
|
|
8559
|
+
nullable: true,
|
|
8560
|
+
operators: [
|
|
8561
|
+
"==",
|
|
8562
|
+
"!=",
|
|
8563
|
+
">",
|
|
8564
|
+
">=",
|
|
8565
|
+
"<",
|
|
8566
|
+
"<=",
|
|
8567
|
+
"=in=",
|
|
8568
|
+
"=out="
|
|
8569
|
+
]
|
|
8570
|
+
},
|
|
8571
|
+
"upload.status": {
|
|
8572
|
+
kind: "text",
|
|
8573
|
+
nullable: false,
|
|
8574
|
+
operators: [
|
|
8575
|
+
"==",
|
|
8576
|
+
"!=",
|
|
8577
|
+
">",
|
|
8578
|
+
">=",
|
|
8579
|
+
"<",
|
|
8580
|
+
"<=",
|
|
8581
|
+
"=in=",
|
|
8582
|
+
"=out="
|
|
8583
|
+
]
|
|
8584
|
+
},
|
|
8585
|
+
"upload.updatedAt": {
|
|
8586
|
+
kind: "number",
|
|
8587
|
+
nullable: true,
|
|
8588
|
+
operators: [
|
|
8589
|
+
"==",
|
|
8590
|
+
"!=",
|
|
8591
|
+
">",
|
|
8592
|
+
">=",
|
|
8593
|
+
"<",
|
|
8594
|
+
"<=",
|
|
8595
|
+
"=in=",
|
|
8596
|
+
"=out="
|
|
8597
|
+
]
|
|
8598
|
+
},
|
|
8599
|
+
"classification.status": {
|
|
8600
|
+
kind: "text",
|
|
8601
|
+
nullable: false,
|
|
8602
|
+
operators: [
|
|
8603
|
+
"==",
|
|
8604
|
+
"!=",
|
|
8605
|
+
">",
|
|
8606
|
+
">=",
|
|
8607
|
+
"<",
|
|
8608
|
+
"<=",
|
|
8609
|
+
"=in=",
|
|
8610
|
+
"=out="
|
|
8611
|
+
]
|
|
8612
|
+
},
|
|
8613
|
+
"classification.updatedAt": {
|
|
8614
|
+
kind: "number",
|
|
8615
|
+
nullable: true,
|
|
8616
|
+
operators: [
|
|
8617
|
+
"==",
|
|
8618
|
+
"!=",
|
|
8619
|
+
">",
|
|
8620
|
+
">=",
|
|
8621
|
+
"<",
|
|
8622
|
+
"<=",
|
|
8623
|
+
"=in=",
|
|
8624
|
+
"=out="
|
|
8625
|
+
]
|
|
8626
|
+
},
|
|
8627
|
+
"classification.completedAt": {
|
|
8628
|
+
kind: "number",
|
|
8629
|
+
nullable: true,
|
|
8630
|
+
operators: [
|
|
8631
|
+
"==",
|
|
8632
|
+
"!=",
|
|
8633
|
+
">",
|
|
8634
|
+
">=",
|
|
8635
|
+
"<",
|
|
8636
|
+
"<=",
|
|
8637
|
+
"=in=",
|
|
8638
|
+
"=out="
|
|
8639
|
+
]
|
|
8640
|
+
},
|
|
8641
|
+
"classification.moderation.status": {
|
|
8642
|
+
kind: "text",
|
|
8643
|
+
nullable: false,
|
|
8644
|
+
operators: [
|
|
8645
|
+
"==",
|
|
8646
|
+
"!=",
|
|
8647
|
+
">",
|
|
8648
|
+
">=",
|
|
8649
|
+
"<",
|
|
8650
|
+
"<=",
|
|
8651
|
+
"=in=",
|
|
8652
|
+
"=out="
|
|
8653
|
+
]
|
|
8654
|
+
},
|
|
8655
|
+
"content.status": {
|
|
8656
|
+
kind: "text",
|
|
8657
|
+
nullable: false,
|
|
8658
|
+
operators: [
|
|
8659
|
+
"==",
|
|
8660
|
+
"!=",
|
|
8661
|
+
">",
|
|
8662
|
+
">=",
|
|
8663
|
+
"<",
|
|
8664
|
+
"<=",
|
|
8665
|
+
"=in=",
|
|
8666
|
+
"=out="
|
|
8667
|
+
]
|
|
8668
|
+
},
|
|
8669
|
+
"content.removalReason": {
|
|
8670
|
+
kind: "text",
|
|
8671
|
+
nullable: true,
|
|
8672
|
+
operators: [
|
|
8673
|
+
"==",
|
|
8674
|
+
"!=",
|
|
8675
|
+
">",
|
|
8676
|
+
">=",
|
|
8677
|
+
"<",
|
|
8678
|
+
"<=",
|
|
8679
|
+
"=in=",
|
|
8680
|
+
"=out="
|
|
8681
|
+
]
|
|
8682
|
+
},
|
|
8683
|
+
"content.updatedAt": {
|
|
8684
|
+
kind: "number",
|
|
8685
|
+
nullable: true,
|
|
8686
|
+
operators: [
|
|
8687
|
+
"==",
|
|
8688
|
+
"!=",
|
|
8689
|
+
">",
|
|
8690
|
+
">=",
|
|
8691
|
+
"<",
|
|
8692
|
+
"<=",
|
|
8693
|
+
"=in=",
|
|
8694
|
+
"=out="
|
|
8695
|
+
]
|
|
8696
|
+
},
|
|
8697
|
+
"content.format": {
|
|
8698
|
+
kind: "text",
|
|
8699
|
+
nullable: true,
|
|
8700
|
+
operators: [
|
|
8701
|
+
"==",
|
|
8702
|
+
"!=",
|
|
8703
|
+
">",
|
|
8704
|
+
">=",
|
|
8705
|
+
"<",
|
|
8706
|
+
"<=",
|
|
8707
|
+
"=in=",
|
|
8708
|
+
"=out="
|
|
8709
|
+
]
|
|
8710
|
+
},
|
|
8711
|
+
"content.extension": {
|
|
8712
|
+
kind: "text",
|
|
8713
|
+
nullable: true,
|
|
8714
|
+
operators: [
|
|
8715
|
+
"==",
|
|
8716
|
+
"!=",
|
|
8717
|
+
">",
|
|
8718
|
+
">=",
|
|
8719
|
+
"<",
|
|
8720
|
+
"<=",
|
|
8721
|
+
"=in=",
|
|
8722
|
+
"=out="
|
|
8723
|
+
]
|
|
8724
|
+
},
|
|
8725
|
+
"content.sizeInBytes": {
|
|
8726
|
+
kind: "number",
|
|
8727
|
+
nullable: true,
|
|
8728
|
+
operators: [
|
|
8729
|
+
"==",
|
|
8730
|
+
"!=",
|
|
8731
|
+
">",
|
|
8732
|
+
">=",
|
|
8733
|
+
"<",
|
|
8734
|
+
"<=",
|
|
8735
|
+
"=in=",
|
|
8736
|
+
"=out="
|
|
8737
|
+
]
|
|
8738
|
+
}
|
|
8739
|
+
};
|
|
8366
8740
|
// src/testing/MockUtils.ts
|
|
8741
|
+
/**
|
|
8742
|
+
* A `sort` query value as the API parses it (`sortQueryField` in shared/Page.ts): comma-separated
|
|
8743
|
+
* fields from `fields`, descending when prefixed with `-`, none repeated and at most `max`.
|
|
8744
|
+
* Undefined for a list that sends none; `undefined`'s default applies.
|
|
8745
|
+
*/
|
|
8746
|
+
const parseSort = (value, fields, max, fail) => {
|
|
8747
|
+
if (value === null) return void 0;
|
|
8748
|
+
const sort = [];
|
|
8749
|
+
for (const part of value.split(",").map((item) => item.trim())) {
|
|
8750
|
+
const field = part.startsWith("-") ? part.slice(1) : part;
|
|
8751
|
+
if (!/^-?[A-Za-z][A-Za-z0-9.]*$/.test(part) || !fields.includes(field)) throw fail();
|
|
8752
|
+
if (sort.some((rule) => rule.field === field)) throw fail();
|
|
8753
|
+
sort.push({
|
|
8754
|
+
field,
|
|
8755
|
+
direction: part.startsWith("-") ? "desc" : "asc"
|
|
8756
|
+
});
|
|
8757
|
+
}
|
|
8758
|
+
if (sort.length > max) throw fail();
|
|
8759
|
+
return sort;
|
|
8760
|
+
};
|
|
8367
8761
|
const toBase64Utf8 = (value) => btoa(Array.from(new TextEncoder().encode(value), (byte) => String.fromCharCode(byte)).join(""));
|
|
8368
8762
|
const fromBase64Utf8 = (value) => new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(atob(value), (char) => char.charCodeAt(0)));
|
|
8369
8763
|
/**
|
|
8370
8764
|
* One keyset page like the API's (packages/shared-backend/src/CursorPagination.ts): ordered by
|
|
8371
|
-
* `
|
|
8372
|
-
*
|
|
8373
|
-
*
|
|
8374
|
-
* point, like the database.
|
|
8765
|
+
* `sort` (newest first by default) with an `id` tie-breaker added, starting after the cursor's
|
|
8766
|
+
* values. The cursor is tied to `scope` (the filter, folder or parent) and the sort, so it only
|
|
8767
|
+
* continues the query it came from. `name` and `id` are compared by code point, like the database.
|
|
8375
8768
|
*/
|
|
8376
|
-
const createPage = (items, query, { scope, fail, defaultPageSize = 50,
|
|
8769
|
+
const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultSort = [{
|
|
8377
8770
|
field: "createdAt",
|
|
8378
8771
|
direction: "desc"
|
|
8379
8772
|
}] }) => {
|
|
@@ -8381,7 +8774,7 @@ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOr
|
|
|
8381
8774
|
if (typeof pageSize !== "number" || !Number.isFinite(pageSize) || pageSize < 1) throw fail("validation/too-small", "pageSize");
|
|
8382
8775
|
if (pageSize > 100) throw fail("validation/too-big", "pageSize");
|
|
8383
8776
|
if (!Number.isInteger(pageSize)) throw require_ModerationContextLimits.invalidArgument("Invalid page size");
|
|
8384
|
-
const ordering = query.
|
|
8777
|
+
const ordering = query.sort?.length ? [...query.sort] : [...defaultSort];
|
|
8385
8778
|
if (!ordering.some(({ field }) => field === "id")) ordering.push({
|
|
8386
8779
|
field: "id",
|
|
8387
8780
|
direction: ordering[0].direction
|
|
@@ -8395,7 +8788,7 @@ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOr
|
|
|
8395
8788
|
values = parsed?.values;
|
|
8396
8789
|
if (parsed?.scope !== signature || !Array.isArray(values) || values.length !== ordering.length || values.some((value, i) => STRING_FIELDS.has(ordering[i].field) ? typeof value !== "string" : typeof value !== "number" || !Number.isFinite(value))) throw new Error();
|
|
8397
8790
|
} catch {
|
|
8398
|
-
throw fail("
|
|
8791
|
+
throw fail("cursor/invalid");
|
|
8399
8792
|
}
|
|
8400
8793
|
remaining = remaining.filter((item) => {
|
|
8401
8794
|
for (const [i, rule] of ordering.entries()) {
|
|
@@ -8410,9 +8803,7 @@ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOr
|
|
|
8410
8803
|
const last = pageItems.at(-1);
|
|
8411
8804
|
return {
|
|
8412
8805
|
items: pageItems,
|
|
8413
|
-
pageSize,
|
|
8414
8806
|
hasMore,
|
|
8415
|
-
ordering,
|
|
8416
8807
|
nextCursor: hasMore && last ? toBase64Utf8(JSON.stringify({
|
|
8417
8808
|
scope: signature,
|
|
8418
8809
|
values: ordering.map(({ field }) => last[field])
|
|
@@ -8428,7 +8819,7 @@ const compareValues = (left, right) => {
|
|
|
8428
8819
|
const [a, b] = [String(left), String(right)];
|
|
8429
8820
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
8430
8821
|
};
|
|
8431
|
-
/** Sorts like the API's `
|
|
8822
|
+
/** Sorts like the API's `sort`; without one, newest first. */
|
|
8432
8823
|
const orderItems = (items, ordering) => {
|
|
8433
8824
|
const rules = ordering?.length ? ordering : [{
|
|
8434
8825
|
field: "createdAt",
|
|
@@ -8442,90 +8833,196 @@ const orderItems = (items, ordering) => {
|
|
|
8442
8833
|
return 0;
|
|
8443
8834
|
});
|
|
8444
8835
|
};
|
|
8445
|
-
|
|
8446
|
-
|
|
8447
|
-
|
|
8448
|
-
|
|
8449
|
-
|
|
8450
|
-
|
|
8451
|
-
|
|
8452
|
-
|
|
8453
|
-
|
|
8836
|
+
/** Thrown for a filter the API refuses with `filter/invalid`. */
|
|
8837
|
+
var MockInvalidFilter = class extends Error {};
|
|
8838
|
+
/** The characters that end an unquoted word, as in @rsql/parser. */
|
|
8839
|
+
const RESERVED = "\"'();,=!~<> \n \r";
|
|
8840
|
+
const LOGIC_WORDS = ["and", "or"];
|
|
8841
|
+
/** Splits a filter into tokens like @rsql/parser's lexer. */
|
|
8842
|
+
const tokenize = (filter) => {
|
|
8843
|
+
const tokens = [];
|
|
8844
|
+
let i = 0;
|
|
8845
|
+
while (i < filter.length) {
|
|
8846
|
+
const char = filter[i];
|
|
8847
|
+
if (" \n \r".includes(char)) i++;
|
|
8848
|
+
else if (char === "\"" || char === "'") {
|
|
8849
|
+
let text = "";
|
|
8850
|
+
let j = i + 1;
|
|
8851
|
+
for (; j < filter.length && filter[j] !== char; j++) {
|
|
8852
|
+
if (filter[j] === "\\" && j + 1 < filter.length) j++;
|
|
8853
|
+
text += filter[j];
|
|
8854
|
+
}
|
|
8855
|
+
if (j >= filter.length) throw new MockInvalidFilter();
|
|
8856
|
+
tokens.push({
|
|
8857
|
+
kind: "quoted",
|
|
8858
|
+
text
|
|
8859
|
+
});
|
|
8860
|
+
i = j + 1;
|
|
8861
|
+
} else if (char === "(" || char === ")") {
|
|
8862
|
+
tokens.push({
|
|
8863
|
+
kind: "paren",
|
|
8864
|
+
text: char
|
|
8865
|
+
});
|
|
8866
|
+
i++;
|
|
8867
|
+
} else if (char === ";" || char === ",") {
|
|
8868
|
+
tokens.push({
|
|
8869
|
+
kind: "logic",
|
|
8870
|
+
text: char === ";" ? "and" : "or"
|
|
8871
|
+
});
|
|
8872
|
+
i++;
|
|
8873
|
+
} else if ("=!~<>".includes(char)) {
|
|
8874
|
+
const operator = /^(==|!=|<=|>=|<|>|=[a-z]*=)/.exec(filter.slice(i))?.[0];
|
|
8875
|
+
if (!operator) throw new MockInvalidFilter();
|
|
8876
|
+
tokens.push({
|
|
8877
|
+
kind: "operator",
|
|
8878
|
+
text: operator
|
|
8879
|
+
});
|
|
8880
|
+
i += operator.length;
|
|
8881
|
+
} else {
|
|
8882
|
+
const word = LOGIC_WORDS.find((logic) => filter.startsWith(`${logic} `, i));
|
|
8883
|
+
if (word) {
|
|
8884
|
+
tokens.push({
|
|
8885
|
+
kind: "logic",
|
|
8886
|
+
text: word
|
|
8887
|
+
});
|
|
8888
|
+
i += word.length;
|
|
8889
|
+
continue;
|
|
8890
|
+
}
|
|
8891
|
+
let j = i + 1;
|
|
8892
|
+
while (j < filter.length && !RESERVED.includes(filter[j])) j++;
|
|
8893
|
+
tokens.push({
|
|
8894
|
+
kind: "word",
|
|
8895
|
+
text: filter.slice(i, j)
|
|
8896
|
+
});
|
|
8897
|
+
i = j;
|
|
8898
|
+
}
|
|
8899
|
+
}
|
|
8900
|
+
return tokens;
|
|
8901
|
+
};
|
|
8902
|
+
/**
|
|
8903
|
+
* A field's value as the API reads it (zodbase/rsql): `null` is a missing value only on a
|
|
8904
|
+
* nullable field, and a number field's value must be a finite number.
|
|
8905
|
+
*/
|
|
8906
|
+
const readFilterValue = (field, text) => {
|
|
8907
|
+
const { kind, nullable } = MOCK_ASSET_FILTER_FIELDS[field];
|
|
8908
|
+
if (text === "null" && nullable) return null;
|
|
8909
|
+
if (kind !== "number") return text;
|
|
8910
|
+
const number = Number(text);
|
|
8911
|
+
if (text === "" || !Number.isFinite(number)) throw new MockInvalidFilter();
|
|
8912
|
+
return number;
|
|
8913
|
+
};
|
|
8914
|
+
/** Parses a filter: `;` (and) binds tighter than `,` (or), and parentheses group. */
|
|
8915
|
+
const parseFilter = (filter) => {
|
|
8916
|
+
const tokens = tokenize(filter);
|
|
8917
|
+
let position = 0;
|
|
8918
|
+
const peek = () => tokens[position];
|
|
8919
|
+
const next = () => {
|
|
8920
|
+
const token = tokens[position++];
|
|
8921
|
+
if (!token) throw new MockInvalidFilter();
|
|
8922
|
+
return token;
|
|
8923
|
+
};
|
|
8924
|
+
const value = () => {
|
|
8925
|
+
const token = next();
|
|
8926
|
+
if (token.kind !== "word" && token.kind !== "quoted") throw new MockInvalidFilter();
|
|
8927
|
+
return token.text;
|
|
8928
|
+
};
|
|
8929
|
+
const term = () => {
|
|
8930
|
+
const token = next();
|
|
8931
|
+
if (token.kind === "paren" && token.text === "(") {
|
|
8932
|
+
const node = alternatives();
|
|
8933
|
+
if (next().text !== ")") throw new MockInvalidFilter();
|
|
8934
|
+
return node;
|
|
8935
|
+
}
|
|
8936
|
+
if (token.kind !== "word" || !Object.hasOwn(MOCK_ASSET_FILTER_FIELDS, token.text)) throw new MockInvalidFilter();
|
|
8937
|
+
const field = token.text;
|
|
8938
|
+
const operator = next();
|
|
8939
|
+
if (operator.kind !== "operator" || !MOCK_ASSET_FILTER_FIELDS[field].operators.includes(operator.text)) throw new MockInvalidFilter();
|
|
8940
|
+
let texts;
|
|
8941
|
+
if (peek()?.kind === "paren" && peek()?.text === "(") {
|
|
8942
|
+
next();
|
|
8943
|
+
texts = [value()];
|
|
8944
|
+
while (peek()?.kind === "logic" && peek()?.text === "or") {
|
|
8945
|
+
next();
|
|
8946
|
+
texts.push(value());
|
|
8947
|
+
}
|
|
8948
|
+
if (next().text !== ")") throw new MockInvalidFilter();
|
|
8949
|
+
} else texts = [value()];
|
|
8950
|
+
if (texts.length > 1 && operator.text !== "=in=" && operator.text !== "=out=") throw new MockInvalidFilter();
|
|
8951
|
+
return {
|
|
8952
|
+
type: "comparison",
|
|
8953
|
+
field,
|
|
8954
|
+
operator: operator.text,
|
|
8955
|
+
values: texts.map((text) => readFilterValue(field, text))
|
|
8956
|
+
};
|
|
8957
|
+
};
|
|
8958
|
+
const conjunction = () => {
|
|
8959
|
+
const nodes = [term()];
|
|
8960
|
+
while (peek()?.kind === "logic" && peek()?.text === "and") {
|
|
8961
|
+
next();
|
|
8962
|
+
nodes.push(term());
|
|
8963
|
+
}
|
|
8964
|
+
return nodes.length === 1 ? nodes[0] : {
|
|
8965
|
+
type: "and",
|
|
8966
|
+
nodes
|
|
8967
|
+
};
|
|
8968
|
+
};
|
|
8969
|
+
const alternatives = () => {
|
|
8970
|
+
const nodes = [conjunction()];
|
|
8971
|
+
while (peek()?.kind === "logic" && peek()?.text === "or") {
|
|
8972
|
+
next();
|
|
8973
|
+
nodes.push(conjunction());
|
|
8974
|
+
}
|
|
8975
|
+
return nodes.length === 1 ? nodes[0] : {
|
|
8976
|
+
type: "or",
|
|
8977
|
+
nodes
|
|
8978
|
+
};
|
|
8979
|
+
};
|
|
8980
|
+
const node = alternatives();
|
|
8981
|
+
if (position !== tokens.length) throw new MockInvalidFilter();
|
|
8982
|
+
return node;
|
|
8454
8983
|
};
|
|
8455
8984
|
const readField = (item, path) => path.split(".").reduce((value, key) => value && typeof value === "object" ? value[key] : void 0, item);
|
|
8456
|
-
|
|
8457
|
-
const
|
|
8458
|
-
|
|
8459
|
-
|
|
8460
|
-
const
|
|
8461
|
-
const
|
|
8462
|
-
|
|
8463
|
-
if (
|
|
8464
|
-
|
|
8465
|
-
const
|
|
8985
|
+
/** `*` matches any run of characters, regardless of case; every other character itself. */
|
|
8986
|
+
const wildcard = (pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "isu");
|
|
8987
|
+
/** Compares like SQL: a missing value never matches, except `== null`. */
|
|
8988
|
+
const matchesComparison = (item, { field, operator, values }) => {
|
|
8989
|
+
const actual = readField(item, field) ?? null;
|
|
8990
|
+
const [value] = values;
|
|
8991
|
+
if (actual === null && MOCK_ASSET_FILTER_FIELDS[field].kind === "list") return operator === "=out=";
|
|
8992
|
+
if (actual === null) return operator === "==" && value === null;
|
|
8993
|
+
if (operator === "!=" && value === null) return true;
|
|
8994
|
+
const actuals = Array.isArray(actual) ? actual : [actual];
|
|
8995
|
+
const equals = (expected) => actuals.some((each) => each === expected);
|
|
8996
|
+
if ((operator === "==" || operator === "!=") && typeof value === "string" && value.includes("*")) {
|
|
8997
|
+
const pattern = wildcard(value);
|
|
8998
|
+
const matched = actuals.some((each) => typeof each === "string" && pattern.test(each));
|
|
8999
|
+
return operator === "==" ? matched : !matched;
|
|
9000
|
+
}
|
|
8466
9001
|
switch (operator) {
|
|
8467
|
-
case "==": return equals(
|
|
8468
|
-
case "!=": return !equals(
|
|
9002
|
+
case "==": return equals(value);
|
|
9003
|
+
case "!=": return !equals(value);
|
|
8469
9004
|
case "=in=": return values.some(equals);
|
|
8470
|
-
case "=out=": return !values.some(equals);
|
|
8471
|
-
|
|
8472
|
-
|
|
8473
|
-
|
|
8474
|
-
|
|
8475
|
-
case "
|
|
8476
|
-
case "
|
|
8477
|
-
|
|
8478
|
-
|
|
8479
|
-
}
|
|
8480
|
-
|
|
8481
|
-
const
|
|
8482
|
-
const parts = [];
|
|
8483
|
-
let depth = 0;
|
|
8484
|
-
let quote = null;
|
|
8485
|
-
let current = "";
|
|
8486
|
-
for (const char of text) {
|
|
8487
|
-
if (quote) {
|
|
8488
|
-
if (char === quote) quote = null;
|
|
8489
|
-
} else if (char === "\"" || char === "'") quote = char;
|
|
8490
|
-
else if (char === "(") depth++;
|
|
8491
|
-
else if (char === ")") depth--;
|
|
8492
|
-
else if (char === separator && depth === 0) {
|
|
8493
|
-
parts.push(current);
|
|
8494
|
-
current = "";
|
|
8495
|
-
continue;
|
|
8496
|
-
}
|
|
8497
|
-
current += char;
|
|
8498
|
-
}
|
|
8499
|
-
parts.push(current);
|
|
8500
|
-
return parts;
|
|
8501
|
-
};
|
|
8502
|
-
/** The expression inside `( … )` when the parentheses enclose all of `text`, else undefined. */
|
|
8503
|
-
const unwrapGroup = (text) => {
|
|
8504
|
-
if (!text.startsWith("(") || !text.endsWith(")")) return void 0;
|
|
8505
|
-
let depth = 0;
|
|
8506
|
-
let quote = null;
|
|
8507
|
-
for (const [index, char] of [...text].entries()) if (quote) {
|
|
8508
|
-
if (char === quote) quote = null;
|
|
8509
|
-
} else if (char === "\"" || char === "'") quote = char;
|
|
8510
|
-
else if (char === "(") depth++;
|
|
8511
|
-
else if (char === ")" && --depth === 0) return index === text.length - 1 ? text.slice(1, -1) : void 0;
|
|
8512
|
-
};
|
|
8513
|
-
/** Evaluates `,` (or) of `;` (and) terms, where a term is a comparison or a `( … )` group. */
|
|
8514
|
-
const matchesExpression = (item, expression) => splitTopLevel(expression, ",").some((alternative) => splitTopLevel(alternative, ";").every((term) => {
|
|
8515
|
-
const trimmed = term.trim();
|
|
8516
|
-
if (!trimmed) throw unsupportedFilter(expression);
|
|
8517
|
-
const group = unwrapGroup(trimmed);
|
|
8518
|
-
return group === void 0 ? matchesComparison(item, trimmed) : matchesExpression(item, group);
|
|
8519
|
-
}));
|
|
9005
|
+
case "=out=": return !values.includes(null) && !values.some(equals);
|
|
9006
|
+
}
|
|
9007
|
+
if (value === null) return false;
|
|
9008
|
+
const order = compareValues(actual, value);
|
|
9009
|
+
switch (operator) {
|
|
9010
|
+
case ">": return order > 0;
|
|
9011
|
+
case ">=": return order >= 0;
|
|
9012
|
+
case "<": return order < 0;
|
|
9013
|
+
default: return order <= 0;
|
|
9014
|
+
}
|
|
9015
|
+
};
|
|
9016
|
+
const matchesNode = (item, node) => node.type === "comparison" ? matchesComparison(item, node) : node.type === "and" ? node.nodes.every((child) => matchesNode(item, child)) : node.nodes.some((child) => matchesNode(item, child));
|
|
8520
9017
|
/**
|
|
8521
|
-
* Applies an RSQL `filter` like the API
|
|
8522
|
-
* than `,` (or), and
|
|
8523
|
-
*
|
|
9018
|
+
* Applies an RSQL `filter` like the API (zodbase/rsql with MOCK_ASSET_FILTER_FIELDS): only the
|
|
9019
|
+
* listed fields, each with its own operators, `;` (and) binding tighter than `,` (or), and parentheses. Throws
|
|
9020
|
+
* `MockInvalidFilter` for any filter the API refuses with `filter/invalid`.
|
|
8524
9021
|
*/
|
|
8525
9022
|
const filterAssets = (items, filter) => {
|
|
8526
9023
|
if (!filter) return items;
|
|
8527
|
-
|
|
8528
|
-
return items.filter((item) =>
|
|
9024
|
+
const node = parseFilter(filter);
|
|
9025
|
+
return items.filter((item) => matchesNode(item, node));
|
|
8529
9026
|
};
|
|
8530
9027
|
const MAX_SEARCH_TOKENS = 8;
|
|
8531
9028
|
/** The keyword fields the API searches, in the order it reports matches. */
|
|
@@ -8600,55 +9097,95 @@ const MOCK_OPERATIONS = [
|
|
|
8600
9097
|
"assets.update",
|
|
8601
9098
|
"assets.listChildren",
|
|
8602
9099
|
"assets.iterateChildren",
|
|
9100
|
+
"assets.listTimeline",
|
|
9101
|
+
"assets.iterateTimeline",
|
|
8603
9102
|
"assets.create",
|
|
8604
9103
|
"assets.classify",
|
|
8605
9104
|
"assets.uploadPart",
|
|
8606
|
-
"assets.createSignedUrl",
|
|
8607
9105
|
"assets.move",
|
|
8608
9106
|
"assets.retry",
|
|
8609
9107
|
"assets.explain",
|
|
8610
9108
|
"assets.decide",
|
|
8611
|
-
"assets.
|
|
9109
|
+
"assets.removeContent",
|
|
8612
9110
|
"assets.delete",
|
|
8613
9111
|
"assets.batch",
|
|
8614
9112
|
"text.classify",
|
|
8615
9113
|
"cdn.serve",
|
|
9114
|
+
"cdn.getAssetInfo",
|
|
9115
|
+
"cdn.signAssetUrl",
|
|
8616
9116
|
"events.list",
|
|
8617
9117
|
"events.pages",
|
|
8618
9118
|
"folders.list",
|
|
9119
|
+
"folders.iterate",
|
|
8619
9120
|
"folders.retrieve",
|
|
8620
9121
|
"folders.create",
|
|
8621
9122
|
"folders.update",
|
|
8622
9123
|
"folders.delete",
|
|
8623
9124
|
"folders.move",
|
|
8624
9125
|
"hashLists.list",
|
|
9126
|
+
"hashLists.iterate",
|
|
8625
9127
|
"hashLists.retrieve",
|
|
8626
9128
|
"hashLists.create",
|
|
8627
9129
|
"hashLists.update",
|
|
8628
9130
|
"hashLists.delete",
|
|
8629
9131
|
"hashLists.listEntries",
|
|
9132
|
+
"hashLists.iterateEntries",
|
|
8630
9133
|
"hashLists.addEntry",
|
|
8631
9134
|
"hashLists.removeEntry",
|
|
8632
9135
|
"policies.list",
|
|
9136
|
+
"policies.iterate",
|
|
8633
9137
|
"policies.retrieve",
|
|
8634
9138
|
"policies.create",
|
|
8635
9139
|
"policies.update",
|
|
8636
|
-
"policies.
|
|
9140
|
+
"policies.reset",
|
|
9141
|
+
"policies.upgrade",
|
|
8637
9142
|
"policies.setAutomaticUpdates",
|
|
8638
9143
|
"policies.delete",
|
|
9144
|
+
"policies.retrieveAssigned",
|
|
8639
9145
|
"policies.assign",
|
|
9146
|
+
"lenses.list",
|
|
9147
|
+
"lenses.iterate",
|
|
9148
|
+
"lenses.create",
|
|
9149
|
+
"lenses.retrieve",
|
|
9150
|
+
"lenses.update",
|
|
9151
|
+
"lenses.delete",
|
|
8640
9152
|
"ensureLens",
|
|
8641
|
-
"ensureLenses"
|
|
9153
|
+
"ensureLenses",
|
|
9154
|
+
"uploadPresets.list",
|
|
9155
|
+
"uploadPresets.iterate",
|
|
9156
|
+
"uploadPresets.ensure",
|
|
9157
|
+
"uploadPresets.delete",
|
|
9158
|
+
"projectSettings.get",
|
|
9159
|
+
"projectSettings.update",
|
|
9160
|
+
"metadataFields.list",
|
|
9161
|
+
"metadataFields.ensure",
|
|
9162
|
+
"metadataFields.delete"
|
|
8642
9163
|
];
|
|
8643
9164
|
const MAX_PAGE_SIZE = 100;
|
|
8644
9165
|
const MAX_DECISION_NOTE_LENGTH = 1499;
|
|
8645
9166
|
/** How the API names a reviewer acting through an unnamed API key. */
|
|
8646
9167
|
const API_KEY_REVIEWER_NAME = "An API key";
|
|
8647
|
-
|
|
9168
|
+
/** The actor of events the mock's API key causes: mock keys have no ID. */
|
|
9169
|
+
const MOCK_API_KEY_ACTOR = {
|
|
9170
|
+
type: "api-key",
|
|
9171
|
+
id: null
|
|
9172
|
+
};
|
|
9173
|
+
/** The actor of a reviewer's decision through the `decide` test hook. */
|
|
9174
|
+
const MOCK_REVIEWER_ACTOR = {
|
|
9175
|
+
type: "user",
|
|
9176
|
+
id: null
|
|
9177
|
+
};
|
|
9178
|
+
const AUTOMATED_ACTOR = {
|
|
9179
|
+
type: "automated",
|
|
9180
|
+
id: null
|
|
9181
|
+
};
|
|
9182
|
+
/** An event type's shape (`resource.action`), as the mock checks `types` without the catalog. */
|
|
9183
|
+
const EVENT_TYPE_PATTERN = /^[a-z][a-z-]*\.[a-z][a-z-]*$/;
|
|
9184
|
+
const MAX_SEARCH_PAGE_SIZE = 20;
|
|
8648
9185
|
const MAX_SEARCH_QUERY_LENGTH = 200;
|
|
8649
9186
|
/**
|
|
8650
|
-
* The ThumbHash the mock gives every
|
|
8651
|
-
* pixels. The `placeholder` resource serves it as a PNG, like the CDN.
|
|
9187
|
+
* The ThumbHash the mock gives every processed asset's preview, standing in for one computed from
|
|
9188
|
+
* its pixels. The `placeholder` resource serves it as a PNG, like the CDN.
|
|
8652
9189
|
*/
|
|
8653
9190
|
const MOCK_THUMBHASH = "1QcSHQRnh493V4dIh4eXh1h4kJUI";
|
|
8654
9191
|
/** Like the API: 1 to 255 printable ASCII characters, once HTTP has trimmed the header value. */
|
|
@@ -8672,10 +9209,19 @@ const toEventAsset = (asset) => ({
|
|
|
8672
9209
|
upload: { status: asset.upload.status },
|
|
8673
9210
|
classification: {
|
|
8674
9211
|
status: asset.classification.status,
|
|
9212
|
+
testInput: asset.classification.testInput,
|
|
8675
9213
|
moderation: { status: asset.classification.moderation.status }
|
|
8676
9214
|
},
|
|
8677
9215
|
content: { status: asset.content.status }
|
|
8678
9216
|
});
|
|
9217
|
+
/** The moderation status each `asset.<status>` event announces. */
|
|
9218
|
+
const ANNOUNCED_STATUS = {
|
|
9219
|
+
"asset.allowed": "allowed",
|
|
9220
|
+
"asset.limited": "limited",
|
|
9221
|
+
"asset.age-restricted": "age-restricted",
|
|
9222
|
+
"asset.blocked": "blocked",
|
|
9223
|
+
"asset.purged": "purged"
|
|
9224
|
+
};
|
|
8679
9225
|
/** A `moderate` answer or `completeProcessing` decision as a checked `MockDecision`. */
|
|
8680
9226
|
const toDecision = (value) => {
|
|
8681
9227
|
if (value instanceof MockDecision) return value;
|
|
@@ -8688,12 +9234,122 @@ const assetNameFact = (asset) => ({
|
|
|
8688
9234
|
value: asset.name,
|
|
8689
9235
|
url: `https://calmlens.com/go/asset/${asset.id}`
|
|
8690
9236
|
});
|
|
8691
|
-
/**
|
|
8692
|
-
const
|
|
8693
|
-
|
|
8694
|
-
|
|
8695
|
-
|
|
8696
|
-
|
|
9237
|
+
/** The page the mock serves at `/embed`, standing in for the CDN's embed page. */
|
|
9238
|
+
const MOCK_EMBED_HTML = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>Embed</title></head><body></body></html>";
|
|
9239
|
+
/** A ThumbHash as the PNG the placeholder resource serves. */
|
|
9240
|
+
const mockPlaceholderPng = (thumbhash) => Uint8Array.from(atob(require_UploadController.placeholderHashToDataURL(thumbhash).split(",", 2)[1]), (char) => char.charCodeAt(0));
|
|
9241
|
+
/** Removing or withholding content removes its rendered file and preview, as the API does. */
|
|
9242
|
+
const NO_RENDERING = {
|
|
9243
|
+
rendered: null,
|
|
9244
|
+
preview: null,
|
|
9245
|
+
hls: null,
|
|
9246
|
+
hlsStatus: null
|
|
9247
|
+
};
|
|
9248
|
+
/** The size of the waveform the API makes as an audio asset's preview. */
|
|
9249
|
+
const WAVEFORM_SIZE = {
|
|
9250
|
+
width: 1200,
|
|
9251
|
+
height: 300
|
|
9252
|
+
};
|
|
9253
|
+
/** Audio and video formats browsers play as uploaded, so the API serves them as stored (Asset.ts). */
|
|
9254
|
+
const BROWSER_SAFE_MEDIA_FORMATS = [
|
|
9255
|
+
"video/mp4",
|
|
9256
|
+
"audio/mpeg",
|
|
9257
|
+
"audio/aac",
|
|
9258
|
+
"audio/mp4",
|
|
9259
|
+
"audio/x-m4a",
|
|
9260
|
+
"audio/ogg"
|
|
9261
|
+
];
|
|
9262
|
+
/** Spreadsheets, which have no rendered file or preview (Asset.ts). */
|
|
9263
|
+
const SPREADSHEET_MIME_TYPES = [
|
|
9264
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
9265
|
+
"application/vnd.ms-excel.sheet.macroenabled.12",
|
|
9266
|
+
"application/vnd.ms-excel",
|
|
9267
|
+
"application/vnd.oasis.opendocument.spreadsheet"
|
|
9268
|
+
];
|
|
9269
|
+
/** Whether browsers play an audio or video upload's format as it is, so it is served as stored. */
|
|
9270
|
+
const isBrowserSafeMediaFormat = (format) => BROWSER_SAFE_MEDIA_FORMATS.includes(require_ModerationContextLimits.normalizeUploadMimeType(format ?? ""));
|
|
9271
|
+
/**
|
|
9272
|
+
* The rendered file and preview the API reports for an asset with its content held (Asset.ts,
|
|
9273
|
+
* getAssetRendered and getAssetPreview). Once uploaded, an image renders as itself with a preview
|
|
9274
|
+
* that has no ThumbHash yet, and a PDF and browser-safe audio and video render as uploaded. Once
|
|
9275
|
+
* processed, a website renders as its screenshot; a document or presentation as a PDF, with its
|
|
9276
|
+
* first page as the preview; video and audio as a browser-safe file (MP4 or M4A unless browsers
|
|
9277
|
+
* play the upload), audio with a waveform preview and video with no poster; and every preview has
|
|
9278
|
+
* its ThumbHash. Text, spreadsheets and other files have neither. The mock decodes nothing, so
|
|
9279
|
+
* sizes are unknown, audio has no peaks, and audio and video never get an HLS stream.
|
|
9280
|
+
*/
|
|
9281
|
+
const mockRendering = (asset, processed) => {
|
|
9282
|
+
const format = asset.content.format;
|
|
9283
|
+
const mimeType = require_ModerationContextLimits.normalizeUploadMimeType(format ?? "");
|
|
9284
|
+
const browserSafe = isBrowserSafeMediaFormat(format);
|
|
9285
|
+
const preview = (size) => ({
|
|
9286
|
+
...size,
|
|
9287
|
+
thumbhash: processed ? MOCK_THUMBHASH : null,
|
|
9288
|
+
averageColor: processed ? "#7f7f7f" : null
|
|
9289
|
+
});
|
|
9290
|
+
const unsized = {
|
|
9291
|
+
width: null,
|
|
9292
|
+
height: null
|
|
9293
|
+
};
|
|
9294
|
+
const rendersOnUpload = asset.type === "image" || mimeType === "application/pdf" || (asset.type === "video" || asset.type === "audio") && browserSafe;
|
|
9295
|
+
if (!processed && !rendersOnUpload) return NO_RENDERING;
|
|
9296
|
+
switch (asset.type) {
|
|
9297
|
+
case "image": return {
|
|
9298
|
+
rendered: {
|
|
9299
|
+
kind: "image",
|
|
9300
|
+
format: format ?? "image/png",
|
|
9301
|
+
...unsized
|
|
9302
|
+
},
|
|
9303
|
+
preview: preview(unsized),
|
|
9304
|
+
hls: null,
|
|
9305
|
+
hlsStatus: null
|
|
9306
|
+
};
|
|
9307
|
+
case "website": return {
|
|
9308
|
+
rendered: {
|
|
9309
|
+
kind: "image",
|
|
9310
|
+
format: "image/png",
|
|
9311
|
+
...unsized
|
|
9312
|
+
},
|
|
9313
|
+
preview: preview(unsized),
|
|
9314
|
+
hls: null,
|
|
9315
|
+
hlsStatus: null
|
|
9316
|
+
};
|
|
9317
|
+
case "multimedia-document":
|
|
9318
|
+
if (SPREADSHEET_MIME_TYPES.includes(mimeType)) return NO_RENDERING;
|
|
9319
|
+
return {
|
|
9320
|
+
rendered: {
|
|
9321
|
+
kind: "pdf",
|
|
9322
|
+
format: "application/pdf",
|
|
9323
|
+
...unsized
|
|
9324
|
+
},
|
|
9325
|
+
preview: processed ? preview(unsized) : null,
|
|
9326
|
+
hls: null,
|
|
9327
|
+
hlsStatus: null
|
|
9328
|
+
};
|
|
9329
|
+
case "video": return {
|
|
9330
|
+
rendered: {
|
|
9331
|
+
kind: "video",
|
|
9332
|
+
format: browserSafe ? format : "video/mp4",
|
|
9333
|
+
...unsized
|
|
9334
|
+
},
|
|
9335
|
+
preview: null,
|
|
9336
|
+
hls: null,
|
|
9337
|
+
hlsStatus: null
|
|
9338
|
+
};
|
|
9339
|
+
case "audio": return {
|
|
9340
|
+
rendered: {
|
|
9341
|
+
kind: "audio",
|
|
9342
|
+
format: browserSafe ? format : "audio/mp4",
|
|
9343
|
+
...unsized,
|
|
9344
|
+
...processed && { peaks: [] }
|
|
9345
|
+
},
|
|
9346
|
+
preview: processed ? preview(WAVEFORM_SIZE) : null,
|
|
9347
|
+
hls: null,
|
|
9348
|
+
hlsStatus: null
|
|
9349
|
+
};
|
|
9350
|
+
default: return NO_RENDERING;
|
|
9351
|
+
}
|
|
9352
|
+
};
|
|
8697
9353
|
/** An asset's type from its content type, or `website` for a URL. */
|
|
8698
9354
|
const inferAssetType = (contentType) => {
|
|
8699
9355
|
if (contentType === void 0) return "website";
|
|
@@ -8715,8 +9371,107 @@ var ApiFailure = class {
|
|
|
8715
9371
|
}
|
|
8716
9372
|
};
|
|
8717
9373
|
const fail = (code, { message, details } = {}) => new ApiFailure(require_ModerationContextLimits.API_ERROR_DEFINITIONS[code].status, code, message ?? require_ModerationContextLimits.API_ERROR_DEFINITIONS[code].message, details);
|
|
8718
|
-
/**
|
|
8719
|
-
|
|
9374
|
+
/**
|
|
9375
|
+
* A request the API's schema refuses: `validation/invalid-request` with HTTP 400, listing the field
|
|
9376
|
+
* and its issue code (such as `validation/too-big`) in `details.issues`.
|
|
9377
|
+
*/
|
|
9378
|
+
/**
|
|
9379
|
+
* The mock's grant, the asset segment of a URL `signAssetUrl` signs: `sig_` and the hex of
|
|
9380
|
+
* `{assetId}.{1|0}.{expiresAt}`, its asset, original access and expiry. Every SDK's mock writes it
|
|
9381
|
+
* the same way. It is readable, not signed, as the mock has no secret to keep.
|
|
9382
|
+
*/
|
|
9383
|
+
const encodeMockGrant = (grant) => `sig_${[...new TextEncoder().encode(`${grant.assetId}.${grant.original ? 1 : 0}.${grant.expiresAt}`)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
9384
|
+
/** Reads a mock grant, or `undefined` for a segment the mock didn't sign. */
|
|
9385
|
+
const decodeMockGrant = (segment) => {
|
|
9386
|
+
const hex = segment.slice(4);
|
|
9387
|
+
if (!/^(?:[0-9a-f]{2})+$/.test(hex)) return void 0;
|
|
9388
|
+
let text;
|
|
9389
|
+
try {
|
|
9390
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(hex.match(/../g), (pair) => Number.parseInt(pair, 16)));
|
|
9391
|
+
} catch {
|
|
9392
|
+
return;
|
|
9393
|
+
}
|
|
9394
|
+
const match = /^(.+)\.([01])\.(\d+)$/s.exec(text);
|
|
9395
|
+
if (!match) return void 0;
|
|
9396
|
+
return {
|
|
9397
|
+
assetId: match[1],
|
|
9398
|
+
original: match[2] === "1",
|
|
9399
|
+
expiresAt: Number(match[3])
|
|
9400
|
+
};
|
|
9401
|
+
};
|
|
9402
|
+
const invalidField = (code, path) => new ApiFailure(400, require_ModerationContextLimits.API_ERROR_CODES.INVALID_REQUEST, `Invalid ${path}`, { issues: [{
|
|
9403
|
+
path,
|
|
9404
|
+
message: `Invalid ${path}`,
|
|
9405
|
+
code
|
|
9406
|
+
}] });
|
|
9407
|
+
/** The asset fields an upload carries in its body; the API refuses them in the query string. */
|
|
9408
|
+
const UPLOAD_OPTION_KEYS = [
|
|
9409
|
+
"name",
|
|
9410
|
+
"description",
|
|
9411
|
+
"processingOptions",
|
|
9412
|
+
"visibility",
|
|
9413
|
+
"metadata",
|
|
9414
|
+
"tags",
|
|
9415
|
+
"authorId",
|
|
9416
|
+
"context",
|
|
9417
|
+
"externalId",
|
|
9418
|
+
"externalUrl",
|
|
9419
|
+
"folderId",
|
|
9420
|
+
"uploadPresetId"
|
|
9421
|
+
];
|
|
9422
|
+
const indexOfBytes = (haystack, needle, from = 0) => {
|
|
9423
|
+
for (let index = haystack.indexOf(needle[0], from); index !== -1;) {
|
|
9424
|
+
if (index + needle.length > haystack.length) return -1;
|
|
9425
|
+
let offset = 1;
|
|
9426
|
+
while (offset < needle.length && haystack[index + offset] === needle[offset]) offset++;
|
|
9427
|
+
if (offset === needle.length) return index;
|
|
9428
|
+
index = haystack.indexOf(needle[0], index + 1);
|
|
9429
|
+
}
|
|
9430
|
+
return -1;
|
|
9431
|
+
};
|
|
9432
|
+
/**
|
|
9433
|
+
* Reads a raw upload's `multipart/form-data` body like the API: an `options` part, then a `file`
|
|
9434
|
+
* part, then the closing boundary. Anything else is refused.
|
|
9435
|
+
*/
|
|
9436
|
+
const readUploadForm = (request) => {
|
|
9437
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
9438
|
+
if (contentType.split(";")[0].trim().toLowerCase() !== "multipart/form-data") throw new ApiFailure(415, require_ModerationContextLimits.API_ERROR_CODES.UNSUPPORTED_CONTENT_TYPE, "Send a raw upload as multipart/form-data: an options part, then a file part.", { contentType: contentType.split(";")[0].trim() || null });
|
|
9439
|
+
const boundary = /;\s*boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType);
|
|
9440
|
+
const invalid = (message) => fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message });
|
|
9441
|
+
if (!boundary) throw invalid("The multipart/form-data Content-Type needs a boundary");
|
|
9442
|
+
const encoder = new TextEncoder();
|
|
9443
|
+
const delimiter = encoder.encode(`\r\n--${boundary[1] ?? boundary[2]}`);
|
|
9444
|
+
const body = new Uint8Array(2 + request.bytes.length);
|
|
9445
|
+
body.set(encoder.encode("\r\n"));
|
|
9446
|
+
body.set(request.bytes, 2);
|
|
9447
|
+
const parts = [];
|
|
9448
|
+
let at = indexOfBytes(body, delimiter);
|
|
9449
|
+
while (at !== -1) {
|
|
9450
|
+
const start = at + delimiter.length;
|
|
9451
|
+
if (body[start] === 45 && body[start + 1] === 45) break;
|
|
9452
|
+
const headerEnd = indexOfBytes(body, encoder.encode("\r\n\r\n"), start);
|
|
9453
|
+
const next = headerEnd === -1 ? -1 : indexOfBytes(body, delimiter, headerEnd + 4);
|
|
9454
|
+
if (next === -1) throw invalid("The upload body ended before its closing boundary");
|
|
9455
|
+
const headers = new TextDecoder().decode(body.slice(start, headerEnd));
|
|
9456
|
+
const name = /content-disposition:\s*form-data\s*;[^\r\n]*?\bname="([^"]*)"/i.exec(headers)?.[1];
|
|
9457
|
+
parts.push({
|
|
9458
|
+
name,
|
|
9459
|
+
content: body.slice(headerEnd + 4, next)
|
|
9460
|
+
});
|
|
9461
|
+
at = next;
|
|
9462
|
+
}
|
|
9463
|
+
if (at === -1) throw invalid("The upload body ended before its closing boundary");
|
|
9464
|
+
if (parts.length !== 2 || parts[0].name !== "options" || parts[1].name !== "file") throw invalid("The upload form must hold an options part, then a file part");
|
|
9465
|
+
return {
|
|
9466
|
+
options: new TextDecoder().decode(parts[0].content),
|
|
9467
|
+
bytes: parts[1].content
|
|
9468
|
+
};
|
|
9469
|
+
};
|
|
9470
|
+
/** A request that names asset fields in its query, which the API refuses. */
|
|
9471
|
+
const assertNoUploadOptionsInQuery = (query) => {
|
|
9472
|
+
const fields = UPLOAD_OPTION_KEYS.filter((key) => query.has(key));
|
|
9473
|
+
if (fields.length) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_OPTIONS_IN_QUERY, { details: { fields } });
|
|
9474
|
+
};
|
|
8720
9475
|
/**
|
|
8721
9476
|
* Refuses `metadata` the API's schema refuses (METADATA_ITEM_SCHEMA): it is `null` or a list of
|
|
8722
9477
|
* `{ id, value }` objects with a string `id` and any JSON `value`.
|
|
@@ -8737,35 +9492,70 @@ const MOCK_PRESET_NAMES = {
|
|
|
8737
9492
|
"education-support": "Learning and support",
|
|
8738
9493
|
"wholesome-community": "Teen-safe"
|
|
8739
9494
|
};
|
|
9495
|
+
/**
|
|
9496
|
+
* The settings of the mock's presets: every category with its default action (`allow` for
|
|
9497
|
+
* personal information and profanity, `block` otherwise) and no rules. The mock holds no built-in
|
|
9498
|
+
* preset settings, and uploads are never decided by a policy.
|
|
9499
|
+
*/
|
|
9500
|
+
const mockPresetSettings = () => ({ categorySettings: Object.fromEntries(require_TestTriggers_D29T_R0M.CLASSIFICATION_CATEGORIES.map((category) => [category, {
|
|
9501
|
+
action: category === "personal-information" || category === "profanity" ? "allow" : "block",
|
|
9502
|
+
allowances: [],
|
|
9503
|
+
restrictions: []
|
|
9504
|
+
}])) });
|
|
9505
|
+
/**
|
|
9506
|
+
* Refuses settings the API refuses (MODERATION_POLICY_SETTINGS_SCHEMA): every category, each with
|
|
9507
|
+
* an `action` and its `allowances` and `restrictions` lists.
|
|
9508
|
+
*/
|
|
9509
|
+
const checkPolicySettings = (settings) => {
|
|
9510
|
+
const categories = settings?.categorySettings;
|
|
9511
|
+
if (!categories || typeof categories !== "object") throw invalidField("validation/invalid-type", "settings.categorySettings");
|
|
9512
|
+
for (const category of require_TestTriggers_D29T_R0M.CLASSIFICATION_CATEGORIES) {
|
|
9513
|
+
const value = categories[category];
|
|
9514
|
+
if (!value || typeof value !== "object") throw invalidField("validation/invalid-type", `settings.categorySettings.${category}`);
|
|
9515
|
+
for (const key of ["allowances", "restrictions"]) if (!Array.isArray(value[key])) throw invalidField("validation/invalid-type", `settings.categorySettings.${category}.${key}`);
|
|
9516
|
+
if (typeof value.action !== "string") throw invalidField("validation/invalid-value", `settings.categorySettings.${category}.action`);
|
|
9517
|
+
}
|
|
9518
|
+
for (const key of Object.keys(categories)) if (!require_TestTriggers_D29T_R0M.CLASSIFICATION_CATEGORIES.includes(key)) throw invalidField("validation/unknown-field", `settings.categorySettings.${key}`);
|
|
9519
|
+
};
|
|
8740
9520
|
/** The client methods that send a request, the one it is recorded under first. */
|
|
8741
9521
|
const operationsOf = (request) => {
|
|
8742
9522
|
const { method, segments, query, cdn } = request;
|
|
8743
|
-
if (cdn) return ["cdn.serve"];
|
|
9523
|
+
if (cdn) return segments[3] === "info" ? ["cdn.getAssetInfo"] : ["cdn.serve"];
|
|
8744
9524
|
const [root] = segments;
|
|
8745
9525
|
if (root === "projects") {
|
|
8746
9526
|
switch (segments.slice(2).join("/")) {
|
|
8747
9527
|
case "events": return ["events.list", "events.pages"];
|
|
8748
|
-
case "lenses": return ["ensureLenses", "ensureLens"];
|
|
8749
|
-
case "folders": return method === "GET" ? ["folders.list"] : ["folders.create"];
|
|
8750
|
-
case "hash-lists": return method === "GET" ? ["hashLists.list"] : ["hashLists.create"];
|
|
8751
|
-
case "
|
|
8752
|
-
case "
|
|
9528
|
+
case "lenses": return method === "GET" ? ["lenses.list", "lenses.iterate"] : method === "POST" ? ["lenses.create"] : ["ensureLenses", "ensureLens"];
|
|
9529
|
+
case "folders": return method === "GET" ? ["folders.list", "folders.iterate"] : ["folders.create"];
|
|
9530
|
+
case "hash-lists": return method === "GET" ? ["hashLists.list", "hashLists.iterate"] : ["hashLists.create"];
|
|
9531
|
+
case "policy": return method === "GET" ? ["policies.retrieveAssigned"] : ["policies.assign"];
|
|
9532
|
+
case "upload-presets": return method === "GET" ? ["uploadPresets.list", "uploadPresets.iterate"] : ["uploadPresets.ensure"];
|
|
9533
|
+
case "settings": return method === "GET" ? ["projectSettings.get"] : ["projectSettings.update"];
|
|
9534
|
+
case "metadata-fields": return method === "GET" ? ["metadataFields.list"] : ["metadataFields.ensure"];
|
|
8753
9535
|
case "assets/search": return ["assets.search"];
|
|
8754
9536
|
case "assets/batch": return ["assets.batch"];
|
|
9537
|
+
case "signed-asset-urls": return ["cdn.signAssetUrl"];
|
|
8755
9538
|
case "assets":
|
|
8756
9539
|
if (method === "GET") return ["assets.list", "assets.iterate"];
|
|
8757
|
-
if (query.get("
|
|
9540
|
+
if (query.get("wait") === "false") return ["assets.create"];
|
|
8758
9541
|
return isTextUpload(request) ? ["assets.classify", "text.classify"] : ["assets.classify"];
|
|
8759
9542
|
}
|
|
8760
|
-
if (segments[2] === "
|
|
8761
|
-
|
|
8762
|
-
if (segments[4] === "automatic-updates") return ["policies.setAutomaticUpdates"];
|
|
8763
|
-
return method === "GET" ? ["policies.retrieve"] : method === "PATCH" ? ["policies.update"] : ["policies.delete"];
|
|
8764
|
-
}
|
|
9543
|
+
if (segments[2] === "assets" && segments[4] === "timeline" && segments.length === 5) return ["assets.listTimeline", "assets.iterateTimeline"];
|
|
9544
|
+
if (segments[2] === "metadata-fields" && segments.length === 4) return ["metadataFields.delete"];
|
|
8765
9545
|
return [];
|
|
8766
9546
|
}
|
|
9547
|
+
if (root === "policies") {
|
|
9548
|
+
const [, policyId, policyAction] = segments;
|
|
9549
|
+
if (policyId === void 0) return method === "GET" ? ["policies.list", "policies.iterate"] : ["policies.create"];
|
|
9550
|
+
if (policyAction === "reset") return ["policies.reset"];
|
|
9551
|
+
if (policyAction === "upgrade") return ["policies.upgrade"];
|
|
9552
|
+
if (policyAction === "automatic-updates") return ["policies.setAutomaticUpdates"];
|
|
9553
|
+
return method === "GET" ? ["policies.retrieve"] : method === "PATCH" ? ["policies.update"] : ["policies.delete"];
|
|
9554
|
+
}
|
|
9555
|
+
if (root === "lenses" && segments[1] !== void 0) return method === "GET" ? ["lenses.retrieve"] : method === "PATCH" ? ["lenses.update"] : ["lenses.delete"];
|
|
9556
|
+
if (root === "upload-presets" && segments.length === 2) return ["uploadPresets.delete"];
|
|
8767
9557
|
if (root === "upload-presets") {
|
|
8768
|
-
if (segments[3] === void 0) return [query.get("
|
|
9558
|
+
if (segments[3] === void 0) return [query.get("wait") === "false" ? "assets.create" : "assets.classify"];
|
|
8769
9559
|
return segments[4] === "part" ? ["assets.uploadPart"] : ["assets.retrieve"];
|
|
8770
9560
|
}
|
|
8771
9561
|
const id = segments[1];
|
|
@@ -8775,16 +9565,15 @@ const operationsOf = (request) => {
|
|
|
8775
9565
|
return method === "GET" ? ["folders.retrieve"] : method === "PATCH" ? ["folders.update"] : ["folders.delete"];
|
|
8776
9566
|
}
|
|
8777
9567
|
if (root === "hash-lists" && id !== void 0) {
|
|
8778
|
-
if (action === "entries") return method === "GET" ? ["hashLists.listEntries"] : ["hashLists.addEntry"];
|
|
9568
|
+
if (action === "entries") return method === "GET" ? ["hashLists.listEntries", "hashLists.iterateEntries"] : ["hashLists.addEntry"];
|
|
8779
9569
|
return method === "GET" ? ["hashLists.retrieve"] : method === "PATCH" ? ["hashLists.update"] : ["hashLists.delete"];
|
|
8780
9570
|
}
|
|
8781
9571
|
if (root === "hash-list-entries" && id !== void 0) return ["hashLists.removeEntry"];
|
|
8782
9572
|
if (root !== "assets" || id === void 0) return [];
|
|
8783
9573
|
switch (action) {
|
|
8784
9574
|
case void 0: return method === "GET" ? ["assets.retrieve", "assets.waitForDecision"] : method === "PATCH" ? ["assets.update"] : ["assets.delete"];
|
|
8785
|
-
case "content": return ["assets.
|
|
9575
|
+
case "content": return ["assets.removeContent"];
|
|
8786
9576
|
case "children": return ["assets.listChildren", "assets.iterateChildren"];
|
|
8787
|
-
case "signed-url": return ["assets.createSignedUrl"];
|
|
8788
9577
|
case "part": return ["assets.uploadPart"];
|
|
8789
9578
|
case "move": return ["assets.move"];
|
|
8790
9579
|
case "retry": return ["assets.retry"];
|
|
@@ -8793,7 +9582,15 @@ const operationsOf = (request) => {
|
|
|
8793
9582
|
}
|
|
8794
9583
|
return [];
|
|
8795
9584
|
};
|
|
8796
|
-
|
|
9585
|
+
/** A plain-text upload: the SDKs send text as a JSON body with `content.plainText`. */
|
|
9586
|
+
const isTextUpload = (request) => {
|
|
9587
|
+
if (request.headers.get("x-calmlens-upload")) return false;
|
|
9588
|
+
try {
|
|
9589
|
+
return typeof JSON.parse(new TextDecoder().decode(request.bytes))?.content?.plainText === "string";
|
|
9590
|
+
} catch {
|
|
9591
|
+
return false;
|
|
9592
|
+
}
|
|
9593
|
+
};
|
|
8797
9594
|
/** Like the API: a new folder is 201 Created, a queued batch 202 Accepted, everything else 200. */
|
|
8798
9595
|
const SUCCESS_STATUS = {
|
|
8799
9596
|
"folders.create": 201,
|
|
@@ -8822,8 +9619,12 @@ const createMonotonicClock = () => {
|
|
|
8822
9619
|
var MockCalmLensApi = class {
|
|
8823
9620
|
constructor(options) {
|
|
8824
9621
|
this.calls = [];
|
|
9622
|
+
this.cdnBaseUrl = "";
|
|
8825
9623
|
this.lenses = /* @__PURE__ */ new Map();
|
|
8826
9624
|
this.eventFeed = [];
|
|
9625
|
+
this.assetEventSequences = /* @__PURE__ */ new Map();
|
|
9626
|
+
this.processingOptions = /* @__PURE__ */ new Map();
|
|
9627
|
+
this.pendingReruns = /* @__PURE__ */ new Set();
|
|
8827
9628
|
this.openUploads = /* @__PURE__ */ new Map();
|
|
8828
9629
|
this.idempotentResults = /* @__PURE__ */ new Map();
|
|
8829
9630
|
this.pendingFailures = [];
|
|
@@ -8832,7 +9633,11 @@ var MockCalmLensApi = class {
|
|
|
8832
9633
|
this.policies = /* @__PURE__ */ new Map();
|
|
8833
9634
|
this.hashLists = /* @__PURE__ */ new Map();
|
|
8834
9635
|
this.hashListEntries = /* @__PURE__ */ new Map();
|
|
8835
|
-
this.pageFailure = (code, path) => code === "
|
|
9636
|
+
this.pageFailure = (code, path) => code === "cursor/invalid" ? fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR) : invalidField(code, path ?? "pageSize");
|
|
9637
|
+
this.configuredPresets = /* @__PURE__ */ new Map();
|
|
9638
|
+
this.settingsRevision = 1;
|
|
9639
|
+
this.projectSettingsValues = {};
|
|
9640
|
+
this.metadataFieldList = [];
|
|
8836
9641
|
this.options = options;
|
|
8837
9642
|
this.projectId = options.projectId;
|
|
8838
9643
|
this.apiKey = options.apiKey;
|
|
@@ -8862,10 +9667,14 @@ var MockCalmLensApi = class {
|
|
|
8862
9667
|
*/
|
|
8863
9668
|
async enqueueEvent(input) {
|
|
8864
9669
|
const asset = input.asset === void 0 && input.assetId ? await this.databaseStorage.getAsset(input.assetId) : void 0;
|
|
8865
|
-
return this.pushEvent(
|
|
9670
|
+
if (!asset) return this.pushEvent(input);
|
|
9671
|
+
const snapshot = toEventAsset(asset);
|
|
9672
|
+
const announced = ANNOUNCED_STATUS[input.type];
|
|
9673
|
+
if (announced) snapshot.classification.moderation.status = announced;
|
|
9674
|
+
return this.pushEvent({
|
|
8866
9675
|
...input,
|
|
8867
|
-
asset:
|
|
8868
|
-
}
|
|
9676
|
+
asset: snapshot
|
|
9677
|
+
});
|
|
8869
9678
|
}
|
|
8870
9679
|
/** Adds an event to the feed, filling the fields the API always sets. */
|
|
8871
9680
|
pushEvent(input) {
|
|
@@ -8878,10 +9687,14 @@ var MockCalmLensApi = class {
|
|
|
8878
9687
|
description: null,
|
|
8879
9688
|
assetId: null,
|
|
8880
9689
|
asset: null,
|
|
9690
|
+
actor: MOCK_API_KEY_ACTOR,
|
|
8881
9691
|
facts: [],
|
|
8882
9692
|
createdAt: now,
|
|
8883
9693
|
...input
|
|
8884
9694
|
};
|
|
9695
|
+
const sequence = event.assetId ? (this.assetEventSequences.get(event.assetId) ?? 0) + 1 : null;
|
|
9696
|
+
if (event.assetId && sequence !== null) this.assetEventSequences.set(event.assetId, sequence);
|
|
9697
|
+
event.assetSequence = sequence;
|
|
8885
9698
|
this.eventFeed.push(event);
|
|
8886
9699
|
return event;
|
|
8887
9700
|
}
|
|
@@ -8908,15 +9721,17 @@ var MockCalmLensApi = class {
|
|
|
8908
9721
|
} catch (failure) {
|
|
8909
9722
|
throw this.toError(failure);
|
|
8910
9723
|
}
|
|
8911
|
-
|
|
9724
|
+
const rerun = this.pendingReruns.has(asset.id);
|
|
9725
|
+
if (!rerun && asset.classification.status !== "processing") throw require_ModerationContextLimits.invalidArgument(`asset ${assetId} isn't processing`);
|
|
8912
9726
|
const settled = decision === void 0 ? void 0 : toDecision(decision);
|
|
8913
|
-
return structuredClone(await this.moderateStored(asset, "complete", settled));
|
|
9727
|
+
if (!rerun) return structuredClone(await this.moderateStored(asset, "complete", settled));
|
|
9728
|
+
return structuredClone(await this.settleRerun(asset, settled ?? await this.decisionFor(asset, "complete", true)));
|
|
8914
9729
|
}
|
|
8915
9730
|
/**
|
|
8916
9731
|
* `POST /assets/:assetId/decision`, like the API: an asset still uploading or processing can't
|
|
8917
9732
|
* be decided, one pending moderation can only be blocked or purged, a decision must change the
|
|
8918
|
-
* status and purged content can only be blocked.
|
|
8919
|
-
* "An API key".
|
|
9733
|
+
* status and purged content can only be blocked. The review is the API key's, and mock API keys
|
|
9734
|
+
* have no ID or name, so its ID is `null` and the event names the reviewer "An API key".
|
|
8920
9735
|
*/
|
|
8921
9736
|
async decideAsset(assetId, body) {
|
|
8922
9737
|
const { decision, note: rawNote } = body;
|
|
@@ -8933,43 +9748,38 @@ var MockCalmLensApi = class {
|
|
|
8933
9748
|
if (decision !== "purged" && decision !== "blocked" && status === "pending") throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_DECISION_NOT_ALLOWED);
|
|
8934
9749
|
if (status === decision) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_DECISION_UNCHANGED);
|
|
8935
9750
|
if (decision !== "purged" && decision !== "blocked" && status === "purged") throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_CONTENT_PURGED);
|
|
8936
|
-
return this.recordDecision(asset, decision, {
|
|
8937
|
-
note,
|
|
8938
|
-
reviewerName: API_KEY_REVIEWER_NAME
|
|
8939
|
-
});
|
|
9751
|
+
return this.recordDecision(asset, decision, { note });
|
|
8940
9752
|
}
|
|
8941
9753
|
/**
|
|
8942
9754
|
* Sets the reviewer's decision: the moderation status, a manual review and the
|
|
8943
|
-
* `asset.<status>` event (after `asset.content-removed` when purging).
|
|
8944
|
-
*
|
|
9755
|
+
* `asset.<status>` event (after `asset.content-removed` when purging). Either way the review is
|
|
9756
|
+
* the mock API key's; the test hook records no note, the API's handler records it.
|
|
8945
9757
|
*/
|
|
8946
9758
|
async recordDecision(asset, decision, review) {
|
|
9759
|
+
this.pendingReruns.delete(asset.id);
|
|
8947
9760
|
const decided = await this.applyOutcome(asset, decision, "requested");
|
|
8948
9761
|
const now = this.now();
|
|
8949
9762
|
decided.classification.moderation.manualReviews = [...decided.classification.moderation.manualReviews ?? [], {
|
|
8950
9763
|
id: this.createId("rev"),
|
|
8951
9764
|
decision,
|
|
8952
9765
|
note: review?.note ?? null,
|
|
8953
|
-
|
|
8954
|
-
|
|
8955
|
-
|
|
9766
|
+
decidedBy: {
|
|
9767
|
+
type: "api-key",
|
|
9768
|
+
id: null
|
|
8956
9769
|
},
|
|
8957
9770
|
reviewedAt: now,
|
|
8958
|
-
|
|
9771
|
+
applied: true
|
|
8959
9772
|
}];
|
|
8960
9773
|
const stored = await this.databaseStorage.updateAsset(decided);
|
|
8961
|
-
if (decision === "purged") this.recordLifecycleEvent("asset.content-removed", stored);
|
|
9774
|
+
if (decision === "purged") this.recordLifecycleEvent("asset.content-removed", stored, { actor: review ? MOCK_API_KEY_ACTOR : MOCK_REVIEWER_ACTOR });
|
|
8962
9775
|
this.pushEvent({
|
|
8963
9776
|
type: `asset.${decision}`,
|
|
8964
9777
|
severity: decision === "allowed" || decision === "limited" ? "low" : "high",
|
|
8965
9778
|
title: `asset.${decision}`,
|
|
8966
9779
|
assetId: stored.id,
|
|
8967
9780
|
asset: toEventAsset(stored),
|
|
9781
|
+
actor: review ? MOCK_API_KEY_ACTOR : MOCK_REVIEWER_ACTOR,
|
|
8968
9782
|
facts: [
|
|
8969
|
-
{
|
|
8970
|
-
key: "decided-by",
|
|
8971
|
-
value: "reviewer"
|
|
8972
|
-
},
|
|
8973
9783
|
{
|
|
8974
9784
|
key: "asset-type",
|
|
8975
9785
|
value: stored.type
|
|
@@ -8980,11 +9790,8 @@ var MockCalmLensApi = class {
|
|
|
8980
9790
|
url: `https://calmlens.com/go/asset/${stored.id}`
|
|
8981
9791
|
},
|
|
8982
9792
|
...review ? [{
|
|
8983
|
-
key: "reviewer-user-id",
|
|
8984
|
-
value: null
|
|
8985
|
-
}, {
|
|
8986
9793
|
key: "reviewer-name",
|
|
8987
|
-
value:
|
|
9794
|
+
value: API_KEY_REVIEWER_NAME
|
|
8988
9795
|
}] : [],
|
|
8989
9796
|
{
|
|
8990
9797
|
key: "note",
|
|
@@ -9012,6 +9819,7 @@ var MockCalmLensApi = class {
|
|
|
9012
9819
|
async handle(input, init, endpoints, session) {
|
|
9013
9820
|
if (init?.signal?.aborted) throw init.signal.reason;
|
|
9014
9821
|
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
9822
|
+
this.cdnBaseUrl = endpoints.cdnBaseUrl;
|
|
9015
9823
|
const cdn = url.startsWith(`${endpoints.cdnBaseUrl}/`);
|
|
9016
9824
|
const base = cdn ? endpoints.cdnBaseUrl : endpoints.baseUrl;
|
|
9017
9825
|
if (!url.startsWith(`${base}/`)) throw new TypeError(`MockCalmLensServerClient does not serve ${url}`);
|
|
@@ -9071,9 +9879,20 @@ var MockCalmLensApi = class {
|
|
|
9071
9879
|
}
|
|
9072
9880
|
return failure;
|
|
9073
9881
|
}
|
|
9074
|
-
describeBody(
|
|
9882
|
+
describeBody(request) {
|
|
9883
|
+
const { bytes, headers } = request;
|
|
9075
9884
|
if (bytes.byteLength === 0) return void 0;
|
|
9076
9885
|
const type = headers.get("content-type") ?? "";
|
|
9886
|
+
if (type.startsWith("multipart/form-data")) try {
|
|
9887
|
+
const form = readUploadForm(request);
|
|
9888
|
+
const file = request.query.get("contentType") ?? "";
|
|
9889
|
+
return {
|
|
9890
|
+
options: JSON.parse(form.options),
|
|
9891
|
+
file: file.startsWith("text/") ? new TextDecoder().decode(form.bytes) : form.bytes.slice()
|
|
9892
|
+
};
|
|
9893
|
+
} catch {
|
|
9894
|
+
return bytes.slice();
|
|
9895
|
+
}
|
|
9077
9896
|
const text = () => new TextDecoder().decode(bytes);
|
|
9078
9897
|
if (type === "application/json") try {
|
|
9079
9898
|
return JSON.parse(text());
|
|
@@ -9115,13 +9934,20 @@ var MockCalmLensApi = class {
|
|
|
9115
9934
|
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);
|
|
9116
9935
|
const key = headers.get("idempotency-key")?.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
|
|
9117
9936
|
const upload = headers.get("x-calmlens-upload");
|
|
9937
|
+
const contentType = headers.get("content-type");
|
|
9938
|
+
const isForm = !!upload && /^multipart\/form-data\b/i.test(contentType ?? "");
|
|
9939
|
+
let formOptions;
|
|
9940
|
+
if (isForm && request.segments.at(-1) !== "part") try {
|
|
9941
|
+
formOptions = readUploadForm(request).options;
|
|
9942
|
+
} catch {}
|
|
9118
9943
|
const fingerprint = JSON.stringify([
|
|
9119
9944
|
request.method,
|
|
9120
9945
|
request.segments,
|
|
9121
9946
|
[...request.query].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0),
|
|
9122
|
-
|
|
9947
|
+
isForm ? "multipart/form-data" : contentType,
|
|
9123
9948
|
upload,
|
|
9124
|
-
upload ? request.bytes.byteLength : new TextDecoder().decode(request.bytes)
|
|
9949
|
+
upload ? request.bytes.byteLength : new TextDecoder().decode(request.bytes),
|
|
9950
|
+
formOptions ?? null
|
|
9125
9951
|
]);
|
|
9126
9952
|
if (key !== void 0) {
|
|
9127
9953
|
if (!isValidIdempotencyKey(key)) return this.failureResponse(fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_IDEMPOTENCY_KEY), url);
|
|
@@ -9161,25 +9987,51 @@ var MockCalmLensApi = class {
|
|
|
9161
9987
|
case "GET assets": return [200, await this.listAssets(request.query)];
|
|
9162
9988
|
case "GET assets/search": return [200, await this.searchAssets(request.query)];
|
|
9163
9989
|
case "POST assets/batch": return [202, await this.batch(this.json(request))];
|
|
9990
|
+
case "POST signed-asset-urls": return [200, await this.signAssetUrl(this.json(request))];
|
|
9164
9991
|
case "GET events": return [200, this.listEvents(request.query)];
|
|
9165
9992
|
case "GET folders": return [200, await this.listFolders(request.query)];
|
|
9166
9993
|
case "POST folders": return [201, await this.createFolder(this.json(request))];
|
|
9167
9994
|
case "GET hash-lists": return [200, this.listHashLists(request.query)];
|
|
9168
9995
|
case "POST hash-lists": return [201, this.createHashList(this.json(request))];
|
|
9169
9996
|
case "PUT lenses": return [200, this.ensureLenses(this.json(request))];
|
|
9170
|
-
case "GET
|
|
9171
|
-
case "POST
|
|
9997
|
+
case "GET lenses": return [200, this.listLenses(request.query)];
|
|
9998
|
+
case "POST lenses": return [201, this.createLens(this.json(request))];
|
|
9999
|
+
case "GET policy": return [200, this.toPolicy(this.findPolicy(this.ensurePolicies()))];
|
|
9172
10000
|
case "PUT policy": return [200, this.assignPolicy(this.json(request))];
|
|
10001
|
+
case "GET upload-presets": return [200, this.listUploadPresets(request.query)];
|
|
10002
|
+
case "PUT upload-presets": return [200, this.ensureUploadPresets(this.json(request))];
|
|
10003
|
+
case "GET settings": return [200, this.toProjectSettings()];
|
|
10004
|
+
case "PUT settings": return [200, this.updateProjectSettings(this.json(request))];
|
|
10005
|
+
case "GET metadata-fields": return [200, this.toMetadataFields()];
|
|
10006
|
+
case "PUT metadata-fields": return [200, this.ensureMetadataFields(this.json(request))];
|
|
10007
|
+
}
|
|
10008
|
+
const [, , collection, itemId, itemAction, ...more] = segments;
|
|
10009
|
+
if (collection === "metadata-fields" && itemId !== void 0 && itemAction === void 0) {
|
|
10010
|
+
if (method === "DELETE") return [200, this.deleteMetadataField(itemId, request.query)];
|
|
9173
10011
|
}
|
|
9174
|
-
|
|
9175
|
-
|
|
9176
|
-
|
|
9177
|
-
|
|
9178
|
-
|
|
9179
|
-
|
|
9180
|
-
|
|
10012
|
+
if (collection === "assets" && itemId !== void 0 && itemAction === "timeline" && more.length === 0 && method === "GET") return [200, await this.listTimeline(itemId, request.query)];
|
|
10013
|
+
}
|
|
10014
|
+
if (root === "policies" && rest.length === 0) {
|
|
10015
|
+
if (id === void 0) {
|
|
10016
|
+
if (method === "GET") return [200, this.listPolicies(request.query)];
|
|
10017
|
+
if (method === "POST") return [201, this.createPolicy(this.json(request))];
|
|
10018
|
+
} else switch (`${method} ${action ?? ""}`) {
|
|
10019
|
+
case "GET ": return [200, this.toPolicy(this.findPolicy(id))];
|
|
10020
|
+
case "PATCH ": return [200, this.updatePolicy(id, this.json(request))];
|
|
10021
|
+
case "DELETE ": return [200, this.deletePolicy(id)];
|
|
10022
|
+
case "POST reset": return [200, this.restorePolicy(id, "reset", this.json(request))];
|
|
10023
|
+
case "POST upgrade": return [200, this.restorePolicy(id, "upgrade", this.json(request))];
|
|
10024
|
+
case "PUT automatic-updates": return [200, this.setPolicyAutomaticUpdates(id, this.json(request))];
|
|
9181
10025
|
}
|
|
9182
10026
|
}
|
|
10027
|
+
if (root === "lenses" && id !== void 0 && action === void 0) switch (method) {
|
|
10028
|
+
case "GET": return [200, this.findLens(id)];
|
|
10029
|
+
case "PATCH": return [200, this.updateLens(id, this.json(request))];
|
|
10030
|
+
case "DELETE": return [200, this.deleteLens(id)];
|
|
10031
|
+
}
|
|
10032
|
+
if (root === "upload-presets" && id !== void 0 && action === void 0) {
|
|
10033
|
+
if (method === "DELETE") return [200, this.deleteUploadPreset(id)];
|
|
10034
|
+
}
|
|
9183
10035
|
if (root === "upload-presets" && id !== void 0 && action === "assets") return [200, await this.presetRoute(request, id, rest, session)];
|
|
9184
10036
|
if (root === "assets" && id !== void 0 && rest.length === 0) switch (`${method} ${action ?? ""}`) {
|
|
9185
10037
|
case "GET ": return [200, await this.findOwnAsset(id)];
|
|
@@ -9187,7 +10039,6 @@ var MockCalmLensApi = class {
|
|
|
9187
10039
|
case "DELETE ": return [200, await this.deleteAsset(id)];
|
|
9188
10040
|
case "GET children": return [200, await this.listChildren(id, request.query)];
|
|
9189
10041
|
case "POST part": return [200, await this.uploadPart(id, request)];
|
|
9190
|
-
case "POST signed-url": return [200, await this.createSignedUrl(id, this.json(request))];
|
|
9191
10042
|
case "POST move": return [200, await this.moveAsset(id, this.json(request))];
|
|
9192
10043
|
case "POST retry": return [200, await this.retryAsset(id)];
|
|
9193
10044
|
case "POST explain": return [200, await this.explainAsset(id, this.json(request))];
|
|
@@ -9213,13 +10064,14 @@ var MockCalmLensApi = class {
|
|
|
9213
10064
|
}
|
|
9214
10065
|
throw fail(require_ModerationContextLimits.API_ERROR_CODES.ROUTE_NOT_FOUND, { message: `No route for ${method} /${segments.join("/")}` });
|
|
9215
10066
|
}
|
|
10067
|
+
/** The project's policy, after creating the organisation's own General policy on first use. */
|
|
9216
10068
|
ensurePolicies() {
|
|
9217
|
-
if (this.projectPolicyId) return;
|
|
10069
|
+
if (this.projectPolicyId) return this.projectPolicyId;
|
|
9218
10070
|
const now = this.now();
|
|
9219
10071
|
const general = this.newPolicy({
|
|
9220
10072
|
name: MOCK_PRESET_NAMES["general-community"],
|
|
9221
|
-
settings:
|
|
9222
|
-
|
|
10073
|
+
settings: mockPresetSettings(),
|
|
10074
|
+
followsPreset: true,
|
|
9223
10075
|
preset: {
|
|
9224
10076
|
id: "general-community",
|
|
9225
10077
|
version: 1,
|
|
@@ -9228,6 +10080,7 @@ var MockCalmLensApi = class {
|
|
|
9228
10080
|
createdAt: now
|
|
9229
10081
|
});
|
|
9230
10082
|
this.projectPolicyId = general.id;
|
|
10083
|
+
return general.id;
|
|
9231
10084
|
}
|
|
9232
10085
|
newPolicy(values) {
|
|
9233
10086
|
const policy = {
|
|
@@ -9236,7 +10089,7 @@ var MockCalmLensApi = class {
|
|
|
9236
10089
|
description: values.description ?? "",
|
|
9237
10090
|
settings: values.settings,
|
|
9238
10091
|
revision: 1,
|
|
9239
|
-
|
|
10092
|
+
followsPreset: values.followsPreset ?? false,
|
|
9240
10093
|
preset: values.preset ?? null,
|
|
9241
10094
|
baseline: structuredClone(values.settings),
|
|
9242
10095
|
createdAt: values.createdAt,
|
|
@@ -9246,12 +10099,14 @@ var MockCalmLensApi = class {
|
|
|
9246
10099
|
return policy;
|
|
9247
10100
|
}
|
|
9248
10101
|
toPolicy(policy) {
|
|
9249
|
-
const { baseline: _baseline, preset, ...rest } = policy;
|
|
10102
|
+
const { baseline: _baseline, preset, followsPreset, ...rest } = policy;
|
|
9250
10103
|
return {
|
|
9251
10104
|
...structuredClone(rest),
|
|
9252
10105
|
preset: preset && {
|
|
9253
|
-
|
|
9254
|
-
|
|
10106
|
+
id: preset.id,
|
|
10107
|
+
version: preset.version,
|
|
10108
|
+
latestVersion: 1,
|
|
10109
|
+
mode: preset.own ? followsPreset ? "live" : "pinned" : "copy"
|
|
9255
10110
|
},
|
|
9256
10111
|
projectIds: policy.id === this.projectPolicyId ? [this.projectId] : []
|
|
9257
10112
|
};
|
|
@@ -9262,22 +10117,28 @@ var MockCalmLensApi = class {
|
|
|
9262
10117
|
if (!policy) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_NOT_FOUND);
|
|
9263
10118
|
return policy;
|
|
9264
10119
|
}
|
|
9265
|
-
|
|
10120
|
+
/** A page of the organisation's policies, oldest first unless `sort` says otherwise. */
|
|
10121
|
+
listPolicies(query) {
|
|
9266
10122
|
this.ensurePolicies();
|
|
9267
|
-
return {
|
|
9268
|
-
|
|
9269
|
-
|
|
9270
|
-
|
|
10123
|
+
return createPage([...this.policies.values()].map((policy) => this.toPolicy(policy)), this.pageQuery(query), {
|
|
10124
|
+
scope: `policies:${this.projectId}`,
|
|
10125
|
+
fail: this.pageFailure,
|
|
10126
|
+
defaultSort: [{
|
|
10127
|
+
field: "createdAt",
|
|
10128
|
+
direction: "asc"
|
|
10129
|
+
}]
|
|
10130
|
+
});
|
|
9271
10131
|
}
|
|
9272
10132
|
createPolicy(body) {
|
|
9273
10133
|
this.ensurePolicies();
|
|
9274
10134
|
const { name, description, settings, presetId } = body;
|
|
9275
10135
|
const preset = typeof presetId === "string" ? presetId : void 0;
|
|
9276
10136
|
if (settings === void 0 === (preset === void 0) || preset !== void 0 && !(preset in MOCK_PRESET_NAMES) || preset === void 0 && (typeof name !== "string" || !name.trim())) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_VALUE, { message: "Send settings with a name, or presetId" });
|
|
10137
|
+
if (!preset) checkPolicySettings(settings);
|
|
9277
10138
|
const policy = this.newPolicy({
|
|
9278
10139
|
name: typeof name === "string" && name.trim() ? name.trim() : MOCK_PRESET_NAMES[preset],
|
|
9279
10140
|
...typeof description === "string" ? { description } : {},
|
|
9280
|
-
settings: preset ?
|
|
10141
|
+
settings: preset ? mockPresetSettings() : settings,
|
|
9281
10142
|
...preset ? { preset: {
|
|
9282
10143
|
id: preset,
|
|
9283
10144
|
version: 1,
|
|
@@ -9301,28 +10162,30 @@ var MockCalmLensApi = class {
|
|
|
9301
10162
|
}
|
|
9302
10163
|
updatePolicy(policyId, body) {
|
|
9303
10164
|
const policy = this.findPolicy(policyId);
|
|
10165
|
+
if (body.settings !== void 0) checkPolicySettings(body.settings);
|
|
9304
10166
|
return this.savePolicy(policy, body.revision, {
|
|
9305
10167
|
...typeof body.name === "string" ? { name: body.name.trim() } : {},
|
|
9306
10168
|
...typeof body.description === "string" ? { description: body.description } : {},
|
|
9307
10169
|
...body.settings !== void 0 ? { settings: body.settings } : {},
|
|
9308
|
-
|
|
10170
|
+
followsPreset: false
|
|
9309
10171
|
});
|
|
9310
10172
|
}
|
|
9311
|
-
|
|
10173
|
+
/** Resets a `pinned` or `copy` policy to its preset release, or upgrades it to the latest. */
|
|
10174
|
+
restorePolicy(policyId, operation, body) {
|
|
9312
10175
|
const policy = this.findPolicy(policyId);
|
|
9313
|
-
if (!policy.preset || policy.
|
|
10176
|
+
if (!policy.preset || policy.followsPreset) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_NO_PRESET);
|
|
9314
10177
|
if (body.presetVersion !== policy.preset.version) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_PRESET_VERSION_CONFLICT);
|
|
9315
|
-
if (
|
|
10178
|
+
if (operation === "upgrade") throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_PRESET_UPDATE_UNAVAILABLE);
|
|
9316
10179
|
return this.savePolicy(policy, body.revision, { settings: structuredClone(policy.baseline) });
|
|
9317
10180
|
}
|
|
9318
10181
|
setPolicyAutomaticUpdates(policyId, body) {
|
|
9319
10182
|
const policy = this.findPolicy(policyId);
|
|
9320
10183
|
const enabled = body.enabled === true;
|
|
9321
|
-
if (!policy.preset?.own || policy.
|
|
10184
|
+
if (!policy.preset?.own || policy.followsPreset === enabled) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_AUTOMATIC_UPDATES_UNAVAILABLE);
|
|
9322
10185
|
if (body.revision !== policy.revision) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_REVISION_CONFLICT);
|
|
9323
10186
|
if (body.presetVersion !== 1) throw fail(require_ModerationContextLimits.API_ERROR_CODES.POLICY_PRESET_VERSION_CONFLICT);
|
|
9324
10187
|
return this.savePolicy(policy, body.revision, {
|
|
9325
|
-
|
|
10188
|
+
followsPreset: enabled,
|
|
9326
10189
|
...enabled ? {
|
|
9327
10190
|
name: MOCK_PRESET_NAMES[policy.preset.id],
|
|
9328
10191
|
description: "",
|
|
@@ -9387,26 +10250,10 @@ var MockCalmLensApi = class {
|
|
|
9387
10250
|
}
|
|
9388
10251
|
listHashListEntries(hashListId, query) {
|
|
9389
10252
|
this.findHashList(hashListId);
|
|
9390
|
-
|
|
9391
|
-
|
|
9392
|
-
|
|
9393
|
-
|
|
9394
|
-
if (!Number.isInteger(start) || start < 0) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR);
|
|
9395
|
-
const items = entries.slice(start, start + pageSize);
|
|
9396
|
-
const hasMore = start + pageSize < entries.length;
|
|
9397
|
-
return {
|
|
9398
|
-
items,
|
|
9399
|
-
hasMore,
|
|
9400
|
-
nextCursor: hasMore ? btoa(String(start + pageSize)) : null,
|
|
9401
|
-
pageSize,
|
|
9402
|
-
ordering: [{
|
|
9403
|
-
field: "createdAt",
|
|
9404
|
-
direction: "desc"
|
|
9405
|
-
}, {
|
|
9406
|
-
field: "id",
|
|
9407
|
-
direction: "desc"
|
|
9408
|
-
}]
|
|
9409
|
-
};
|
|
10253
|
+
return createPage([...this.hashListEntries.values()].filter((entry) => entry.hashListId === hashListId), this.pageQuery(query), {
|
|
10254
|
+
scope: `hash-list-entries:${hashListId}`,
|
|
10255
|
+
fail: this.pageFailure
|
|
10256
|
+
});
|
|
9410
10257
|
}
|
|
9411
10258
|
async addHashListEntry(hashListId, body) {
|
|
9412
10259
|
const list = this.findHashList(hashListId);
|
|
@@ -9415,10 +10262,10 @@ var MockCalmLensApi = class {
|
|
|
9415
10262
|
const assetId = typeof body.assetId === "string" ? body.assetId : void 0;
|
|
9416
10263
|
if (hash === void 0 === (assetId === void 0)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Send either hash or assetId" });
|
|
9417
10264
|
if (assetId) {
|
|
9418
|
-
const
|
|
9419
|
-
if (!
|
|
9420
|
-
hash =
|
|
9421
|
-
quality =
|
|
10265
|
+
const { content } = await this.findOwnAsset(assetId);
|
|
10266
|
+
if (!content.perceptualHash) throw fail(require_ModerationContextLimits.API_ERROR_CODES.HASH_LIST_ASSET_NOT_HASHED);
|
|
10267
|
+
hash = content.perceptualHash;
|
|
10268
|
+
quality = content.perceptualHashQuality ?? null;
|
|
9422
10269
|
}
|
|
9423
10270
|
if (!/^[0-9a-f]{64}$/.test(hash)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Use a PDQ hash of 64 hexadecimal characters" });
|
|
9424
10271
|
const existing = [...this.hashListEntries.values()].find((entry) => entry.hashListId === list.id && entry.hash === hash);
|
|
@@ -9430,7 +10277,7 @@ var MockCalmLensApi = class {
|
|
|
9430
10277
|
hash,
|
|
9431
10278
|
quality,
|
|
9432
10279
|
label: typeof body.label === "string" ? body.label : null,
|
|
9433
|
-
|
|
10280
|
+
assetId: assetId ?? null,
|
|
9434
10281
|
createdAt: this.now()
|
|
9435
10282
|
};
|
|
9436
10283
|
this.hashListEntries.set(entry.id, entry);
|
|
@@ -9443,7 +10290,7 @@ var MockCalmLensApi = class {
|
|
|
9443
10290
|
const body = JSON.parse(new TextDecoder().decode(request.bytes));
|
|
9444
10291
|
return body && typeof body === "object" ? body : {};
|
|
9445
10292
|
} catch {
|
|
9446
|
-
throw
|
|
10293
|
+
throw invalidField("validation/invalid-type", "");
|
|
9447
10294
|
}
|
|
9448
10295
|
}
|
|
9449
10296
|
/** A whole number from the query, or `fallback` when absent; other values fail like zod. */
|
|
@@ -9455,26 +10302,22 @@ var MockCalmLensApi = class {
|
|
|
9455
10302
|
if (!Number.isInteger(value)) throw invalidField("validation/invalid-type", name);
|
|
9456
10303
|
return value;
|
|
9457
10304
|
}
|
|
9458
|
-
/** `
|
|
9459
|
-
|
|
9460
|
-
|
|
9461
|
-
for (const [key, value] of query) {
|
|
9462
|
-
const match = /^ordering\[(\d+)\]\[(field|direction)\]$/.exec(key);
|
|
9463
|
-
if (!match) continue;
|
|
9464
|
-
const index = Number(match[1]);
|
|
9465
|
-
ordering[index] = {
|
|
9466
|
-
...ordering[index],
|
|
9467
|
-
[match[2]]: value
|
|
9468
|
-
};
|
|
9469
|
-
}
|
|
9470
|
-
return ordering.filter(Boolean);
|
|
10305
|
+
/** The list's `sort`, from `fields`, as the API's `sortQueryField` reads it. */
|
|
10306
|
+
sort(query, fields, max) {
|
|
10307
|
+
return parseSort(query.get("sort"), fields, max, () => invalidField("validation/invalid-value", "sort"));
|
|
9471
10308
|
}
|
|
10309
|
+
/**
|
|
10310
|
+
* A cursor list's query, checked like CURSOR_PAGE_QUERY_SCHEMA before anything else: `pageSize`
|
|
10311
|
+
* from 1 to 100, and a `sort` of at most two fields from `createdAt` and `id`.
|
|
10312
|
+
*/
|
|
9472
10313
|
pageQuery(query) {
|
|
9473
|
-
const
|
|
10314
|
+
const pageSize = this.integer(query, "pageSize", 50);
|
|
10315
|
+
if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
|
|
10316
|
+
if (pageSize > 100) throw invalidField("validation/too-big", "pageSize");
|
|
9474
10317
|
return {
|
|
9475
|
-
pageSize
|
|
10318
|
+
pageSize,
|
|
9476
10319
|
cursor: query.get("cursor") ?? void 0,
|
|
9477
|
-
|
|
10320
|
+
sort: this.sort(query, ["createdAt", "id"], 2)
|
|
9478
10321
|
};
|
|
9479
10322
|
}
|
|
9480
10323
|
async findOwnAsset(assetId) {
|
|
@@ -9484,16 +10327,16 @@ var MockCalmLensApi = class {
|
|
|
9484
10327
|
}
|
|
9485
10328
|
async listAssets(query) {
|
|
9486
10329
|
let assets = await this.databaseStorage.listAssets(this.projectId);
|
|
9487
|
-
const
|
|
9488
|
-
if (folderId !== null) assets = assets.filter((asset) => (asset.folderId ?? null) === folderId);
|
|
10330
|
+
const page = this.pageQuery(query);
|
|
9489
10331
|
const filter = query.get("filter") ?? void 0;
|
|
9490
|
-
|
|
9491
|
-
|
|
9492
|
-
|
|
9493
|
-
|
|
9494
|
-
|
|
9495
|
-
|
|
9496
|
-
|
|
10332
|
+
try {
|
|
10333
|
+
assets = filterAssets(assets, filter);
|
|
10334
|
+
} catch (error) {
|
|
10335
|
+
if (error instanceof MockInvalidFilter) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_FILTER);
|
|
10336
|
+
throw error;
|
|
10337
|
+
}
|
|
10338
|
+
return createPage(assets, page, {
|
|
10339
|
+
scope: JSON.stringify([this.projectId, filter ?? null]),
|
|
9497
10340
|
fail: this.pageFailure
|
|
9498
10341
|
});
|
|
9499
10342
|
}
|
|
@@ -9506,12 +10349,12 @@ var MockCalmLensApi = class {
|
|
|
9506
10349
|
const query = (params.get("query") ?? "").trim();
|
|
9507
10350
|
if (!query) throw invalidField("validation/too-small", "query");
|
|
9508
10351
|
if (query.length > MAX_SEARCH_QUERY_LENGTH) throw invalidField("validation/too-big", "query");
|
|
9509
|
-
const
|
|
9510
|
-
if (
|
|
9511
|
-
if (
|
|
10352
|
+
const pageSize = this.integer(params, "pageSize", 10);
|
|
10353
|
+
if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
|
|
10354
|
+
if (pageSize > MAX_SEARCH_PAGE_SIZE) throw invalidField("validation/too-big", "pageSize");
|
|
9512
10355
|
return {
|
|
9513
10356
|
query,
|
|
9514
|
-
items: searchAssets(await this.databaseStorage.listAssets(this.projectId), query,
|
|
10357
|
+
items: searchAssets(await this.databaseStorage.listAssets(this.projectId), query, pageSize),
|
|
9515
10358
|
semanticStatus: "disabled"
|
|
9516
10359
|
};
|
|
9517
10360
|
}
|
|
@@ -9523,6 +10366,24 @@ var MockCalmLensApi = class {
|
|
|
9523
10366
|
fail: this.pageFailure
|
|
9524
10367
|
});
|
|
9525
10368
|
}
|
|
10369
|
+
/**
|
|
10370
|
+
* An asset's findings timeline, as the API lists it (publicGetAssetTimeline.ts): refused while a
|
|
10371
|
+
* safety hold is on. The mock analyses no audio or video, so it keeps no segments: every
|
|
10372
|
+
* timeline is empty, and no cursor continues one.
|
|
10373
|
+
*/
|
|
10374
|
+
async listTimeline(assetId, query) {
|
|
10375
|
+
const asset = await this.findOwnAsset(assetId);
|
|
10376
|
+
const pageSize = this.integer(query, "pageSize", 50);
|
|
10377
|
+
if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
|
|
10378
|
+
if (pageSize > 100) throw invalidField("validation/too-big", "pageSize");
|
|
10379
|
+
if (asset.content.safetyHold) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_HELD, { details: { hold: "safety" } });
|
|
10380
|
+
if (query.get("cursor") !== null) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR);
|
|
10381
|
+
return {
|
|
10382
|
+
items: [],
|
|
10383
|
+
nextCursor: null,
|
|
10384
|
+
hasMore: false
|
|
10385
|
+
};
|
|
10386
|
+
}
|
|
9526
10387
|
async updateAsset(assetId, body) {
|
|
9527
10388
|
checkMetadata(body.metadata);
|
|
9528
10389
|
if (body.name === null) throw invalidField("validation/invalid-type", "name");
|
|
@@ -9552,21 +10413,46 @@ var MockCalmLensApi = class {
|
|
|
9552
10413
|
updatedAt: this.now()
|
|
9553
10414
|
});
|
|
9554
10415
|
}
|
|
9555
|
-
|
|
10416
|
+
/**
|
|
10417
|
+
* Signs an asset URL like the API (`POST /projects/:projectId/signed-asset-urls`): a grant to one
|
|
10418
|
+
* asset, by ID or external ID, until it expires, serving the original only when asked. The mock's
|
|
10419
|
+
* grant is readable (its asset, original access and expiry), unlike the CDN's, and only the
|
|
10420
|
+
* mock's CDN accepts it.
|
|
10421
|
+
*/
|
|
10422
|
+
async signAssetUrl(body) {
|
|
9556
10423
|
for (const key of [
|
|
9557
|
-
"
|
|
9558
|
-
"
|
|
9559
|
-
"
|
|
9560
|
-
"
|
|
9561
|
-
|
|
9562
|
-
|
|
9563
|
-
|
|
9564
|
-
|
|
9565
|
-
|
|
9566
|
-
|
|
10424
|
+
"assetId",
|
|
10425
|
+
"externalId",
|
|
10426
|
+
"expiresIn",
|
|
10427
|
+
"original"
|
|
10428
|
+
]) if (body[key] === null) throw invalidField("validation/invalid-type", key);
|
|
10429
|
+
const { assetId, externalId } = body;
|
|
10430
|
+
if (assetId === void 0 === (externalId === void 0)) throw new ApiFailure(400, require_ModerationContextLimits.API_ERROR_CODES.INVALID_REQUEST, "Send either assetId or externalId", { issues: [{
|
|
10431
|
+
path: "",
|
|
10432
|
+
message: "Send either assetId or externalId",
|
|
10433
|
+
code: "custom"
|
|
10434
|
+
}] });
|
|
10435
|
+
const expiresIn = body.expiresIn ?? 900;
|
|
10436
|
+
if (typeof expiresIn !== "number" || !Number.isInteger(expiresIn)) throw invalidField("validation/invalid-type", "expiresIn");
|
|
10437
|
+
if (expiresIn < 1) throw invalidField("validation/too-small", "expiresIn");
|
|
10438
|
+
if (expiresIn > 86400) throw invalidField("validation/too-big", "expiresIn");
|
|
10439
|
+
const original = body.original ?? false;
|
|
10440
|
+
if (typeof original !== "boolean") throw invalidField("validation/invalid-type", "original");
|
|
10441
|
+
let asset;
|
|
10442
|
+
if (externalId !== void 0) {
|
|
10443
|
+
asset = (await this.databaseStorage.listAssets(this.projectId)).find((candidate) => candidate.externalId === externalId);
|
|
10444
|
+
if (!asset) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_NOT_FOUND);
|
|
10445
|
+
} else asset = await this.findOwnAsset(String(assetId));
|
|
10446
|
+
if (asset.content.safetyHold) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_HELD);
|
|
10447
|
+
const expiresAt = this.now() + expiresIn * 1e3;
|
|
10448
|
+
const grant = encodeMockGrant({
|
|
10449
|
+
assetId: asset.id,
|
|
10450
|
+
original,
|
|
10451
|
+
expiresAt
|
|
10452
|
+
});
|
|
9567
10453
|
return {
|
|
9568
|
-
url: `${this.
|
|
9569
|
-
expiresAt
|
|
10454
|
+
url: `${this.cdnBaseUrl}/assets/${encodeURIComponent(this.projectId)}/${grant}`,
|
|
10455
|
+
expiresAt
|
|
9570
10456
|
};
|
|
9571
10457
|
}
|
|
9572
10458
|
async retryAsset(assetId) {
|
|
@@ -9596,8 +10482,27 @@ var MockCalmLensApi = class {
|
|
|
9596
10482
|
}
|
|
9597
10483
|
if (asset.classification.moderation.manualReviews.length) throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_REVIEWED);
|
|
9598
10484
|
if (asset.content.status === "removed") throw fail(require_ModerationContextLimits.API_ERROR_CODES.ASSET_CONTENT_UNAVAILABLE);
|
|
9599
|
-
|
|
9600
|
-
|
|
10485
|
+
this.pushEvent({
|
|
10486
|
+
type: "asset.rerun-requested",
|
|
10487
|
+
actor: MOCK_API_KEY_ACTOR,
|
|
10488
|
+
severity: "low",
|
|
10489
|
+
assetId: asset.id,
|
|
10490
|
+
asset: toEventAsset(asset),
|
|
10491
|
+
facts: [
|
|
10492
|
+
assetNameFact(asset),
|
|
10493
|
+
{
|
|
10494
|
+
key: "asset-type",
|
|
10495
|
+
value: asset.type
|
|
10496
|
+
},
|
|
10497
|
+
{
|
|
10498
|
+
key: "moderation-status",
|
|
10499
|
+
value: asset.classification.moderation.status
|
|
10500
|
+
}
|
|
10501
|
+
]
|
|
10502
|
+
});
|
|
10503
|
+
const response = structuredClone(asset);
|
|
10504
|
+
await this.settleRerun(asset, await this.decisionFor(asset, "rerun", true));
|
|
10505
|
+
return response;
|
|
9601
10506
|
}
|
|
9602
10507
|
/**
|
|
9603
10508
|
* Checks every asset like the API (an ID that is not an asset ID is
|
|
@@ -9605,7 +10510,8 @@ var MockCalmLensApi = class {
|
|
|
9605
10510
|
* one `asset/not-found`, and either refuses the whole batch), then applies the operation at
|
|
9606
10511
|
* once instead of in the background: `delete` deletes each asset with its stored child
|
|
9607
10512
|
* assets and records `asset.deleted` with the asset as it was; `remove-content` removes
|
|
9608
|
-
* the content like `
|
|
10513
|
+
* the content like `removeContent`. Each event carries the batch's `batch-id` fact. Mock assets
|
|
10514
|
+
* carry no safety holds, so none is skipped.
|
|
9609
10515
|
*/
|
|
9610
10516
|
async batch(body) {
|
|
9611
10517
|
const assetIds = Array.isArray(body.assetIds) ? body.assetIds : [];
|
|
@@ -9618,26 +10524,31 @@ var MockCalmLensApi = class {
|
|
|
9618
10524
|
});
|
|
9619
10525
|
const assets = [];
|
|
9620
10526
|
for (const assetId of new Set(assetIds)) assets.push(await this.findOwnAsset(assetId));
|
|
10527
|
+
const batchId = this.createId("batch");
|
|
9621
10528
|
for (const asset of assets) if (operation === "delete") {
|
|
9622
10529
|
await this.deleteAssetTree(asset);
|
|
9623
|
-
this.recordLifecycleEvent("asset.deleted", asset);
|
|
9624
|
-
} else await this.removeContent(asset);
|
|
9625
|
-
return {
|
|
10530
|
+
this.recordLifecycleEvent("asset.deleted", asset, { batchId });
|
|
10531
|
+
} else await this.removeContent(asset, batchId);
|
|
10532
|
+
return {
|
|
10533
|
+
batchId,
|
|
10534
|
+
status: "queued",
|
|
10535
|
+
assetCount: assets.length
|
|
10536
|
+
};
|
|
9626
10537
|
}
|
|
9627
10538
|
/**
|
|
9628
10539
|
* Removes an asset's content like the API: the record and report stay; stored content,
|
|
9629
10540
|
* extracted text and the placeholder go. Content already removed keeps its reason, and an
|
|
9630
10541
|
* `asset.content-removed` event is recorded either way.
|
|
9631
10542
|
*/
|
|
9632
|
-
async removeContent(asset) {
|
|
10543
|
+
async removeContent(asset, batchId) {
|
|
9633
10544
|
await this.imageStorage.deleteContent(asset.id);
|
|
9634
10545
|
let removed = asset;
|
|
9635
10546
|
if (asset.content.status === "removed") {
|
|
9636
|
-
if (asset.content.
|
|
10547
|
+
if (asset.content.rendered || asset.content.preview) removed = await this.databaseStorage.updateAsset({
|
|
9637
10548
|
...asset,
|
|
9638
10549
|
content: {
|
|
9639
10550
|
...asset.content,
|
|
9640
|
-
|
|
10551
|
+
...NO_RENDERING
|
|
9641
10552
|
}
|
|
9642
10553
|
});
|
|
9643
10554
|
} else {
|
|
@@ -9651,13 +10562,13 @@ var MockCalmLensApi = class {
|
|
|
9651
10562
|
removalReason: "requested",
|
|
9652
10563
|
updatedAt: now,
|
|
9653
10564
|
extractedText: null,
|
|
9654
|
-
|
|
9655
|
-
|
|
10565
|
+
metadata: null,
|
|
10566
|
+
...NO_RENDERING
|
|
9656
10567
|
},
|
|
9657
10568
|
updatedAt: now
|
|
9658
10569
|
});
|
|
9659
10570
|
}
|
|
9660
|
-
this.recordLifecycleEvent("asset.content-removed", removed);
|
|
10571
|
+
this.recordLifecycleEvent("asset.content-removed", removed, { batchId });
|
|
9661
10572
|
return removed;
|
|
9662
10573
|
}
|
|
9663
10574
|
/** Deletes an asset, its stored child assets and their content. */
|
|
@@ -9676,41 +10587,49 @@ var MockCalmLensApi = class {
|
|
|
9676
10587
|
await this.databaseStorage.deleteAsset(id);
|
|
9677
10588
|
}
|
|
9678
10589
|
}
|
|
9679
|
-
/**
|
|
10590
|
+
/**
|
|
10591
|
+
* The upload fields of `POST .../assets`, from the JSON body (text and URLs) or an upload form's
|
|
10592
|
+
* options (files). Like the API, asset fields in the query are refused.
|
|
10593
|
+
*/
|
|
9680
10594
|
uploadFields(request) {
|
|
10595
|
+
const { query } = request;
|
|
10596
|
+
assertNoUploadOptionsInQuery(query);
|
|
9681
10597
|
const upload = request.headers.get("x-calmlens-upload");
|
|
9682
10598
|
if (upload !== "content" && upload !== "part") {
|
|
9683
10599
|
const body = this.json(request);
|
|
9684
10600
|
checkMetadata(body.metadata);
|
|
9685
|
-
|
|
10601
|
+
const { content, part, sizeInBytes: _size, totalSizeInBytes, ...fields } = body;
|
|
10602
|
+
const text = content ?? part;
|
|
10603
|
+
if (text === void 0) return fields;
|
|
10604
|
+
if (typeof text.plainText !== "string" || typeof text.type !== "string") throw invalidField("validation/invalid-type", content ? "content" : "part");
|
|
10605
|
+
return {
|
|
10606
|
+
...fields,
|
|
10607
|
+
contentType: text.type,
|
|
10608
|
+
bytes: new TextEncoder().encode(text.plainText),
|
|
10609
|
+
part: part ? {
|
|
10610
|
+
partNumber: typeof part.partNumber === "number" ? part.partNumber : 1,
|
|
10611
|
+
isFinal: part.isFinal === true,
|
|
10612
|
+
totalSizeInBytes: typeof totalSizeInBytes === "number" ? totalSizeInBytes : void 0
|
|
10613
|
+
} : void 0
|
|
10614
|
+
};
|
|
9686
10615
|
}
|
|
9687
|
-
const
|
|
9688
|
-
|
|
9689
|
-
|
|
9690
|
-
|
|
9691
|
-
|
|
9692
|
-
|
|
9693
|
-
|
|
9694
|
-
|
|
9695
|
-
|
|
9696
|
-
|
|
9697
|
-
|
|
10616
|
+
const form = readUploadForm(request);
|
|
10617
|
+
let options;
|
|
10618
|
+
try {
|
|
10619
|
+
options = JSON.parse(form.options);
|
|
10620
|
+
} catch {
|
|
10621
|
+
throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "The options part must be a JSON object with the asset's fields" });
|
|
10622
|
+
}
|
|
10623
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "The options part must be a JSON object with the asset's fields" });
|
|
10624
|
+
const unknown = Object.keys(options).find((key) => !UPLOAD_OPTION_KEYS.includes(key));
|
|
10625
|
+
if (unknown !== void 0) throw invalidField("validation/unknown-field", unknown);
|
|
10626
|
+
if (typeof options.name !== "string") throw invalidField("validation/invalid-type", "name");
|
|
10627
|
+
checkMetadata(options.metadata);
|
|
9698
10628
|
const total = query.get("totalSizeInBytes");
|
|
9699
|
-
checkMetadata(parsed("metadata"));
|
|
9700
10629
|
return {
|
|
9701
|
-
|
|
9702
|
-
|
|
9703
|
-
|
|
9704
|
-
visibility: text("visibility"),
|
|
9705
|
-
metadata: parsed("metadata"),
|
|
9706
|
-
authorId: text("authorId"),
|
|
9707
|
-
context: parsed("context"),
|
|
9708
|
-
externalId: text("externalId"),
|
|
9709
|
-
externalUrl: text("externalUrl"),
|
|
9710
|
-
folderId: text("folderId"),
|
|
9711
|
-
uploadPresetId: text("uploadPresetId"),
|
|
9712
|
-
contentType: query.get("contentType") ?? request.headers.get("content-type") ?? "",
|
|
9713
|
-
bytes: request.bytes,
|
|
10630
|
+
...options,
|
|
10631
|
+
contentType: query.get("contentType") ?? "",
|
|
10632
|
+
bytes: form.bytes,
|
|
9714
10633
|
part: upload === "part" ? {
|
|
9715
10634
|
partNumber: this.integer(query, "partNumber", 1),
|
|
9716
10635
|
isFinal: query.get("isFinal") === "true",
|
|
@@ -9719,22 +10638,25 @@ var MockCalmLensApi = class {
|
|
|
9719
10638
|
};
|
|
9720
10639
|
}
|
|
9721
10640
|
async createAsset(request) {
|
|
9722
|
-
return this.storeAsset(this.uploadFields(request), request.query.get("
|
|
10641
|
+
return this.storeAsset(this.uploadFields(request), request.query.get("wait") === "false");
|
|
9723
10642
|
}
|
|
9724
10643
|
async storeAsset(fields, queue) {
|
|
9725
10644
|
if (!fields.name) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Asset name is required" });
|
|
9726
10645
|
const { contentType, part } = fields;
|
|
9727
10646
|
const bytes = fields.bytes ?? /* @__PURE__ */ new Uint8Array(0);
|
|
9728
|
-
if (contentType !== void 0 && !require_ModerationContextLimits.isAcceptedUploadMimeType(contentType)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.
|
|
10647
|
+
if (contentType !== void 0 && !require_ModerationContextLimits.isAcceptedUploadMimeType(contentType)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, {
|
|
9729
10648
|
message: require_ModerationContextLimits.getRejectedUploadMimeTypeError(contentType),
|
|
9730
|
-
details: {
|
|
10649
|
+
details: {
|
|
10650
|
+
mimeType: contentType,
|
|
10651
|
+
source: "calmlens"
|
|
10652
|
+
}
|
|
9731
10653
|
});
|
|
9732
10654
|
const type = inferAssetType(fields.url === void 0 ? contentType ?? "" : void 0);
|
|
9733
10655
|
if (part) {
|
|
9734
10656
|
if (part.partNumber > 1) throw fail(require_ModerationContextLimits.API_ERROR_CODES.USE_UPLOAD_PART);
|
|
9735
10657
|
const partSize = bytes.byteLength;
|
|
9736
10658
|
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);
|
|
9737
|
-
if (sizeError) throw
|
|
10659
|
+
if (sizeError) throw this.sizeFailure(sizeError);
|
|
9738
10660
|
const validation = require_CalmLensOptionKeys.validateAssetPayload({ uint8Array: bytes }, {
|
|
9739
10661
|
multipart: true,
|
|
9740
10662
|
isFinal: part.isFinal
|
|
@@ -9754,12 +10676,14 @@ var MockCalmLensApi = class {
|
|
|
9754
10676
|
const isOpenUpload = part !== void 0 && !part.isFinal;
|
|
9755
10677
|
const processingOptions = fields.processingOptions ?? { keepContentAfterProcessing: false };
|
|
9756
10678
|
const keepContent = processingOptions.keepContentAfterProcessing === true;
|
|
10679
|
+
this.processingOptions.set(id, processingOptions);
|
|
9757
10680
|
const hasContent = fields.url === void 0;
|
|
9758
10681
|
const contextItems = require_ModerationContextLimits.selectModerationContextItems(fields.context?.items ?? []);
|
|
9759
10682
|
const asset = {
|
|
9760
10683
|
id,
|
|
9761
10684
|
projectId: this.projectId,
|
|
9762
10685
|
parentId: null,
|
|
10686
|
+
parentPages: [],
|
|
9763
10687
|
folderId: fields.folderId ?? null,
|
|
9764
10688
|
uploadPresetId: fields.uploadPresetId ?? null,
|
|
9765
10689
|
createdAt: now,
|
|
@@ -9769,11 +10693,10 @@ var MockCalmLensApi = class {
|
|
|
9769
10693
|
externalId: fields.externalId ?? null,
|
|
9770
10694
|
externalUrl: fields.url ?? fields.externalUrl ?? null,
|
|
9771
10695
|
type,
|
|
9772
|
-
metadata: fields.metadata ??
|
|
10696
|
+
metadata: fields.metadata ?? [],
|
|
9773
10697
|
authorId: fields.authorId ?? null,
|
|
9774
10698
|
context: contextItems.length ? { items: contextItems } : null,
|
|
9775
|
-
tags:
|
|
9776
|
-
processingOptions,
|
|
10699
|
+
tags: fields.tags ?? [],
|
|
9777
10700
|
visibility: fields.visibility ?? "private",
|
|
9778
10701
|
content: {
|
|
9779
10702
|
status: keepContent ? "stored" : "temporary",
|
|
@@ -9784,9 +10707,15 @@ var MockCalmLensApi = class {
|
|
|
9784
10707
|
extension: null,
|
|
9785
10708
|
sizeInBytes: hasContent ? bytes.byteLength : null,
|
|
9786
10709
|
checksums: null,
|
|
9787
|
-
|
|
10710
|
+
width: null,
|
|
10711
|
+
height: null,
|
|
10712
|
+
durationSeconds: null,
|
|
10713
|
+
pageCount: null,
|
|
10714
|
+
perceptualHash: null,
|
|
10715
|
+
perceptualHashQuality: null,
|
|
10716
|
+
metadata: null,
|
|
9788
10717
|
extractedText: null,
|
|
9789
|
-
|
|
10718
|
+
...NO_RENDERING
|
|
9790
10719
|
},
|
|
9791
10720
|
upload: {
|
|
9792
10721
|
status: isOpenUpload ? "uploading" : "completed",
|
|
@@ -9794,16 +10723,29 @@ var MockCalmLensApi = class {
|
|
|
9794
10723
|
partsReceived: isOpenUpload ? part.partNumber : null
|
|
9795
10724
|
},
|
|
9796
10725
|
classification: {
|
|
9797
|
-
status: isOpenUpload ? "
|
|
10726
|
+
status: isOpenUpload ? "queued" : "processing",
|
|
9798
10727
|
failureReason: null,
|
|
9799
10728
|
updatedAt: now,
|
|
9800
10729
|
completedAt: null,
|
|
10730
|
+
progress: null,
|
|
10731
|
+
testInput: false,
|
|
9801
10732
|
moderation: {
|
|
9802
10733
|
status: "pending",
|
|
9803
10734
|
manualReviews: [],
|
|
10735
|
+
automatedStatus: null,
|
|
10736
|
+
policy: null,
|
|
10737
|
+
pendingReview: null,
|
|
10738
|
+
source: null,
|
|
10739
|
+
rule: null,
|
|
10740
|
+
explanationComplete: null,
|
|
10741
|
+
categories: null,
|
|
9804
10742
|
flaggedCategories: [],
|
|
9805
|
-
regions: []
|
|
9806
|
-
|
|
10743
|
+
regions: [],
|
|
10744
|
+
raw: null,
|
|
10745
|
+
timeline: null
|
|
10746
|
+
},
|
|
10747
|
+
ocr: null,
|
|
10748
|
+
linkDetection: null
|
|
9807
10749
|
}
|
|
9808
10750
|
};
|
|
9809
10751
|
if (part) {
|
|
@@ -9822,6 +10764,10 @@ var MockCalmLensApi = class {
|
|
|
9822
10764
|
type: contentType ?? ""
|
|
9823
10765
|
});
|
|
9824
10766
|
if (isOpenUpload) return this.databaseStorage.createAsset(asset);
|
|
10767
|
+
if (hasContent) asset.content = {
|
|
10768
|
+
...asset.content,
|
|
10769
|
+
...mockRendering(asset, false)
|
|
10770
|
+
};
|
|
9825
10771
|
const decision = await this.decisionFor(asset, "upload", queue, hasContent ? bytes : null);
|
|
9826
10772
|
const stored = await this.databaseStorage.createAsset(decision.status === "pending" ? asset : await this.decided(asset, decision));
|
|
9827
10773
|
this.recordUploaded(asset);
|
|
@@ -9846,7 +10792,7 @@ var MockCalmLensApi = class {
|
|
|
9846
10792
|
const received = (asset.content.sizeInBytes ?? 0) + bytes.byteLength;
|
|
9847
10793
|
const upload = this.openUploads.get(assetId);
|
|
9848
10794
|
const sizeError = this.multipartImageSizeError(asset.type, received) ?? this.multipartTotalSizeError(upload?.totalSizeInBytes, received, isFinal);
|
|
9849
|
-
if (sizeError) throw
|
|
10795
|
+
if (sizeError) throw this.sizeFailure(sizeError);
|
|
9850
10796
|
const validation = require_CalmLensOptionKeys.validateAssetPayload({ uint8Array: bytes }, {
|
|
9851
10797
|
multipart: true,
|
|
9852
10798
|
isFinal
|
|
@@ -9857,8 +10803,8 @@ var MockCalmLensApi = class {
|
|
|
9857
10803
|
partNumber,
|
|
9858
10804
|
isFinal
|
|
9859
10805
|
});
|
|
9860
|
-
const
|
|
9861
|
-
const queue =
|
|
10806
|
+
const waitOverride = query.get("wait");
|
|
10807
|
+
const queue = waitOverride === null ? upload?.queue ?? false : waitOverride === "false";
|
|
9862
10808
|
if (isFinal) this.openUploads.delete(assetId);
|
|
9863
10809
|
const now = this.now();
|
|
9864
10810
|
const next = {
|
|
@@ -9885,7 +10831,14 @@ var MockCalmLensApi = class {
|
|
|
9885
10831
|
/** Like the API: image uploads in parts total at most 20 MiB, at any size below that. */
|
|
9886
10832
|
multipartImageSizeError(type, sizeInBytes) {
|
|
9887
10833
|
if (type !== "image") return void 0;
|
|
9888
|
-
if (sizeInBytes > require_ModerationContextLimits.MAX_IMAGE_UPLOAD_BYTES) return require_ModerationContextLimits.API_ERROR_CODES.
|
|
10834
|
+
if (sizeInBytes > require_ModerationContextLimits.MAX_IMAGE_UPLOAD_BYTES) return require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_TOO_LARGE;
|
|
10835
|
+
}
|
|
10836
|
+
/** The failure for a size error code, with the limit `upload/too-large` carries. */
|
|
10837
|
+
sizeFailure(code) {
|
|
10838
|
+
return fail(code, code === require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_TOO_LARGE ? { details: {
|
|
10839
|
+
limitBytes: require_ModerationContextLimits.MAX_IMAGE_UPLOAD_BYTES,
|
|
10840
|
+
source: "plan"
|
|
10841
|
+
} } : {});
|
|
9889
10842
|
}
|
|
9890
10843
|
/** Like the API: the parts may not overshoot a declared total, and must reach it at the end. */
|
|
9891
10844
|
multipartTotalSizeError(totalSizeInBytes, receivedSizeInBytes, isFinal) {
|
|
@@ -9914,9 +10867,37 @@ var MockCalmLensApi = class {
|
|
|
9914
10867
|
queued
|
|
9915
10868
|
}));
|
|
9916
10869
|
}
|
|
9917
|
-
/**
|
|
9918
|
-
|
|
9919
|
-
|
|
10870
|
+
/**
|
|
10871
|
+
* `asset` decided as `decision` says, with its report. Like the API for an image with nobody in
|
|
10872
|
+
* it, a decided image reports the person and face detection its upload turned on.
|
|
10873
|
+
*/
|
|
10874
|
+
async decided(asset, decision) {
|
|
10875
|
+
const next = await this.applyOutcome(asset, decision.status, "policy", decision.report());
|
|
10876
|
+
const features = this.processingOptions.get(asset.id)?.features;
|
|
10877
|
+
if (next.classification.status !== "completed" || asset.type !== "image") return next;
|
|
10878
|
+
return {
|
|
10879
|
+
...next,
|
|
10880
|
+
classification: {
|
|
10881
|
+
...next.classification,
|
|
10882
|
+
...features?.ocr?.enabled === true && { ocr: {
|
|
10883
|
+
status: "evaluated",
|
|
10884
|
+
textRegions: []
|
|
10885
|
+
} },
|
|
10886
|
+
...features?.linkDetection?.enabled !== false && { linkDetection: {
|
|
10887
|
+
status: "evaluated",
|
|
10888
|
+
qrCodes: [],
|
|
10889
|
+
links: []
|
|
10890
|
+
} },
|
|
10891
|
+
...features?.personDetection?.enabled === true && { personDetection: {
|
|
10892
|
+
status: "evaluated",
|
|
10893
|
+
people: []
|
|
10894
|
+
} },
|
|
10895
|
+
...features?.faceDetection?.enabled === true && { faceDetection: {
|
|
10896
|
+
status: "evaluated",
|
|
10897
|
+
faces: []
|
|
10898
|
+
} }
|
|
10899
|
+
}
|
|
10900
|
+
};
|
|
9920
10901
|
}
|
|
9921
10902
|
/**
|
|
9922
10903
|
* Stores a processing asset's `decision` and records its events; a `pending` decision leaves it
|
|
@@ -9928,6 +10909,20 @@ var MockCalmLensApi = class {
|
|
|
9928
10909
|
this.recordProcessingEvents(stored, decision);
|
|
9929
10910
|
return stored;
|
|
9930
10911
|
}
|
|
10912
|
+
/**
|
|
10913
|
+
* Applies a re-run's `decision` to a decided asset like the pipeline: a `pending` decision stays
|
|
10914
|
+
* queued for `completeProcessing`, a `failed` one keeps the asset's decision, and any other
|
|
10915
|
+
* replaces it with the pipeline's events.
|
|
10916
|
+
*/
|
|
10917
|
+
async settleRerun(asset, decision) {
|
|
10918
|
+
this.pendingReruns.delete(asset.id);
|
|
10919
|
+
if (decision.status === "pending") {
|
|
10920
|
+
this.pendingReruns.add(asset.id);
|
|
10921
|
+
return asset;
|
|
10922
|
+
}
|
|
10923
|
+
if (decision.status === "failed") return asset;
|
|
10924
|
+
return this.settle(asset, decision);
|
|
10925
|
+
}
|
|
9931
10926
|
/** Asks `moderate` (unless `decision` is given) and settles a processing asset. */
|
|
9932
10927
|
async moderateStored(asset, trigger, decision) {
|
|
9933
10928
|
return this.settle(asset, decision ?? await this.decisionFor(asset, trigger, true));
|
|
@@ -9961,7 +10956,8 @@ var MockCalmLensApi = class {
|
|
|
9961
10956
|
if (decision.status === "pending") return;
|
|
9962
10957
|
const event = {
|
|
9963
10958
|
assetId: asset.id,
|
|
9964
|
-
asset: toEventAsset(asset)
|
|
10959
|
+
asset: toEventAsset(asset),
|
|
10960
|
+
actor: AUTOMATED_ACTOR
|
|
9965
10961
|
};
|
|
9966
10962
|
if (decision.status === "failed") {
|
|
9967
10963
|
this.pushEvent({
|
|
@@ -10012,10 +11008,6 @@ var MockCalmLensApi = class {
|
|
|
10012
11008
|
type: `asset.${decision.status}`,
|
|
10013
11009
|
severity: decision.status === "allowed" || decision.status === "limited" ? "low" : "high",
|
|
10014
11010
|
facts: [
|
|
10015
|
-
{
|
|
10016
|
-
key: "decided-by",
|
|
10017
|
-
value: "automated"
|
|
10018
|
-
},
|
|
10019
11011
|
{
|
|
10020
11012
|
key: "flagged-categories",
|
|
10021
11013
|
value: flaggedCategories
|
|
@@ -10031,8 +11023,8 @@ var MockCalmLensApi = class {
|
|
|
10031
11023
|
/**
|
|
10032
11024
|
* Moves an asset to `outcome` like the pipeline would: a decision finishes processing, `purged`
|
|
10033
11025
|
* deletes the content (with `purgeReason`, `policy` for the pipeline), and finished processing
|
|
10034
|
-
* removes content kept only temporarily (`keepContentAfterProcessing` off). A
|
|
10035
|
-
*
|
|
11026
|
+
* removes content kept only temporarily (`keepContentAfterProcessing` off). A decided asset gets
|
|
11027
|
+
* its rendered file and preview (with a ThumbHash for its placeholder), which go with its content.
|
|
10036
11028
|
*/
|
|
10037
11029
|
async applyOutcome(asset, outcome, purgeReason = "policy", report) {
|
|
10038
11030
|
const now = this.now();
|
|
@@ -10041,15 +11033,7 @@ var MockCalmLensApi = class {
|
|
|
10041
11033
|
const purge = outcome === "purged" && asset.content.status !== "removed";
|
|
10042
11034
|
const removeContent = purge || classificationStatus === "completed" && asset.content.status === "temporary";
|
|
10043
11035
|
if (removeContent) await this.imageStorage.deleteContent(asset.id);
|
|
10044
|
-
const
|
|
10045
|
-
width: null,
|
|
10046
|
-
height: null,
|
|
10047
|
-
perceptualHash: null,
|
|
10048
|
-
perceptualHashQuality: null,
|
|
10049
|
-
...asset.content.image,
|
|
10050
|
-
thumbhash: MOCK_THUMBHASH,
|
|
10051
|
-
averageColor: asset.content.image?.averageColor ?? "#7f7f7f"
|
|
10052
|
-
} : outcome === "purged" ? withoutPlaceholder(asset.content.image) : asset.content.image;
|
|
11036
|
+
const rendering = asset.content.status !== "removed" && !purge && !asset.content.safetyHold ? mockRendering(asset, decided) : NO_RENDERING;
|
|
10053
11037
|
return {
|
|
10054
11038
|
...asset,
|
|
10055
11039
|
updatedAt: now,
|
|
@@ -10060,11 +11044,11 @@ var MockCalmLensApi = class {
|
|
|
10060
11044
|
removalReason: purge ? purgeReason : "retention",
|
|
10061
11045
|
updatedAt: now,
|
|
10062
11046
|
extractedText: null,
|
|
10063
|
-
|
|
10064
|
-
|
|
11047
|
+
metadata: null,
|
|
11048
|
+
...NO_RENDERING
|
|
10065
11049
|
} : {
|
|
10066
11050
|
...asset.content,
|
|
10067
|
-
|
|
11051
|
+
...rendering
|
|
10068
11052
|
},
|
|
10069
11053
|
upload: {
|
|
10070
11054
|
...asset.upload,
|
|
@@ -10086,20 +11070,29 @@ var MockCalmLensApi = class {
|
|
|
10086
11070
|
};
|
|
10087
11071
|
}
|
|
10088
11072
|
/** Adds an `asset.deleted`, `asset.content-removed` or `asset.retried` event, like the API. */
|
|
10089
|
-
recordLifecycleEvent(type, asset) {
|
|
11073
|
+
recordLifecycleEvent(type, asset, options = {}) {
|
|
11074
|
+
const { batchId, actor = MOCK_API_KEY_ACTOR } = options;
|
|
10090
11075
|
this.pushEvent({
|
|
10091
11076
|
type,
|
|
11077
|
+
actor,
|
|
10092
11078
|
severity: "low",
|
|
10093
11079
|
assetId: asset.id,
|
|
10094
11080
|
asset: toEventAsset(asset),
|
|
10095
|
-
facts: [
|
|
10096
|
-
|
|
10097
|
-
|
|
10098
|
-
|
|
10099
|
-
|
|
10100
|
-
|
|
10101
|
-
|
|
10102
|
-
|
|
11081
|
+
facts: [
|
|
11082
|
+
{
|
|
11083
|
+
key: "asset-name",
|
|
11084
|
+
value: asset.name,
|
|
11085
|
+
...type === "asset.deleted" ? {} : { url: `https://calmlens.com/go/asset/${asset.id}` }
|
|
11086
|
+
},
|
|
11087
|
+
{
|
|
11088
|
+
key: "asset-type",
|
|
11089
|
+
value: asset.type
|
|
11090
|
+
},
|
|
11091
|
+
...batchId ? [{
|
|
11092
|
+
key: "batch-id",
|
|
11093
|
+
value: batchId
|
|
11094
|
+
}] : []
|
|
11095
|
+
]
|
|
10103
11096
|
});
|
|
10104
11097
|
}
|
|
10105
11098
|
/**
|
|
@@ -10114,7 +11107,15 @@ var MockCalmLensApi = class {
|
|
|
10114
11107
|
name: asset.name,
|
|
10115
11108
|
uploadPresetId,
|
|
10116
11109
|
createdAt: asset.createdAt,
|
|
10117
|
-
|
|
11110
|
+
upload: {
|
|
11111
|
+
status: asset.upload.status,
|
|
11112
|
+
partsReceived: asset.upload.partsReceived
|
|
11113
|
+
},
|
|
11114
|
+
classification: {
|
|
11115
|
+
status: asset.classification.status,
|
|
11116
|
+
failureReason: asset.classification.failureReason,
|
|
11117
|
+
...preset.showDecisions !== false && { moderation: { status: asset.classification.moderation.status } }
|
|
11118
|
+
}
|
|
10118
11119
|
});
|
|
10119
11120
|
const [assetId, action] = rest;
|
|
10120
11121
|
if (assetId !== void 0) {
|
|
@@ -10128,19 +11129,32 @@ var MockCalmLensApi = class {
|
|
|
10128
11129
|
const fields = this.uploadFields(request);
|
|
10129
11130
|
const token = request.headers.get("authorization");
|
|
10130
11131
|
if (preset.requireToken && !token) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_TOKEN_REQUIRED);
|
|
11132
|
+
const tokenExternalId = token ? require_CalmLensServerClient.decodeUploadToken(token.replace(/^Bearer /, ""))?.claims.x : void 0;
|
|
11133
|
+
if (fields.externalId && fields.externalId !== tokenExternalId) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field: "externalId" } });
|
|
11134
|
+
for (const field of [
|
|
11135
|
+
"metadata",
|
|
11136
|
+
"tags",
|
|
11137
|
+
"authorId",
|
|
11138
|
+
"context",
|
|
11139
|
+
"processingOptions"
|
|
11140
|
+
]) if (fields[field] !== void 0 && fields[field] !== null) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field } });
|
|
10131
11141
|
if (preset.allowedContentTypes && !require_UploadController.isFileAccepted({
|
|
10132
11142
|
name: fields.name,
|
|
10133
11143
|
type: fields.contentType ?? ""
|
|
10134
|
-
}, preset.allowedContentTypes.join(","))) throw fail(require_ModerationContextLimits.API_ERROR_CODES.
|
|
11144
|
+
}, preset.allowedContentTypes.join(","))) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, { details: { source: "preset" } });
|
|
10135
11145
|
const size = fields.part?.totalSizeInBytes ?? fields.bytes?.byteLength;
|
|
10136
|
-
if (preset.maxFileSizeInBytes !== void 0 && size !== void 0 && size > preset.maxFileSizeInBytes) throw fail(require_ModerationContextLimits.API_ERROR_CODES.
|
|
11146
|
+
if (preset.maxFileSizeInBytes !== void 0 && size !== void 0 && size > preset.maxFileSizeInBytes) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_TOO_LARGE, { details: {
|
|
11147
|
+
limitBytes: preset.maxFileSizeInBytes,
|
|
11148
|
+
source: "preset"
|
|
11149
|
+
} });
|
|
10137
11150
|
const asset = await this.storeAsset({
|
|
10138
11151
|
...fields,
|
|
11152
|
+
externalId: tokenExternalId,
|
|
10139
11153
|
uploadPresetId,
|
|
10140
11154
|
visibility: preset.visibility ?? "public",
|
|
10141
11155
|
folderId: preset.folderId ?? void 0,
|
|
10142
11156
|
processingOptions: { keepContentAfterProcessing: preset.keepContentAfterProcessing ?? true }
|
|
10143
|
-
}, request.query.get("
|
|
11157
|
+
}, request.query.get("wait") === "false");
|
|
10144
11158
|
session.uploads.add(asset.id);
|
|
10145
11159
|
return toUploaded(asset);
|
|
10146
11160
|
}
|
|
@@ -10153,22 +11167,33 @@ var MockCalmLensApi = class {
|
|
|
10153
11167
|
const pageSize = this.integer(query, "pageSize", 50);
|
|
10154
11168
|
if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
|
|
10155
11169
|
if (pageSize > MAX_PAGE_SIZE) throw invalidField("validation/too-big", "pageSize");
|
|
11170
|
+
const typesValue = query.get("types");
|
|
11171
|
+
const types = typesValue === null ? [] : typesValue.split(",");
|
|
11172
|
+
if (typesValue !== null && (types.length === 0 || types.some((type) => !EVENT_TYPE_PATTERN.test(type)))) throw invalidField("validation/invalid-value", "types");
|
|
11173
|
+
const assetId = query.get("assetId");
|
|
11174
|
+
if (assetId !== null && !isId(assetId, "asset")) throw invalidField("validation/invalid-format", "assetId");
|
|
11175
|
+
const filter = btoa(JSON.stringify([[...new Set(types)].sort(), assetId]));
|
|
11176
|
+
const matches = (event) => (!types.length || types.includes(event.type)) && (assetId === null || event.assetId === assetId);
|
|
10156
11177
|
const cursor = query.get("cursor");
|
|
10157
11178
|
if (!cursor) return {
|
|
10158
11179
|
items: [],
|
|
10159
|
-
nextCursor: `mock_${this.eventFeed.length}`,
|
|
11180
|
+
nextCursor: `mock_${this.eventFeed.length}~${filter}`,
|
|
10160
11181
|
hasMore: false,
|
|
10161
11182
|
excludedTypes: []
|
|
10162
11183
|
};
|
|
10163
|
-
const match = /^mock_(\d+)$/.exec(cursor);
|
|
10164
|
-
const position = match ? Number(match[1]) : NaN;
|
|
11184
|
+
const match = /^mock_(\d+)~(.*)$/.exec(cursor);
|
|
11185
|
+
const position = match && match[2] === filter ? Number(match[1]) : NaN;
|
|
10165
11186
|
if (!Number.isSafeInteger(position) || position > this.eventFeed.length) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR);
|
|
10166
|
-
const items =
|
|
10167
|
-
|
|
11187
|
+
const items = [];
|
|
11188
|
+
let next = position;
|
|
11189
|
+
while (next < this.eventFeed.length && items.length < pageSize) {
|
|
11190
|
+
const event = this.eventFeed[next++];
|
|
11191
|
+
if (matches(event)) items.push(event);
|
|
11192
|
+
}
|
|
10168
11193
|
return {
|
|
10169
11194
|
items,
|
|
10170
|
-
nextCursor: `mock_${next}`,
|
|
10171
|
-
hasMore:
|
|
11195
|
+
nextCursor: `mock_${next}~${filter}`,
|
|
11196
|
+
hasMore: this.eventFeed.slice(next).some(matches),
|
|
10172
11197
|
excludedTypes: []
|
|
10173
11198
|
};
|
|
10174
11199
|
}
|
|
@@ -10180,12 +11205,12 @@ var MockCalmLensApi = class {
|
|
|
10180
11205
|
const all = await this.databaseStorage.listFolders?.(this.projectId) ?? [];
|
|
10181
11206
|
const parentId = query.get("parentId");
|
|
10182
11207
|
const search = query.get("search")?.trim() || null;
|
|
10183
|
-
const
|
|
11208
|
+
const sort = this.sort(query, ["name", "createdAt"], 1);
|
|
10184
11209
|
const matching = all.filter((folder) => (folder.parentId ?? null) === parentId && (!search || folder.name.toLowerCase().includes(search.toLowerCase())));
|
|
10185
11210
|
const page = createPage(matching, {
|
|
10186
11211
|
cursor: query.get("cursor") ?? void 0,
|
|
10187
11212
|
pageSize: this.integer(query, "pageSize", 50),
|
|
10188
|
-
|
|
11213
|
+
sort
|
|
10189
11214
|
}, {
|
|
10190
11215
|
scope: JSON.stringify([
|
|
10191
11216
|
this.projectId,
|
|
@@ -10193,7 +11218,7 @@ var MockCalmLensApi = class {
|
|
|
10193
11218
|
search
|
|
10194
11219
|
]),
|
|
10195
11220
|
fail: this.pageFailure,
|
|
10196
|
-
|
|
11221
|
+
defaultSort: [{
|
|
10197
11222
|
field: "name",
|
|
10198
11223
|
direction: "asc"
|
|
10199
11224
|
}]
|
|
@@ -10209,21 +11234,9 @@ var MockCalmLensApi = class {
|
|
|
10209
11234
|
items: folders,
|
|
10210
11235
|
ancestors: all.filter((folder) => ids.has(folder.id) && !folders.some((item) => item.id === folder.id)),
|
|
10211
11236
|
nextCursor: page.nextCursor,
|
|
10212
|
-
|
|
10213
|
-
hasMore: page.hasMore,
|
|
10214
|
-
ordering: page.ordering
|
|
11237
|
+
hasMore: page.hasMore
|
|
10215
11238
|
};
|
|
10216
11239
|
}
|
|
10217
|
-
/** The folder list's `ordering`: at most one rule, by `name` or `createdAt`. */
|
|
10218
|
-
folderOrdering(query) {
|
|
10219
|
-
const ordering = this.ordering(query);
|
|
10220
|
-
if (ordering.length > 1) throw invalidField("validation/too-big", "ordering");
|
|
10221
|
-
for (const [index, rule] of ordering.entries()) {
|
|
10222
|
-
if (rule.field !== "name" && rule.field !== "createdAt") throw invalidField("validation/invalid-value", `ordering.${index}.field`);
|
|
10223
|
-
if (rule.direction !== "asc" && rule.direction !== "desc") throw invalidField("validation/invalid-value", `ordering.${index}.direction`);
|
|
10224
|
-
}
|
|
10225
|
-
return ordering;
|
|
10226
|
-
}
|
|
10227
11240
|
async createFolder(body) {
|
|
10228
11241
|
const name = body.name;
|
|
10229
11242
|
if (typeof name !== "string" || !name) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Folder name is required" });
|
|
@@ -10294,7 +11307,140 @@ var MockCalmLensApi = class {
|
|
|
10294
11307
|
async assertUniqueFolderName(name, parentId, excludeFolderId) {
|
|
10295
11308
|
if ((await this.databaseStorage.listFolders?.(this.projectId) ?? []).find((folder) => folder.id !== excludeFolderId && (folder.parentId ?? null) === parentId && folder.name === name)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.DUPLICATE_FOLDER_NAME, { message: `A folder named "${name}" already exists in this location.` });
|
|
10296
11309
|
}
|
|
10297
|
-
/**
|
|
11310
|
+
/** A page of the project's upload presets, oldest first unless `sort` says otherwise. */
|
|
11311
|
+
listUploadPresets(query) {
|
|
11312
|
+
return createPage([...this.configuredPresets.values()], this.pageQuery(query), {
|
|
11313
|
+
scope: `upload-presets:${this.projectId}`,
|
|
11314
|
+
fail: this.pageFailure,
|
|
11315
|
+
defaultSort: [{
|
|
11316
|
+
field: "createdAt",
|
|
11317
|
+
direction: "asc"
|
|
11318
|
+
}]
|
|
11319
|
+
});
|
|
11320
|
+
}
|
|
11321
|
+
/** Like the API: every preset's revision and settings are checked before any is saved. */
|
|
11322
|
+
ensureUploadPresets(body) {
|
|
11323
|
+
const definitions = Array.isArray(body.uploadPresets) ? body.uploadPresets : [];
|
|
11324
|
+
if (definitions.length === 0) throw invalidField("validation/too-small", "uploadPresets");
|
|
11325
|
+
return { uploadPresets: definitions.map((definition, index) => {
|
|
11326
|
+
if (typeof definition.key !== "string" || !definition.key) throw invalidField("validation/invalid-type", `uploadPresets.${index}.key`);
|
|
11327
|
+
if (typeof definition.name !== "string" || !definition.name) throw invalidField("validation/invalid-type", `uploadPresets.${index}.name`);
|
|
11328
|
+
const existing = this.configuredPresets.get(definition.key);
|
|
11329
|
+
if (definition.revision !== void 0 && definition.revision !== (existing?.revision ?? 0)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_REVISION_CONFLICT, { details: {
|
|
11330
|
+
key: definition.key,
|
|
11331
|
+
revision: existing?.revision ?? 0
|
|
11332
|
+
} });
|
|
11333
|
+
const list = (value) => Array.isArray(value) && value.length ? [...new Set(value)] : null;
|
|
11334
|
+
const values = {
|
|
11335
|
+
key: definition.key,
|
|
11336
|
+
name: definition.name,
|
|
11337
|
+
access: definition.access ?? "token",
|
|
11338
|
+
enabled: definition.enabled ?? true,
|
|
11339
|
+
allowedContentTypes: list(definition.allowedContentTypes),
|
|
11340
|
+
maxSizeInBytes: definition.maxSizeInBytes ?? null,
|
|
11341
|
+
folderId: definition.folderId ?? null,
|
|
11342
|
+
policyId: definition.policyId ?? null,
|
|
11343
|
+
visibility: definition.visibility ?? "private",
|
|
11344
|
+
processingOptions: definition.processingOptions ?? null,
|
|
11345
|
+
revealDecision: definition.revealDecision ?? false,
|
|
11346
|
+
dailyUploadLimit: definition.dailyUploadLimit ?? null,
|
|
11347
|
+
allowedOrigins: list(definition.allowedOrigins)
|
|
11348
|
+
};
|
|
11349
|
+
if (values.access === "anyone" && !values.dailyUploadLimit) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_DAILY_LIMIT_REQUIRED);
|
|
11350
|
+
return {
|
|
11351
|
+
existing,
|
|
11352
|
+
values
|
|
11353
|
+
};
|
|
11354
|
+
}).map(({ existing, values }) => {
|
|
11355
|
+
if (existing) {
|
|
11356
|
+
if (Object.entries(values).every(([key, value]) => require_CalmLensServerClient.stringifyJsonCanonical(value) === require_CalmLensServerClient.stringifyJsonCanonical(existing[key] ?? null))) return existing;
|
|
11357
|
+
}
|
|
11358
|
+
const now = this.now();
|
|
11359
|
+
const preset = {
|
|
11360
|
+
id: existing?.id ?? this.createId("preset"),
|
|
11361
|
+
projectId: this.projectId,
|
|
11362
|
+
createdByUserId: null,
|
|
11363
|
+
...values,
|
|
11364
|
+
revision: (existing?.revision ?? 0) + 1,
|
|
11365
|
+
createdAt: existing?.createdAt ?? now,
|
|
11366
|
+
updatedAt: now
|
|
11367
|
+
};
|
|
11368
|
+
this.configuredPresets.set(preset.key, preset);
|
|
11369
|
+
return preset;
|
|
11370
|
+
}) };
|
|
11371
|
+
}
|
|
11372
|
+
deleteUploadPreset(uploadPresetId) {
|
|
11373
|
+
const preset = [...this.configuredPresets.values()].find(({ id }) => id === uploadPresetId);
|
|
11374
|
+
if (!preset) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_NOT_FOUND);
|
|
11375
|
+
this.configuredPresets.delete(preset.key);
|
|
11376
|
+
return {};
|
|
11377
|
+
}
|
|
11378
|
+
toProjectSettings() {
|
|
11379
|
+
return {
|
|
11380
|
+
projectId: this.projectId,
|
|
11381
|
+
revision: this.settingsRevision,
|
|
11382
|
+
settings: {
|
|
11383
|
+
optOutJurisdictions: [],
|
|
11384
|
+
blockUnmoderatedAssets: true,
|
|
11385
|
+
storeSensitiveMetadata: false,
|
|
11386
|
+
streamingEnabled: false,
|
|
11387
|
+
aiMediaSearchEnabled: false,
|
|
11388
|
+
remoteUrlRule: null,
|
|
11389
|
+
websiteSubmissionsPerMinute: null,
|
|
11390
|
+
...this.projectSettingsValues,
|
|
11391
|
+
humanReview: {
|
|
11392
|
+
allowedSamplePercent: 0,
|
|
11393
|
+
restrictedSamplePercent: 0,
|
|
11394
|
+
uncertaintyMarginPercent: 0,
|
|
11395
|
+
reviewMissingEvidence: false,
|
|
11396
|
+
...this.projectSettingsValues.humanReview
|
|
11397
|
+
}
|
|
11398
|
+
}
|
|
11399
|
+
};
|
|
11400
|
+
}
|
|
11401
|
+
checkSettingsRevision(revision) {
|
|
11402
|
+
if (revision !== void 0 && revision !== null && Number(revision) !== this.settingsRevision) throw fail(require_ModerationContextLimits.API_ERROR_CODES.PROJECT_SETTINGS_REVISION_CONFLICT);
|
|
11403
|
+
}
|
|
11404
|
+
/** Replaces the settings: those left out return to their defaults. */
|
|
11405
|
+
updateProjectSettings(body) {
|
|
11406
|
+
this.checkSettingsRevision(body.revision);
|
|
11407
|
+
const settings = body.settings;
|
|
11408
|
+
if (!settings || typeof settings !== "object" || Array.isArray(settings)) throw invalidField("validation/invalid-type", "settings");
|
|
11409
|
+
const before = require_CalmLensServerClient.stringifyJsonCanonical(this.toProjectSettings().settings);
|
|
11410
|
+
const previous = this.projectSettingsValues;
|
|
11411
|
+
this.projectSettingsValues = { ...settings };
|
|
11412
|
+
if (require_CalmLensServerClient.stringifyJsonCanonical(this.toProjectSettings().settings) === before) this.projectSettingsValues = previous;
|
|
11413
|
+
else this.settingsRevision += 1;
|
|
11414
|
+
return this.toProjectSettings();
|
|
11415
|
+
}
|
|
11416
|
+
toMetadataFields() {
|
|
11417
|
+
return {
|
|
11418
|
+
projectId: this.projectId,
|
|
11419
|
+
revision: this.settingsRevision,
|
|
11420
|
+
fields: this.metadataFieldList
|
|
11421
|
+
};
|
|
11422
|
+
}
|
|
11423
|
+
/** Creates or replaces fields by ID, keeping the others in order. */
|
|
11424
|
+
ensureMetadataFields(body) {
|
|
11425
|
+
this.checkSettingsRevision(body.revision);
|
|
11426
|
+
const fields = Array.isArray(body.fields) ? body.fields : [];
|
|
11427
|
+
if (fields.length === 0) throw invalidField("validation/too-small", "fields");
|
|
11428
|
+
const byId = new Map(fields.map((field) => [field.id, field]));
|
|
11429
|
+
const merged = [...this.metadataFieldList.map((field) => byId.get(field.id) ?? field), ...fields.filter((field) => !this.metadataFieldList.some(({ id }) => id === field.id))];
|
|
11430
|
+
if (require_CalmLensServerClient.stringifyJsonCanonical(merged) !== require_CalmLensServerClient.stringifyJsonCanonical(this.metadataFieldList)) {
|
|
11431
|
+
this.metadataFieldList = merged;
|
|
11432
|
+
this.settingsRevision += 1;
|
|
11433
|
+
}
|
|
11434
|
+
return this.toMetadataFields();
|
|
11435
|
+
}
|
|
11436
|
+
deleteMetadataField(fieldId, query) {
|
|
11437
|
+
if (!this.metadataFieldList.some(({ id }) => id === fieldId)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.METADATA_FIELD_NOT_FOUND, { details: { fieldId } });
|
|
11438
|
+
this.checkSettingsRevision(query.get("revision") ?? void 0);
|
|
11439
|
+
this.metadataFieldList = this.metadataFieldList.filter(({ id }) => id !== fieldId);
|
|
11440
|
+
this.settingsRevision += 1;
|
|
11441
|
+
return this.toMetadataFields();
|
|
11442
|
+
}
|
|
11443
|
+
/** Saves each lens in order, like the API: new ones, or a changed definition. */
|
|
10298
11444
|
ensureLenses(body) {
|
|
10299
11445
|
const lenses = Array.isArray(body.lenses) ? body.lenses : [];
|
|
10300
11446
|
if (lenses.length === 0) throw invalidField("validation/too-small", "lenses");
|
|
@@ -10302,61 +11448,124 @@ var MockCalmLensApi = class {
|
|
|
10302
11448
|
}
|
|
10303
11449
|
ensureLens(options) {
|
|
10304
11450
|
const existing = this.lenses.get(options.identifier);
|
|
10305
|
-
if (!existing)
|
|
10306
|
-
|
|
10307
|
-
|
|
10308
|
-
|
|
10309
|
-
|
|
10310
|
-
|
|
10311
|
-
|
|
10312
|
-
|
|
10313
|
-
|
|
10314
|
-
|
|
10315
|
-
|
|
10316
|
-
|
|
10317
|
-
|
|
10318
|
-
|
|
10319
|
-
|
|
10320
|
-
|
|
10321
|
-
|
|
10322
|
-
|
|
10323
|
-
|
|
10324
|
-
|
|
10325
|
-
|
|
10326
|
-
|
|
10327
|
-
|
|
10328
|
-
|
|
10329
|
-
|
|
10330
|
-
|
|
10331
|
-
|
|
11451
|
+
if (!existing) return this.saveNewLens(options);
|
|
11452
|
+
if (existing.name === options.name && (existing.description ?? null) === (options.description ?? null) && existing.type === options.type && existing.active === options.active && require_CalmLensServerClient.stringifyJsonCanonical(existing.transform ?? null) === require_CalmLensServerClient.stringifyJsonCanonical(options.transform ?? null)) return existing;
|
|
11453
|
+
const lens = {
|
|
11454
|
+
...existing,
|
|
11455
|
+
...options,
|
|
11456
|
+
updatedAt: this.now()
|
|
11457
|
+
};
|
|
11458
|
+
this.lenses.set(lens.identifier, lens);
|
|
11459
|
+
return lens;
|
|
11460
|
+
}
|
|
11461
|
+
saveNewLens(options) {
|
|
11462
|
+
const now = this.now();
|
|
11463
|
+
const lens = {
|
|
11464
|
+
id: this.createId("lens"),
|
|
11465
|
+
projectId: this.projectId,
|
|
11466
|
+
...options,
|
|
11467
|
+
createdAt: now,
|
|
11468
|
+
updatedAt: now
|
|
11469
|
+
};
|
|
11470
|
+
this.lenses.set(lens.identifier, lens);
|
|
11471
|
+
return lens;
|
|
11472
|
+
}
|
|
11473
|
+
/** A page of the project's lenses, newest first unless `sort` says otherwise. */
|
|
11474
|
+
listLenses(query) {
|
|
11475
|
+
return createPage([...this.lenses.values()], this.pageQuery(query), {
|
|
11476
|
+
scope: `lenses:${this.projectId}`,
|
|
11477
|
+
fail: this.pageFailure
|
|
11478
|
+
});
|
|
11479
|
+
}
|
|
11480
|
+
createLens(body) {
|
|
11481
|
+
const definition = body;
|
|
11482
|
+
if (typeof definition.identifier !== "string" || !definition.identifier) throw invalidField("validation/invalid-type", "identifier");
|
|
11483
|
+
if (this.lenses.has(definition.identifier)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.LENS_IDENTIFIER_TAKEN, { details: { identifier: definition.identifier } });
|
|
11484
|
+
return this.saveNewLens(definition);
|
|
11485
|
+
}
|
|
11486
|
+
findLens(lensId) {
|
|
11487
|
+
const lens = [...this.lenses.values()].find((candidate) => candidate.id === lensId);
|
|
11488
|
+
if (!lens) throw fail(require_ModerationContextLimits.API_ERROR_CODES.LENS_NOT_FOUND);
|
|
11489
|
+
return lens;
|
|
11490
|
+
}
|
|
11491
|
+
updateLens(lensId, body) {
|
|
11492
|
+
const lens = this.findLens(lensId);
|
|
11493
|
+
const { identifier: _identifier, ...changes } = body;
|
|
11494
|
+
return this.ensureLens({
|
|
11495
|
+
...lens,
|
|
11496
|
+
...changes
|
|
11497
|
+
});
|
|
11498
|
+
}
|
|
11499
|
+
deleteLens(lensId) {
|
|
11500
|
+
this.lenses.delete(this.findLens(lensId).identifier);
|
|
11501
|
+
return {};
|
|
10332
11502
|
}
|
|
10333
11503
|
/**
|
|
10334
|
-
* Serves
|
|
11504
|
+
* Serves an asset's resources like the CDN (`/assets/:projectId/:asset/:resource`): `200` with
|
|
10335
11505
|
* `Content-Type`, `Content-Length`, `Cache-Control`, `Cache-Tag`, the CDN's protection headers
|
|
10336
|
-
* and, for images, `ETag` and `Expires`; or a JSON error body with `404
|
|
10337
|
-
* `
|
|
11506
|
+
* and, for still images, `ETag` and `Expires`; or a JSON error body with `400`, `403` or `404`.
|
|
11507
|
+
* `original` is the upload; `rendered` the image, PDF, video or audio file `content.rendered`
|
|
11508
|
+
* describes; `preview` the still `content.preview` describes; and `placeholder` its ThumbHash as a
|
|
11509
|
+
* PNG. The mock converts nothing: an upload stands in for its rendered file, an image for its own
|
|
11510
|
+
* preview, and the placeholder PNG for a screenshot, page, poster or waveform.
|
|
10338
11511
|
*/
|
|
10339
11512
|
async serveCdn(request) {
|
|
10340
11513
|
const { url, segments, query } = request;
|
|
10341
|
-
const [root, projectId,
|
|
11514
|
+
const [root, projectId, , resource] = segments;
|
|
11515
|
+
const assetSegment = request.rawSegments[2] ?? "";
|
|
11516
|
+
const selectorPath = request.rawSegments.slice(4);
|
|
10342
11517
|
const notFound = () => this.jsonResponse(404, {
|
|
10343
11518
|
code: "asset/not-found",
|
|
10344
11519
|
message: "Asset not found"
|
|
10345
11520
|
}, url);
|
|
11521
|
+
const noRenderedVersion = () => this.jsonResponse(404, {
|
|
11522
|
+
code: "asset/no-rendered-version",
|
|
11523
|
+
message: "This asset has no such resource"
|
|
11524
|
+
}, url);
|
|
10346
11525
|
const invalidTransform = () => this.jsonResponse(400, {
|
|
10347
|
-
code: "
|
|
11526
|
+
code: "transform/invalid",
|
|
10348
11527
|
message: "Invalid transform selector"
|
|
10349
11528
|
}, url);
|
|
11529
|
+
const isHls = resource === "hls";
|
|
10350
11530
|
let selector;
|
|
10351
11531
|
try {
|
|
10352
|
-
selector = require_ModerationContextLimits.parseTransformSelector(
|
|
11532
|
+
selector = require_ModerationContextLimits.parseTransformSelector(isHls ? "" : selectorPath.join("/"));
|
|
10353
11533
|
} catch {
|
|
10354
11534
|
return invalidTransform();
|
|
10355
11535
|
}
|
|
10356
|
-
|
|
10357
|
-
if (
|
|
10358
|
-
|
|
11536
|
+
const hasSelector = Boolean(selector.lens || selector.options);
|
|
11537
|
+
if ((resource === "original" || resource === "embed" || resource === "info") && hasSelector) return invalidTransform();
|
|
11538
|
+
if (root !== "assets" || projectId !== this.projectId || !assetSegment) return notFound();
|
|
11539
|
+
const assets = await this.databaseStorage.listAssets(this.projectId);
|
|
11540
|
+
let grant;
|
|
11541
|
+
let asset;
|
|
11542
|
+
if (assetSegment.startsWith("sig_")) {
|
|
11543
|
+
grant = decodeMockGrant(assetSegment);
|
|
11544
|
+
if (!grant) return this.jsonResponse(403, {
|
|
11545
|
+
code: "signed-url/invalid",
|
|
11546
|
+
message: "The signed asset URL's grant is invalid"
|
|
11547
|
+
}, url);
|
|
11548
|
+
if (grant.expiresAt <= this.now()) return this.jsonResponse(403, {
|
|
11549
|
+
code: "signed-url/expired",
|
|
11550
|
+
message: "The signed URL has expired"
|
|
11551
|
+
}, url);
|
|
11552
|
+
const grantedId = grant.assetId;
|
|
11553
|
+
asset = assets.find((candidate) => candidate.id === grantedId);
|
|
11554
|
+
} else if (assetSegment.startsWith("ext:")) {
|
|
11555
|
+
let externalId;
|
|
11556
|
+
try {
|
|
11557
|
+
externalId = decodeURIComponent(assetSegment.slice(4));
|
|
11558
|
+
} catch {}
|
|
11559
|
+
asset = externalId ? assets.find((candidate) => candidate.externalId === externalId) : void 0;
|
|
11560
|
+
} else {
|
|
11561
|
+
const assetId = decodeSegment(assetSegment);
|
|
11562
|
+
asset = assets.find((candidate) => candidate.id === assetId);
|
|
11563
|
+
}
|
|
10359
11564
|
if (!asset) return notFound();
|
|
11565
|
+
if (resource === "original" && grant && !grant.original) return this.jsonResponse(403, {
|
|
11566
|
+
code: "signed-url/original-not-granted",
|
|
11567
|
+
message: "This signed asset URL doesn't grant the original file"
|
|
11568
|
+
}, url);
|
|
10360
11569
|
const notAvailable = () => this.jsonResponse(403, {
|
|
10361
11570
|
code: "asset/not-available",
|
|
10362
11571
|
message: "Asset is not available"
|
|
@@ -10366,11 +11575,13 @@ var MockCalmLensApi = class {
|
|
|
10366
11575
|
const canDownload = () => permits(grants, "assets:download", asset.folderId ?? null, folders);
|
|
10367
11576
|
const status = asset.classification.moderation.status;
|
|
10368
11577
|
const isHead = request.method === "HEAD";
|
|
11578
|
+
const { rendered, preview } = asset.content;
|
|
11579
|
+
if (resource === "info") return this.serveInfo(request, asset, Boolean(grant) || canDownload());
|
|
11580
|
+
if (asset.content.safetyHold) return notAvailable();
|
|
10369
11581
|
if (resource === "placeholder") {
|
|
10370
|
-
const thumbhash =
|
|
11582
|
+
const thumbhash = preview?.thumbhash;
|
|
10371
11583
|
if (!thumbhash || status === "purged") return notAvailable();
|
|
10372
|
-
|
|
10373
|
-
return this.cdnResponse(isHead, png, url, {
|
|
11584
|
+
return this.cdnResponse(isHead, mockPlaceholderPng(thumbhash), url, {
|
|
10374
11585
|
"Content-Type": "image/png",
|
|
10375
11586
|
"Cache-Control": "public, max-age=3600",
|
|
10376
11587
|
"Cache-Tag": `asset-${asset.id}`,
|
|
@@ -10378,40 +11589,59 @@ var MockCalmLensApi = class {
|
|
|
10378
11589
|
});
|
|
10379
11590
|
}
|
|
10380
11591
|
const storedContent = await this.imageStorage.getContent(asset.id);
|
|
10381
|
-
if (asset.upload.status === "uploading" || status === "purged" || status === "blocked" || asset.classification.status === "failed" || asset.content.status === "removed" || !storedContent) return notAvailable();
|
|
11592
|
+
if (asset.upload.status === "uploading" || status === "purged" || status === "blocked" || asset.classification.status === "failed" || asset.content.status === "removed" || resource === "original" && !storedContent) return notAvailable();
|
|
10382
11593
|
let claims = {};
|
|
10383
11594
|
try {
|
|
10384
11595
|
claims = JSON.parse(query.get("viewerClaims") ?? request.headers.get("X-CalmLens-Viewer-Claims") ?? "{}");
|
|
10385
11596
|
} catch {
|
|
10386
|
-
return this.jsonResponse(400, { code: "viewer/invalid
|
|
11597
|
+
return this.jsonResponse(400, { code: "viewer-claims/invalid" }, url);
|
|
10387
11598
|
}
|
|
10388
11599
|
if (status === "age-restricted" && claims.ageConfirmed !== true) return this.jsonResponse(403, { code: "viewer/age-confirmation-required" }, url);
|
|
10389
11600
|
const isPrivate = asset.visibility !== "public";
|
|
10390
|
-
if (isPrivate && !canDownload()) return this.jsonResponse(403, {
|
|
10391
|
-
code: "
|
|
11601
|
+
if (isPrivate && !grant && !canDownload()) return this.jsonResponse(403, {
|
|
11602
|
+
code: "auth/permission-denied",
|
|
10392
11603
|
message: "This API key needs assets:download permission for this asset’s folder."
|
|
10393
11604
|
}, url);
|
|
11605
|
+
if (resource === "embed") return this.cdnResponse(isHead, new TextEncoder().encode(MOCK_EMBED_HTML), url, {
|
|
11606
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
11607
|
+
"Cache-Control": Object.keys(claims).length ? "private, no-store" : `${isPrivate ? "private" : "public"}, max-age=3600`,
|
|
11608
|
+
"Cache-Tag": `asset-${asset.id}`,
|
|
11609
|
+
"X-Content-Type-Options": "nosniff"
|
|
11610
|
+
});
|
|
11611
|
+
if (resource === "rendered" && !rendered || resource === "preview" && !preview) return noRenderedVersion();
|
|
11612
|
+
if (isHls && !asset.content.hls) return noRenderedVersion();
|
|
11613
|
+
const stillImage = resource === "preview" || resource === "rendered" && rendered?.kind === "image";
|
|
11614
|
+
if (!stillImage && hasSelector) return invalidTransform();
|
|
10394
11615
|
if (selector.options) {
|
|
10395
11616
|
const { unknownKeys, invalidKeys } = require_ModerationContextLimits.checkTransformOptions(selector.options);
|
|
10396
11617
|
if (unknownKeys.length || invalidKeys.length) return this.jsonResponse(400, {
|
|
10397
|
-
code: "
|
|
11618
|
+
code: "transform-options/invalid",
|
|
10398
11619
|
message: `Invalid transform options: ${[...unknownKeys, ...invalidKeys].join(", ")}`
|
|
10399
11620
|
}, url);
|
|
10400
11621
|
}
|
|
10401
|
-
const
|
|
10402
|
-
|
|
10403
|
-
let
|
|
10404
|
-
|
|
10405
|
-
|
|
10406
|
-
|
|
11622
|
+
const servesUpload = resource === "original" || resource === "rendered" && rendered?.kind !== "image" || asset.type === "image";
|
|
11623
|
+
let bytes;
|
|
11624
|
+
let contentType;
|
|
11625
|
+
if (servesUpload) {
|
|
11626
|
+
if (!storedContent) return notAvailable();
|
|
11627
|
+
const parts = [...storedContent.parts.entries()].sort(([left], [right]) => left - right).map(([, value]) => value);
|
|
11628
|
+
bytes = new Uint8Array(parts.reduce((sum, value) => sum + value.byteLength, 0));
|
|
11629
|
+
let offset = 0;
|
|
11630
|
+
for (const part of parts) {
|
|
11631
|
+
bytes.set(part, offset);
|
|
11632
|
+
offset += part.byteLength;
|
|
11633
|
+
}
|
|
11634
|
+
contentType = resource === "rendered" && rendered ? rendered.format : storedContent.type ?? "application/octet-stream";
|
|
11635
|
+
} else {
|
|
11636
|
+
bytes = mockPlaceholderPng(preview?.thumbhash ?? MOCK_THUMBHASH);
|
|
11637
|
+
contentType = "image/png";
|
|
10407
11638
|
}
|
|
10408
|
-
const
|
|
10409
|
-
const isImage = asset.type === "image";
|
|
11639
|
+
const immutable = stillImage || resource === "original" && asset.type === "image";
|
|
10410
11640
|
return this.cdnResponse(isHead, bytes, url, {
|
|
10411
11641
|
"Content-Type": contentType,
|
|
10412
|
-
"Cache-Control": Object.keys(claims).length ? "private, no-store" : `${isPrivate ? "private" : "public"}, ${
|
|
11642
|
+
"Cache-Control": Object.keys(claims).length ? "private, no-store" : `${isPrivate ? "private" : "public"}, ${immutable ? "max-age=31536000, immutable" : "max-age=3600"}`,
|
|
10413
11643
|
"Cache-Tag": `asset-${asset.id}`,
|
|
10414
|
-
...
|
|
11644
|
+
...immutable ? {
|
|
10415
11645
|
ETag: `"${asset.id}"`,
|
|
10416
11646
|
Expires: new Date(this.now() + 31536e6).toUTCString()
|
|
10417
11647
|
} : {},
|
|
@@ -10420,6 +11650,51 @@ var MockCalmLensApi = class {
|
|
|
10420
11650
|
...isActiveContentType(contentType) ? { "Content-Disposition": "attachment" } : {}
|
|
10421
11651
|
});
|
|
10422
11652
|
}
|
|
11653
|
+
/**
|
|
11654
|
+
* The display info at `/info`, like the CDN's (AssetInfo.ts): the allowlisted fields and whether
|
|
11655
|
+
* the viewer the claims describe can see the content, decided as the other resources decide it.
|
|
11656
|
+
* A private asset's needs a grant or an API key with `assets:download`.
|
|
11657
|
+
*/
|
|
11658
|
+
serveInfo(request, asset, authorised) {
|
|
11659
|
+
const { url, query } = request;
|
|
11660
|
+
const isPrivate = asset.visibility !== "public";
|
|
11661
|
+
if (isPrivate && !authorised) return this.jsonResponse(404, {
|
|
11662
|
+
code: "asset/not-found",
|
|
11663
|
+
message: "Asset not found"
|
|
11664
|
+
}, url);
|
|
11665
|
+
let claims = {};
|
|
11666
|
+
try {
|
|
11667
|
+
claims = JSON.parse(query.get("viewerClaims") ?? request.headers.get("X-CalmLens-Viewer-Claims") ?? "{}");
|
|
11668
|
+
} catch {
|
|
11669
|
+
return this.jsonResponse(400, { code: "viewer-claims/invalid" }, url);
|
|
11670
|
+
}
|
|
11671
|
+
const status = asset.classification.moderation.status;
|
|
11672
|
+
const availability = asset.content.safetyHold || asset.upload.status === "uploading" || status === "blocked" || status === "purged" || asset.classification.status === "failed" || asset.content.status === "removed" ? "unavailable" : status === "age-restricted" && claims.ageConfirmed !== true ? "age-restricted" : "available";
|
|
11673
|
+
const { content } = asset;
|
|
11674
|
+
const info = {
|
|
11675
|
+
id: asset.id,
|
|
11676
|
+
projectId: asset.projectId,
|
|
11677
|
+
type: asset.type,
|
|
11678
|
+
externalUrl: asset.externalUrl ?? null,
|
|
11679
|
+
content: {
|
|
11680
|
+
format: content.format,
|
|
11681
|
+
width: content.width,
|
|
11682
|
+
height: content.height,
|
|
11683
|
+
durationSeconds: content.durationSeconds,
|
|
11684
|
+
pageCount: content.pageCount,
|
|
11685
|
+
rendered: content.rendered,
|
|
11686
|
+
preview: content.preview,
|
|
11687
|
+
hls: content.hls
|
|
11688
|
+
},
|
|
11689
|
+
availability
|
|
11690
|
+
};
|
|
11691
|
+
const bytes = new TextEncoder().encode(JSON.stringify(info));
|
|
11692
|
+
return this.cdnResponse(request.method === "HEAD", bytes, url, {
|
|
11693
|
+
"Content-Type": "application/json",
|
|
11694
|
+
"Cache-Control": `${isPrivate ? "private" : "public"}, max-age=60`,
|
|
11695
|
+
"Cache-Tag": `asset-${asset.id}`
|
|
11696
|
+
});
|
|
11697
|
+
}
|
|
10423
11698
|
cdnResponse(isHead, bytes, url, headers) {
|
|
10424
11699
|
return this.response(200, isHead ? null : bytes, url, {
|
|
10425
11700
|
...headers,
|
|
@@ -10521,7 +11796,7 @@ const mockClientOptions = (api, endpoints, session) => {
|
|
|
10521
11796
|
const fetch = api.createFetch(endpoints, session);
|
|
10522
11797
|
const hooks = {
|
|
10523
11798
|
sleep: async (ms, signal) => {
|
|
10524
|
-
await
|
|
11799
|
+
await require_ModerationContextLimits.sleep(0, signal);
|
|
10525
11800
|
api.waitedMs += ms;
|
|
10526
11801
|
},
|
|
10527
11802
|
now: () => api.waitedMs,
|
|
@@ -10547,6 +11822,7 @@ const mockClientOptions = (api, endpoints, session) => {
|
|
|
10547
11822
|
*/
|
|
10548
11823
|
var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLensServerClient {
|
|
10549
11824
|
#api;
|
|
11825
|
+
#fetch;
|
|
10550
11826
|
#projectId;
|
|
10551
11827
|
/**
|
|
10552
11828
|
* Accepts the same options as `CalmLensServerClient` (validated the same way), plus
|
|
@@ -10568,8 +11844,7 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
|
|
|
10568
11844
|
imageStorage: mockOptions.imageStorage ?? new InMemoryMockImageStorage(),
|
|
10569
11845
|
createId: mockOptions.createId ?? newId,
|
|
10570
11846
|
now: mockOptions.now ?? createMonotonicClock(),
|
|
10571
|
-
moderate: mockOptions.moderate ?? defaultModerate
|
|
10572
|
-
signedUrlBaseUrl: mockOptions.signedUrlBaseUrl ?? "mock://calmlens"
|
|
11847
|
+
moderate: mockOptions.moderate ?? defaultModerate
|
|
10573
11848
|
});
|
|
10574
11849
|
let endpoints;
|
|
10575
11850
|
super({
|
|
@@ -10584,6 +11859,7 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
|
|
|
10584
11859
|
cdnBaseUrl
|
|
10585
11860
|
};
|
|
10586
11861
|
this.#api = api;
|
|
11862
|
+
this.#fetch = api.createFetch(() => endpoints);
|
|
10587
11863
|
this.#projectId = options.projectId;
|
|
10588
11864
|
this.databaseStorage = api.databaseStorage;
|
|
10589
11865
|
this.imageStorage = api.imageStorage;
|
|
@@ -10608,6 +11884,14 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
|
|
|
10608
11884
|
callsTo(operation) {
|
|
10609
11885
|
return this.#api.calls.filter(({ operations }) => operations.includes(operation)).map(({ call }) => call);
|
|
10610
11886
|
}
|
|
11887
|
+
/**
|
|
11888
|
+
* Fetches a URL of the mock's CDN as a browser would, without the API key: a signed asset URL
|
|
11889
|
+
* from `cdn.signAssetUrl` (with a resource appended), or a public one from `cdn.getAssetUrl`.
|
|
11890
|
+
* The request is recorded like any other.
|
|
11891
|
+
*/
|
|
11892
|
+
fetchCdn(url, init) {
|
|
11893
|
+
return this.#fetch(url, init);
|
|
11894
|
+
}
|
|
10611
11895
|
/** Forgets the requests recorded so far, so `calls` lists only later ones. */
|
|
10612
11896
|
clearCalls() {
|
|
10613
11897
|
this.#api.calls.length = 0;
|
|
@@ -10640,7 +11924,7 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
|
|
|
10640
11924
|
* Applies a reviewer's decision to a stored asset, as the portal or API would: the moderation
|
|
10641
11925
|
* status changes (`purged` also removes the content, with reason `requested` and an
|
|
10642
11926
|
* `asset.content-removed` event), the review joins `manualReviews`, and an `asset.<decision>`
|
|
10643
|
-
* event
|
|
11927
|
+
* event whose `actor` is a `user` joins the events feed. Rejects with
|
|
10644
11928
|
* `asset/not-found` for an unknown asset. It sends no request.
|
|
10645
11929
|
*/
|
|
10646
11930
|
decide(assetId, decision) {
|
|
@@ -10651,8 +11935,11 @@ var MockCalmLensServerClient = class extends require_CalmLensServerClient.CalmLe
|
|
|
10651
11935
|
* else what `mockOptions.moderate` returns for the `complete` trigger (`allowed` by default).
|
|
10652
11936
|
* The asset gets the decision's report, and `asset.classified` and the automated
|
|
10653
11937
|
* `asset.<status>` (or `asset.failed`) join the events feed. No review is recorded, so the
|
|
10654
|
-
* asset can still be moderated again.
|
|
10655
|
-
* `
|
|
11938
|
+
* asset can still be moderated again. A decided asset whose re-run (`assets.explain` with
|
|
11939
|
+
* `rerun: true`) is still pending gets the decision in place of its old one, unless it is
|
|
11940
|
+
* `pending` or `failed`. Rejects with `asset/not-found` for an unknown asset and
|
|
11941
|
+
* `sdk/invalid-argument` for one that isn't processing or awaiting a pending re-run. It sends
|
|
11942
|
+
* no request.
|
|
10656
11943
|
*/
|
|
10657
11944
|
completeProcessing(assetId, decision) {
|
|
10658
11945
|
return this.#api.completeProcessing(assetId, decision);
|
|
@@ -10713,11 +12000,13 @@ var MockCalmLensAppClient = class extends require_CalmLensAppClient.CalmLensAppC
|
|
|
10713
12000
|
const toWebhookEventPayload = (event) => ({
|
|
10714
12001
|
id: event.id,
|
|
10715
12002
|
projectId: event.projectId,
|
|
12003
|
+
actor: event.actor,
|
|
10716
12004
|
type: event.type,
|
|
10717
12005
|
severity: event.severity,
|
|
10718
12006
|
title: event.title,
|
|
10719
12007
|
description: event.description ?? null,
|
|
10720
12008
|
assetId: event.assetId ?? null,
|
|
12009
|
+
assetSequence: event.assetSequence ?? null,
|
|
10721
12010
|
asset: event.asset ?? null,
|
|
10722
12011
|
facts: event.facts,
|
|
10723
12012
|
createdAt: event.createdAt
|