@panneau/protocol 5.0.0-alpha.0 → 5.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +13 -8
  2. package/dist/conditions.d.ts +1 -1
  3. package/dist/conformance/index.d.ts.map +1 -1
  4. package/dist/conformance/index.js +310 -4
  5. package/dist/conformance/index.js.map +1 -1
  6. package/dist/constants.d.ts +44 -0
  7. package/dist/constants.d.ts.map +1 -0
  8. package/dist/constants.js +128 -0
  9. package/dist/constants.js.map +1 -0
  10. package/dist/index.d.ts +4 -9
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +22 -15
  13. package/dist/libraries.d.ts +16 -0
  14. package/dist/libraries.d.ts.map +1 -0
  15. package/dist/libraries.js +15 -0
  16. package/dist/libraries.js.map +1 -0
  17. package/dist/lint.d.ts +4 -3
  18. package/dist/lint.d.ts.map +1 -1
  19. package/dist/lint.js +34 -2
  20. package/dist/lint.js.map +1 -1
  21. package/dist/mock/example.d.ts +3 -2
  22. package/dist/mock/example.d.ts.map +1 -1
  23. package/dist/mock/example.js +223 -138
  24. package/dist/mock/example.js.map +1 -1
  25. package/dist/mock/index.d.ts +19 -5
  26. package/dist/mock/index.d.ts.map +1 -1
  27. package/dist/mock/index.js +383 -19
  28. package/dist/mock/index.js.map +1 -1
  29. package/dist/openapi.d.ts +2 -0
  30. package/dist/openapi.d.ts.map +1 -1
  31. package/dist/openapi.js +113 -109
  32. package/dist/openapi.js.map +1 -1
  33. package/dist/problem.d.ts +7 -0
  34. package/dist/problem.d.ts.map +1 -0
  35. package/dist/problem.js +22 -0
  36. package/dist/problem.js.map +1 -0
  37. package/dist/query.d.ts +40 -2
  38. package/dist/query.d.ts.map +1 -1
  39. package/dist/query.js +47 -6
  40. package/dist/query.js.map +1 -1
  41. package/dist/rules.d.ts +6 -3
  42. package/dist/rules.d.ts.map +1 -1
  43. package/dist/rules.js +51 -9
  44. package/dist/rules.js.map +1 -1
  45. package/dist/runtime/index.d.ts +14 -0
  46. package/dist/runtime/index.d.ts.map +1 -0
  47. package/dist/runtime/index.js +13 -0
  48. package/dist/schemas/action.d.ts +69 -13
  49. package/dist/schemas/action.d.ts.map +1 -1
  50. package/dist/schemas/action.js +21 -14
  51. package/dist/schemas/action.js.map +1 -1
  52. package/dist/schemas/api.d.ts +224 -39
  53. package/dist/schemas/api.d.ts.map +1 -1
  54. package/dist/schemas/api.js +125 -31
  55. package/dist/schemas/api.js.map +1 -1
  56. package/dist/schemas/boot.d.ts +24 -6
  57. package/dist/schemas/boot.d.ts.map +1 -1
  58. package/dist/schemas/boot.js +3 -7
  59. package/dist/schemas/boot.js.map +1 -1
  60. package/dist/schemas/common.d.ts +1 -0
  61. package/dist/schemas/common.d.ts.map +1 -1
  62. package/dist/schemas/common.js +2 -1
  63. package/dist/schemas/common.js.map +1 -1
  64. package/dist/schemas/definition.d.ts +222 -20
  65. package/dist/schemas/definition.d.ts.map +1 -1
  66. package/dist/schemas/definition.js +16 -11
  67. package/dist/schemas/definition.js.map +1 -1
  68. package/dist/schemas/field.d.ts +162 -8
  69. package/dist/schemas/field.d.ts.map +1 -1
  70. package/dist/schemas/field.js +69 -49
  71. package/dist/schemas/field.js.map +1 -1
  72. package/dist/schemas/index.d.ts +955 -63
  73. package/dist/schemas/index.d.ts.map +1 -1
  74. package/dist/schemas/index.js +41 -12
  75. package/dist/schemas/index.js.map +1 -1
  76. package/dist/schemas/jsonRules.d.ts +83 -0
  77. package/dist/schemas/jsonRules.d.ts.map +1 -0
  78. package/dist/schemas/jsonRules.js +46 -0
  79. package/dist/schemas/jsonRules.js.map +1 -0
  80. package/dist/schemas/layout.d.ts +1 -4
  81. package/dist/schemas/layout.d.ts.map +1 -1
  82. package/dist/schemas/layout.js +1 -13
  83. package/dist/schemas/layout.js.map +1 -1
  84. package/dist/schemas/list.d.ts +6 -3
  85. package/dist/schemas/list.d.ts.map +1 -1
  86. package/dist/schemas/list.js +3 -9
  87. package/dist/schemas/list.js.map +1 -1
  88. package/dist/schemas/resource.d.ts +144 -14
  89. package/dist/schemas/resource.d.ts.map +1 -1
  90. package/dist/schemas/resource.js +6 -1
  91. package/dist/schemas/resource.js.map +1 -1
  92. package/dist/schemas/theme.d.ts +179 -0
  93. package/dist/schemas/theme.d.ts.map +1 -0
  94. package/dist/schemas/theme.js +66 -0
  95. package/dist/schemas/theme.js.map +1 -0
  96. package/dist/search.d.ts +51 -0
  97. package/dist/search.d.ts.map +1 -0
  98. package/dist/search.js +53 -0
  99. package/dist/search.js.map +1 -0
  100. package/dist/themes.d.ts +11 -0
  101. package/dist/themes.d.ts.map +1 -0
  102. package/dist/themes.js +80 -0
  103. package/dist/themes.js.map +1 -0
  104. package/dist/transforms.d.ts +17 -0
  105. package/dist/transforms.d.ts.map +1 -0
  106. package/dist/transforms.js +34 -0
  107. package/dist/transforms.js.map +1 -0
  108. package/dist/validate.d.ts +4 -6
  109. package/dist/validate.d.ts.map +1 -1
  110. package/dist/validate.js +24 -9
  111. package/dist/validate.js.map +1 -1
  112. package/dist/values.d.ts +5 -1
  113. package/dist/values.d.ts.map +1 -1
  114. package/dist/values.js +16 -2
  115. package/dist/values.js.map +1 -1
  116. package/package.json +12 -3
  117. package/schema/boot.schema.json +580 -16
  118. package/schema/definition.schema.json +577 -16
  119. package/schema/openapi.json +1818 -543
  120. package/schema/theme.schema.json +234 -0
