@panneau/protocol 5.0.0-alpha.36 → 5.0.0-alpha.38

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 (63) hide show
  1. package/dist/aggregates.d.ts +135 -0
  2. package/dist/aggregates.d.ts.map +1 -0
  3. package/dist/aggregates.js +236 -0
  4. package/dist/aggregates.js.map +1 -0
  5. package/dist/conformance/index.d.ts.map +1 -1
  6. package/dist/conformance/index.js +201 -24
  7. package/dist/conformance/index.js.map +1 -1
  8. package/dist/dashboards.d.ts +95 -0
  9. package/dist/dashboards.d.ts.map +1 -0
  10. package/dist/dashboards.js +140 -0
  11. package/dist/dashboards.js.map +1 -0
  12. package/dist/index.js +8 -5
  13. package/dist/lint.d.ts.map +1 -1
  14. package/dist/lint.js +249 -15
  15. package/dist/lint.js.map +1 -1
  16. package/dist/mock/index.d.ts +27 -8
  17. package/dist/mock/index.d.ts.map +1 -1
  18. package/dist/mock/index.js +42 -6
  19. package/dist/mock/index.js.map +1 -1
  20. package/dist/openapi.d.ts.map +1 -1
  21. package/dist/openapi.js +77 -3
  22. package/dist/openapi.js.map +1 -1
  23. package/dist/periods.d.ts +49 -0
  24. package/dist/periods.d.ts.map +1 -0
  25. package/dist/periods.js +93 -0
  26. package/dist/periods.js.map +1 -0
  27. package/dist/runtime/index.d.ts +4 -1
  28. package/dist/runtime/index.d.ts.map +1 -1
  29. package/dist/runtime/index.js +5 -2
  30. package/dist/schemas/action.d.ts +1 -0
  31. package/dist/schemas/action.d.ts.map +1 -1
  32. package/dist/schemas/definition.d.ts +127 -0
  33. package/dist/schemas/definition.d.ts.map +1 -1
  34. package/dist/schemas/definition.js +8 -3
  35. package/dist/schemas/definition.js.map +1 -1
  36. package/dist/schemas/field.d.ts +1 -0
  37. package/dist/schemas/field.d.ts.map +1 -1
  38. package/dist/schemas/field.js +1 -0
  39. package/dist/schemas/field.js.map +1 -1
  40. package/dist/schemas/index.d.ts +283 -1
  41. package/dist/schemas/index.d.ts.map +1 -1
  42. package/dist/schemas/index.js +11 -5
  43. package/dist/schemas/index.js.map +1 -1
  44. package/dist/schemas/list.d.ts +11 -0
  45. package/dist/schemas/list.d.ts.map +1 -1
  46. package/dist/schemas/list.js +8 -2
  47. package/dist/schemas/list.js.map +1 -1
  48. package/dist/schemas/resource.d.ts +100 -0
  49. package/dist/schemas/resource.d.ts.map +1 -1
  50. package/dist/schemas/resource.js +9 -1
  51. package/dist/schemas/resource.js.map +1 -1
  52. package/dist/schemas/widget.d.ts +62 -2
  53. package/dist/schemas/widget.d.ts.map +1 -1
  54. package/dist/schemas/widget.js +36 -8
  55. package/dist/schemas/widget.js.map +1 -1
  56. package/dist/widgets.d.ts +48 -9
  57. package/dist/widgets.d.ts.map +1 -1
  58. package/dist/widgets.js +81 -10
  59. package/dist/widgets.js.map +1 -1
  60. package/package.json +1 -1
  61. package/schema/boot.schema.json +235 -66
  62. package/schema/definition.schema.json +235 -66
  63. package/schema/openapi.json +508 -7
