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