@panneau/protocol 5.0.0-alpha.2 → 5.0.0-alpha.20
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/dist/addresses.d.ts +23 -0
- package/dist/addresses.d.ts.map +1 -0
- package/dist/addresses.js +52 -0
- package/dist/addresses.js.map +1 -0
- package/dist/compound.d.ts +20 -0
- package/dist/compound.d.ts.map +1 -0
- package/dist/compound.js +27 -0
- package/dist/compound.js.map +1 -0
- package/dist/conditions.d.ts +1 -1
- package/dist/conformance/index.d.ts +6 -0
- package/dist/conformance/index.d.ts.map +1 -1
- package/dist/conformance/index.js +787 -11
- package/dist/conformance/index.js.map +1 -1
- package/dist/constants.d.ts +101 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +174 -3
- package/dist/constants.js.map +1 -1
- package/dist/context.d.ts +15 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +34 -0
- package/dist/context.js.map +1 -0
- package/dist/currencies.d.ts +22 -0
- package/dist/currencies.d.ts.map +1 -0
- package/dist/currencies.js +231 -0
- package/dist/currencies.js.map +1 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +17 -7
- package/dist/libraries.d.ts +26 -0
- package/dist/libraries.d.ts.map +1 -0
- package/dist/libraries.js +22 -0
- package/dist/libraries.js.map +1 -0
- package/dist/links.d.ts +38 -0
- package/dist/links.d.ts.map +1 -0
- package/dist/links.js +65 -0
- package/dist/links.js.map +1 -0
- package/dist/lint.d.ts +4 -3
- package/dist/lint.d.ts.map +1 -1
- package/dist/lint.js +114 -2
- package/dist/lint.js.map +1 -1
- package/dist/mock/auth.d.ts +71 -0
- package/dist/mock/auth.d.ts.map +1 -0
- package/dist/mock/auth.js +346 -0
- package/dist/mock/auth.js.map +1 -0
- package/dist/mock/example.d.ts +3 -2
- package/dist/mock/example.d.ts.map +1 -1
- package/dist/mock/example.js +223 -142
- package/dist/mock/example.js.map +1 -1
- package/dist/mock/index.d.ts +77 -7
- package/dist/mock/index.d.ts.map +1 -1
- package/dist/mock/index.js +577 -34
- package/dist/mock/index.js.map +1 -1
- package/dist/openapi.d.ts.map +1 -1
- package/dist/openapi.js +394 -145
- package/dist/openapi.js.map +1 -1
- package/dist/problem.d.ts +1 -1
- package/dist/query.d.ts +18 -0
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +34 -8
- package/dist/query.js.map +1 -1
- package/dist/rules.d.ts +16 -4
- package/dist/rules.d.ts.map +1 -1
- package/dist/rules.js +230 -13
- package/dist/rules.js.map +1 -1
- package/dist/runtime/index.d.ts +19 -10
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +12 -3
- package/dist/schemas/action.d.ts +117 -10
- package/dist/schemas/action.d.ts.map +1 -1
- package/dist/schemas/action.js +21 -3
- package/dist/schemas/action.js.map +1 -1
- package/dist/schemas/api.d.ts +326 -42
- package/dist/schemas/api.d.ts.map +1 -1
- package/dist/schemas/api.js +192 -34
- package/dist/schemas/api.js.map +1 -1
- package/dist/schemas/boot.d.ts +25 -1
- package/dist/schemas/boot.d.ts.map +1 -1
- package/dist/schemas/boot.js +2 -1
- package/dist/schemas/boot.js.map +1 -1
- package/dist/schemas/common.d.ts +1 -0
- package/dist/schemas/common.d.ts.map +1 -1
- package/dist/schemas/common.js +2 -1
- package/dist/schemas/common.js.map +1 -1
- package/dist/schemas/definition.d.ts +332 -28
- package/dist/schemas/definition.d.ts.map +1 -1
- package/dist/schemas/definition.js +65 -19
- package/dist/schemas/definition.js.map +1 -1
- package/dist/schemas/field.d.ts +356 -2
- package/dist/schemas/field.d.ts.map +1 -1
- package/dist/schemas/field.js +159 -20
- package/dist/schemas/field.js.map +1 -1
- package/dist/schemas/index.d.ts +1384 -72
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +58 -9
- package/dist/schemas/index.js.map +1 -1
- package/dist/schemas/jsonRules.d.ts +83 -0
- package/dist/schemas/jsonRules.d.ts.map +1 -0
- package/dist/schemas/jsonRules.js +46 -0
- package/dist/schemas/jsonRules.js.map +1 -0
- package/dist/schemas/layout.d.ts +1 -1
- package/dist/schemas/list.d.ts +23 -2
- package/dist/schemas/list.d.ts.map +1 -1
- package/dist/schemas/list.js +14 -5
- package/dist/schemas/list.js.map +1 -1
- package/dist/schemas/resource.d.ts +247 -15
- package/dist/schemas/resource.d.ts.map +1 -1
- package/dist/schemas/resource.js +6 -1
- package/dist/schemas/resource.js.map +1 -1
- package/dist/schemas/widget.d.ts +109 -0
- package/dist/schemas/widget.d.ts.map +1 -0
- package/dist/schemas/widget.js +74 -0
- package/dist/schemas/widget.js.map +1 -0
- package/dist/search.d.ts +51 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +53 -0
- package/dist/search.js.map +1 -0
- package/dist/themes.d.ts +1 -1
- package/dist/transforms.d.ts +17 -0
- package/dist/transforms.d.ts.map +1 -0
- package/dist/transforms.js +34 -0
- package/dist/transforms.js.map +1 -0
- package/dist/validate.d.ts +5 -3
- package/dist/validate.d.ts.map +1 -1
- package/dist/validate.js +36 -2
- package/dist/validate.js.map +1 -1
- package/dist/values.d.ts +5 -1
- package/dist/values.d.ts.map +1 -1
- package/dist/values.js +16 -2
- package/dist/values.js.map +1 -1
- package/dist/widgets.d.ts +42 -0
- package/dist/widgets.d.ts.map +1 -0
- package/dist/widgets.js +130 -0
- package/dist/widgets.js.map +1 -0
- package/package.json +6 -3
- package/schema/boot.schema.json +666 -18
- package/schema/definition.schema.json +663 -18
- package/schema/openapi.json +5694 -2328
package/dist/mock/index.js
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import { PROBLEM_CONTENT_TYPE } from "../version.js";
|
|
2
|
+
import { CONTEXT_HEADER, CONTEXT_PROBLEM_TYPE, ITEM_ACTION_ABILITIES, isBuiltInItemAction } from "../constants.js";
|
|
2
3
|
import { isRecord } from "../values.js";
|
|
3
4
|
import { checkValues } from "../rules.js";
|
|
5
|
+
import { getMediaLibraries } from "../libraries.js";
|
|
4
6
|
import { fromSearchParams, isFilterRange, matchesFilterRange } from "../query.js";
|
|
7
|
+
import { checkWidgetData, getWidgetResource } from "../widgets.js";
|
|
8
|
+
import { readSearchQuery } from "../search.js";
|
|
9
|
+
import { contextBefore, parseContextHeader } from "../context.js";
|
|
10
|
+
import { createMockAuth } from "./auth.js";
|
|
5
11
|
import { createExampleDefinition } from "./example.js";
|
|
6
12
|
//#region src/mock/index.ts
|
|
7
13
|
var RESERVED_KEYS = /* @__PURE__ */ new Set([
|
|
@@ -9,6 +15,51 @@ var RESERVED_KEYS = /* @__PURE__ */ new Set([
|
|
|
9
15
|
"version",
|
|
10
16
|
"abilities"
|
|
11
17
|
]);
|
|
18
|
+
function escapeHtml(text) {
|
|
19
|
+
return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
|
|
20
|
+
}
|
|
21
|
+
/** A plain page with the values of an item, as a `data:` URL, for iframe previews. */
|
|
22
|
+
function defaultPreviewUrl(item) {
|
|
23
|
+
const rows = Object.entries(item).filter(([key]) => !RESERVED_KEYS.has(key)).map(([key, value]) => `<dt>${escapeHtml(key)}</dt><dd>${escapeHtml(typeof value === "string" ? value : JSON.stringify(value))}</dd>`).join("");
|
|
24
|
+
const html = `<!doctype html><meta charset="utf-8"><title>Preview</title><body style="font-family:system-ui;margin:2rem"><h1>Item ${escapeHtml(item.id)}</h1><dl>${rows}</dl></body>`;
|
|
25
|
+
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
|
|
26
|
+
}
|
|
27
|
+
/** What the mock knows of a URL to embed: a video of YouTube or Vimeo, or a web page. */
|
|
28
|
+
function defaultEmbed(url) {
|
|
29
|
+
if (!URL.canParse(url)) return null;
|
|
30
|
+
const parsed = new URL(url);
|
|
31
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
32
|
+
const host = parsed.hostname.replace(/^www\./, "");
|
|
33
|
+
const youtube = host === "youtu.be" ? parsed.pathname.slice(1) : host.endsWith("youtube.com") ? parsed.searchParams.get("v") : null;
|
|
34
|
+
if (youtube !== null && youtube !== "") return {
|
|
35
|
+
url,
|
|
36
|
+
type: "video",
|
|
37
|
+
provider: "YouTube",
|
|
38
|
+
title: `YouTube video ${youtube}`,
|
|
39
|
+
thumbnailUrl: `https://i.ytimg.com/vi/${youtube}/hqdefault.jpg`,
|
|
40
|
+
html: `<iframe src="https://www.youtube.com/embed/${youtube}" width="560" height="315" allowfullscreen></iframe>`,
|
|
41
|
+
width: 560,
|
|
42
|
+
height: 315
|
|
43
|
+
};
|
|
44
|
+
if (host === "vimeo.com") {
|
|
45
|
+
const id = parsed.pathname.split("/").filter(Boolean)[0] ?? "";
|
|
46
|
+
return {
|
|
47
|
+
url,
|
|
48
|
+
type: "video",
|
|
49
|
+
provider: "Vimeo",
|
|
50
|
+
title: `Vimeo video ${id}`,
|
|
51
|
+
html: `<iframe src="https://player.vimeo.com/video/${id}" width="640" height="360" allowfullscreen></iframe>`,
|
|
52
|
+
width: 640,
|
|
53
|
+
height: 360
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
url,
|
|
58
|
+
type: "link",
|
|
59
|
+
provider: host,
|
|
60
|
+
title: host
|
|
61
|
+
};
|
|
62
|
+
}
|
|
12
63
|
var DEFAULT_MESSAGES = {
|
|
13
64
|
required: () => "This field is required.",
|
|
14
65
|
min: (failure) => `This value must be at least ${String(failure.value)}.`,
|
|
@@ -16,11 +67,17 @@ var DEFAULT_MESSAGES = {
|
|
|
16
67
|
pattern: () => "This value has an invalid format.",
|
|
17
68
|
email: () => "This value must be an email address.",
|
|
18
69
|
url: () => "This value must be a URL.",
|
|
70
|
+
json: () => "This value must be valid JSON: an object or an array.",
|
|
19
71
|
in: () => "This value is not one of the choices.",
|
|
20
72
|
accept: () => "This file type is not accepted.",
|
|
21
73
|
maxSize: () => "This file is too large.",
|
|
22
74
|
before: () => "This date is too late.",
|
|
23
|
-
after: () => "This date is too early."
|
|
75
|
+
after: () => "This date is too early.",
|
|
76
|
+
providers: (failure) => `This embed must come from ${Array.isArray(failure.value) ? failure.value.join(" or ") : "another provider"}.`,
|
|
77
|
+
crop: (failure) => {
|
|
78
|
+
const ratios = isRecord(failure.value) ? failure.value.ratios : void 0;
|
|
79
|
+
return Array.isArray(ratios) && ratios.length > 0 ? `Crop this image to ${ratios.join(" or ")}.` : "Crop this image.";
|
|
80
|
+
}
|
|
24
81
|
};
|
|
25
82
|
function message(failure) {
|
|
26
83
|
return failure.message ?? DEFAULT_MESSAGES[failure.rule]?.(failure) ?? "This value is invalid.";
|
|
@@ -57,12 +114,20 @@ function searchableText(value) {
|
|
|
57
114
|
if (isRecord(value)) return Object.values(value).map(searchableText).join(" ");
|
|
58
115
|
return "";
|
|
59
116
|
}
|
|
117
|
+
/** What a value sorts by: the start of a `daterange`, the amount of `money`, or its text. */
|
|
118
|
+
function sortValue(value) {
|
|
119
|
+
if (!isRecord(value)) return value;
|
|
120
|
+
if ("start" in value && "end" in value) return value.start ?? value.end;
|
|
121
|
+
if ("currency" in value && typeof value.amount === "number") return value.amount;
|
|
122
|
+
return searchableText(value);
|
|
123
|
+
}
|
|
60
124
|
function compare(a, b) {
|
|
61
|
-
const left =
|
|
62
|
-
const right =
|
|
125
|
+
const left = sortValue(a);
|
|
126
|
+
const right = sortValue(b);
|
|
63
127
|
if (left === right) return 0;
|
|
64
128
|
if (left === void 0 || left === null) return 1;
|
|
65
129
|
if (right === void 0 || right === null) return -1;
|
|
130
|
+
if (typeof left === "number" && typeof right === "number") return left - right;
|
|
66
131
|
return String(left).localeCompare(String(right), void 0, { numeric: true });
|
|
67
132
|
}
|
|
68
133
|
function applyQuery(items, query) {
|
|
@@ -74,7 +139,7 @@ function applyQuery(items, query) {
|
|
|
74
139
|
}
|
|
75
140
|
const accepted = (Array.isArray(expected) ? expected : [expected]).map(String);
|
|
76
141
|
result = result.filter((item) => {
|
|
77
|
-
const value = item[key];
|
|
142
|
+
const value = key in item ? item[key] : isRecord(item.media) ? item.media[key] : void 0;
|
|
78
143
|
return (Array.isArray(value) ? value : [value]).some((candidate) => accepted.includes(String(candidate)));
|
|
79
144
|
});
|
|
80
145
|
});
|
|
@@ -94,38 +159,110 @@ function applyQuery(items, query) {
|
|
|
94
159
|
});
|
|
95
160
|
return result;
|
|
96
161
|
}
|
|
162
|
+
/** The type of a media, from its MIME type. */
|
|
163
|
+
function mediaType(mime) {
|
|
164
|
+
const family = (mime ?? "").split("/")[0] ?? "";
|
|
165
|
+
if (family === "image" || family === "video" || family === "audio") return family;
|
|
166
|
+
return mime === "application/pdf" || family === "text" ? "document" : "other";
|
|
167
|
+
}
|
|
168
|
+
/** What the mock computes about a stored file: no renditions, ready at once. */
|
|
169
|
+
function mediaOf(file) {
|
|
170
|
+
const type = mediaType(file.mime);
|
|
171
|
+
return {
|
|
172
|
+
type,
|
|
173
|
+
mime: file.mime ?? null,
|
|
174
|
+
size: file.size ?? null,
|
|
175
|
+
url: file.url ?? null,
|
|
176
|
+
thumbnailUrl: type === "image" ? file.url ?? null : null,
|
|
177
|
+
status: "ready"
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* A media item with its own transform (its `transform` field) in its `media`, where references
|
|
182
|
+
* give it to clients (decision 0031).
|
|
183
|
+
*/
|
|
184
|
+
function withOwnTransform(resource, item) {
|
|
185
|
+
if (resource.kind !== "media" || !isRecord(item.media)) return item;
|
|
186
|
+
const { transform: _previous, ...media } = item.media;
|
|
187
|
+
return {
|
|
188
|
+
...item,
|
|
189
|
+
media: isRecord(item.transform) ? {
|
|
190
|
+
...media,
|
|
191
|
+
transform: item.transform
|
|
192
|
+
} : media
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Whether an item allows an action, as clients read its abilities (decision 0040): a built-in item
|
|
197
|
+
* action needs its ability (`delete`, `duplicate`…), and another action its id.
|
|
198
|
+
*/
|
|
199
|
+
function allows(item, actionId) {
|
|
200
|
+
const ability = isBuiltInItemAction(actionId) ? ITEM_ACTION_ABILITIES[actionId] : actionId;
|
|
201
|
+
return item.abilities[ability] === true && item.abilities[actionId] !== false;
|
|
202
|
+
}
|
|
203
|
+
/** The names of the fields of a resource whose ability is `false` (decision 0046). */
|
|
204
|
+
function fieldsWithout(resource, ability) {
|
|
205
|
+
return new Set(resource.fields.filter((field) => field.abilities?.[ability] === false).map((field) => field.name));
|
|
206
|
+
}
|
|
207
|
+
/** A body without the values of the fields the user can't see or update, which are ignored. */
|
|
208
|
+
function writableValues(resource, body) {
|
|
209
|
+
const ignored = /* @__PURE__ */ new Set([...fieldsWithout(resource, "view"), ...fieldsWithout(resource, "update")]);
|
|
210
|
+
return Object.fromEntries(Object.entries(body).filter(([key]) => !ignored.has(key)));
|
|
211
|
+
}
|
|
97
212
|
/**
|
|
98
213
|
* An in-memory backend that implements the protocol's resource routes: definition, list, show,
|
|
99
|
-
* create, update (with `If-Match`), delete and the built-in `delete` action.
|
|
100
|
-
*
|
|
101
|
-
*
|
|
214
|
+
* create, update (with `If-Match`), delete, duplicate and the built-in `delete` action. A resource
|
|
215
|
+
* that declares its `delete` `undoable` has a trash: the result of `delete` says how to undo it,
|
|
216
|
+
* and the built-in `restore` puts the items back (decision 0063). Its items
|
|
217
|
+
* allow every built-in item action (`view`, `update`, `duplicate`, `delete`), unless an item of
|
|
218
|
+
* `items` gives its own `abilities`. It reads abilities as clients do (decision 0046): a resource
|
|
219
|
+
* without `viewAny` answers `403` on its list, one without `create` on creates, an item without
|
|
220
|
+
* `view`, `update` or `delete` on those requests; items leave out the values of fields with
|
|
221
|
+
* `view: false`, and writes ignore those of fields with `update: false`. Values are checked with
|
|
222
|
+
* the portable rules. Used to test the conformance kit, and to develop frontends without a real
|
|
223
|
+
* backend.
|
|
102
224
|
*/
|
|
103
|
-
function createMockBackend(
|
|
225
|
+
function createMockBackend(options) {
|
|
226
|
+
const { definition, items = {} } = options;
|
|
227
|
+
const auth = options.auth !== void 0 ? createMockAuth(options.auth, definition.auth) : null;
|
|
104
228
|
const store = /* @__PURE__ */ new Map();
|
|
229
|
+
const trash = /* @__PURE__ */ new Map();
|
|
105
230
|
let nextId = 1;
|
|
106
231
|
const abilitiesFor = (resource) => Object.fromEntries([
|
|
232
|
+
["view", true],
|
|
107
233
|
["update", true],
|
|
234
|
+
["duplicate", true],
|
|
108
235
|
["delete", true],
|
|
109
236
|
...(resource.actions ?? []).map((action) => [action.id, true])
|
|
110
237
|
]);
|
|
111
238
|
const makeItem = (resource, values) => {
|
|
112
239
|
const id = typeof values.id === "string" || typeof values.id === "number" ? String(values.id) : String(nextId++);
|
|
240
|
+
const rest = Object.fromEntries(Object.entries(values).filter(([key]) => !RESERVED_KEYS.has(key)));
|
|
241
|
+
const own = isRecord(values.abilities) ? values.abilities : {};
|
|
113
242
|
return {
|
|
114
|
-
...
|
|
243
|
+
...rest,
|
|
115
244
|
id,
|
|
116
245
|
version: "1",
|
|
117
|
-
abilities:
|
|
246
|
+
abilities: {
|
|
247
|
+
...abilitiesFor(resource),
|
|
248
|
+
...own
|
|
249
|
+
}
|
|
118
250
|
};
|
|
119
251
|
};
|
|
252
|
+
const present = (resource, item) => {
|
|
253
|
+
const hidden = fieldsWithout(resource, "view");
|
|
254
|
+
return hidden.size === 0 ? item : Object.fromEntries(Object.entries(item).filter(([key]) => !hidden.has(key)));
|
|
255
|
+
};
|
|
120
256
|
definition.resources.forEach((resource) => {
|
|
121
257
|
store.set(resource.id, (items[resource.id] ?? []).map((values) => makeItem(resource, values)));
|
|
122
258
|
});
|
|
123
259
|
const basePath = new URL(definition.api.baseUrl, "http://panneau.test").pathname.replace(/\/$/, "");
|
|
124
|
-
const validationProblem = (resource, values, mode) => {
|
|
260
|
+
const validationProblem = (resource, values, mode, item) => {
|
|
125
261
|
const failures = checkValues(resource.fields, values, {
|
|
126
262
|
mode,
|
|
127
263
|
partial: mode === "update",
|
|
128
|
-
locales: definition.locales
|
|
264
|
+
locales: definition.locales,
|
|
265
|
+
...item !== void 0 ? { item } : {}
|
|
129
266
|
});
|
|
130
267
|
const paths = Object.keys(failures);
|
|
131
268
|
if (paths.length === 0) return null;
|
|
@@ -147,7 +284,219 @@ function createMockBackend({ definition, items = {} }) {
|
|
|
147
284
|
if (q !== void 0) query.q = q;
|
|
148
285
|
return applyQuery(list, query).filter((item) => !except.includes(item.id));
|
|
149
286
|
};
|
|
287
|
+
const uploads = /* @__PURE__ */ new Map();
|
|
288
|
+
let nextUpload = 1;
|
|
289
|
+
const handleUploads = async (segments, method, readBody) => {
|
|
290
|
+
if (definition.uploads?.mode !== "presigned") return problem(404, "Not found.");
|
|
291
|
+
if (method !== "POST") return problem(405, "Method not allowed.");
|
|
292
|
+
if (segments.length === 2 && segments[1] === "sign") {
|
|
293
|
+
const body = await readBody();
|
|
294
|
+
if (body.uploadId === void 0 && (body.method === "POST" || body.method === "PUT")) {
|
|
295
|
+
const id = `upl_${nextUpload++}`;
|
|
296
|
+
const upload = {
|
|
297
|
+
id,
|
|
298
|
+
key: `uploads/${id}`
|
|
299
|
+
};
|
|
300
|
+
uploads.set(id, upload);
|
|
301
|
+
return json(200, {
|
|
302
|
+
url: `https://storage.test/${upload.key}?signature=mock`,
|
|
303
|
+
key: upload.key,
|
|
304
|
+
upload: id
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
const upload = [...uploads.values()].find((candidate) => candidate.key === body.key);
|
|
308
|
+
if (upload === void 0) return problem(404, "Upload not found.");
|
|
309
|
+
return json(200, { url: `https://storage.test/${upload.key}?signature=mock` });
|
|
310
|
+
}
|
|
311
|
+
if (segments.length === 3 && segments[2] === "complete" && segments[1] !== void 0) {
|
|
312
|
+
const upload = uploads.get(segments[1]);
|
|
313
|
+
if (upload === void 0) return problem(404, "Upload not found.");
|
|
314
|
+
const { name } = await readBody();
|
|
315
|
+
if (typeof name === "string") upload.name = name;
|
|
316
|
+
return json(200, { data: upload });
|
|
317
|
+
}
|
|
318
|
+
return problem(404, "Not found.");
|
|
319
|
+
};
|
|
320
|
+
const resolveFiles = (resource, values) => {
|
|
321
|
+
const missing = [];
|
|
322
|
+
const resolved = { ...values };
|
|
323
|
+
const toFile = (value, path) => {
|
|
324
|
+
if (!isRecord(value) || typeof value.upload !== "string") return value;
|
|
325
|
+
const upload = uploads.get(value.upload);
|
|
326
|
+
if (upload === void 0) {
|
|
327
|
+
missing.push(path);
|
|
328
|
+
return value;
|
|
329
|
+
}
|
|
330
|
+
return {
|
|
331
|
+
name: upload.name ?? (typeof value.name === "string" ? value.name : upload.id),
|
|
332
|
+
url: `https://storage.test/${upload.key ?? upload.id}`,
|
|
333
|
+
mime: upload.mime ?? (typeof value.mime === "string" ? value.mime : null),
|
|
334
|
+
size: upload.size ?? (typeof value.size === "number" ? value.size : null)
|
|
335
|
+
};
|
|
336
|
+
};
|
|
337
|
+
resource.fields.filter((field) => field.type === "file" && field.name in values).forEach((field) => {
|
|
338
|
+
const value = values[field.name];
|
|
339
|
+
resolved[field.name] = Array.isArray(value) ? value.map((entry, index) => toFile(entry, `${field.name}.${String(index)}`)) : toFile(value, field.name);
|
|
340
|
+
});
|
|
341
|
+
return {
|
|
342
|
+
values: resolved,
|
|
343
|
+
missing
|
|
344
|
+
};
|
|
345
|
+
};
|
|
346
|
+
const missingMedia = (paths) => problem(422, "The given data was invalid.", {
|
|
347
|
+
type: "urn:panneau:problem:validation",
|
|
348
|
+
errors: Object.fromEntries(Object.entries(paths).map(([path, message]) => [path, [message]]))
|
|
349
|
+
});
|
|
350
|
+
const missingUploads = (paths) => problem(422, "The given data was invalid.", {
|
|
351
|
+
type: "urn:panneau:problem:validation",
|
|
352
|
+
errors: Object.fromEntries(paths.map((path) => [path, ["This upload does not exist."]]))
|
|
353
|
+
});
|
|
354
|
+
const resolveMedia = (resource, values) => {
|
|
355
|
+
const missing = {};
|
|
356
|
+
const resolved = { ...values };
|
|
357
|
+
resource.fields.filter((field) => (field.type === "media" || field.type === "image") && field.name in values).forEach((field) => {
|
|
358
|
+
const allowed = getMediaLibraries(definition, field);
|
|
359
|
+
const toReference = (value, path) => {
|
|
360
|
+
const id = isRecord(value) ? value.id : value;
|
|
361
|
+
if (typeof id !== "string" && typeof id !== "number") return value;
|
|
362
|
+
const named = isRecord(value) && typeof value.resource === "string" ? value.resource : void 0;
|
|
363
|
+
if (named === void 0 && allowed.length > 1) {
|
|
364
|
+
missing[path] = "This field allows several libraries: name the library.";
|
|
365
|
+
return value;
|
|
366
|
+
}
|
|
367
|
+
const libraryId = named ?? allowed[0];
|
|
368
|
+
const library = definition.resources.find((candidate) => candidate.id === libraryId && allowed.includes(candidate.id));
|
|
369
|
+
const media = (store.get(library?.id ?? "") ?? []).find((candidate) => candidate.id === String(id));
|
|
370
|
+
if (media === void 0 || library === void 0) {
|
|
371
|
+
missing[path] = "This media does not exist.";
|
|
372
|
+
return value;
|
|
373
|
+
}
|
|
374
|
+
const title = media[library.itemTitle ?? "name"];
|
|
375
|
+
return {
|
|
376
|
+
id: media.id,
|
|
377
|
+
...allowed.length > 1 ? { resource: library.id } : {},
|
|
378
|
+
...typeof title === "string" ? { label: title } : {},
|
|
379
|
+
...isRecord(media.media) ? { media: media.media } : {},
|
|
380
|
+
...isRecord(value) && isRecord(value.transform) ? { transform: value.transform } : {}
|
|
381
|
+
};
|
|
382
|
+
};
|
|
383
|
+
const value = values[field.name];
|
|
384
|
+
resolved[field.name] = Array.isArray(value) ? value.map((entry, index) => toReference(entry, `${field.name}.${String(index)}`)) : toReference(value, field.name);
|
|
385
|
+
});
|
|
386
|
+
return {
|
|
387
|
+
values: resolved,
|
|
388
|
+
missing
|
|
389
|
+
};
|
|
390
|
+
};
|
|
391
|
+
const resolveValues = (resource, body) => {
|
|
392
|
+
const sent = { ...body };
|
|
393
|
+
if (resource.kind === "media") delete sent.media;
|
|
394
|
+
const files = resolveFiles(resource, sent);
|
|
395
|
+
if (files.missing.length > 0) return {
|
|
396
|
+
values: body,
|
|
397
|
+
problem: missingUploads(files.missing)
|
|
398
|
+
};
|
|
399
|
+
const media = resolveMedia(resource, files.values);
|
|
400
|
+
if (Object.keys(media.missing).length > 0) return {
|
|
401
|
+
values: body,
|
|
402
|
+
problem: missingMedia(media.missing)
|
|
403
|
+
};
|
|
404
|
+
const values = media.values;
|
|
405
|
+
if (resource.kind === "media" && isRecord(values.file)) values.media = mediaOf(values.file);
|
|
406
|
+
return {
|
|
407
|
+
values,
|
|
408
|
+
problem: null
|
|
409
|
+
};
|
|
410
|
+
};
|
|
411
|
+
const search = (params, inScope) => {
|
|
412
|
+
const read = readSearchQuery(params, definition);
|
|
413
|
+
if (read.errors !== void 0) return problem(422, "The given data was invalid.", {
|
|
414
|
+
type: "urn:panneau:problem:validation",
|
|
415
|
+
errors: read.errors
|
|
416
|
+
});
|
|
417
|
+
const { q, limit, resources } = read.query;
|
|
418
|
+
let left = 20;
|
|
419
|
+
return json(200, { data: resources.flatMap((id) => {
|
|
420
|
+
if (left === 0) return [];
|
|
421
|
+
const searched = definition.resources.find((candidate) => candidate.id === id);
|
|
422
|
+
if (searched === void 0 || searched.abilities?.viewAny === false) return [];
|
|
423
|
+
const found = applyQuery(inScope(id, store.get(id) ?? []), { q });
|
|
424
|
+
const items = found.slice(0, Math.min(limit, left)).map((item) => present(searched, item));
|
|
425
|
+
left -= items.length;
|
|
426
|
+
return items.length > 0 ? [{
|
|
427
|
+
resource: id,
|
|
428
|
+
items,
|
|
429
|
+
total: found.length
|
|
430
|
+
}] : [];
|
|
431
|
+
}) });
|
|
432
|
+
};
|
|
433
|
+
const params = definition.context?.params ?? [];
|
|
434
|
+
const names = params.map(({ name }) => name);
|
|
435
|
+
const choicesOf = (name, values) => {
|
|
436
|
+
return params.find((candidate) => candidate.name === name)?.options ?? options.context?.options?.(name, contextBefore(values, names, name)) ?? [];
|
|
437
|
+
};
|
|
438
|
+
const refused = (name) => problem(403, "This value of the context can’t be used.", {
|
|
439
|
+
type: CONTEXT_PROBLEM_TYPE,
|
|
440
|
+
param: name
|
|
441
|
+
});
|
|
442
|
+
/**
|
|
443
|
+
* The values of the header that the definition declares, each one checked against its
|
|
444
|
+
* choices, in order: a value that isn't one is a `403` problem with its `param`. A `fixed`
|
|
445
|
+
* param has the value of the definition, as a backend would take it from the request: another
|
|
446
|
+
* value in the header is refused.
|
|
447
|
+
*/
|
|
448
|
+
const readContext = (header) => {
|
|
449
|
+
const sent = parseContextHeader(header);
|
|
450
|
+
const values = {};
|
|
451
|
+
for (const param of params) {
|
|
452
|
+
const { name } = param;
|
|
453
|
+
const value = sent[name];
|
|
454
|
+
if (param.fixed === true && typeof param.value === "string") {
|
|
455
|
+
if (value !== void 0 && value !== param.value) return refused(name);
|
|
456
|
+
values[name] = param.value;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (value === void 0) continue;
|
|
460
|
+
if (!choicesOf(name, values).some((choice) => choice.value === value)) return refused(name);
|
|
461
|
+
values[name] = value;
|
|
462
|
+
}
|
|
463
|
+
return values;
|
|
464
|
+
};
|
|
465
|
+
/** The definition for the values of the context: the `value` and `valueLabel` of each param. */
|
|
466
|
+
const answerWidget = async (id, values, inScope) => {
|
|
467
|
+
const widget = definitionFor(values).dashboard?.widgets.find((candidate) => candidate.id === id);
|
|
468
|
+
const data = options.widgets?.[id];
|
|
469
|
+
if (widget === void 0 || getWidgetResource(widget) !== null || data === void 0) return problem(404, "Widget not found.");
|
|
470
|
+
const answer = typeof data === "function" ? await data({
|
|
471
|
+
context: values,
|
|
472
|
+
items: (resource) => inScope(resource, store.get(resource) ?? [])
|
|
473
|
+
}) : data;
|
|
474
|
+
if (answer instanceof Response) return answer;
|
|
475
|
+
const wrong = checkWidgetData(widget.type, answer);
|
|
476
|
+
return wrong.length === 0 ? json(200, answer) : problem(500, `The data of the widget doesn't have the shape of \`${widget.type}\`.`, { detail: `Wrong keys: ${wrong.map((key) => key === "" ? "(the data)" : key).join(", ")}.` });
|
|
477
|
+
};
|
|
478
|
+
const definitionFor = (values) => definition.context === void 0 ? definition : {
|
|
479
|
+
...definition,
|
|
480
|
+
context: {
|
|
481
|
+
...definition.context,
|
|
482
|
+
params: params.map((param) => {
|
|
483
|
+
if (param.fixed === true) return param;
|
|
484
|
+
const value = values[param.name] ?? null;
|
|
485
|
+
const label = value !== null ? choicesOf(param.name, values).find((choice) => choice.value === value)?.label : void 0;
|
|
486
|
+
return {
|
|
487
|
+
...param,
|
|
488
|
+
value,
|
|
489
|
+
valueLabel: label ?? null
|
|
490
|
+
};
|
|
491
|
+
})
|
|
492
|
+
}
|
|
493
|
+
};
|
|
150
494
|
const handle = async (request) => {
|
|
495
|
+
const response = await answer(request);
|
|
496
|
+
if (definition.context !== void 0) response.headers.set("Vary", CONTEXT_HEADER);
|
|
497
|
+
return response;
|
|
498
|
+
};
|
|
499
|
+
const answer = async (request) => {
|
|
151
500
|
const url = new URL(request.url, "http://panneau.test");
|
|
152
501
|
if (!url.pathname.startsWith(basePath)) return problem(404, "Not found.");
|
|
153
502
|
const segments = url.pathname.slice(basePath.length).split("/").filter((segment) => segment !== "").map(decodeURIComponent);
|
|
@@ -156,23 +505,75 @@ function createMockBackend({ definition, items = {} }) {
|
|
|
156
505
|
const body = await request.json().catch(() => null);
|
|
157
506
|
return isRecord(body) ? body : {};
|
|
158
507
|
};
|
|
159
|
-
if (
|
|
508
|
+
if (auth !== null) {
|
|
509
|
+
if (segments[0] === "auth") return auth.answer(segments.slice(1), method, readBody, url);
|
|
510
|
+
const account = segments[0] === "account" ? auth.account(segments.slice(1), method, readBody) : null;
|
|
511
|
+
if (account !== null) return account;
|
|
512
|
+
const refused = auth.refuse();
|
|
513
|
+
if (refused !== null) return refused;
|
|
514
|
+
}
|
|
515
|
+
const context = readContext(request.headers.get(CONTEXT_HEADER));
|
|
516
|
+
if (context instanceof Response) return context;
|
|
517
|
+
const inScope = (resource, list) => {
|
|
518
|
+
const scope = options.context?.scope;
|
|
519
|
+
return scope !== void 0 ? list.filter((item) => scope(resource, item, context)) : list;
|
|
520
|
+
};
|
|
521
|
+
if (segments.length === 1 && segments[0] === "definition" && method === "GET") {
|
|
522
|
+
const built = definitionFor(context);
|
|
523
|
+
return json(200, auth !== null ? {
|
|
524
|
+
...built,
|
|
525
|
+
user: auth.user()
|
|
526
|
+
} : built);
|
|
527
|
+
}
|
|
528
|
+
if (segments.length === 3 && segments[0] === "context" && segments[2] === "options" && method === "GET") {
|
|
529
|
+
const name = segments[1] ?? "";
|
|
530
|
+
if (!names.includes(name)) return problem(404, "The context has no such param.");
|
|
531
|
+
const q = (url.searchParams.get("q") ?? "").trim().toLocaleLowerCase();
|
|
532
|
+
return json(200, { data: choicesOf(name, context).filter((choice) => choice.label.toLocaleLowerCase().includes(q)).slice(0, 20) });
|
|
533
|
+
}
|
|
534
|
+
if (segments.length === 1 && segments[0] === "embeds" && method === "GET") {
|
|
535
|
+
const url = new URL(request.url, "http://panneau.test").searchParams.get("url") ?? "";
|
|
536
|
+
const embed = url === "" ? null : (options.embed ?? defaultEmbed)(url);
|
|
537
|
+
return embed !== null ? json(200, { data: embed }) : problem(422, "The given data was invalid.", {
|
|
538
|
+
type: "urn:panneau:problem:validation",
|
|
539
|
+
errors: { url: ["This URL can’t be embedded."] }
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
if (segments.length === 3 && segments[0] === "dashboard" && segments[1] === "widgets" && method === "GET") return answerWidget(segments[2] ?? "", context, inScope);
|
|
543
|
+
if (segments.length === 1 && segments[0] === "search" && method === "GET") return search(url.searchParams, inScope);
|
|
544
|
+
if (segments[0] === "uploads") return handleUploads(segments, method, readBody);
|
|
160
545
|
if (segments[0] !== "resources" || segments[1] === void 0) return problem(404, "Not found.");
|
|
161
546
|
const resource = definition.resources.find((candidate) => candidate.id === segments[1]);
|
|
162
547
|
const list = resource !== void 0 ? store.get(resource.id) : void 0;
|
|
163
548
|
if (resource === void 0 || list === void 0) return problem(404, "Resource not found.");
|
|
549
|
+
const scoped = inScope(resource.id, list);
|
|
164
550
|
if (segments.length === 2) {
|
|
165
551
|
if (method === "GET") {
|
|
552
|
+
if (resource.abilities?.viewAny === false) return problem(403, "This resource can’t be listed.");
|
|
166
553
|
const query = fromSearchParams(url.searchParams);
|
|
167
554
|
const perPage = query.perPage ?? resource.list?.perPage ?? 20;
|
|
168
555
|
const page = query.page ?? 1;
|
|
169
556
|
const sort = query.sort ?? resource.list?.defaultSort?.split(",");
|
|
170
|
-
const matching = applyQuery(
|
|
557
|
+
const matching = applyQuery(scoped, {
|
|
171
558
|
...query,
|
|
172
559
|
...sort !== void 0 ? { sort } : {}
|
|
173
560
|
});
|
|
561
|
+
if (resource.list?.pagination === "cursor") {
|
|
562
|
+
const cursor = query.cursor ?? "o0";
|
|
563
|
+
if (!/^o\d+$/.test(cursor)) return problem(422, "The cursor is invalid.", { errors: { cursor: ["The cursor is invalid."] } });
|
|
564
|
+
const offset = Number(cursor.slice(1));
|
|
565
|
+
const end = offset + perPage;
|
|
566
|
+
return json(200, {
|
|
567
|
+
data: matching.slice(offset, end).map((item) => present(resource, item)),
|
|
568
|
+
meta: {
|
|
569
|
+
perPage,
|
|
570
|
+
nextCursor: end < matching.length ? `o${String(end)}` : null,
|
|
571
|
+
previousCursor: offset - perPage > 0 ? `o${String(offset - perPage)}` : null
|
|
572
|
+
}
|
|
573
|
+
});
|
|
574
|
+
}
|
|
174
575
|
return json(200, {
|
|
175
|
-
data: matching.slice((page - 1) * perPage, page * perPage),
|
|
576
|
+
data: matching.slice((page - 1) * perPage, page * perPage).map((item) => present(resource, item)),
|
|
176
577
|
meta: {
|
|
177
578
|
page,
|
|
178
579
|
perPage,
|
|
@@ -182,59 +583,201 @@ function createMockBackend({ definition, items = {} }) {
|
|
|
182
583
|
});
|
|
183
584
|
}
|
|
184
585
|
if (method === "POST") {
|
|
185
|
-
|
|
186
|
-
const
|
|
586
|
+
if (resource.abilities?.create === false) return problem(403, "Items of this resource can’t be created.");
|
|
587
|
+
const body = writableValues(resource, await readBody());
|
|
588
|
+
const invalid = validationProblem(resource, body, "create");
|
|
187
589
|
if (invalid !== null) return invalid;
|
|
188
|
-
const
|
|
590
|
+
const { values, problem: unresolved } = resolveValues(resource, body);
|
|
591
|
+
if (unresolved !== null) return unresolved;
|
|
592
|
+
const item = withOwnTransform(resource, makeItem(resource, {
|
|
189
593
|
...values,
|
|
190
594
|
id: void 0
|
|
191
|
-
});
|
|
595
|
+
}));
|
|
192
596
|
list.push(item);
|
|
193
|
-
return json(201, { data: item }, etag(item));
|
|
597
|
+
return json(201, { data: present(resource, item) }, etag(item));
|
|
194
598
|
}
|
|
195
599
|
return problem(405, "Method not allowed.");
|
|
196
600
|
}
|
|
601
|
+
if (segments[2] === "fields" && segments[4] === "check" && segments.length === 5) {
|
|
602
|
+
if (method !== "POST") return problem(405, "Method not allowed.");
|
|
603
|
+
const field = resource.fields.find((candidate) => candidate.name === segments[3] && candidate.check === true);
|
|
604
|
+
if (field === void 0) return problem(404, "Field not found.");
|
|
605
|
+
const body = await readBody();
|
|
606
|
+
if (typeof body.value !== "string") return problem(422, "The given data was invalid.", {
|
|
607
|
+
type: "urn:panneau:problem:validation",
|
|
608
|
+
errors: { value: ["The value is required."] }
|
|
609
|
+
});
|
|
610
|
+
const locale = typeof body.locale === "string" ? body.locale : null;
|
|
611
|
+
const id = typeof body.id === "string" || typeof body.id === "number" ? String(body.id) : null;
|
|
612
|
+
const valueOf = (item) => {
|
|
613
|
+
const value = item[field.name];
|
|
614
|
+
return locale !== null && isRecord(value) ? value[locale] : value;
|
|
615
|
+
};
|
|
616
|
+
const taken = (candidate) => list.some((item) => item.id !== id && valueOf(item) === candidate);
|
|
617
|
+
const available = !taken(body.value);
|
|
618
|
+
let suggestion = null;
|
|
619
|
+
for (let index = 2; !available && suggestion === null; index += 1) {
|
|
620
|
+
const candidate = `${body.value}-${String(index)}`;
|
|
621
|
+
suggestion = taken(candidate) ? null : candidate;
|
|
622
|
+
}
|
|
623
|
+
const prefix = typeof field.settings?.prefix === "string" ? field.settings.prefix : null;
|
|
624
|
+
return json(200, {
|
|
625
|
+
available,
|
|
626
|
+
suggestion,
|
|
627
|
+
prefix,
|
|
628
|
+
url: prefix !== null ? `${prefix}${body.value}` : null
|
|
629
|
+
});
|
|
630
|
+
}
|
|
197
631
|
if (segments[2] === "actions" && segments[3] !== void 0 && segments.length === 4) {
|
|
198
632
|
if (method !== "POST") return problem(405, "Method not allowed.");
|
|
199
|
-
|
|
633
|
+
const actionId = segments[3];
|
|
634
|
+
const action = (resource.actions ?? []).find((candidate) => candidate.id === actionId);
|
|
200
635
|
const body = await readBody();
|
|
201
|
-
|
|
202
|
-
|
|
636
|
+
if (body.dryRun === true) {
|
|
637
|
+
if (action?.dryRun !== true && actionId !== "delete") return problem(400, "This action does not support dry runs.");
|
|
638
|
+
const selected = selectItems(scoped, body.selection);
|
|
639
|
+
const allowed = selected.filter((item) => allows(item, actionId));
|
|
640
|
+
return json(200, {
|
|
641
|
+
summary: {
|
|
642
|
+
succeeded: allowed.length,
|
|
643
|
+
failed: 0,
|
|
644
|
+
skipped: selected.length - allowed.length
|
|
645
|
+
},
|
|
646
|
+
results: selected.filter((item) => !allowed.includes(item)).slice(0, 20).map((item) => ({
|
|
647
|
+
id: item.id,
|
|
648
|
+
status: "skipped",
|
|
649
|
+
reason: "forbidden"
|
|
650
|
+
}))
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
const hasTrash = (resource.actions ?? []).some((candidate) => candidate.id === "delete" && candidate.undoable === true);
|
|
654
|
+
if (actionId === "restore" && hasTrash) {
|
|
655
|
+
const selection = body.selection;
|
|
656
|
+
const ids = selection !== void 0 && "ids" in selection && Array.isArray(selection.ids) ? selection.ids.map(String) : null;
|
|
657
|
+
if (ids === null) return problem(422, "The selection needs ids.", {
|
|
658
|
+
type: "urn:panneau:problem:validation",
|
|
659
|
+
errors: { selection: ["The selection needs ids."] }
|
|
660
|
+
});
|
|
661
|
+
const deleted = trash.get(resource.id) ?? [];
|
|
662
|
+
const restored = deleted.filter((item) => ids.includes(item.id));
|
|
663
|
+
const missing = ids.filter((id) => !restored.some((item) => item.id === id));
|
|
664
|
+
if (ids.length === 1 && missing.length === 1) return problem(404, "Item not found.");
|
|
665
|
+
trash.set(resource.id, deleted.filter((item) => !restored.includes(item)));
|
|
666
|
+
store.set(resource.id, [...list, ...restored]);
|
|
667
|
+
return json(200, {
|
|
668
|
+
summary: {
|
|
669
|
+
succeeded: restored.length,
|
|
670
|
+
failed: 0,
|
|
671
|
+
skipped: missing.length
|
|
672
|
+
},
|
|
673
|
+
...missing.length > 0 ? { results: missing.map((id) => ({
|
|
674
|
+
id,
|
|
675
|
+
status: "skipped",
|
|
676
|
+
reason: "not_found"
|
|
677
|
+
})) } : {},
|
|
678
|
+
refresh: "list"
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
if (actionId !== "delete") return problem(404, "Action not found.");
|
|
682
|
+
const selection = body.selection;
|
|
683
|
+
const selected = selectItems(scoped, selection);
|
|
684
|
+
const allowed = selected.filter((item) => allows(item, "delete"));
|
|
685
|
+
const skipped = selected.filter((item) => !allowed.includes(item));
|
|
686
|
+
const inUse = allowed.filter((item) => options.inUse?.({
|
|
687
|
+
resource: resource.id,
|
|
688
|
+
item
|
|
689
|
+
}) === true);
|
|
690
|
+
const deleted = allowed.filter((item) => !inUse.includes(item));
|
|
691
|
+
if ((selection !== void 0 && "ids" in selection && Array.isArray(selection.ids) ? selection.ids : null)?.length === 1 && skipped.length > 0) return problem(403, "This item can’t be deleted.");
|
|
692
|
+
store.set(resource.id, list.filter((item) => !deleted.includes(item)));
|
|
693
|
+
if (hasTrash) trash.set(resource.id, [...trash.get(resource.id) ?? [], ...deleted]);
|
|
203
694
|
return json(200, {
|
|
204
|
-
message: `${
|
|
695
|
+
message: `${deleted.length} deleted.`,
|
|
696
|
+
...hasTrash && deleted.length > 0 && deleted.length <= 100 ? { undo: {
|
|
697
|
+
action: "restore",
|
|
698
|
+
items: deleted.map((item) => item.id)
|
|
699
|
+
} } : {},
|
|
205
700
|
summary: {
|
|
206
|
-
succeeded:
|
|
701
|
+
succeeded: deleted.length,
|
|
207
702
|
failed: 0,
|
|
208
|
-
skipped:
|
|
703
|
+
skipped: skipped.length + inUse.length
|
|
209
704
|
},
|
|
705
|
+
...skipped.length + inUse.length > 0 ? { results: [...skipped.map((item) => ({
|
|
706
|
+
id: item.id,
|
|
707
|
+
status: "skipped",
|
|
708
|
+
reason: "forbidden"
|
|
709
|
+
})), ...inUse.map((item) => ({
|
|
710
|
+
id: item.id,
|
|
711
|
+
status: "skipped",
|
|
712
|
+
reason: "in_use"
|
|
713
|
+
}))].slice(0, 20) } : {},
|
|
210
714
|
refresh: "list"
|
|
211
715
|
});
|
|
212
716
|
}
|
|
717
|
+
if (segments.length === 4 && segments[3] === "duplicate" && segments[2] !== void 0) {
|
|
718
|
+
const current = scoped.find((item) => item.id === segments[2]);
|
|
719
|
+
if (current === void 0) return problem(404, "Item not found.");
|
|
720
|
+
if (method !== "POST") return problem(405, "Method not allowed.");
|
|
721
|
+
if (!allows(current, "duplicate")) return problem(403, "This item can’t be duplicated.");
|
|
722
|
+
const { id: _id, version: _version, abilities: _abilities, ...values } = current;
|
|
723
|
+
let copyId = String(nextId++);
|
|
724
|
+
while (list.some((item) => item.id === copyId)) copyId = String(nextId++);
|
|
725
|
+
const copy = makeItem(resource, {
|
|
726
|
+
...values,
|
|
727
|
+
id: copyId
|
|
728
|
+
});
|
|
729
|
+
list.push(copy);
|
|
730
|
+
return json(201, { data: present(resource, copy) }, etag(copy));
|
|
731
|
+
}
|
|
732
|
+
if (segments.length === 4 && segments[3] === "preview" && segments[2] !== void 0) {
|
|
733
|
+
const current = scoped.find((item) => item.id === segments[2]);
|
|
734
|
+
if (current === void 0) return problem(404, "Item not found.");
|
|
735
|
+
if (method !== "POST") return problem(405, "Method not allowed.");
|
|
736
|
+
const body = await readBody();
|
|
737
|
+
const item = {
|
|
738
|
+
...current,
|
|
739
|
+
...isRecord(body) ? body : {}
|
|
740
|
+
};
|
|
741
|
+
return json(200, {
|
|
742
|
+
url: options.previewUrl?.({
|
|
743
|
+
resource: resource.id,
|
|
744
|
+
item
|
|
745
|
+
}) ?? defaultPreviewUrl(item),
|
|
746
|
+
expiresAt: new Date(Date.now() + 3e5).toISOString()
|
|
747
|
+
});
|
|
748
|
+
}
|
|
213
749
|
if (segments.length !== 3 || segments[2] === void 0) return problem(404, "Not found.");
|
|
214
750
|
const id = segments[2];
|
|
215
|
-
const index = list.findIndex((item) => item.id === id);
|
|
751
|
+
const index = scoped.some((item) => item.id === id) ? list.findIndex((item) => item.id === id) : -1;
|
|
216
752
|
const current = list[index];
|
|
217
753
|
if (current === void 0) return problem(404, "Item not found.");
|
|
218
|
-
if (method === "GET")
|
|
754
|
+
if (method === "GET") {
|
|
755
|
+
if (current.abilities.view !== true) return problem(403, "This item can’t be viewed.");
|
|
756
|
+
return json(200, { data: present(resource, current) }, etag(current));
|
|
757
|
+
}
|
|
219
758
|
if (method === "PATCH") {
|
|
759
|
+
if (current.abilities.update !== true) return problem(403, "This item can’t be updated.");
|
|
220
760
|
const ifMatch = request.headers.get("If-Match");
|
|
221
761
|
if (ifMatch !== null && current.version !== null && parseEtag(ifMatch) !== current.version) return problem(412, "The item was changed by someone else.", {
|
|
222
762
|
type: "urn:panneau:problem:version-conflict",
|
|
223
|
-
current
|
|
763
|
+
current: present(resource, current)
|
|
224
764
|
});
|
|
225
|
-
const
|
|
226
|
-
const invalid = validationProblem(resource,
|
|
765
|
+
const body = writableValues(resource, await readBody());
|
|
766
|
+
const invalid = validationProblem(resource, body, "update", current);
|
|
227
767
|
if (invalid !== null) return invalid;
|
|
768
|
+
const { values, problem: unresolved } = resolveValues(resource, body);
|
|
769
|
+
if (unresolved !== null) return unresolved;
|
|
228
770
|
const updates = Object.fromEntries(Object.entries(values).filter(([key]) => !RESERVED_KEYS.has(key)));
|
|
229
|
-
const updated = {
|
|
771
|
+
const updated = withOwnTransform(resource, {
|
|
230
772
|
...current,
|
|
231
773
|
...updates,
|
|
232
774
|
version: current.version === null ? null : String(Number(current.version) + 1)
|
|
233
|
-
};
|
|
775
|
+
});
|
|
234
776
|
list[index] = updated;
|
|
235
|
-
return json(200, { data: updated }, etag(updated));
|
|
777
|
+
return json(200, { data: present(resource, updated) }, etag(updated));
|
|
236
778
|
}
|
|
237
779
|
if (method === "DELETE") {
|
|
780
|
+
if (current.abilities.delete !== true) return problem(403, "This item can’t be deleted.");
|
|
238
781
|
list.splice(index, 1);
|
|
239
782
|
return json(204, null);
|
|
240
783
|
}
|