@@ -0,0 +1,95 @@
1
+ import { type WidgetPeriod } from './periods.js';
2
+ import { type ListQuery } from './query.js';
3
+ import type { DefinitionInput, OverviewPeriod, ResourceInput, Widget } from './schemas/index.js';
4
+ /** The page whose dashboard is the home page, and the `page` of a widget request without one. */
5
+ export declare const HOME_PAGE = "home";
6
+ /** The component of the built-in dashboard page. */
7
+ export declare const DASHBOARD_COMPONENT = "dashboard";
8
+ /** The parts of a definition that declare dashboards: its pages, and `dashboard`. */
9
+ type DashboardsOf = Pick<DefinitionInput, 'pages' | 'dashboard'>;
10
+ /**
11
+ * The widgets of the dashboard of a page, in order (decisions 0064 and 0084): the `widgets` of a
12
+ * page whose component is the built-in `dashboard`. The home page is the dashboard of `pages.home`,
13
+ * and `definition.dashboard` is its shorthand: its widgets are `pages.home.widgets` when set, else
14
+ * those of `definition.dashboard`. Empty for any other page.
15
+ */
16
+ export declare function getDashboardWidgets(definition: DashboardsOf, page?: string): Widget[];
17
+ /**
18
+ * The pages that have a dashboard of widgets, home first: `home` when its widgets are declared
19
+ * (`pages.home.widgets` or `definition.dashboard`), then each other page whose component is the
20
+ * built-in `dashboard`, in the order of `pages`.
21
+ */
22
+ export declare function getDashboardPages(definition: DashboardsOf): string[];
23
+ /**
24
+ * The period of the dashboard of a page (decision 0084): the `period` of a page whose component is
25
+ * the built-in `dashboard`. For the home page, `pages.home.period` when set, else that of
26
+ * `definition.dashboard`, its shorthand. `undefined` without one.
27
+ */
28
+ export declare function getDashboardPeriod(definition: DashboardsOf, page?: string): OverviewPeriod | undefined;
29
+ /**
30
+ * The id of the list's `date-range` filter that the period of the summary of a resource sets
31
+ * (decision 0084): its `period.filter`, or the first `date-range` filter of the list. `null`
32
+ * without a period, or without such a filter.
33
+ */
34
+ export declare function getSummaryPeriodFilter(resource: Pick<ResourceInput, 'summary' | 'list'>): string | null;
35
+ /** The parts of a definition that declare summaries: its resources. */
36
+ type SummariesOf = Pick<DefinitionInput, 'resources'>;
37
+ /**
38
+ * The widgets of the summary above the list of a resource, in order (decision 0084): its
39
+ * `summary.widgets`. Empty for a resource without a summary, or that doesn't exist.
40
+ */
41
+ export declare function getSummaryWidgets(definition: SummariesOf, resource: string): Widget[];
42
+ /** The ids of the resources that have a summary above their list, in the order of `resources`. */
43
+ export declare function getSummaryResources(definition: SummariesOf): string[];
44
+ /** The query of a list that a widget of its summary gets: its filters and its search. */
45
+ export type WidgetListQuery = Pick<ListQuery, 'filter' | 'q'>;
46
+ /**
47
+ * Where a widget with data of its own is asked for (decisions 0064 and 0084): on a dashboard page,
48
+ * or in the summary of a resource, with the query of its list.
49
+ */
50
+ export interface WidgetDataRequest {
51
+ /** The id of the dashboard page of the widget, in `pages`. Defaults to `home`. */
52
+ page?: string;
53
+ /** The resource whose summary holds the widget. With it, `page` is left out. */
54
+ resource?: string;
55
+ /** In a summary: the filters and the search of the list, when the widget follows it. */
56
+ query?: WidgetListQuery;
57
+ /** The period chosen in the overview, unless the widget has `settings.period: false`. */
58
+ period?: WidgetPeriod;
59
+ }
60
+ /**
61
+ * The query parameters of `GET /dashboard/widgets/{widget}`: `resource` and the filters and search
62
+ * of the list (`filter[…]`, `q`) for a widget of a summary, or `page` for a dashboard page other
63
+ * than home, and the period of the overview (`period[option]`, `period[from]`, `period[to]`). The
64
+ * widgets of the home page are asked for without `page`. The list's sort and paging are never
65
+ * sent: `page` is the dashboard page.
66
+ */
67
+ export declare function toWidgetDataParams(request?: WidgetDataRequest): URLSearchParams;
68
+ /** What `readWidgetDataQuery()` reads: where the widget is, or the errors of its parameters. */
69
+ export type ReadWidgetDataQueryResult = {
70
+ page: string;
71
+ resource?: undefined;
72
+ query?: undefined;
73
+ period: WidgetPeriod | null;
74
+ errors?: undefined;
75
+ } | {
76
+ resource: string;
77
+ query: WidgetListQuery;
78
+ page?: undefined;
79
+ period: WidgetPeriod | null;
80
+ errors?: undefined;
81
+ } | {
82
+ errors: Record<string, string[]>;
83
+ page?: undefined;
84
+ resource?: undefined;
85
+ };
86
+ /**
87
+ * Reads the query parameters of `GET /dashboard/widgets/{widget}` (decision 0084), as a backend
88
+ * does: a widget of the summary of `resource`, with the filters and the search of its list, or of
89
+ * the dashboard page `page`, `home` without it, and the period of the overview, or `null`. `page`
90
+ * and `resource` together, an empty one, or a wrong period are errors keyed by `page`, `resource`
91
+ * or `period`: a `422`.
92
+ */
93
+ export declare function readWidgetDataQuery(params: URLSearchParams): ReadWidgetDataQueryResult;
94
+ export {};
95
+ //# sourceMappingURL=dashboards.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dashboards.d.ts","sourceRoot":"","sources":["../src/dashboards.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAA2B,MAAM,WAAW,CAAC;AACvE,OAAO,EAAE,KAAK,SAAS,EAAoC,MAAM,SAAS,CAAC;AAC3E,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAExF,iGAAiG;AACjG,eAAO,MAAM,SAAS,SAAS,CAAC;AAEhC,oDAAoD;AACpD,eAAO,MAAM,mBAAmB,cAAc,CAAC;AAE/C,qFAAqF;AACrF,KAAK,YAAY,GAAG,IAAI,CAAC,eAAe,EAAE,OAAO,GAAG,WAAW,CAAC,CAAC;AAEjE;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,YAAY,EAAE,IAAI,GAAE,MAAkB,GAAG,MAAM,EAAE,CAMhG;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,YAAY,GAAG,MAAM,EAAE,CAWpE;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAC9B,UAAU,EAAE,YAAY,EACxB,IAAI,GAAE,MAAkB,GACzB,cAAc,GAAG,SAAS,CAM5B;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAClC,QAAQ,EAAE,IAAI,CAAC,aAAa,EAAE,SAAS,GAAG,MAAM,CAAC,GAClD,MAAM,GAAG,IAAI,CAQf;AAED,uEAAuE;AACvE,KAAK,WAAW,GAAG,IAAI,CAAC,eAAe,EAAE,WAAW,CAAC,CAAC;AAEtD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,CAIrF;AAED,kGAAkG;AAClG,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,WAAW,GAAG,MAAM,EAAE,CAIrE;AAED,yFAAyF;AACzF,MAAM,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,EAAE,QAAQ,GAAG,GAAG,CAAC,CAAC;AAE9D;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAC9B,kFAAkF;IAClF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gFAAgF;IAChF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,wFAAwF;IACxF,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,yFAAyF;IACzF,MAAM,CAAC,EAAE,YAAY,CAAC;CACzB;AAYD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,iBAAsB,GAAG,eAAe,CAWnF;AAED,gGAAgG;AAChG,MAAM,MAAM,yBAAyB,GAC/B;IACI,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,MAAM,EAAE,YAAY,GAAG,IAAI,CAAC;IAC5B,MAAM,CAAC,EAAE,SAAS,CAAC;CACtB,GACD;IACI,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,eAAe,CAAC;IACvB,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,MAAM,EAAE,YAAY,GAAG,IAAI,CAAC;IAC5B,MAAM,CAAC,EAAE,SAAS,CAAC;CACtB,GACD;IAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAAC,IAAI,CAAC,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,EAAE,SAAS,CAAA;CAAE,CAAC;AAsBnF;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,eAAe,GAAG,yBAAyB,CAyBtF"}
@@ -0,0 +1,140 @@
1
+ import { fromSearchParams, toSearchParams } from "./query.js";
2
+ import { isDay, isOverviewPeriod } from "./periods.js";
3
+ //#region src/dashboards.ts
4
+ /** The page whose dashboard is the home page, and the `page` of a widget request without one. */
5
+ var HOME_PAGE = "home";
6
+ /** The component of the built-in dashboard page. */
7
+ var DASHBOARD_COMPONENT = "dashboard";
8
+ /**
9
+ * The widgets of the dashboard of a page, in order (decisions 0064 and 0084): the `widgets` of a
10
+ * page whose component is the built-in `dashboard`. The home page is the dashboard of `pages.home`,
11
+ * and `definition.dashboard` is its shorthand: its widgets are `pages.home.widgets` when set, else
12
+ * those of `definition.dashboard`. Empty for any other page.
13
+ */
14
+ function getDashboardWidgets(definition, page = HOME_PAGE) {
15
+ const own = definition.pages?.[page];
16
+ if (own?.component === "dashboard" && own.widgets !== void 0) return own.widgets;
17
+ return page === "home" ? definition.dashboard?.widgets ?? [] : [];
18
+ }
19
+ /**
20
+ * The pages that have a dashboard of widgets, home first: `home` when its widgets are declared
21
+ * (`pages.home.widgets` or `definition.dashboard`), then each other page whose component is the
22
+ * built-in `dashboard`, in the order of `pages`.
23
+ */
24
+ function getDashboardPages(definition) {
25
+ const home = definition.pages?.[HOME_PAGE];
26
+ return [...definition.dashboard !== void 0 || home?.component === "dashboard" && home.widgets !== void 0 ? [HOME_PAGE] : [], ...Object.entries(definition.pages ?? {}).filter(([id, page]) => id !== "home" && page.component === "dashboard").map(([id]) => id)];
27
+ }
28
+ /**
29
+ * The period of the dashboard of a page (decision 0084): the `period` of a page whose component is
30
+ * the built-in `dashboard`. For the home page, `pages.home.period` when set, else that of
31
+ * `definition.dashboard`, its shorthand. `undefined` without one.
32
+ */
33
+ function getDashboardPeriod(definition, page = HOME_PAGE) {
34
+ const own = definition.pages?.[page];
35
+ if (own?.component === "dashboard" && own.period !== void 0) return own.period;
36
+ return page === "home" ? definition.dashboard?.period : void 0;
37
+ }
38
+ /**
39
+ * The id of the list's `date-range` filter that the period of the summary of a resource sets
40
+ * (decision 0084): its `period.filter`, or the first `date-range` filter of the list. `null`
41
+ * without a period, or without such a filter.
42
+ */
43
+ function getSummaryPeriodFilter(resource) {
44
+ const period = resource.summary?.period;
45
+ if (period === void 0) return null;
46
+ const filters = (resource.list?.filters ?? []).filter((filter) => filter.type === "date-range");
47
+ const id = period.filter ?? filters[0]?.id;
48
+ return filters.some((filter) => filter.id === id) ? id ?? null : null;
49
+ }
50
+ /**
51
+ * The widgets of the summary above the list of a resource, in order (decision 0084): its
52
+ * `summary.widgets`. Empty for a resource without a summary, or that doesn't exist.
53
+ */
54
+ function getSummaryWidgets(definition, resource) {
55
+ return definition.resources.find((candidate) => candidate.id === resource)?.summary?.widgets ?? [];
56
+ }
57
+ /** The ids of the resources that have a summary above their list, in the order of `resources`. */
58
+ function getSummaryResources(definition) {
59
+ return definition.resources.filter((resource) => resource.summary !== void 0).map((resource) => resource.id);
60
+ }
61
+ /** Writes the period of a widget: `period[option]`, `period[from]` and `period[to]`. */
62
+ function appendPeriod(params, period) {
63
+ if (period !== void 0) {
64
+ params.set("period[option]", period.option);
65
+ params.set("period[from]", period.from);
66
+ params.set("period[to]", period.to);
67
+ }
68
+ return params;
69
+ }
70
+ /**
71
+ * The query parameters of `GET /dashboard/widgets/{widget}`: `resource` and the filters and search
72
+ * of the list (`filter[…]`, `q`) for a widget of a summary, or `page` for a dashboard page other
73
+ * than home, and the period of the overview (`period[option]`, `period[from]`, `period[to]`). The
74
+ * widgets of the home page are asked for without `page`. The list's sort and paging are never
75
+ * sent: `page` is the dashboard page.
76
+ */
77
+ function toWidgetDataParams(request = {}) {
78
+ if (request.resource !== void 0) {
79
+ const params = new URLSearchParams({ resource: request.resource });
80
+ toSearchParams({
81
+ ...request.query?.filter !== void 0 && { filter: request.query.filter },
82
+ ...request.query?.q !== void 0 && { q: request.query.q }
83
+ }).forEach((value, key) => params.append(key, value));
84
+ return appendPeriod(params, request.period);
85
+ }
86
+ const page = request.page ?? "home";
87
+ return appendPeriod(new URLSearchParams(page !== "home" ? { page } : {}), request.period);
88
+ }
89
+ /**
90
+ * The period of a request, from `period[option]`, `period[from]` and `period[to]`: `null` without
91
+ * any, and an error when one is missing or wrong, or when `from` is after `to`.
92
+ */
93
+ function readPeriod(params) {
94
+ const option = params.get("period[option]");
95
+ const from = params.get("period[from]");
96
+ const to = params.get("period[to]");
97
+ if (option === null && from === null && to === null) return null;
98
+ if (!isOverviewPeriod(option)) return "The period must be one of 7d, 30d, 90d, month and year.";
99
+ if (!isDay(from) || !isDay(to) || from > to) return "The period needs its first and last days, from before to.";
100
+ return {
101
+ option,
102
+ from,
103
+ to
104
+ };
105
+ }
106
+ /**
107
+ * Reads the query parameters of `GET /dashboard/widgets/{widget}` (decision 0084), as a backend
108
+ * does: a widget of the summary of `resource`, with the filters and the search of its list, or of
109
+ * the dashboard page `page`, `home` without it, and the period of the overview, or `null`. `page`
110
+ * and `resource` together, an empty one, or a wrong period are errors keyed by `page`, `resource`
111
+ * or `period`: a `422`.
112
+ */
113
+ function readWidgetDataQuery(params) {
114
+ const page = params.get("page");
115
+ const resource = params.get("resource");
116
+ if (resource !== null && page !== null) return { errors: { page: ["A widget is on a page or in a summary, not both."] } };
117
+ if (resource === "") return { errors: { resource: ["The resource must not be empty."] } };
118
+ if (page === "") return { errors: { page: ["The page must not be empty."] } };
119
+ const period = readPeriod(params);
120
+ if (typeof period === "string") return { errors: { period: [period] } };
121
+ if (resource !== null) {
122
+ const { filter, q } = fromSearchParams(params);
123
+ return {
124
+ resource,
125
+ query: {
126
+ ...filter !== void 0 && { filter },
127
+ ...q !== void 0 && { q }
128
+ },
129
+ period
130
+ };
131
+ }
132
+ return {
133
+ page: page ?? "home",
134
+ period
135
+ };
136
+ }
137
+ //#endregion
138
+ export { DASHBOARD_COMPONENT, HOME_PAGE, getDashboardPages, getDashboardPeriod, getDashboardWidgets, getSummaryPeriodFilter, getSummaryResources, getSummaryWidgets, readWidgetDataQuery, toWidgetDataParams };
139
+
140
+ //# sourceMappingURL=dashboards.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dashboards.js","names":[],"sources":["../src/dashboards.ts"],"sourcesContent":["import { type WidgetPeriod, isDay, isOverviewPeriod } from './periods';\nimport { type ListQuery, fromSearchParams, toSearchParams } from './query';\nimport type { DefinitionInput, OverviewPeriod, ResourceInput, Widget } from './schemas';\n\n/** The page whose dashboard is the home page, and the `page` of a widget request without one. */\nexport const HOME_PAGE = 'home';\n\n/** The component of the built-in dashboard page. */\nexport const DASHBOARD_COMPONENT = 'dashboard';\n\n/** The parts of a definition that declare dashboards: its pages, and `dashboard`. */\ntype DashboardsOf = Pick<DefinitionInput, 'pages' | 'dashboard'>;\n\n/**\n * The widgets of the dashboard of a page, in order (decisions 0064 and 0084): the `widgets` of a\n * page whose component is the built-in `dashboard`. The home page is the dashboard of `pages.home`,\n * and `definition.dashboard` is its shorthand: its widgets are `pages.home.widgets` when set, else\n * those of `definition.dashboard`. Empty for any other page.\n */\nexport function getDashboardWidgets(definition: DashboardsOf, page: string = HOME_PAGE): Widget[] {\n const own = definition.pages?.[page];\n if (own?.component === DASHBOARD_COMPONENT && own.widgets !== undefined) {\n return own.widgets;\n }\n return page === HOME_PAGE ? (definition.dashboard?.widgets ?? []) : [];\n}\n\n/**\n * The pages that have a dashboard of widgets, home first: `home` when its widgets are declared\n * (`pages.home.widgets` or `definition.dashboard`), then each other page whose component is the\n * built-in `dashboard`, in the order of `pages`.\n */\nexport function getDashboardPages(definition: DashboardsOf): string[] {\n const home = definition.pages?.[HOME_PAGE];\n const hasHome =\n definition.dashboard !== undefined ||\n (home?.component === DASHBOARD_COMPONENT && home.widgets !== undefined);\n return [\n ...(hasHome ? [HOME_PAGE] : []),\n ...Object.entries(definition.pages ?? {})\n .filter(([id, page]) => id !== HOME_PAGE && page.component === DASHBOARD_COMPONENT)\n .map(([id]) => id),\n ];\n}\n\n/**\n * The period of the dashboard of a page (decision 0084): the `period` of a page whose component is\n * the built-in `dashboard`. For the home page, `pages.home.period` when set, else that of\n * `definition.dashboard`, its shorthand. `undefined` without one.\n */\nexport function getDashboardPeriod(\n definition: DashboardsOf,\n page: string = HOME_PAGE,\n): OverviewPeriod | undefined {\n const own = definition.pages?.[page];\n if (own?.component === DASHBOARD_COMPONENT && own.period !== undefined) {\n return own.period;\n }\n return page === HOME_PAGE ? definition.dashboard?.period : undefined;\n}\n\n/**\n * The id of the list's `date-range` filter that the period of the summary of a resource sets\n * (decision 0084): its `period.filter`, or the first `date-range` filter of the list. `null`\n * without a period, or without such a filter.\n */\nexport function getSummaryPeriodFilter(\n resource: Pick<ResourceInput, 'summary' | 'list'>,\n): string | null {\n const period = resource.summary?.period;\n if (period === undefined) {\n return null;\n }\n const filters = (resource.list?.filters ?? []).filter((filter) => filter.type === 'date-range');\n const id = period.filter ?? filters[0]?.id;\n return filters.some((filter) => filter.id === id) ? (id ?? null) : null;\n}\n\n/** The parts of a definition that declare summaries: its resources. */\ntype SummariesOf = Pick<DefinitionInput, 'resources'>;\n\n/**\n * The widgets of the summary above the list of a resource, in order (decision 0084): its\n * `summary.widgets`. Empty for a resource without a summary, or that doesn't exist.\n */\nexport function getSummaryWidgets(definition: SummariesOf, resource: string): Widget[] {\n return (\n definition.resources.find((candidate) => candidate.id === resource)?.summary?.widgets ?? []\n );\n}\n\n/** The ids of the resources that have a summary above their list, in the order of `resources`. */\nexport function getSummaryResources(definition: SummariesOf): string[] {\n return definition.resources\n .filter((resource) => resource.summary !== undefined)\n .map((resource) => resource.id);\n}\n\n/** The query of a list that a widget of its summary gets: its filters and its search. */\nexport type WidgetListQuery = Pick<ListQuery, 'filter' | 'q'>;\n\n/**\n * Where a widget with data of its own is asked for (decisions 0064 and 0084): on a dashboard page,\n * or in the summary of a resource, with the query of its list.\n */\nexport interface WidgetDataRequest {\n /** The id of the dashboard page of the widget, in `pages`. Defaults to `home`. */\n page?: string;\n /** The resource whose summary holds the widget. With it, `page` is left out. */\n resource?: string;\n /** In a summary: the filters and the search of the list, when the widget follows it. */\n query?: WidgetListQuery;\n /** The period chosen in the overview, unless the widget has `settings.period: false`. */\n period?: WidgetPeriod;\n}\n\n/** Writes the period of a widget: `period[option]`, `period[from]` and `period[to]`. */\nfunction appendPeriod(params: URLSearchParams, period: WidgetPeriod | undefined): URLSearchParams {\n if (period !== undefined) {\n params.set('period[option]', period.option);\n params.set('period[from]', period.from);\n params.set('period[to]', period.to);\n }\n return params;\n}\n\n/**\n * The query parameters of `GET /dashboard/widgets/{widget}`: `resource` and the filters and search\n * of the list (`filter[…]`, `q`) for a widget of a summary, or `page` for a dashboard page other\n * than home, and the period of the overview (`period[option]`, `period[from]`, `period[to]`). The\n * widgets of the home page are asked for without `page`. The list's sort and paging are never\n * sent: `page` is the dashboard page.\n */\nexport function toWidgetDataParams(request: WidgetDataRequest = {}): URLSearchParams {\n if (request.resource !== undefined) {\n const params = new URLSearchParams({ resource: request.resource });\n toSearchParams({\n ...(request.query?.filter !== undefined && { filter: request.query.filter }),\n ...(request.query?.q !== undefined && { q: request.query.q }),\n }).forEach((value, key) => params.append(key, value));\n return appendPeriod(params, request.period);\n }\n const page = request.page ?? HOME_PAGE;\n return appendPeriod(new URLSearchParams(page !== HOME_PAGE ? { page } : {}), request.period);\n}\n\n/** What `readWidgetDataQuery()` reads: where the widget is, or the errors of its parameters. */\nexport type ReadWidgetDataQueryResult =\n | {\n page: string;\n resource?: undefined;\n query?: undefined;\n period: WidgetPeriod | null;\n errors?: undefined;\n }\n | {\n resource: string;\n query: WidgetListQuery;\n page?: undefined;\n period: WidgetPeriod | null;\n errors?: undefined;\n }\n | { errors: Record<string, string[]>; page?: undefined; resource?: undefined };\n\n/**\n * The period of a request, from `period[option]`, `period[from]` and `period[to]`: `null` without\n * any, and an error when one is missing or wrong, or when `from` is after `to`.\n */\nfunction readPeriod(params: URLSearchParams): WidgetPeriod | null | string {\n const option = params.get('period[option]');\n const from = params.get('period[from]');\n const to = params.get('period[to]');\n if (option === null && from === null && to === null) {\n return null;\n }\n if (!isOverviewPeriod(option)) {\n return 'The period must be one of 7d, 30d, 90d, month and year.';\n }\n if (!isDay(from) || !isDay(to) || from > to) {\n return 'The period needs its first and last days, from before to.';\n }\n return { option, from, to };\n}\n\n/**\n * Reads the query parameters of `GET /dashboard/widgets/{widget}` (decision 0084), as a backend\n * does: a widget of the summary of `resource`, with the filters and the search of its list, or of\n * the dashboard page `page`, `home` without it, and the period of the overview, or `null`. `page`\n * and `resource` together, an empty one, or a wrong period are errors keyed by `page`, `resource`\n * or `period`: a `422`.\n */\nexport function readWidgetDataQuery(params: URLSearchParams): ReadWidgetDataQueryResult {\n const page = params.get('page');\n const resource = params.get('resource');\n if (resource !== null && page !== null) {\n return { errors: { page: ['A widget is on a page or in a summary, not both.'] } };\n }\n if (resource === '') {\n return { errors: { resource: ['The resource must not be empty.'] } };\n }\n if (page === '') {\n return { errors: { page: ['The page must not be empty.'] } };\n }\n const period = readPeriod(params);\n if (typeof period === 'string') {\n return { errors: { period: [period] } };\n }\n if (resource !== null) {\n const { filter, q } = fromSearchParams(params);\n return {\n resource,\n query: { ...(filter !== undefined && { filter }), ...(q !== undefined && { q }) },\n period,\n };\n }\n return { page: page ?? HOME_PAGE, period };\n}\n"],"mappings":"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"}
package/dist/index.js CHANGED
@@ -11,7 +11,10 @@ import { checkRules, checkValues } from "./rules.js";
11
11
  import { getImageUrl, getItemImageField, getMediaLibraries } from "./libraries.js";
