@panneau/protocol 5.0.0-alpha.17 → 5.0.0-alpha.18

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 (59) hide show
  1. package/dist/conformance/index.d.ts.map +1 -1
  2. package/dist/conformance/index.js +94 -0
  3. package/dist/conformance/index.js.map +1 -1
  4. package/dist/constants.d.ts +5 -0
  5. package/dist/constants.d.ts.map +1 -1
  6. package/dist/constants.js +6 -1
  7. package/dist/constants.js.map +1 -1
  8. package/dist/index.js +7 -5
  9. package/dist/libraries.d.ts +10 -0
  10. package/dist/libraries.d.ts.map +1 -1
  11. package/dist/libraries.js +8 -1
  12. package/dist/libraries.js.map +1 -1
  13. package/dist/lint.d.ts.map +1 -1
  14. package/dist/lint.js +59 -0
  15. package/dist/lint.js.map +1 -1
  16. package/dist/mock/index.d.ts +20 -1
  17. package/dist/mock/index.d.ts.map +1 -1
  18. package/dist/mock/index.js +51 -1
  19. package/dist/mock/index.js.map +1 -1
  20. package/dist/openapi.d.ts.map +1 -1
  21. package/dist/openapi.js +13 -6
  22. package/dist/openapi.js.map +1 -1
  23. package/dist/runtime/index.d.ts +2 -1
  24. package/dist/runtime/index.d.ts.map +1 -1
  25. package/dist/runtime/index.js +5 -4
  26. package/dist/schemas/action.d.ts +1 -0
  27. package/dist/schemas/action.d.ts.map +1 -1
  28. package/dist/schemas/action.js +1 -0
  29. package/dist/schemas/action.js.map +1 -1
  30. package/dist/schemas/api.d.ts +15 -0
  31. package/dist/schemas/api.d.ts.map +1 -1
  32. package/dist/schemas/api.js +6 -1
  33. package/dist/schemas/api.js.map +1 -1
  34. package/dist/schemas/common.js +1 -1
  35. package/dist/schemas/common.js.map +1 -1
  36. package/dist/schemas/definition.d.ts +5 -9
  37. package/dist/schemas/definition.d.ts.map +1 -1
  38. package/dist/schemas/definition.js +3 -9
  39. package/dist/schemas/definition.js.map +1 -1
  40. package/dist/schemas/index.d.ts +81 -2
  41. package/dist/schemas/index.d.ts.map +1 -1
  42. package/dist/schemas/index.js +11 -3
  43. package/dist/schemas/index.js.map +1 -1
  44. package/dist/schemas/resource.d.ts +1 -0
  45. package/dist/schemas/resource.d.ts.map +1 -1
  46. package/dist/schemas/resource.js +1 -1
  47. package/dist/schemas/resource.js.map +1 -1
  48. package/dist/schemas/widget.d.ts +109 -0
  49. package/dist/schemas/widget.d.ts.map +1 -0
  50. package/dist/schemas/widget.js +74 -0
  51. package/dist/schemas/widget.js.map +1 -0
  52. package/dist/widgets.d.ts +42 -0
  53. package/dist/widgets.d.ts.map +1 -0
  54. package/dist/widgets.js +130 -0
  55. package/dist/widgets.js.map +1 -0
  56. package/package.json +1 -1
  57. package/schema/boot.schema.json +41 -5
  58. package/schema/definition.schema.json +41 -5
  59. package/schema/openapi.json +294 -12
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PROBLEM_CONTENT_TYPE, PROTOCOL_VERSION } from "./version.js";
2
- import { ADDRESS_PARTS, AUTH_ERROR_CODES, AUTH_ERROR_PARAM, AUTH_PAGE_PATHS, BOOT_CONFIG_ELEMENT_ID, BUILT_IN_ACTIONS, BUILT_IN_FIELD_TYPES, BUILT_IN_ITEM_ACTIONS, BUILT_IN_LAYOUT_NODE_TYPES, BUILT_IN_LINK_ACTIONS, BUILT_IN_LINK_TYPES, BUILT_IN_LIST_LAYOUTS, CONTEXT_HEADER, CONTEXT_PROBLEM_TYPE, DATE_RANGE_OPEN_BOUNDS, DEFAULT_ADDRESS_REQUIRED_PARTS, DURATION_UNITS, EMAIL_UNVERIFIED_PROBLEM_TYPE, ITEM_ACTION_ABILITIES, PASSWORD_CONFIRMATION_PROBLEM_TYPE, PORTABLE_RULES, RESERVED_ROUTE_SEGMENTS, RICH_TEXT_STYLE_ELEMENTS, TWO_FACTOR_REQUIRED_PROBLEM_TYPE, isBuiltInItemAction, isBuiltInLink } from "./constants.js";
2
+ import { ADDRESS_PARTS, AUTH_ERROR_CODES, AUTH_ERROR_PARAM, AUTH_PAGE_PATHS, BOOT_CONFIG_ELEMENT_ID, BUILT_IN_ACTIONS, BUILT_IN_FIELD_TYPES, BUILT_IN_ITEM_ACTIONS, BUILT_IN_LAYOUT_NODE_TYPES, BUILT_IN_LINK_ACTIONS, BUILT_IN_LINK_TYPES, BUILT_IN_LIST_LAYOUTS, CONTEXT_HEADER, CONTEXT_PROBLEM_TYPE, DATE_RANGE_OPEN_BOUNDS, DEFAULT_ADDRESS_REQUIRED_PARTS, DURATION_UNITS, EMAIL_UNVERIFIED_PROBLEM_TYPE, ITEM_ACTION_ABILITIES, PASSWORD_CONFIRMATION_PROBLEM_TYPE, PORTABLE_RULES, RESERVED_ROUTE_SEGMENTS, RICH_TEXT_STYLE_ELEMENTS, TWO_FACTOR_REQUIRED_PROBLEM_TYPE, UNDO_LIMIT, isBuiltInItemAction, isBuiltInLink } from "./constants.js";
3
3
  import { CURRENCY_CODES, fromMinorUnits, getCurrencyDigits, isCurrencyCode, toMinorUnits } from "./currencies.js";
4
4
  import { POSTAL_CODE_COUNTRIES, getAddressRequiredParts, isAddressPart, isPostalCode, normalizePostalCode } from "./addresses.js";
5
5
  import { getValue, isFilled } from "./values.js";
@@ -7,9 +7,10 @@ import { evaluateCondition } from "./conditions.js";
7
7
  import { getLinkNewTab, getLinkTypes, isBuiltInLinkType, isExternalUrl, resolveLinkNewTab } from "./links.js";
8
8
  import { matchesRatio, parseRatio, renderedCropSize } from "./transforms.js";
9
9
  import { checkRules, checkValues } from "./rules.js";