@@ -1,7 +1,10 @@
1
1
  import { PROBLEM_CONTENT_TYPE } from "../version.js";
2
+ import { ITEM_ACTION_ABILITIES, isBuiltInItemAction } from "../constants.js";
2
3
  import { isRecord } from "../values.js";
3
4
  import { checkValues } from "../rules.js";
4
- import { fromSearchParams } from "../query.js";
5
+ import { getMediaLibraries } from "../libraries.js";
6
+ import { fromSearchParams, isFilterRange, matchesFilterRange } from "../query.js";
7
+ import { readSearchQuery } from "../search.js";
5
8
  import { createExampleDefinition } from "./example.js";
6
9
  //#region src/mock/index.ts
7
10
  var RESERVED_KEYS = /* @__PURE__ */ new Set([
@@ -9,6 +12,51 @@ var RESERVED_KEYS = /* @__PURE__ */ new Set([
9
12
  "version",
10
13
  "abilities"
11
14
  ]);
15
+ function escapeHtml(text) {
16
+ return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
17
+ }
18
+ /** A plain page with the values of an item, as a `data:` URL, for iframe previews. */
19
+ function defaultPreviewUrl(item) {
20
+ 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("");
21
+ 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>`;
22
+ return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
23
+ }
24
+ /** What the mock knows of a URL to embed: a video of YouTube or Vimeo, or a web page. */
25
+ function defaultEmbed(url) {
26
+ if (!URL.canParse(url)) return null;
27
+ const parsed = new URL(url);
28
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
29
+ const host = parsed.hostname.replace(/^www\./, "");
30
+ const youtube = host === "youtu.be" ? parsed.pathname.slice(1) : host.endsWith("youtube.com") ? parsed.searchParams.get("v") : null;
31
+ if (youtube !== null && youtube !== "") return {
32
+ url,
33
+ type: "video",
34
+ provider: "YouTube",
35
+ title: `YouTube video ${youtube}`,
36
+ thumbnailUrl: `https://i.ytimg.com/vi/${youtube}/hqdefault.jpg`,
37
+ html: `<iframe src="https://www.youtube.com/embed/${youtube}" width="560" height="315" allowfullscreen></iframe>`,
38
+ width: 560,
39
+ height: 315
40
+ };
41
+ if (host === "vimeo.com") {
42
+ const id = parsed.pathname.split("/").filter(Boolean)[0] ?? "";
43
+ return {
44
+ url,
45
+ type: "video",
46
+ provider: "Vimeo",
47
+ title: `Vimeo video ${id}`,
48
+ html: `<iframe src="https://player.vimeo.com/video/${id}" width="640" height="360" allowfullscreen></iframe>`,
49
+ width: 640,
50
+ height: 360
51
+ };
52
+ }
53
+ return {
54
+ url,
55
+ type: "link",
56
+ provider: host,
57
+ title: host
58
+ };
59
+ }
12
60
  var DEFAULT_MESSAGES = {
13
61
  required: () => "This field is required.",
14
62
  min: (failure) => `This value must be at least ${String(failure.value)}.`,
@@ -16,11 +64,16 @@ var DEFAULT_MESSAGES = {
16
64
  pattern: () => "This value has an invalid format.",
17
65
  email: () => "This value must be an email address.",
18
66
  url: () => "This value must be a URL.",
67
+ json: () => "This value must be valid JSON: an object or an array.",
19
68
  in: () => "This value is not one of the choices.",
20
69
  accept: () => "This file type is not accepted.",
21
70
  maxSize: () => "This file is too large.",
22
71
  before: () => "This date is too late.",
23
- after: () => "This date is too early."
72
+ after: () => "This date is too early.",
73
+ crop: (failure) => {
74
+ const ratios = isRecord(failure.value) ? failure.value.ratios : void 0;
75
+ return Array.isArray(ratios) && ratios.length > 0 ? `Crop this image to ${ratios.join(" or ")}.` : "Crop this image.";
76
+ }
24
77
  };
25
78
  function message(failure) {
26
79
  return failure.message ?? DEFAULT_MESSAGES[failure.rule]?.(failure) ?? "This value is invalid.";
@@ -68,9 +121,13 @@ function compare(a, b) {
68
121
  function applyQuery(items, query) {
69
122
  let result = items;
70
123
  Object.entries(query.filter ?? {}).forEach(([key, expected]) => {
124
+ if (isFilterRange(expected)) {
125
+ result = result.filter((item) => matchesFilterRange(item[key], expected));
126
+ return;
127
+ }
71
128
  const accepted = (Array.isArray(expected) ? expected : [expected]).map(String);
72
129
  result = result.filter((item) => {
73
- const value = item[key];
130
+ const value = key in item ? item[key] : isRecord(item.media) ? item.media[key] : void 0;
74
131
  return (Array.isArray(value) ? value : [value]).some((candidate) => accepted.includes(String(candidate)));
75
132
  });
76
133
  });
@@ -90,17 +147,62 @@ function applyQuery(items, query) {
90
147
  });
91
148
  return result;
92
149
  }
150
+ /** The type of a media, from its MIME type. */
151
+ function mediaType(mime) {
152
+ const family = (mime ?? "").split("/")[0] ?? "";
153
+ if (family === "image" || family === "video" || family === "audio") return family;
154
+ return mime === "application/pdf" || family === "text" ? "document" : "other";
155
+ }
156
+ /** What the mock computes about a stored file: no renditions, ready at once. */
157
+ function mediaOf(file) {
158
+ const type = mediaType(file.mime);
159
+ return {
160
+ type,
161
+ mime: file.mime ?? null,
162
+ size: file.size ?? null,
163
+ url: file.url ?? null,
164
+ thumbnailUrl: type === "image" ? file.url ?? null : null,
165
+ status: "ready"
166
+ };
167
+ }
168
+ /**
169
+ * A media item with its own transform (its `transform` field) in its `media`, where references
170
+ * give it to clients (decision 0031).
171
+ */
172
+ function withOwnTransform(resource, item) {
173
+ if (resource.kind !== "media" || !isRecord(item.media)) return item;
174
+ const { transform: _previous, ...media } = item.media;
175
+ return {
176
+ ...item,
177
+ media: isRecord(item.transform) ? {
178
+ ...media,
179
+ transform: item.transform
180
+ } : media
181
+ };
182
+ }
183
+ /**
184
+ * Whether an item allows an action, as clients read its abilities (decision 0040): a built-in item
185
+ * action needs its ability (`delete`, `duplicate`…), and another action its id.
186
+ */
187
+ function allows(item, actionId) {
188
+ const ability = isBuiltInItemAction(actionId) ? ITEM_ACTION_ABILITIES[actionId] : actionId;
189
+ return item.abilities[ability] === true && item.abilities[actionId] !== false;
190
+ }
93
191
  /**
94
192
  * An in-memory backend that implements the protocol's resource routes: definition, list, show,
95
- * create, update (with `If-Match`), delete and the built-in `delete` action. Values are checked
193
+ * create, update (with `If-Match`), delete, duplicate and the built-in `delete` action. Its items
194
+ * allow every built-in item action (`view`, `update`, `duplicate`, `delete`). Values are checked
96
195
  * with the portable rules. Used to test the conformance kit, and to develop frontends without a
97
196
  * real backend.
98
197
  */
99
- function createMockBackend({ definition, items = {} }) {
198
+ function createMockBackend(options) {
199
+ const { definition, items = {} } = options;
100
200
  const store = /* @__PURE__ */ new Map();
101
201
  let nextId = 1;
102
202
  const abilitiesFor = (resource) => Object.fromEntries([
203
+ ["view", true],
103
204
  ["update", true],
205
+ ["duplicate", true],
104
206
  ["delete", true],
105
207
  ...(resource.actions ?? []).map((action) => [action.id, true])
106
208
  ]);
@@ -143,6 +245,150 @@ function createMockBackend({ definition, items = {} }) {
143
245
  if (q !== void 0) query.q = q;
144
246
  return applyQuery(list, query).filter((item) => !except.includes(item.id));
145
247
  };
248
+ const uploads = /* @__PURE__ */ new Map();
249
+ let nextUpload = 1;
250
+ const handleUploads = async (segments, method, readBody) => {
251
+ if (definition.uploads?.mode !== "presigned") return problem(404, "Not found.");
252
+ if (method !== "POST") return problem(405, "Method not allowed.");
253
+ if (segments.length === 2 && segments[1] === "sign") {
254
+ const body = await readBody();
255
+ if (body.uploadId === void 0 && (body.method === "POST" || body.method === "PUT")) {
256
+ const id = `upl_${nextUpload++}`;
257
+ const upload = {
258
+ id,
259
+ key: `uploads/${id}`
260
+ };
261
+ uploads.set(id, upload);
262
+ return json(200, {
263
+ url: `https://storage.test/${upload.key}?signature=mock`,
264
+ key: upload.key,
265
+ upload: id
266
+ });
267
+ }
268
+ const upload = [...uploads.values()].find((candidate) => candidate.key === body.key);
269
+ if (upload === void 0) return problem(404, "Upload not found.");
270
+ return json(200, { url: `https://storage.test/${upload.key}?signature=mock` });
271
+ }
272
+ if (segments.length === 3 && segments[2] === "complete" && segments[1] !== void 0) {
273
+ const upload = uploads.get(segments[1]);
274
+ if (upload === void 0) return problem(404, "Upload not found.");
275
+ const { name } = await readBody();
276
+ if (typeof name === "string") upload.name = name;
277
+ return json(200, { data: upload });
278
+ }
279
+ return problem(404, "Not found.");
280
+ };
281
+ const resolveFiles = (resource, values) => {
282
+ const missing = [];
283
+ const resolved = { ...values };
284
+ const toFile = (value, path) => {
285
+ if (!isRecord(value) || typeof value.upload !== "string") return value;
286
+ const upload = uploads.get(value.upload);
287
+ if (upload === void 0) {
288
+ missing.push(path);
289
+ return value;
290
+ }
291
+ return {
292
+ name: upload.name ?? (typeof value.name === "string" ? value.name : upload.id),
293
+ url: `https://storage.test/${upload.key ?? upload.id}`,
294
+ mime: upload.mime ?? (typeof value.mime === "string" ? value.mime : null),
295
+ size: upload.size ?? (typeof value.size === "number" ? value.size : null)
296
+ };
297
+ };
298
+ resource.fields.filter((field) => field.type === "file" && field.name in values).forEach((field) => {
299
+ const value = values[field.name];
300
+ resolved[field.name] = Array.isArray(value) ? value.map((entry, index) => toFile(entry, `${field.name}.${String(index)}`)) : toFile(value, field.name);
301
+ });
302
+ return {
303
+ values: resolved,
304
+ missing
305
+ };
306
+ };
307
+ const missingMedia = (paths) => problem(422, "The given data was invalid.", {
308
+ type: "urn:panneau:problem:validation",
309
+ errors: Object.fromEntries(Object.entries(paths).map(([path, message]) => [path, [message]]))
310
+ });
311
+ const missingUploads = (paths) => problem(422, "The given data was invalid.", {
312
+ type: "urn:panneau:problem:validation",
313
+ errors: Object.fromEntries(paths.map((path) => [path, ["This upload does not exist."]]))
314
+ });
315
+ const resolveMedia = (resource, values) => {
316
+ const missing = {};
317
+ const resolved = { ...values };
318
+ resource.fields.filter((field) => (field.type === "media" || field.type === "image") && field.name in values).forEach((field) => {
319
+ const allowed = getMediaLibraries(definition, field);
320
+ const toReference = (value, path) => {
321
+ const id = isRecord(value) ? value.id : value;
322
+ if (typeof id !== "string" && typeof id !== "number") return value;
323
+ const named = isRecord(value) && typeof value.resource === "string" ? value.resource : void 0;
324
+ if (named === void 0 && allowed.length > 1) {
325
+ missing[path] = "This field allows several libraries: name the library.";
326
+ return value;
327
+ }
328
+ const libraryId = named ?? allowed[0];
329
+ const library = definition.resources.find((candidate) => candidate.id === libraryId && allowed.includes(candidate.id));
330
+ const media = (store.get(library?.id ?? "") ?? []).find((candidate) => candidate.id === String(id));
331
+ if (media === void 0 || library === void 0) {
332
+ missing[path] = "This media does not exist.";
333
+ return value;
334
+ }
335
+ const title = media[library.itemTitle ?? "name"];
336
+ return {
337
+ id: media.id,
338
+ ...allowed.length > 1 ? { resource: library.id } : {},
339
+ ...typeof title === "string" ? { label: title } : {},
340
+ ...isRecord(media.media) ? { media: media.media } : {},
341
+ ...isRecord(value) && isRecord(value.transform) ? { transform: value.transform } : {}
342
+ };
343
+ };
344
+ const value = values[field.name];
345
+ resolved[field.name] = Array.isArray(value) ? value.map((entry, index) => toReference(entry, `${field.name}.${String(index)}`)) : toReference(value, field.name);
346
+ });
347
+ return {
348
+ values: resolved,
349
+ missing
350
+ };
351
+ };
352
+ const resolveValues = (resource, body) => {
353
+ const sent = { ...body };
354
+ if (resource.kind === "media") delete sent.media;
355
+ const files = resolveFiles(resource, sent);
356
+ if (files.missing.length > 0) return {
357
+ values: body,
358
+ problem: missingUploads(files.missing)
359
+ };
360
+ const media = resolveMedia(resource, files.values);
361
+ if (Object.keys(media.missing).length > 0) return {
362
+ values: body,
363
+ problem: missingMedia(media.missing)
364
+ };
365
+ const values = media.values;
366
+ if (resource.kind === "media" && isRecord(values.file)) values.media = mediaOf(values.file);
367
+ return {
368
+ values,
369
+ problem: null
370
+ };
371
+ };
372
+ const search = (params) => {
373
+ const read = readSearchQuery(params, definition);
374
+ if (read.errors !== void 0) return problem(422, "The given data was invalid.", {
375
+ type: "urn:panneau:problem:validation",
376
+ errors: read.errors
377
+ });
378
+ const { q, limit, resources } = read.query;
379
+ let left = 20;
380
+ return json(200, { data: resources.flatMap((id) => {
381
+ if (left === 0) return [];
382
+ const found = applyQuery(store.get(id) ?? [], { q });
383
+ const items = found.slice(0, Math.min(limit, left));
384
+ left -= items.length;
385
+ return items.length > 0 ? [{
386
+ resource: id,
387
+ items,
388
+ total: found.length
389
+ }] : [];
390
+ }) });
391
+ };
146
392
  const handle = async (request) => {
147
393
  const url = new URL(request.url, "http://panneau.test");
148
394
  if (!url.pathname.startsWith(basePath)) return problem(404, "Not found.");
@@ -153,6 +399,16 @@ function createMockBackend({ definition, items = {} }) {
153
399
  return isRecord(body) ? body : {};
154
400
  };
155
401
  if (segments.length === 1 && segments[0] === "definition" && method === "GET") return json(200, definition);
402
+ if (segments.length === 1 && segments[0] === "embeds" && method === "GET") {
403
+ const url = new URL(request.url, "http://panneau.test").searchParams.get("url") ?? "";
404
+ const embed = url === "" ? null : (options.embed ?? defaultEmbed)(url);
405
+ return embed !== null ? json(200, { data: embed }) : problem(422, "The given data was invalid.", {
406
+ type: "urn:panneau:problem:validation",
407
+ errors: { url: ["This URL can’t be embedded."] }
408
+ });
409
+ }
410
+ if (segments.length === 1 && segments[0] === "search" && method === "GET") return search(url.searchParams);
411
+ if (segments[0] === "uploads") return handleUploads(segments, method, readBody);
156
412
  if (segments[0] !== "resources" || segments[1] === void 0) return problem(404, "Not found.");
157
413
  const resource = definition.resources.find((candidate) => candidate.id === segments[1]);
158
414
  const list = resource !== void 0 ? store.get(resource.id) : void 0;
@@ -167,6 +423,20 @@ function createMockBackend({ definition, items = {} }) {
167
423
  ...query,
168
424
  ...sort !== void 0 ? { sort } : {}
169
425
  });
426
+ if (resource.list?.pagination === "cursor") {
427
+ const cursor = query.cursor ?? "o0";
428
+ if (!/^o\d+$/.test(cursor)) return problem(422, "The cursor is invalid.", { errors: { cursor: ["The cursor is invalid."] } });
429
+ const offset = Number(cursor.slice(1));
430
+ const end = offset + perPage;
431
+ return json(200, {
432
+ data: matching.slice(offset, end),
433
+ meta: {
434
+ perPage,
435
+ nextCursor: end < matching.length ? `o${String(end)}` : null,
436
+ previousCursor: offset - perPage > 0 ? `o${String(offset - perPage)}` : null
437
+ }
438
+ });
439
+ }
170
440
  return json(200, {
171
441
  data: matching.slice((page - 1) * perPage, page * perPage),
172
442
  meta: {
@@ -178,34 +448,126 @@ function createMockBackend({ definition, items = {} }) {
178
448
  });
179
449
  }
180
450
  if (method === "POST") {
181
- const values = await readBody();
182
- const invalid = validationProblem(resource, values, "create");
451
+ const body = await readBody();
452
+ const invalid = validationProblem(resource, body, "create");
183
453
  if (invalid !== null) return invalid;
184
- const item = makeItem(resource, {
454
+ const { values, problem: unresolved } = resolveValues(resource, body);
455
+ if (unresolved !== null) return unresolved;
456
+ const item = withOwnTransform(resource, makeItem(resource, {
185
457
  ...values,
186
458
  id: void 0
187
- });
459
+ }));
188
460
  list.push(item);
189
461
  return json(201, { data: item }, etag(item));
190
462
  }
191
463
  return problem(405, "Method not allowed.");
192
464
  }
465
+ if (segments[2] === "fields" && segments[4] === "check" && segments.length === 5) {
466
+ if (method !== "POST") return problem(405, "Method not allowed.");
467
+ const field = resource.fields.find((candidate) => candidate.name === segments[3] && candidate.check === true);
468
+ if (field === void 0) return problem(404, "Field not found.");
469
+ const body = await readBody();
470
+ if (typeof body.value !== "string") return problem(422, "The given data was invalid.", {
471
+ type: "urn:panneau:problem:validation",
472
+ errors: { value: ["The value is required."] }
473
+ });
474
+ const locale = typeof body.locale === "string" ? body.locale : null;
475
+ const id = typeof body.id === "string" || typeof body.id === "number" ? String(body.id) : null;
476
+ const valueOf = (item) => {
477
+ const value = item[field.name];
478
+ return locale !== null && isRecord(value) ? value[locale] : value;
479
+ };
480
+ const taken = (candidate) => list.some((item) => item.id !== id && valueOf(item) === candidate);
481
+ const available = !taken(body.value);
482
+ let suggestion = null;
483
+ for (let index = 2; !available && suggestion === null; index += 1) {
484
+ const candidate = `${body.value}-${String(index)}`;
485
+ suggestion = taken(candidate) ? null : candidate;
486
+ }
487
+ const prefix = typeof field.settings?.prefix === "string" ? field.settings.prefix : null;
488
+ return json(200, {
489
+ available,
490
+ suggestion,
491
+ prefix,
492
+ url: prefix !== null ? `${prefix}${body.value}` : null
493
+ });
494
+ }
193
495
  if (segments[2] === "actions" && segments[3] !== void 0 && segments.length === 4) {
194
496
  if (method !== "POST") return problem(405, "Method not allowed.");
195
- if (segments[3] !== "delete") return problem(404, "Action not found.");
497
+ const actionId = segments[3];
498
+ const action = (resource.actions ?? []).find((candidate) => candidate.id === actionId);
196
499
  const body = await readBody();
197
- const selected = selectItems(list, body.selection);
198
- store.set(resource.id, list.filter((item) => !selected.includes(item)));
500
+ if (body.dryRun === true) {
501
+ if (action?.dryRun !== true && actionId !== "delete") return problem(400, "This action does not support dry runs.");
502
+ const selected = selectItems(list, body.selection);
503
+ const allowed = selected.filter((item) => allows(item, actionId));
504
+ return json(200, {
505
+ summary: {
506
+ succeeded: allowed.length,
507
+ failed: 0,
508
+ skipped: selected.length - allowed.length
509
+ },
510
+ results: selected.filter((item) => !allowed.includes(item)).slice(0, 20).map((item) => ({
511
+ id: item.id,
512
+ status: "skipped",
513
+ reason: "forbidden"
514
+ }))
515
+ });
516
+ }
517
+ if (actionId !== "delete") return problem(404, "Action not found.");
518
+ const selection = body.selection;
519
+ const selected = selectItems(list, selection);
520
+ const deleted = selected.filter((item) => allows(item, "delete"));
521
+ const skipped = selected.filter((item) => !deleted.includes(item));
522
+ 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.");
523
+ store.set(resource.id, list.filter((item) => !deleted.includes(item)));
199
524
  return json(200, {
200
- message: `${selected.length} deleted.`,
525
+ message: `${deleted.length} deleted.`,
201
526
  summary: {
202
- succeeded: selected.length,
527
+ succeeded: deleted.length,
203
528
  failed: 0,
204
- skipped: 0
529
+ skipped: skipped.length
205
530
  },
531
+ ...skipped.length > 0 ? { results: skipped.slice(0, 20).map((item) => ({
532
+ id: item.id,
533
+ status: "skipped",
534
+ reason: "forbidden"
535
+ })) } : {},
206
536
  refresh: "list"
207
537
  });
208
538
  }
539
+ if (segments.length === 4 && segments[3] === "duplicate" && segments[2] !== void 0) {
540
+ const current = list.find((item) => item.id === segments[2]);
541
+ if (current === void 0) return problem(404, "Item not found.");
542
+ if (method !== "POST") return problem(405, "Method not allowed.");
543
+ if (!allows(current, "duplicate")) return problem(403, "This item can’t be duplicated.");
544
+ const { id: _id, version: _version, abilities: _abilities, ...values } = current;
545
+ let copyId = String(nextId++);
546
+ while (list.some((item) => item.id === copyId)) copyId = String(nextId++);
547
+ const copy = makeItem(resource, {
548
+ ...values,
549
+ id: copyId
550
+ });
551
+ list.push(copy);
552
+ return json(201, { data: copy }, etag(copy));
553
+ }
554
+ if (segments.length === 4 && segments[3] === "preview" && segments[2] !== void 0) {
555
+ const current = list.find((item) => item.id === segments[2]);
556
+ if (current === void 0) return problem(404, "Item not found.");
557
+ if (method !== "POST") return problem(405, "Method not allowed.");
558
+ const body = await readBody();
559
+ const item = {
560
+ ...current,
561
+ ...isRecord(body) ? body : {}
562
+ };
563
+ return json(200, {
564
+ url: options.previewUrl?.({
565
+ resource: resource.id,
566
+ item
567
+ }) ?? defaultPreviewUrl(item),
568
+ expiresAt: new Date(Date.now() + 3e5).toISOString()
569
+ });
570
+ }
209
571
  if (segments.length !== 3 || segments[2] === void 0) return problem(404, "Not found.");
210
572
  const id = segments[2];
211
573
  const index = list.findIndex((item) => item.id === id);
@@ -218,15 +580,17 @@ function createMockBackend({ definition, items = {} }) {
218
580
  type: "urn:panneau:problem:version-conflict",
219
581
  current
220
582
  });
221
- const values = await readBody();
222
- const invalid = validationProblem(resource, values, "update");
583
+ const body = await readBody();
584
+ const invalid = validationProblem(resource, body, "update");
223
585
  if (invalid !== null) return invalid;
586
+ const { values, problem: unresolved } = resolveValues(resource, body);
587
+ if (unresolved !== null) return unresolved;
224
588
  const updates = Object.fromEntries(Object.entries(values).filter(([key]) => !RESERVED_KEYS.has(key)));
225
- const updated = {
589
+ const updated = withOwnTransform(resource, {
226
590
  ...current,
227
591
  ...updates,
228
592
  version: current.version === null ? null : String(Number(current.version) + 1)
229
- };
593
+ });
230
594
  list[index] = updated;
231
595
  return json(200, { data: updated }, etag(updated));
232
596
  }