12
12
  import { ITEM_TYPE_KEY, getCreatableTypes, getItemType, getResourceType, getTypeFields, hasResourceTypes } from "./resourceTypes.js";
13
13
  import { fromSearchParams, isCursorPage, isFilterRange, matchesFilterRange, toSearchParams } from "./query.js";
14
- 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";
14
+ import { BUILT_IN_WIDGET_TYPES, GROUPED_WIDGET_TYPES, RESOURCE_WIDGET_TYPES, WIDGET_BREAKDOWN_MAX_ITEMS, WIDGET_LIST_MAX_ITEMS, WIDGET_RESERVED_QUERY_PARAMS, WIDGET_SERIES_PERIODS, checkWidgetData, followsList, followsPeriod, getWidgetResource, isBuiltInWidgetType } from "./widgets.js";
15
+ import { AGGREGATE_COUNT, AGGREGATE_MAX_POINTS, aggregateItems, getAggregateWidgetType, getFilterRange, listPeriods, nextPeriod, parseAggregateGroup, parseAggregateMeasure, readAggregateQuery, startOfPeriod, toAggregateParams } from "./aggregates.js";
16
+ import { OVERVIEW_PERIODS, PERIOD_PARAM, findPeriodOption, getDefaultPeriod, getPeriodRange, isDay, isOverviewPeriod, localDay, readPeriodOption } from "./periods.js";
17
+ import { DASHBOARD_COMPONENT, HOME_PAGE, getDashboardPages, getDashboardPeriod, getDashboardWidgets, getSummaryPeriodFilter, getSummaryResources, getSummaryWidgets, readWidgetDataQuery, toWidgetDataParams } from "./dashboards.js";
15
18
  import { lintDefinition } from "./lint.js";