10
- import { getMediaLibraries } from "./libraries.js";
11
- import { lintDefinition } from "./lint.js";
10
+ import { getItemImageField, getMediaLibraries } from "./libraries.js";
12
11
  import { fromSearchParams, isCursorPage, isFilterRange, matchesFilterRange, toSearchParams } from "./query.js";
12
+ import { BUILT_IN_WIDGET_TYPES, RESOURCE_WIDGET_TYPES, WIDGET_LIST_MAX_ITEMS, WIDGET_RESERVED_QUERY_PARAMS, WIDGET_SERIES_PERIODS, checkWidgetData, getWidgetResource, isBuiltInWidgetType } from "./widgets.js";
13
+ import { lintDefinition } from "./lint.js";
13
14
  import { SEARCH_DEFAULT_LIMIT, SEARCH_MAX_LENGTH, SEARCH_MAX_LIMIT, SEARCH_MIN_LENGTH, isSearchableResource, readSearchQuery, toSearchQueryParams } from "./search.js";
14
15
  import { contextBefore, formatContextHeader, parseContextHeader } from "./context.js";
15
16
  import { isProblem } from "./problem.js";
@@ -21,10 +22,11 @@ import { Action, ActionConfirm, ActionPlacement, ActionScope } from "./schemas/a
21
22
  import { Column, Filter, ListCalendar, ListDefinition } from "./schemas/list.js";
22
23
  import { Resource, ResourceFeatures } from "./schemas/resource.js";
23
24
  import { DefinitionTheme, Theme, ThemeFont, ThemeFontFace, ThemeFontStylesheet, ThemeTokens, ToneInput, ToneValues } from "./schemas/theme.js";
24
- import { Auth, AuthProvider, AuthToken, ContextOption, ContextParam, Definition, DefinitionContext, MenuItem, Page, Uploads, User, Widget } from "./schemas/definition.js";
25
+ import { ListWidgetData, ListWidgetItem, SeriesPoint, SeriesWidgetData, StatWidgetData, Widget, WidgetBadge, WidgetSettings, widgetDataSchemas } from "./schemas/widget.js";
26
+ import { Auth, AuthProvider, AuthToken, ContextOption, ContextParam, Definition, DefinitionContext, MenuItem, Page, Uploads, User } from "./schemas/definition.js";
25
27
  import { ActionItemResult, ActionRequest, ActionResult, ActionRun, ActionRunResponse, AddressValue, ContextOptionsResponse, CursorPagination, DateRangeValue, EmbedResponse, EmbedValue, FieldCheckRequest, FieldCheckResponse, Item, ItemResponse, LinkValue, ListResponse, LocationValue, MediaInfo, MediaItem, MediaReference, MediaTransform, MoneyValue, Pagination, Passkey, PreviewResponse, Problem, RecoveryCodes, SearchResponse, Selection, Session, StoredFile, TwoFactorChallenge, TwoFactorSetup, TwoFactorStatus, Upload, UploadReference, UploadResponse, UploadSignRequest, UploadSignResponse, WebAuthnOptions } from "./schemas/api.js";
26
28
  import { BootConfig } from "./schemas/boot.js";
27
29
  import { createSchemaRegistry, namedSchemas } from "./schemas/index.js";
28
30
  import { validate, validateBootConfig, validateDefinition } from "./validate.js";
29
31
  import { createBootConfigJsonSchema, createComponentSchemas, createDefinitionJsonSchema, createOpenApiDocument, createThemeJsonSchema } from "./openapi.js";