16
19
  import { SEARCH_DEFAULT_LIMIT, SEARCH_MAX_LENGTH, SEARCH_MAX_LIMIT, SEARCH_MIN_LENGTH, isSearchableResource, readSearchQuery, toSearchQueryParams } from "./search.js";
17
20
  import { contextBefore, formatContextHeader, parseContextHeader } from "./context.js";
@@ -21,14 +24,14 @@ import { Abilities, Condition, Id, Option, RouteReference } from "./schemas/comm
21
24
  import { AddressSettings, BlockType, DateRangeSettings, DurationSettings, Field, LinkSettings, LinkTypeSetting, MoneySettings, RichTextSettings, RichTextStyle, Rule } from "./schemas/field.js";
22
25
  import { LayoutNode } from "./schemas/layout.js";
23
26
  import { Action, ActionConfirm, ActionPlacement, ActionScope } from "./schemas/action.js";
24
- import { Column, Filter, ListCalendar, ListDefinition } from "./schemas/list.js";
25
- import { Resource, ResourceFeatures, ResourceType } from "./schemas/resource.js";
27
+ import { Column, Filter, ListAggregates, ListCalendar, ListDefinition } from "./schemas/list.js";
28
+ import { BreakdownWidgetData, BreakdownWidgetItem, ListWidgetData, ListWidgetItem, OverviewPeriod, SeriesPoint, SeriesWidgetData, StatWidgetData, Widget, WidgetBadge, WidgetSettings, widgetDataSchemas } from "./schemas/widget.js";
29
+ import { Resource, ResourceFeatures, ResourceSummary, ResourceType, SummaryPeriod } from "./schemas/resource.js";
26
30
  import { DefinitionTheme, Theme, ThemeFont, ThemeFontFace, ThemeFontStylesheet, ThemeTokens, ToneInput, ToneValues } from "./schemas/theme.js";