30
- export { ADDRESS_PARTS, AUTH_ERROR_CODES, AUTH_ERROR_PARAM, AUTH_PAGE_PATHS, Abilities, Action, ActionConfirm, ActionItemResult, ActionPlacement, ActionRequest, ActionResult, ActionRun, ActionRunResponse, ActionScope, AddressSettings, AddressValue, Auth, AuthProvider, AuthToken, BOOT_CONFIG_ELEMENT_ID, BUILT_IN_ACTIONS, BUILT_IN_FIELD_TYPES, BUILT_IN_ITEM_ACTIONS, BUILT_IN_LAYOUT_NODE_TYPES, BUILT_IN_LINK_ACTIONS, BUILT_IN_LINK_TYPES, BUILT_IN_LIST_LAYOUTS, BlockType, BootConfig, CONTEXT_HEADER, CONTEXT_PROBLEM_TYPE, CURRENCY_CODES, Column, Condition, ContextOption, ContextOptionsResponse, ContextParam, CursorPagination, DATE_RANGE_OPEN_BOUNDS, DEFAULT_ADDRESS_REQUIRED_PARTS, DURATION_UNITS, DateRangeSettings, DateRangeValue, Definition, DefinitionContext, DefinitionTheme, DurationSettings, EMAIL_UNVERIFIED_PROBLEM_TYPE, EmbedResponse, EmbedValue, Field, FieldCheckRequest, FieldCheckResponse, Filter, ITEM_ACTION_ABILITIES, Id, Item, ItemResponse, LayoutNode, LinkSettings, LinkTypeSetting, LinkValue, ListCalendar, ListDefinition, ListResponse, LocationValue, MediaInfo, MediaItem, MediaReference, MediaTransform, MenuItem, MoneySettings, MoneyValue, Option, PASSWORD_CONFIRMATION_PROBLEM_TYPE, PORTABLE_RULES, POSTAL_CODE_COUNTRIES, PROBLEM_CONTENT_TYPE, PROTOCOL_VERSION, Page, Pagination, Passkey, PreviewResponse, Problem, RESERVED_ROUTE_SEGMENTS, RICH_TEXT_STYLE_ELEMENTS, RecoveryCodes, Resource, ResourceFeatures, RichTextSettings, RichTextStyle, RouteReference, Rule, SEARCH_DEFAULT_LIMIT, SEARCH_MAX_LENGTH, SEARCH_MAX_LIMIT, SEARCH_MIN_LENGTH, SearchResponse, Selection, Session, StoredFile, TWO_FACTOR_REQUIRED_PROBLEM_TYPE, Theme, ThemeFont, ThemeFontFace, ThemeFontStylesheet, ThemeTokens, ToneInput, ToneValues, TwoFactorChallenge, TwoFactorSetup, TwoFactorStatus, Upload, UploadReference, UploadResponse, UploadSignRequest, UploadSignResponse, Uploads, User, WebAuthnOptions, Widget, checkRules, checkValues, contextBefore, createBootConfigJsonSchema, createComponentSchemas, createDefinitionJsonSchema, createOpenApiDocument, createSchemaRegistry, createThemeJsonSchema, evaluateCondition, formatContextHeader, fromMinorUnits, fromSearchParams, getAddressRequiredParts, getCurrencyDigits, getLinkNewTab, getLinkTypes, getMediaLibraries, getValue, isAddressPart, isBuiltInItemAction, isBuiltInLink, isBuiltInLinkType, isCurrencyCode, isCursorPage, isExternalUrl, isFilled, isFilterRange, isPostalCode, isProblem, isSearchableResource, lintDefinition, matchesFilterRange, matchesRatio, mergeThemes, namedSchemas, normalizePostalCode, parseContextHeader, parseRatio, readSearchQuery, renderedCropSize, resolveLinkNewTab, toMinorUnits, toSearchParams, toSearchQueryParams, validate, validateBootConfig, validateDefinition };
32
+ export { ADDRESS_PARTS, AUTH_ERROR_CODES, AUTH_ERROR_PARAM, AUTH_PAGE_PATHS, Abilities, Action, ActionConfirm, ActionItemResult, ActionPlacement, ActionRequest, ActionResult, ActionRun, ActionRunResponse, ActionScope, AddressSettings, AddressValue, Auth, AuthProvider, AuthToken, BOOT_CONFIG_ELEMENT_ID, BUILT_IN_ACTIONS, BUILT_IN_FIELD_TYPES, BUILT_IN_ITEM_ACTIONS, BUILT_IN_LAYOUT_NODE_TYPES, BUILT_IN_LINK_ACTIONS, BUILT_IN_LINK_TYPES, BUILT_IN_LIST_LAYOUTS, BUILT_IN_WIDGET_TYPES, BlockType, BootConfig, CONTEXT_HEADER, CONTEXT_PROBLEM_TYPE, CURRENCY_CODES, Column, Condition, ContextOption, ContextOptionsResponse, ContextParam, CursorPagination, DATE_RANGE_OPEN_BOUNDS, DEFAULT_ADDRESS_REQUIRED_PARTS, DURATION_UNITS, DateRangeSettings, DateRangeValue, Definition, DefinitionContext, DefinitionTheme, DurationSettings, EMAIL_UNVERIFIED_PROBLEM_TYPE, EmbedResponse, EmbedValue, Field, FieldCheckRequest, FieldCheckResponse, Filter, ITEM_ACTION_ABILITIES, Id, Item, ItemResponse, LayoutNode, LinkSettings, LinkTypeSetting, LinkValue, ListCalendar, ListDefinition, ListResponse, ListWidgetData, ListWidgetItem, LocationValue, MediaInfo, MediaItem, MediaReference, MediaTransform, MenuItem, MoneySettings, MoneyValue, Option, PASSWORD_CONFIRMATION_PROBLEM_TYPE, PORTABLE_RULES, POSTAL_CODE_COUNTRIES, PROBLEM_CONTENT_TYPE, PROTOCOL_VERSION, Page, Pagination, Passkey, PreviewResponse, Problem, RESERVED_ROUTE_SEGMENTS, RESOURCE_WIDGET_TYPES, RICH_TEXT_STYLE_ELEMENTS, RecoveryCodes, Resource, ResourceFeatures, RichTextSettings, RichTextStyle, RouteReference, Rule, SEARCH_DEFAULT_LIMIT, SEARCH_MAX_LENGTH, SEARCH_MAX_LIMIT, SEARCH_MIN_LENGTH, SearchResponse, Selection, SeriesPoint, SeriesWidgetData, Session, StatWidgetData, StoredFile, TWO_FACTOR_REQUIRED_PROBLEM_TYPE, Theme, ThemeFont, ThemeFontFace, ThemeFontStylesheet, ThemeTokens, ToneInput, ToneValues, TwoFactorChallenge, TwoFactorSetup, TwoFactorStatus, UNDO_LIMIT, Upload, UploadReference, UploadResponse, UploadSignRequest, UploadSignResponse, Uploads, User, WIDGET_LIST_MAX_ITEMS, WIDGET_RESERVED_QUERY_PARAMS, WIDGET_SERIES_PERIODS, WebAuthnOptions, Widget, WidgetBadge, WidgetSettings, checkRules, checkValues, checkWidgetData, contextBefore, createBootConfigJsonSchema, createComponentSchemas, createDefinitionJsonSchema, createOpenApiDocument, createSchemaRegistry, createThemeJsonSchema, evaluateCondition, formatContextHeader, fromMinorUnits, fromSearchParams, getAddressRequiredParts, getCurrencyDigits, getItemImageField, getLinkNewTab, getLinkTypes, getMediaLibraries, getValue, getWidgetResource, isAddressPart, isBuiltInItemAction, isBuiltInLink, isBuiltInLinkType, isBuiltInWidgetType, isCurrencyCode, isCursorPage, isExternalUrl, isFilled, isFilterRange, isPostalCode, isProblem, isSearchableResource, lintDefinition, matchesFilterRange, matchesRatio, mergeThemes, namedSchemas, normalizePostalCode, parseContextHeader, parseRatio, readSearchQuery, renderedCropSize, resolveLinkNewTab, toMinorUnits, toSearchParams, toSearchQueryParams, validate, validateBootConfig, validateDefinition, widgetDataSchemas };
@@ -13,4 +13,14 @@ export interface MediaLibrariesDefinition {
13
13
  export declare function getMediaLibraries(definition: MediaLibrariesDefinition | null, field: {
14
14
  resource?: string | readonly string[] | undefined;
15
15
  }): string[];
16
+ /** What `getItemImageField()` reads of a resource. */
17
+ export interface ItemImageResource {
18
+ kind?: string | undefined;
19
+ itemImage?: string | undefined;
20
+ }
21
+ /**
22
+ * The key of an item that holds its image (decision 0061): the resource's `itemImage`, or `media`
23
+ * in a media library, whose items all have one. `undefined` for a resource without an image.
24
+ */
25
+ export declare function getItemImageField(resource: ItemImageResource): string | undefined;
16
26
  //# sourceMappingURL=libraries.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"libraries.d.ts","sourceRoot":"","sources":["../src/libraries.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,MAAM,WAAW,wBAAwB;IACrC,SAAS,EAAE,SAAS;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,EAAE,CAAC;CACnE;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAC7B,UAAU,EAAE,wBAAwB,GAAG,IAAI,EAC3C,KAAK,EAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,GAAG,SAAS,CAAA;CAAE,GAC7D,MAAM,EAAE,CAUV"}
1
+ {"version":3,"file":"libraries.d.ts","sourceRoot":"","sources":["../src/libraries.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,MAAM,WAAW,wBAAwB;IACrC,SAAS,EAAE,SAAS;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,EAAE,CAAC;CACnE;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAC7B,UAAU,EAAE,wBAAwB,GAAG,IAAI,EAC3C,KAAK,EAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,GAAG,SAAS,CAAA;CAAE,GAC7D,MAAM,EAAE,CAUV;AAED,sDAAsD;AACtD,MAAM,WAAW,iBAAiB;IAC9B,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAClC;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,MAAM,GAAG,SAAS,CAEjF"}
package/dist/libraries.js CHANGED
@@ -9,7 +9,14 @@ function getMediaLibraries(definition, field) {
9
9
  if (field.resource === void 0) return libraries;
10
10
  return (typeof field.resource === "string" ? [field.resource] : field.resource).filter((id) => libraries.includes(id));
11
11
  }
12
+ /**
13
+ * The key of an item that holds its image (decision 0061): the resource's `itemImage`, or `media`
14
+ * in a media library, whose items all have one. `undefined` for a resource without an image.
15
+ */
16
+ function getItemImageField(resource) {
17
+ return resource.itemImage ?? (resource.kind === "media" ? "media" : void 0);
18
+ }
12
19
  //#endregion
13
- export { getMediaLibraries };
20
+ export { getItemImageField, getMediaLibraries };
14
21
 
15
22
  //# sourceMappingURL=libraries.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"libraries.js","names":[],"sources":["../src/libraries.ts"],"sourcesContent":["/** What `getMediaLibraries()` reads of a definition. */\nexport interface MediaLibrariesDefinition {\n resources: readonly { id: string; kind?: string | undefined }[];\n}\n\n/**\n * The ids of the libraries a `media` field allows (decision 0027), in the order of its `resource`:\n * the one it names, the ones it lists, or every resource of kind `media` of the definition when it\n * names none. Ids that aren't libraries are left out: `lintDefinition()` reports them.\n */\nexport function getMediaLibraries(\n definition: MediaLibrariesDefinition | null,\n field: { resource?: string | readonly string[] | undefined },\n): string[] {\n const libraries = (definition?.resources ?? [])\n .filter((resource) => resource.kind === 'media')\n .map((resource) => resource.id);\n if (field.resource === undefined) {\n return libraries;\n }\n const named: readonly string[] =\n typeof field.resource === 'string' ? [field.resource] : field.resource;\n return named.filter((id) => libraries.includes(id));\n}\n"],"mappings":";;;;;;AAUA,SAAgB,kBACZ,YACA,OACQ;CACR,MAAM,aAAa,YAAY,aAAa,CAAC,EAAA,CACxC,QAAQ,aAAa,SAAS,SAAS,OAAO,CAAC,CAC/C,KAAK,aAAa,SAAS,EAAE;CAClC,IAAI,MAAM,aAAa,KAAA,GACnB,OAAO;CAIX,QADI,OAAO,MAAM,aAAa,WAAW,CAAC,MAAM,QAAQ,IAAI,MAAM,SAAA,CACrD,QAAQ,OAAO,UAAU,SAAS,EAAE,CAAC;AACtD"}
1
+ {"version":3,"file":"libraries.js","names":[],"sources":["../src/libraries.ts"],"sourcesContent":["/** What `getMediaLibraries()` reads of a definition. */\nexport interface MediaLibrariesDefinition {\n resources: readonly { id: string; kind?: string | undefined }[];\n}\n\n/**\n * The ids of the libraries a `media` field allows (decision 0027), in the order of its `resource`:\n * the one it names, the ones it lists, or every resource of kind `media` of the definition when it\n * names none. Ids that aren't libraries are left out: `lintDefinition()` reports them.\n */\nexport function getMediaLibraries(\n definition: MediaLibrariesDefinition | null,\n field: { resource?: string | readonly string[] | undefined },\n): string[] {\n const libraries = (definition?.resources ?? [])\n .filter((resource) => resource.kind === 'media')\n .map((resource) => resource.id);\n if (field.resource === undefined) {\n return libraries;\n }\n const named: readonly string[] =\n typeof field.resource === 'string' ? [field.resource] : field.resource;\n return named.filter((id) => libraries.includes(id));\n}\n\n/** What `getItemImageField()` reads of a resource. */\nexport interface ItemImageResource {\n kind?: string | undefined;\n itemImage?: string | undefined;\n}\n\n/**\n * The key of an item that holds its image (decision 0061): the resource's `itemImage`, or `media`\n * in a media library, whose items all have one. `undefined` for a resource without an image.\n */\nexport function getItemImageField(resource: ItemImageResource): string | undefined {\n return resource.itemImage ?? (resource.kind === 'media' ? 'media' : undefined);\n}\n"],"mappings":";;;;;;AAUA,SAAgB,kBACZ,YACA,OACQ;CACR,MAAM,aAAa,YAAY,aAAa,CAAC,EAAA,CACxC,QAAQ,aAAa,SAAS,SAAS,OAAO,CAAC,CAC/C,KAAK,aAAa,SAAS,EAAE;CAClC,IAAI,MAAM,aAAa,KAAA,GACnB,OAAO;CAIX,QADI,OAAO,MAAM,aAAa,WAAW,CAAC,MAAM,QAAQ,IAAI,MAAM,SAAA,CACrD,QAAQ,OAAO,UAAU,SAAS,EAAE,CAAC;AACtD;;;;;AAYA,SAAgB,kBAAkB,UAAiD;CAC/E,OAAO,SAAS,cAAc,SAAS,SAAS,UAAU,UAAU,KAAA;AACxE"}
@@ -1 +1 @@
1
- {"version":3,"file":"lint.d.ts","sourceRoot":"","sources":["../src/lint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAoC,MAAM,WAAW,CAAC;AACnF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAyHlD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,eAAe,GAAG,eAAe,EAAE,CAgD7E"}
1
+ {"version":3,"file":"lint.d.ts","sourceRoot":"","sources":["../src/lint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAoC,MAAM,WAAW,CAAC;AACnF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AA8HlD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,eAAe,GAAG,eAAe,EAAE,CAiD7E"}
package/dist/lint.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { RESOURCE_WIDGET_TYPES, WIDGET_RESERVED_QUERY_PARAMS, isBuiltInWidgetType } from "./widgets.js";
1
2
  //#region src/lint.ts
2
3
  function fieldNames(fields) {
3
4
  return new Set(fields.map((field) => field.name));
@@ -118,8 +119,66 @@ function lintDefinition(definition) {
118
119
  }
119
120
  });
120
121
  });
122
+ checkWidgets(definition, issues);
121
123
  return issues;
122
124
  }
125
+ var FILTER_PARAM = /^filter\[([^\]]+)\]/;
126
+ /**
127
+ * The widgets of the dashboard (decision 0064): unique ids, and the built-in `stat` and `list` on
128
+ * a resource that exists, with filters of its list. A `stat` counts the items of the list, so the
129
+ * list can't be paged with cursors, which give no total.
130
+ */
131
+ function checkWidgets(definition, issues) {
132
+ const ids = /* @__PURE__ */ new Set();
133
+ (definition.dashboard?.widgets ?? []).forEach((widget, index) => {
134
+ const path = `dashboard.widgets.${index}`;
135
+ if (ids.has(widget.id)) issues.push({
136
+ path: `${path}.id`,
137
+ message: `Duplicate widget id \`${widget.id}\`.`
138
+ });
139
+ ids.add(widget.id);
140
+ if (!isBuiltInWidgetType(widget.type)) return;
141
+ const settings = widget.settings ?? {};
142
+ if (!(typeof settings.resource === "string")) {
143
+ if (settings.query !== void 0) issues.push({
144
+ path: `${path}.settings.query`,
145
+ message: "`query` goes with a `resource`."
146
+ });
147
+ return;
148
+ }
149
+ if (!RESOURCE_WIDGET_TYPES.includes(widget.type)) {
150
+ issues.push({
151
+ path: `${path}.settings.resource`,
152
+ message: `A \`${widget.type}\` widget has data of its own: only \`stat\` and \`list\` read a resource.`
153
+ });
154
+ return;
155
+ }
156
+ const resource = definition.resources.find((candidate) => candidate.id === settings.resource);
157
+ if (resource === void 0) {
158
+ issues.push({
159
+ path: `${path}.settings.resource`,
160
+ message: `No resource \`${String(settings.resource)}\`.`
161
+ });
162
+ return;
163
+ }
164
+ if (widget.type === "stat" && resource.list?.pagination === "cursor") issues.push({
165
+ path: `${path}.settings.resource`,
166
+ message: `The list of \`${resource.id}\` is paged with cursors and has no total: it can't feed a \`stat\`.`
167
+ });
168
+ const filters = new Set((resource.list?.filters ?? []).map((filter) => filter.id));
169
+ Object.keys(settings.query ?? {}).forEach((key) => {
170
+ const filter = FILTER_PARAM.exec(key)?.[1];
171
+ if (WIDGET_RESERVED_QUERY_PARAMS.includes(key)) issues.push({
172
+ path: `${path}.settings.query.${key}`,
173
+ message: `The client sets \`${key}\`.`
174
+ });
175
+ else if (filter !== void 0 && !filters.has(filter)) issues.push({
176
+ path: `${path}.settings.query.${key}`,
177
+ message: `The list of \`${resource.id}\` has no filter \`${filter}\`.`
178
+ });
179
+ });
180
+ });
181
+ }
123
182
  //#endregion