27
- import { ListWidgetData, ListWidgetItem, SeriesPoint, SeriesWidgetData, StatWidgetData, Widget, WidgetBadge, WidgetSettings, widgetDataSchemas } from "./schemas/widget.js";
28
31
  import { Auth, AuthProvider, AuthToken, ContextOption, ContextParam, Definition, DefinitionContext, InterfaceLocale, MenuItem, Page, Uploads, User } from "./schemas/definition.js";
29
32
  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";
30
33
  import { BootConfig } from "./schemas/boot.js";
31
34
  import { createSchemaRegistry, namedSchemas } from "./schemas/index.js";
32
35
  import { validate, validateBootConfig, validateDefinition } from "./validate.js";
33
36
  import { createBootConfigJsonSchema, createComponentSchemas, createDefinitionJsonSchema, createOpenApiDocument, createThemeJsonSchema } from "./openapi.js";
34
- 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, IDS_FILTER, IDS_FILTER_LIMIT, ITEM_ACTION_ABILITIES, ITEM_TYPE_KEY, Id, InterfaceLocale, 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, ResourceType, 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, getCreatableTypes, getCurrencyDigits, getImageUrl, getItemImageField, getItemType, getLinkNewTab, getLinkTypes, getMediaLibraries, getNestedShape, getResourceType, getTypeFields, getValue, getWidgetResource, hasResourceTypes, isAddressPart, isBuiltInFieldType, isBuiltInItemAction, isBuiltInLink, isBuiltInLinkType, isBuiltInWidgetType, isCompoundField, 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 };
37
+ export { ADDRESS_PARTS, AGGREGATE_COUNT, AGGREGATE_MAX_POINTS, 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, BreakdownWidgetData, BreakdownWidgetItem, CONTEXT_HEADER, CONTEXT_PROBLEM_TYPE, CURRENCY_CODES, Column, Condition, ContextOption, ContextOptionsResponse, ContextParam, CursorPagination, DASHBOARD_COMPONENT, 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, GROUPED_WIDGET_TYPES, HOME_PAGE, IDS_FILTER, IDS_FILTER_LIMIT, ITEM_ACTION_ABILITIES, ITEM_TYPE_KEY, Id, InterfaceLocale, Item, ItemResponse, LayoutNode, LinkSettings, LinkTypeSetting, LinkValue, ListAggregates, ListCalendar, ListDefinition, ListResponse, ListWidgetData, ListWidgetItem, LocationValue, MediaInfo, MediaItem, MediaReference, MediaTransform, MenuItem, MoneySettings, MoneyValue, OVERVIEW_PERIODS, Option, OverviewPeriod, PASSWORD_CONFIRMATION_PROBLEM_TYPE, PERIOD_PARAM, 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, ResourceSummary, ResourceType, RichTextSettings, RichTextStyle, RouteReference, Rule, SEARCH_DEFAULT_LIMIT, SEARCH_MAX_LENGTH, SEARCH_MAX_LIMIT, SEARCH_MIN_LENGTH, SearchResponse, Selection, SeriesPoint, SeriesWidgetData, Session, StatWidgetData, StoredFile, SummaryPeriod, 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_BREAKDOWN_MAX_ITEMS, WIDGET_LIST_MAX_ITEMS, WIDGET_RESERVED_QUERY_PARAMS, WIDGET_SERIES_PERIODS, WebAuthnOptions, Widget, WidgetBadge, WidgetSettings, aggregateItems, checkRules, checkValues, checkWidgetData, contextBefore, createBootConfigJsonSchema, createComponentSchemas, createDefinitionJsonSchema, createOpenApiDocument, createSchemaRegistry, createThemeJsonSchema, evaluateCondition, findPeriodOption, followsList, followsPeriod, formatContextHeader, fromMinorUnits, fromSearchParams, getAddressRequiredParts, getAggregateWidgetType, getCreatableTypes, getCurrencyDigits, getDashboardPages, getDashboardPeriod, getDashboardWidgets, getDefaultPeriod, getFilterRange, getImageUrl, getItemImageField, getItemType, getLinkNewTab, getLinkTypes, getMediaLibraries, getNestedShape, getPeriodRange, getResourceType, getSummaryPeriodFilter, getSummaryResources, getSummaryWidgets, getTypeFields, getValue, getWidgetResource, hasResourceTypes, isAddressPart, isBuiltInFieldType, isBuiltInItemAction, isBuiltInLink, isBuiltInLinkType, isBuiltInWidgetType, isCompoundField, isCurrencyCode, isCursorPage, isDay, isExternalUrl, isFilled, isFilterRange, isOverviewPeriod, isPostalCode, isProblem, isSearchableResource, lintDefinition, listPeriods, localDay, matchesFilterRange, matchesRatio, mergeThemes, namedSchemas, nextPeriod, normalizePostalCode, parseAggregateGroup, parseAggregateMeasure, parseContextHeader, parseRatio, readAggregateQuery, readPeriodOption, readSearchQuery, readWidgetDataQuery, renderedCropSize, resolveLinkNewTab, startOfPeriod, toAggregateParams, toMinorUnits, toSearchParams, toSearchQueryParams, toWidgetDataParams, validate, validateBootConfig, validateDefinition, widgetDataSchemas };
@@ -1 +1 @@
1
- {"version":3,"file":"lint.d.ts","sourceRoot":"","sources":["../src/lint.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAoC,MAAM,WAAW,CAAC;AACnF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AA+LlD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,eAAe,GAAG,eAAe,EAAE,CAiD7E"}
1
+ {"version":3,"file":"lint.d.ts","sourceRoot":"","sources":["../src/lint.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACR,eAAe,EAMlB,MAAM,WAAW,CAAC;AACnB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAqQlD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,eAAe,GAAG,eAAe,EAAE,CAuF7E"}
package/dist/lint.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { ITEM_TYPE_KEY } from "./resourceTypes.js";
2
- import { RESOURCE_WIDGET_TYPES, WIDGET_RESERVED_QUERY_PARAMS, isBuiltInWidgetType } from "./widgets.js";
2
+ import { GROUPED_WIDGET_TYPES, RESOURCE_WIDGET_TYPES, WIDGET_RESERVED_QUERY_PARAMS, getWidgetResource, isBuiltInWidgetType } from "./widgets.js";
3
+ import { parseAggregateGroup, parseAggregateMeasure } from "./aggregates.js";
4
+ import { DASHBOARD_COMPONENT, HOME_PAGE, getSummaryPeriodFilter } from "./dashboards.js";
3
5
  //#region src/lint.ts
4
6
  function fieldNames(fields) {
5
7
  return new Set(fields.map((field) => field.name));
@@ -72,6 +74,58 @@ function allFields(resource, path) {
72
74
  path: `${path}.types.${typeIndex}.fields.${index}`
73
75
  })))];