124
183
  export { lintDefinition };
125
184
 
package/dist/lint.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lint.js","names":[],"sources":["../src/lint.ts"],"sourcesContent":["import type { DefinitionInput, Field, LayoutNode, ResourceInput } from './schemas';\nimport type { ValidationIssue } from './validate';\n\nfunction fieldNames(fields: Field[]): Set<string> {\n return new Set(fields.map((field) => field.name));\n}\n\nfunction checkLayout(\n nodes: LayoutNode[],\n names: Set<string>,\n path: string,\n issues: ValidationIssue[],\n) {\n nodes.forEach((node, index) => {\n const nodePath = `${path}.${index}`;\n if (node.type === 'field') {\n if (node.name === undefined) {\n issues.push({ path: nodePath, message: 'A `field` node needs a `name`.' });\n } else if (!names.has(node.name)) {\n issues.push({\n path: `${nodePath}.name`,\n message: `No field named \\`${node.name}\\`.`,\n });\n }\n }\n if (node.type === 'component' && node.component === undefined) {\n issues.push({ path: nodePath, message: 'A `component` node needs a `component`.' });\n }\n if (node.type === 'tabs' && node.children?.some((child) => child.type !== 'tab')) {\n issues.push({\n path: `${nodePath}.children`,\n message: 'The children of `tabs` must be `tab` nodes.',\n });\n }\n if (node.children !== undefined) {\n checkLayout(node.children, names, `${nodePath}.children`, issues);\n }\n });\n}\n\nfunction checkResource(resource: ResourceInput, path: string, issues: ValidationIssue[]) {\n const names = fieldNames(resource.fields);\n if (names.size !== resource.fields.length) {\n issues.push({ path: `${path}.fields`, message: 'Field names must be unique.' });\n }\n if (resource.form?.layout !== undefined) {\n checkLayout(resource.form.layout, names, `${path}.form.layout`, issues);\n }\n (resource.list?.columns ?? []).forEach((column, index) => {\n if (column.field !== undefined && !names.has(column.field)) {\n issues.push({\n path: `${path}.list.columns.${index}.field`,\n message: `No field named \\`${column.field}\\`.`,\n });\n }\n });\n const calendar = resource.list?.calendar;\n if (calendar !== undefined) {\n const field = resource.fields.find((candidate) => candidate.name === calendar.field);\n const filter = calendar.filter ?? calendar.field;\n if (field === undefined) {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: `No field named \\`${calendar.field}\\`.`,\n });\n } else if (!['date', 'datetime', 'daterange'].includes(field.type)) {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: 'The field of a calendar must be a `date`, a `datetime` or a `daterange`.',\n });\n }\n if (\n !(resource.list?.filters ?? []).some(\n (candidate) => candidate.id === filter && candidate.type === 'date-range',\n )\n ) {\n issues.push({\n path: `${path}.list.calendar`,\n message: `The calendar needs a \\`date-range\\` filter \\`${filter}\\` in the list.`,\n });\n }\n }\n (resource.actions ?? []).forEach((action, index) => {\n if (action.layout !== undefined) {\n checkLayout(\n action.layout,\n fieldNames(action.fields ?? []),\n `${path}.actions.${index}.layout`,\n issues,\n );\n }\n });\n if (resource.kind === 'media') {\n const file = resource.fields.findIndex((field) => field.name === 'file');\n const field = resource.fields[file];\n if (field === undefined) {\n issues.push({\n path: `${path}.fields`,\n message: 'A resource of kind `media` needs a `file` field.',\n });\n } else if (field.type !== 'file' || field.multiple === true) {\n issues.push({\n path: `${path}.fields.${file}`,\n message: 'The `file` field of a `media` resource must be a single `file`.',\n });\n }\n }\n resource.fields.forEach((field, index) => {\n if (field.type === 'relation' && field.resource === undefined) {\n issues.push({\n path: `${path}.fields.${index}.resource`,\n message: 'A `relation` field needs a `resource`.',\n });\n } else if (field.type === 'relation' && Array.isArray(field.resource)) {\n issues.push({\n path: `${path}.fields.${index}.resource`,\n message: 'A `relation` field names one resource.',\n });\n }\n });\n}\n\n/**\n * Checks what the schema can't: references between parts of a definition (layout nodes and\n * columns that name existing fields, relations, `media` and `image` fields that name a resource,\n * unique names), and the `file` field of `media` resources.\n */\nexport function lintDefinition(definition: DefinitionInput): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const resourceIds = new Set(definition.resources.map((resource) => resource.id));\n const libraries = definition.resources\n .filter((resource) => resource.kind === 'media')\n .map((resource) => resource.id);\n definition.resources.forEach((resource, index) => {\n checkResource(resource, `resources.${index}`, issues);\n resource.fields.forEach((field, fieldIndex) => {\n if (\n field.type === 'relation' &&\n typeof field.resource === 'string' &&\n !resourceIds.has(field.resource)\n ) {\n issues.push({\n path: `resources.${index}.fields.${fieldIndex}.resource`,\n message: `No resource \\`${field.resource}\\`.`,\n });\n }\n if (field.type === 'media' || field.type === 'image') {\n const fieldPath = `resources.${index}.fields.${fieldIndex}.resource`;\n if (field.resource === undefined) {\n // Every library of the definition (decision 0027).\n if (libraries.length === 0) {\n issues.push({\n path: fieldPath,\n message: `${field.type === 'image' ? 'An' : 'A'} \\`${field.type}\\` field needs a resource of kind \\`media\\`.`,\n });\n }\n } else {\n const named =\n typeof field.resource === 'string' ? [field.resource] : field.resource;\n named.forEach((id, idIndex) => {\n if (!libraries.includes(id)) {\n issues.push({\n path:\n typeof field.resource === 'string'\n ? fieldPath\n : `${fieldPath}.${String(idIndex)}`,\n message: `No resource of kind \\`media\\` named \\`${id}\\`.`,\n });\n }\n });\n }\n }\n });\n });\n return issues;\n}\n"],"mappings":";AAGA,SAAS,WAAW,QAA8B;CAC9C,OAAO,IAAI,IAAI,OAAO,KAAK,UAAU,MAAM,IAAI,CAAC;AACpD;AAEA,SAAS,YACL,OACA,OACA,MACA,QACF;CACE,MAAM,SAAS,MAAM,UAAU;EAC3B,M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sources":["../src/lint.ts"],"sourcesContent":["import type { DefinitionInput, Field, LayoutNode, ResourceInput } from './schemas';\nimport type { ValidationIssue } from './validate';\nimport {\n RESOURCE_WIDGET_TYPES,\n WIDGET_RESERVED_QUERY_PARAMS,\n isBuiltInWidgetType,\n} from './widgets';\n\nfunction fieldNames(fields: Field[]): Set<string> {\n return new Set(fields.map((field) => field.name));\n}\n\nfunction checkLayout(\n nodes: LayoutNode[],\n names: Set<string>,\n path: string,\n issues: ValidationIssue[],\n) {\n nodes.forEach((node, index) => {\n const nodePath = `${path}.${index}`;\n if (node.type === 'field') {\n if (node.name === undefined) {\n issues.push({ path: nodePath, message: 'A `field` node needs a `name`.' });\n } else if (!names.has(node.name)) {\n issues.push({\n path: `${nodePath}.name`,\n message: `No field named \\`${node.name}\\`.`,\n });\n }\n }\n if (node.type === 'component' && node.component === undefined) {\n issues.push({ path: nodePath, message: 'A `component` node needs a `component`.' });\n }\n if (node.type === 'tabs' && node.children?.some((child) => child.type !== 'tab')) {\n issues.push({\n path: `${nodePath}.children`,\n message: 'The children of `tabs` must be `tab` nodes.',\n });\n }\n if (node.children !== undefined) {\n checkLayout(node.children, names, `${nodePath}.children`, issues);\n }\n });\n}\n\nfunction checkResource(resource: ResourceInput, path: string, issues: ValidationIssue[]) {\n const names = fieldNames(resource.fields);\n if (names.size !== resource.fields.length) {\n issues.push({ path: `${path}.fields`, message: 'Field names must be unique.' });\n }\n if (resource.form?.layout !== undefined) {\n checkLayout(resource.form.layout, names, `${path}.form.layout`, issues);\n }\n (resource.list?.columns ?? []).forEach((column, index) => {\n if (column.field !== undefined && !names.has(column.field)) {\n issues.push({\n path: `${path}.list.columns.${index}.field`,\n message: `No field named \\`${column.field}\\`.`,\n });\n }\n });\n const calendar = resource.list?.calendar;\n if (calendar !== undefined) {\n const field = resource.fields.find((candidate) => candidate.name === calendar.field);\n const filter = calendar.filter ?? calendar.field;\n if (field === undefined) {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: `No field named \\`${calendar.field}\\`.`,\n });\n } else if (!['date', 'datetime', 'daterange'].includes(field.type)) {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: 'The field of a calendar must be a `date`, a `datetime` or a `daterange`.',\n });\n }\n if (\n !(resource.list?.filters ?? []).some(\n (candidate) => candidate.id === filter && candidate.type === 'date-range',\n )\n ) {\n issues.push({\n path: `${path}.list.calendar`,\n message: `The calendar needs a \\`date-range\\` filter \\`${filter}\\` in the list.`,\n });\n }\n }\n (resource.actions ?? []).forEach((action, index) => {\n if (action.layout !== undefined) {\n checkLayout(\n action.layout,\n fieldNames(action.fields ?? []),\n `${path}.actions.${index}.layout`,\n issues,\n );\n }\n });\n if (resource.kind === 'media') {\n const file = resource.fields.findIndex((field) => field.name === 'file');\n const field = resource.fields[file];\n if (field === undefined) {\n issues.push({\n path: `${path}.fields`,\n message: 'A resource of kind `media` needs a `file` field.',\n });\n } else if (field.type !== 'file' || field.multiple === true) {\n issues.push({\n path: `${path}.fields.${file}`,\n message: 'The `file` field of a `media` resource must be a single `file`.',\n });\n }\n }\n resource.fields.forEach((field, index) => {\n if (field.type === 'relation' && field.resource === undefined) {\n issues.push({\n path: `${path}.fields.${index}.resource`,\n message: 'A `relation` field needs a `resource`.',\n });\n } else if (field.type === 'relation' && Array.isArray(field.resource)) {\n issues.push({\n path: `${path}.fields.${index}.resource`,\n message: 'A `relation` field names one resource.',\n });\n }\n });\n}\n\n/**\n * Checks what the schema can't: references between parts of a definition (layout nodes and\n * columns that name existing fields, relations, `media` and `image` fields that name a resource,\n * unique names), and the `file` field of `media` resources.\n */\nexport function lintDefinition(definition: DefinitionInput): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const resourceIds = new Set(definition.resources.map((resource) => resource.id));\n const libraries = definition.resources\n .filter((resource) => resource.kind === 'media')\n .map((resource) => resource.id);\n definition.resources.forEach((resource, index) => {\n checkResource(resource, `resources.${index}`, issues);\n resource.fields.forEach((field, fieldIndex) => {\n if (\n field.type === 'relation' &&\n typeof field.resource === 'string' &&\n !resourceIds.has(field.resource)\n ) {\n issues.push({\n path: `resources.${index}.fields.${fieldIndex}.resource`,\n message: `No resource \\`${field.resource}\\`.`,\n });\n }\n if (field.type === 'media' || field.type === 'image') {\n const fieldPath = `resources.${index}.fields.${fieldIndex}.resource`;\n if (field.resource === undefined) {\n // Every library of the definition (decision 0027).\n if (libraries.length === 0) {\n issues.push({\n path: fieldPath,\n message: `${field.type === 'image' ? 'An' : 'A'} \\`${field.type}\\` field needs a resource of kind \\`media\\`.`,\n });\n }\n } else {\n const named =\n typeof field.resource === 'string' ? [field.resource] : field.resource;\n named.forEach((id, idIndex) => {\n if (!libraries.includes(id)) {\n issues.push({\n path:\n typeof field.resource === 'string'\n ? fieldPath\n : `${fieldPath}.${String(idIndex)}`,\n message: `No resource of kind \\`media\\` named \\`${id}\\`.`,\n });\n }\n });\n }\n }\n });\n });\n checkWidgets(definition, issues);\n return issues;\n}\n\nconst FILTER_PARAM = /^filter\\[([^\\]]+)\\]/;\n\n/**\n * The widgets of the dashboard (decision 0064): unique ids, and the built-in `stat` and `list` on\n * a resource that exists, with filters of its list. A `stat` counts the items of the list, so the\n * list can't be paged with cursors, which give no total.\n */\nfunction checkWidgets(definition: DefinitionInput, issues: ValidationIssue[]) {\n const ids = new Set<string>();\n (definition.dashboard?.widgets ?? []).forEach((widget, index) => {\n const path = `dashboard.widgets.${index}`;\n if (ids.has(widget.id)) {\n issues.push({ path: `${path}.id`, message: `Duplicate widget id \\`${widget.id}\\`.` });\n }\n ids.add(widget.id);\n if (!isBuiltInWidgetType(widget.type)) {\n return;\n }\n const settings = widget.settings ?? {};\n const onResource = typeof settings.resource === 'string';\n if (!onResource) {\n if (settings.query !== undefined) {\n issues.push({\n path: `${path}.settings.query`,\n message: '`query` goes with a `resource`.',\n });\n }\n return;\n }\n if (!(RESOURCE_WIDGET_TYPES as readonly string[]).includes(widget.type)) {\n issues.push({\n path: `${path}.settings.resource`,\n message: `A \\`${widget.type}\\` widget has data of its own: only \\`stat\\` and \\`list\\` read a resource.`,\n });\n return;\n }\n const resource = definition.resources.find(\n (candidate) => candidate.id === settings.resource,\n );\n if (resource === undefined) {\n issues.push({\n path: `${path}.settings.resource`,\n message: `No resource \\`${String(settings.resource)}\\`.`,\n });\n return;\n }\n if (widget.type === 'stat' && resource.list?.pagination === 'cursor') {\n issues.push({\n path: `${path}.settings.resource`,\n message: `The list of \\`${resource.id}\\` is paged with cursors and has no total: it can't feed a \\`stat\\`.`,\n });\n }\n const filters = new Set((resource.list?.filters ?? []).map((filter) => filter.id));\n Object.keys(settings.query ?? {}).forEach((key) => {\n const filter = FILTER_PARAM.exec(key)?.[1];\n if ((WIDGET_RESERVED_QUERY_PARAMS as readonly string[]).includes(key)) {\n issues.push({\n path: `${path}.settings.query.${key}`,\n message: `The client sets \\`${key}\\`.`,\n });\n } else if (filter !== undefined && !filters.has(filter)) {\n issues.push({\n path: `${path}.settings.query.${key}`,\n message: `The list of \\`${resource.id}\\` has no filter \\`${filter}\\`.`,\n });\n }\n });\n });\n}\n"],"mappings":";;AAQA,SAAS,WAAW,QAA8B;CAC9C,OAAO,IAAI,IAAI,OAAO,KAAK,UAAU,MAAM,IAAI,CAAC;AACpD;AAEA,SAAS,YACL,OACA,OACA,MACA,QACF;CACE,MAAM,SAAS,MAAM,UAAU;EAC3B,MAAM,WAAW,GAAG,KAAK,GAAG;EAC5B,IAAI,KAAK,SAAS,SAAS;GACvB,IAAI,KAAK,SAAS,KAAA,GACd,OAAO,KAAK;IAAE,MAAM;IAAU,SAAS;GAAiC,CAAC;QACtE,IAAI,CAAC,MAAM,IAAI,KAAK,IAAI,GAC3B,OAAO,KAAK;IACR,MAAM,GAAG,SAAS;IAClB,SAAS,oBAAoB,KAAK,KAAK;GAC3C,CAAC;EAET;EACA,IAAI,KAAK,SAAS,eAAe,KAAK,cAAc,KAAA,GAChD,OAAO,KAAK;GAAE,MAAM;GAAU,SAAS;EAA0C,CAAC;EAEtF,IAAI,KAAK,SAAS,U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,CAAC;EAErC,IAAI,EADe,OAAO,SAAS,aAAa,WAC/B;GACb,IAAI,SAAS,UAAU,KAAA,GACnB,OAAO,KAAK;IACR,MAAM,GAAG,KAAK;IACd,SAAS;GACb,CAAC;GAEL;EACJ;EACA,IAAI,CAAE,sBAA4C,SAAS,OAAO,IAAI,GAAG;GACrE,OAAO,KAAK;IACR,MAAM,GAAG,KAAK;IACd,SAAS,OAAO,OAAO,KAAK;GAChC,CAAC;GACD;EACJ;EACA,MAAM,WAAW,WAAW,UAAU,MACjC,cAAc,UAAU,OAAO,SAAS,QAC7C;EACA,IAAI,aAAa,KAAA,GAAW;GACxB,OAAO,KAAK;IACR,MAAM,GAAG,KAAK;IACd,SAAS,iBAAiB,OAAO,SAAS,QAAQ,EAAE;GACxD,CAAC;GACD;EACJ;EACA,IAAI,OAAO,SAAS,UAAU,SAAS,MAAM,eAAe,UACxD,OAAO,KAAK;GACR,MAAM,GAAG,KAAK;GACd,SAAS,iBAAiB,SAAS,GAAG;EAC1C,CAAC;EAEL,MAAM,UAAU,IAAI,KAAK,SAAS,MAAM,WAAW,CAAC,EAAA,CAAG,KAAK,WAAW,OAAO,EAAE,CAAC;EACjF,OAAO,KAAK,SAAS,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,QAAQ;GAC/C,MAAM,SAAS,aAAa,KAAK,GAAG,CAAC,GAAG;GACxC,IAAK,6BAAmD,SAAS,GAAG,GAChE,OAAO,KAAK;IACR,MAAM,GAAG,KAAK,kBAAkB;IAChC,SAAS,qBAAqB,IAAI;GACtC,CAAC;QACE,IAAI,WAAW,KAAA,KAAa,CAAC,QAAQ,IAAI,MAAM,GAClD,OAAO,KAAK;IACR,MAAM,GAAG,KAAK,kBAAkB;IAChC,SAAS,iBAAiB,SAAS,GAAG,qBAAqB,OAAO;GACtE,CAAC;EAET,CAAC;CACL,CAAC;AACL"}
@@ -34,6 +34,23 @@ export interface MockBackendOptions {
34
34
  * get its `403` problem (decision 0048). Without it, every request is the user's.
35
35
  */
36
36
  auth?: MockAuthOptions;
37
+ /**
38
+ * The data of `GET /dashboard/widgets/{widget}`, per widget id (decision 0064): the data, a
39
+ * function that returns it for the current context, or a `Response` to answer as is (a `403`,
40
+ * a slow or failing widget). Data that doesn't have the shape of a built-in type is a `500`
41
+ * problem that names the wrong keys, as a backend answers it. Widgets of the dashboard without
42
+ * data, and built-in `stat` and `list` on a resource, are a `404`.
43
+ */
44
+ widgets?: Record<string, MockWidget>;
45
+ }
46
+ /** The data of a widget in the mock backend: its data, or what answers it. */
47
+ export type MockWidget = Response | Record<string, unknown> | ((context: MockWidgetContext) => Response | Record<string, unknown> | Promise<Response | Record<string, unknown>>);
48
+ /** What the function of a widget of the mock backend gets. */
49
+ export interface MockWidgetContext {
50
+ /** The values of the context of the request. */
51
+ context: ContextValues;
52
+ /** The current items of a resource, in the context. */
53
+ items: (resource: string) => Item[];
37
54
  }
38
55
  /** How the mock backend answers the context of its definition (decision 0045). */
39
56
  export interface MockContextOptions {
@@ -53,7 +70,9 @@ export interface MockBackend {
53
70
  }
54
71
  /**
55
72
  * An in-memory backend that implements the protocol's resource routes: definition, list, show,
56
- * create, update (with `If-Match`), delete, duplicate and the built-in `delete` action. Its items
73
+ * create, update (with `If-Match`), delete, duplicate and the built-in `delete` action. A resource
74
+ * that declares its `delete` `undoable` has a trash: the result of `delete` says how to undo it,
75
+ * and the built-in `restore` puts the items back (decision 0063). Its items
57
76
  * allow every built-in item action (`view`, `update`, `duplicate`, `delete`), unless an item of
58
77
  * `items` gives its own `abilities`. It reads abilities as clients do (decision 0046): a resource
59
78
  * without `viewAny` answers `403` on its list, one without `create` on creates, an item without
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mock/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,aAAa,EAAqC,MAAM,YAAY,CAAC;AAInF,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAiB,MAAM,YAAY,CAAC;AAChF,OAAO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kValues } from "../rules.js";
5
5
  import { getMediaLibraries } from "../libraries.js";
6
6
  import { fromSearchParams, isFilterRange, matchesFilterRange } from "../query.js";
7
+ import { checkWidgetData, getWidgetResource } from "../widgets.js";
7
8
  import { readSearchQuery } from "../search.js";
8
9
  import { contextBefore, parseContextHeader } from "../context.js";
9
10
  import { createMockAuth } from "./auth.js";
@@ -210,7 +211,9 @@ function writableValues(resource, body) {
210
211
  }
211
212
  /**
212
213
  * An in-memory backend that implements the protocol's resource routes: definition, list, show,
213
- * create, update (with `If-Match`), delete, duplicate and the built-in `delete` action. Its items
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
214
217
  * allow every built-in item action (`view`, `update`, `duplicate`, `delete`), unless an item of
215
218
  * `items` gives its own `abilities`. It reads abilities as clients do (decision 0046): a resource
216
219
  * without `viewAny` answers `403` on its list, one without `create` on creates, an item without
@@ -223,6 +226,7 @@ function createMockBackend(options) {
223
226
  const { definition, items = {} } = options;
224
227
  const auth = options.auth !== void 0 ? createMockAuth(options.auth, definition.auth) : null;
225
228
  const store = /* @__PURE__ */ new Map();
229
+ const trash = /* @__PURE__ */ new Map();
226
230
  let nextId = 1;
227
231
  const abilitiesFor = (resource) => Object.fromEntries([
228
232
  ["view", true],
@@ -459,6 +463,18 @@ function createMockBackend(options) {
459
463
  return values;
460
464
  };
461
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
+ };
462
478
  const definitionFor = (values) => definition.context === void 0 ? definition : {
463
479
  ...definition,
464
480
  context: {
@@ -523,6 +539,7 @@ function createMockBackend(options) {
523
539
  errors: { url: ["This URL can’t be embedded."] }
524
540
  });
525
541
  }
542
+ if (segments.length === 3 && segments[0] === "dashboard" && segments[1] === "widgets" && method === "GET") return answerWidget(segments[2] ?? "", context, inScope);
526
543
  if (segments.length === 1 && segments[0] === "search" && method === "GET") return search(url.searchParams, inScope);
527
544
  if (segments[0] === "uploads") return handleUploads(segments, method, readBody);
528
545
  if (segments[0] !== "resources" || segments[1] === void 0) return problem(404, "Not found.");
@@ -633,6 +650,34 @@ function createMockBackend(options) {
633
650
  }))
634
651
  });
635
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
+ }
636
681
  if (actionId !== "delete") return problem(404, "Action not found.");
637
682
  const selection = body.selection;
638
683
  const selected = selectItems(scoped, selection);
@@ -640,8 +685,13 @@ function createMockBackend(options) {
640
685
  const skipped = selected.filter((item) => !deleted.includes(item));
641
686
  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.");
642
687
  store.set(resource.id, list.filter((item) => !deleted.includes(item)));
688
+ if (hasTrash) trash.set(resource.id, [...trash.get(resource.id) ?? [], ...deleted]);
643
689
  return json(200, {
644
690
  message: `${deleted.length} deleted.`,
691
+ ...hasTrash && deleted.length > 0 && deleted.length <= 100 ? { undo: {
692
+ action: "restore",
693
+ items: deleted.map((item) => item.id)
694
+ } } : {},
645
695
  summary: {
646
696
  succeeded: deleted.length,
647
697
  failed: 0,