74
76
  }
77
+ /** Field types whose values can be summed: numbers, and amounts of `money` of one currency. */
78
+ var SUMMABLE_TYPES = [
79
+ "number",
80
+ "range",
81
+ "duration",
82
+ "money"
83
+ ];
84
+ /** Field types whose days can be grouped by. */
85
+ var DATE_TYPES = ["date", "datetime"];
86
+ /** Field types whose values are structures that can't be grouped by. */
87
+ var UNGROUPABLE_TYPES = [
88
+ "richtext",
89
+ "media",
90
+ "image",
91
+ "file",
92
+ "group",
93
+ "repeater",
94
+ "json",
95
+ "embed",
96
+ "location",
97
+ "address",
98
+ "link",
99
+ "daterange",
100
+ "money"
101
+ ];
102
+ /**
103
+ * The aggregates of a list (decision 0084): each one names a field of the resource that the user
104
+ * can view, `sum` a number or `money` of one currency, `dates` a date, `groupBy` a value.
105
+ */
106
+ function checkAggregates(resource, path, issues) {
107
+ const aggregates = resource.list?.aggregates;
108
+ if (aggregates === void 0) return;
109
+ const fields = allFields(resource, path).map(({ field }) => field);
110
+ const check = (key, accepts) => {
111
+ (aggregates[key] ?? []).forEach((name, index) => {
112
+ const issuePath = `${path}.list.aggregates.${key}.${index}`;
113
+ const field = fields.find((candidate) => candidate.name === name);
114
+ const message = field === void 0 ? `No field named \`${name}\`.` : field.abilities?.view === false ? `The user can't view \`${name}\`: it can't be aggregated.` : accepts(field);
115
+ if (message !== null) issues.push({
116
+ path: issuePath,
117
+ message
118
+ });
119
+ });
120
+ };
121
+ check("sum", (field) => {
122
+ if (!SUMMABLE_TYPES.includes(field.type)) return `\`${field.name}\` can't be summed: only \`number\`, \`range\`, \`duration\` and \`money\` fields can.`;
123
+ const currency = field.settings?.currency;
124
+ return field.type === "money" && typeof currency !== "string" ? `\`${field.name}\` can't be summed: amounts add up only in one \`currency\`.` : null;
125
+ });
126
+ check("dates", (field) => DATE_TYPES.includes(field.type) ? null : `\`${field.name}\` must be a \`date\` or a \`datetime\` to be grouped by period.`);
127
+ check("groupBy", (field) => UNGROUPABLE_TYPES.includes(field.type) ? `The items can't be grouped by a \`${field.type}\` field.` : null);
128
+ }
75
129
  function checkResource(resource, path, issues) {
76
130
  const names = fieldNames(resource.fields);
77
131
  if (names.size !== resource.fields.length) issues.push({
@@ -110,6 +164,7 @@ function checkResource(resource, path, issues) {
110
164
  message: `The calendar needs a \`date-range\` filter \`${filter}\` in the list.`
111
165
  });
112
166
  }
167
+ checkAggregates(resource, path, issues);
113
168
  (resource.actions ?? []).forEach((action, index) => {
114
169
  if (action.layout !== void 0) checkLayout(action.layout, fieldNames(action.fields ?? []), `${path}.actions.${index}.layout`, issues);
115
170
  });
@@ -147,6 +202,21 @@ function lintDefinition(definition) {
147
202
  const libraries = definition.resources.filter((resource) => resource.kind === "media").map((resource) => resource.id);
148
203
  definition.resources.forEach((resource, index) => {
149
204
  checkResource(resource, `resources.${index}`, issues);
205
+ if (resource.summary !== void 0) {
206
+ const summaryPath = `resources.${index}.summary`;
207
+ const period = resource.summary.period;
208
+ if (period !== void 0) {
209
+ checkPeriod(period, `${summaryPath}.period`, issues);
210
+ if (getSummaryPeriodFilter(resource) === null) issues.push({
211
+ path: `${summaryPath}.period${period.filter !== void 0 ? ".filter" : ""}`,
212
+ message: period.filter !== void 0 ? `The list of \`${resource.id}\` has no \`date-range\` filter \`${period.filter}\`.` : `The period of a summary is a \`date-range\` filter of the list of \`${resource.id}\`: it has none.`
213
+ });
214
+ }
215
+ checkWidgets(definition, resource.summary.widgets, `${summaryPath}.widgets`, issues, {
216
+ summaryOf: resource.id,
217
+ hasPeriod: period !== void 0
218
+ });
219
+ }
150
220
  allFields(resource, `resources.${index}`).forEach(({ field, path }) => {
151
221
  if (field.type === "relation" && typeof field.resource === "string" && !resourceIds.has(field.resource)) issues.push({
152
222
  path: `${path}.resource`,
@@ -165,40 +235,194 @@ function lintDefinition(definition) {
165
235
  message: `No resource of kind \`media\` named \`${id}\`.`
166
236
  });
167
237
  });
238
+ if (field.transforms === false) {
239
+ if (field.ratios !== void 0 && field.ratios.length > 0) issues.push({
240
+ path: `${path}.ratios`,
241
+ message: "A field without transforms has no editor to suggest ratios."
242
+ });
243
+ field.rules?.forEach((rule, ruleIndex) => {
244
+ if (rule.rule === "crop") issues.push({
245
+ path: `${path}.rules.${String(ruleIndex)}`,
246
+ message: "A field without transforms keeps no crop for the `crop` rule."
247
+ });
248
+ });
249
+ }
168
250
  }
169
251
  });
170
252
  });
171
- checkWidgets(definition, issues);
253
+ checkDashboards(definition, issues);
172
254
  return issues;
173
255
  }
256
+ /**
257
+ * The dashboards (decision 0084): the widgets of each page whose component is the built-in
258
+ * `dashboard`, and those of `dashboard`, the shorthand of the home page, unless `pages.home` has
259
+ * its own, which can't come with them. Only a `dashboard` page has widgets.
260
+ */
261
+ function checkDashboards(definition, issues) {
262
+ const home = definition.pages?.[HOME_PAGE];
263
+ const homePeriod = (home?.component === "dashboard" ? home.period : void 0) ?? definition.dashboard?.period;
264
+ Object.entries(definition.pages ?? {}).forEach(([id, page]) => {
265
+ if (page.period !== void 0) {
266
+ if (page.component !== "dashboard") issues.push({
267
+ path: `pages.${id}.period`,
268
+ message: `Only a \`${DASHBOARD_COMPONENT}\` page has a period.`
269
+ });
270
+ else checkPeriod(page.period, `pages.${id}.period`, issues);
271
+ }
272
+ if (page.widgets === void 0) return;
273
+ if (page.component !== "dashboard") {
274
+ issues.push({
275
+ path: `pages.${id}.widgets`,
276
+ message: `Only a \`${DASHBOARD_COMPONENT}\` page has widgets.`
277
+ });
278
+ return;
279
+ }
280
+ checkWidgets(definition, page.widgets, `pages.${id}.widgets`, issues, { hasPeriod: (id === "home" ? homePeriod : page.period) !== void 0 });
281
+ });
282
+ if (definition.dashboard === void 0) return;
283
+ if (definition.dashboard.period !== void 0) {
284
+ if (home?.component === "dashboard" && home.period !== void 0) issues.push({
285
+ path: "dashboard.period",
286
+ message: `\`pages.${HOME_PAGE}.period\` replaces it: set only one.`
287
+ });
288
+ else checkPeriod(definition.dashboard.period, "dashboard.period", issues);
289
+ }
290
+ if (home?.component === "dashboard" && home.widgets !== void 0) {
291
+ if (definition.dashboard.widgets.length > 0) issues.push({
292
+ path: "dashboard.widgets",
293
+ message: `\`pages.${HOME_PAGE}.widgets\` replaces them: set only one.`
294
+ });
295
+ return;
296
+ }
297
+ checkWidgets(definition, definition.dashboard.widgets, "dashboard.widgets", issues, { hasPeriod: homePeriod !== void 0 });
298
+ }
299
+ /** A period (decision 0084): its options once each, and its default among them. */
300
+ function checkPeriod(period, path, issues) {
301
+ if (new Set(period.options).size !== period.options.length) issues.push({
302
+ path: `${path}.options`,
303
+ message: "Each period is offered once."
304
+ });
305
+ if (period.default !== void 0 && !period.options.includes(period.default)) issues.push({
306
+ path: `${path}.default`,
307
+ message: `\`${period.default}\` isn't one of the options.`
308
+ });
309
+ }
174
310
  var FILTER_PARAM = /^filter\[([^\]]+)\]/;
311
+ /** The settings of a widget that go with a `resource`. */
312
+ var RESOURCE_SETTINGS = [
313
+ "query",
314
+ "measure",
315
+ "group",
316
+ "target"
317
+ ];
318
+ /**
319
+ * The measure and the group of a widget on a resource (decision 0084): a `sum:` and a group name
320
+ * aggregates of its list, a `series` needs a period of a date, a `breakdown` a field of `groupBy`,
321
+ * and a `list` has neither.
322
+ */
323
+ function checkAggregateSettings(widget, resource, path, issues) {
324
+ const settings = widget.settings ?? {};
325
+ const aggregates = resource.list?.aggregates ?? {};
326
+ const grouped = GROUPED_WIDGET_TYPES.includes(widget.type);
327
+ if (widget.type === "list") {
328
+ ["measure", "group"].forEach((key) => {
329
+ if (settings[key] !== void 0) issues.push({
330
+ path: `${path}.settings.${key}`,
331
+ message: `A \`list\` shows items: it has no \`${key}\`.`
332
+ });
333
+ });
334
+ return;
335
+ }
336
+ if (settings.measure !== void 0) {
337
+ const measure = typeof settings.measure === "string" ? parseAggregateMeasure(settings.measure) : null;
338
+ if (measure === null) issues.push({
339
+ path: `${path}.settings.measure`,
340
+ message: "The measure must be `count` or `sum:{field}`."
341
+ });
342
+ else if (measure.type === "sum" && !(aggregates.sum ?? []).includes(measure.field)) issues.push({
343
+ path: `${path}.settings.measure`,
344
+ message: `The list of \`${resource.id}\` can't sum \`${measure.field}\`: it isn't in the \`sum\` of its aggregates.`
345
+ });
346
+ }
347
+ if (!grouped) {
348
+ if (settings.group !== void 0) issues.push({
349
+ path: `${path}.settings.group`,
350
+ message: `A \`${widget.type}\` isn't grouped: only a \`series\` and a \`breakdown\` are.`
351
+ });
352
+ return;
353
+ }
354
+ const group = typeof settings.group === "string" ? parseAggregateGroup(settings.group) : null;
355
+ if (widget.type === "series") {
356
+ if (group?.type !== "period") issues.push({
357
+ path: `${path}.settings.group`,
358
+ message: "A `series` on a resource needs a `group` on the period of a date: `day:created_at`."
359
+ });
360
+ else if (!(aggregates.dates ?? []).includes(group.field)) issues.push({
361
+ path: `${path}.settings.group`,
362
+ message: `The list of \`${resource.id}\` can't group by \`${group.field}\`: it isn't in the \`dates\` of its aggregates.`
363
+ });
364
+ return;
365
+ }
366
+ if (group?.type !== "field") issues.push({
367
+ path: `${path}.settings.group`,
368
+ message: "A `breakdown` on a resource needs a `group` on a field: `status`."
369
+ });
370
+ else if (!(aggregates.groupBy ?? []).includes(group.field)) issues.push({
371
+ path: `${path}.settings.group`,
372
+ message: `The list of \`${resource.id}\` can't group by \`${group.field}\`: it isn't in the \`groupBy\` of its aggregates.`
373
+ });
374
+ }
175
375
  /**
176
- * The widgets of the dashboard (decision 0064): unique ids, and the built-in `stat` and `list` on
177
- * a resource that exists, with filters of its list. A `stat` counts the items of the list, so the
178
- * list can't be paged with cursors, which give no total.
376
+ * The widgets of a dashboard or of the summary of a resource (decisions 0064 and 0084): unique ids,
377
+ * and the built-in types on a resource that exists, with filters of its list and aggregates it
378
+ * declares. A `stat` that counts reads the total of the list, so the list can't be paged with
379
+ * cursors, which give no total. Only the widgets of a summary follow its list (`followsList`): those
380
+ * on its resource, and those with data of their own.
179
381
  */
180
- function checkWidgets(definition, issues) {
382
+ function checkWidgets(definition, widgets, widgetsPath, issues, { summaryOf, hasPeriod = false } = {}) {
181
383
  const ids = /* @__PURE__ */ new Set();
182
- (definition.dashboard?.widgets ?? []).forEach((widget, index) => {
183
- const path = `dashboard.widgets.${index}`;
384
+ widgets.forEach((widget, index) => {
385
+ const path = `${widgetsPath}.${index}`;
184
386
  if (ids.has(widget.id)) issues.push({
185
387
  path: `${path}.id`,
186
388
  message: `Duplicate widget id \`${widget.id}\`.`
187
389
  });
188
390
  ids.add(widget.id);
391
+ if (widget.settings?.followsList !== void 0) {
392
+ const other = getWidgetResource(widget)?.resource;
393
+ if (summaryOf === void 0) issues.push({
394
+ path: `${path}.settings.followsList`,
395
+ message: "Only the widgets of the summary of a resource follow its list."
396
+ });
397
+ else if (other !== void 0 && other !== summaryOf) issues.push({
398
+ path: `${path}.settings.followsList`,
399
+ message: `A widget on \`${other}\` doesn't follow the list of \`${summaryOf}\`.`
400
+ });
401
+ }
189
402
  if (!isBuiltInWidgetType(widget.type)) return;
190
403
  const settings = widget.settings ?? {};
191
- if (!(typeof settings.resource === "string")) {
192
- if (settings.query !== void 0) issues.push({
193
- path: `${path}.settings.query`,
194
- message: "`query` goes with a `resource`."
404
+ const onResource = typeof settings.resource === "string";
405
+ if (settings.period !== void 0 && !hasPeriod) issues.push({
406
+ path: `${path}.settings.period`,
407
+ message: `Its ${summaryOf !== void 0 ? "summary" : "dashboard"} has no \`period\`.`
408
+ });
409
+ if (!onResource) {
410
+ if (typeof settings.period === "string") issues.push({
411
+ path: `${path}.settings.period`,
412
+ message: "`period` names a `date-range` filter of the list of its `resource`: without one, it can only be `false`."
413
+ });
414
+ RESOURCE_SETTINGS.forEach((key) => {
415
+ if (settings[key] !== void 0) issues.push({
416
+ path: `${path}.settings.${key}`,
417
+ message: `\`${key}\` goes with a \`resource\`.`
418
+ });
195
419
  });
196
420
  return;
197
421
  }
198
422
  if (!RESOURCE_WIDGET_TYPES.includes(widget.type)) {
199
423
  issues.push({
200
424
  path: `${path}.settings.resource`,
201
- message: `A \`${widget.type}\` widget has data of its own: only \`stat\` and \`list\` read a resource.`
425
+ message: `A \`${widget.type}\` widget has data of its own: it can't read a resource.`
202
426
  });
203
427
  return;
204
428
  }
@@ -210,9 +434,19 @@ function checkWidgets(definition, issues) {
210
434
  });
211
435
  return;
212
436
  }
213
- if (widget.type === "stat" && resource.list?.pagination === "cursor") issues.push({
437
+ if (settings.target !== void 0 && widget.type !== "stat") issues.push({
438
+ path: `${path}.settings.target`,
439
+ message: "Only a `stat` has a `target`."
440
+ });
441
+ checkAggregateSettings(widget, resource, path, issues);
442
+ const sums = typeof settings.measure === "string" && settings.measure.startsWith("sum:");
443
+ if (widget.type === "stat" && !sums && resource.list?.pagination === "cursor") issues.push({
214
444
  path: `${path}.settings.resource`,
215
- message: `The list of \`${resource.id}\` is paged with cursors and has no total: it can't feed a \`stat\`.`
445
+ message: `The list of \`${resource.id}\` is paged with cursors and has no total: it can't feed a \`stat\` that counts.`
446
+ });
447
+ if (typeof settings.period === "string" && !(resource.list?.filters ?? []).some((filter) => filter.id === settings.period && filter.type === "date-range")) issues.push({
448
+ path: `${path}.settings.period`,
449
+ message: `The list of \`${resource.id}\` has no \`date-range\` filter \`${settings.period}\`.`
216
450
  });
217
451
  const filters = new Set((resource.list?.filters ?? []).map((filter) => filter.id));
218
452
  Object.keys(settings.query ?? {}).forEach((key) => {