derive-dashboards 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +5 -3
  2. package/dist/cache.mjs +2 -1
  3. package/dist/cli/add.mjs +130 -0
  4. package/dist/cli/cli.mjs +14 -12
  5. package/dist/cli/config.mjs +12 -1
  6. package/dist/cli/doctor.mjs +162 -0
  7. package/dist/cli/init.mjs +3 -2
  8. package/dist/cli/json.mjs +21 -0
  9. package/dist/cli/layers.mjs +33 -0
  10. package/dist/core/document/display.d.mts +63 -0
  11. package/dist/core/document/display.mjs +139 -0
  12. package/dist/core/document/layout.mjs +1 -1
  13. package/dist/core/document/view-layout.d.mts +14 -0
  14. package/dist/core/document/view-layout.mjs +157 -0
  15. package/dist/core/engine/filter.mjs +2 -2
  16. package/dist/core/engine/leaf.mjs +9 -4
  17. package/dist/core/engine/members.mjs +1 -1
  18. package/dist/core/engine/version.d.mts +5 -4
  19. package/dist/core/engine/version.mjs +5 -4
  20. package/dist/core/error/codes.d.mts +4 -1
  21. package/dist/core/error/codes.mjs +4 -1
  22. package/dist/core/index.d.mts +12 -8
  23. package/dist/core/index.mjs +11 -7
  24. package/dist/core/model/member.mjs +5 -2
  25. package/dist/core/model/types.d.mts +13 -13
  26. package/dist/core/model/validate/drill.mjs +6 -15
  27. package/dist/core/model/validate/fields.mjs +130 -0
  28. package/dist/core/model/validate/index.mjs +11 -3
  29. package/dist/core/model/validate/known-members.mjs +133 -0
  30. package/dist/core/model/validate/known-nested.mjs +85 -0
  31. package/dist/core/model/validate/known.mjs +94 -0
  32. package/dist/core/model/validate/members.mjs +7 -4
  33. package/dist/core/model/validate/source.mjs +8 -1
  34. package/dist/core/policy/bind-query.d.mts +12 -0
  35. package/dist/core/policy/bind-query.mjs +53 -0
  36. package/dist/core/query/alias.mjs +11 -1
  37. package/dist/core/query/drill/selection.d.mts +7 -2
  38. package/dist/core/query/drill/selection.mjs +18 -15
  39. package/dist/core/query/filter.d.mts +6 -0
  40. package/dist/core/query/picks.d.mts +8 -2
  41. package/dist/core/query/picks.mjs +11 -4
  42. package/dist/core/query/segments.mjs +2 -1
  43. package/dist/core/result/columns.d.mts +10 -1
  44. package/dist/core/result/columns.mjs +27 -5
  45. package/dist/core/result/time-axis.d.mts +23 -0
  46. package/dist/core/result/time-axis.mjs +72 -0
  47. package/dist/core/result/types.d.mts +36 -1
  48. package/dist/core/schema/aliases.d.mts +7 -0
  49. package/dist/core/schema/aliases.mjs +77 -0
  50. package/dist/core/schema/answer-parts.mjs +23 -1
  51. package/dist/core/schema/answers.d.mts +204 -0
  52. package/dist/core/schema/answers.mjs +2 -0
  53. package/dist/core/schema/index.d.mts +3 -2
  54. package/dist/core/schema/index.mjs +3 -2
  55. package/dist/core/schema/query.d.mts +81 -0
  56. package/dist/core/schema/query.mjs +9 -5
  57. package/dist/core/schema/tools.d.mts +2 -0
  58. package/dist/core/schema/tools.mjs +27 -1
  59. package/dist/core/time/bucket.mjs +8 -2
  60. package/dist/core/types/api.d.mts +7 -1
  61. package/dist/core/types/api.mjs +1 -1
  62. package/dist/dashboards.mjs +4 -0
  63. package/dist/drill-change.mjs +1 -1
  64. package/dist/drill-seal.mjs +1 -0
  65. package/dist/editing.mjs +2 -2
  66. package/dist/endpoints/dashboards.mjs +17 -2
  67. package/dist/endpoints/index.d.mts +15 -2
  68. package/dist/endpoints/meta.mjs +10 -1
  69. package/dist/execute.mjs +32 -17
  70. package/dist/handler.mjs +5 -1
  71. package/dist/index.mjs +6 -1
  72. package/dist/llms.txt +22 -0
  73. package/dist/mcp/format.mjs +42 -8
  74. package/dist/mcp/query.mjs +34 -4
  75. package/dist/postgres-store.mjs +1 -0
  76. package/dist/react/Canvas.mjs +28 -5
  77. package/dist/react/Cell.mjs +2 -1
  78. package/dist/react/Dashboard.d.mts +4 -0
  79. package/dist/react/Dashboard.mjs +27 -4
  80. package/dist/react/DashboardList.mjs +22 -22
  81. package/dist/react/DashboardListRow.mjs +49 -0
  82. package/dist/react/Discard.mjs +5 -2
  83. package/dist/react/Editing.mjs +19 -5
  84. package/dist/react/FilterBar.d.mts +7 -9
  85. package/dist/react/Grid.mjs +7 -19
  86. package/dist/react/Header.mjs +1 -1
  87. package/dist/react/History.mjs +5 -0
  88. package/dist/react/ReadFailed.mjs +23 -0
  89. package/dist/react/Spaces.mjs +15 -1
  90. package/dist/react/Tile.d.mts +2 -0
  91. package/dist/react/Tile.mjs +45 -10
  92. package/dist/react/_virtual/_rolldown/runtime.mjs +12 -0
  93. package/dist/react/arrange-steps.mjs +16 -13
  94. package/dist/react/arrange.mjs +10 -3
  95. package/dist/react/builder/Calcs.mjs +35 -11
  96. package/dist/react/builder/FilterEditor.mjs +196 -0
  97. package/dist/react/builder/Filters.mjs +172 -116
  98. package/dist/react/builder/Formula.mjs +82 -0
  99. package/dist/react/builder/Groups.mjs +1 -0
  100. package/dist/react/builder/Preview.mjs +1 -1
  101. package/dist/react/builder/RangeEditor.mjs +184 -0
  102. package/dist/react/builder/Sections.mjs +41 -6
  103. package/dist/react/builder/Time.mjs +138 -60
  104. package/dist/react/builder/Values.mjs +85 -0
  105. package/dist/react/builder/WidgetBuilder.mjs +50 -49
  106. package/dist/react/builder/base.d.mts +5 -0
  107. package/dist/react/builder/base.mjs +33 -8
  108. package/dist/react/builder/calc.mjs +15 -1
  109. package/dist/react/builder/escape.d.mts +1 -0
  110. package/dist/react/builder/escape.mjs +62 -0
  111. package/dist/react/builder/filter-tree.d.mts +9 -0
  112. package/dist/react/builder/filter-tree.mjs +186 -0
  113. package/dist/react/builder/formula-parse.d.mts +18 -0
  114. package/dist/react/builder/formula-parse.mjs +136 -0
  115. package/dist/react/builder/labels.d.mts +1 -1
  116. package/dist/react/builder/state.d.mts +2 -1
  117. package/dist/react/builder/state.mjs +23 -37
  118. package/dist/react/builder/useBuilder.d.mts +12 -1
  119. package/dist/react/builder/useBuilder.mjs +6 -3
  120. package/dist/react/builder/words.d.mts +59 -0
  121. package/dist/react/builder/words.mjs +73 -0
  122. package/dist/react/context.d.mts +15 -1
  123. package/dist/react/context.mjs +9 -3
  124. package/dist/react/drill/Bars.mjs +2 -2
  125. package/dist/react/drill/props.mjs +2 -1
  126. package/dist/react/drill/useDrill.d.mts +1 -1
  127. package/dist/react/drill/words.d.mts +3 -0
  128. package/dist/react/drill/words.mjs +2 -0
  129. package/dist/react/english.mjs +20 -5
  130. package/dist/react/filters/bar.d.mts +12 -0
  131. package/dist/react/filters/bar.mjs +135 -0
  132. package/dist/react/filters/calendar.mjs +193 -0
  133. package/dist/react/filters/chip.mjs +174 -0
  134. package/dist/react/filters/context.d.mts +22 -0
  135. package/dist/react/filters/context.mjs +78 -0
  136. package/dist/react/filters/dates.mjs +89 -0
  137. package/dist/react/filters/days.d.mts +36 -0
  138. package/dist/react/filters/days.mjs +87 -0
  139. package/dist/react/filters/field-step.mjs +81 -0
  140. package/dist/react/filters/hooks.d.mts +34 -0
  141. package/dist/react/filters/hooks.mjs +94 -0
  142. package/dist/react/filters/listbox.mjs +131 -0
  143. package/dist/react/filters/logic.d.mts +59 -0
  144. package/dist/react/filters/logic.mjs +109 -0
  145. package/dist/react/filters/menu-search.mjs +211 -0
  146. package/dist/react/filters/menu.mjs +85 -0
  147. package/dist/react/filters/number.mjs +127 -0
  148. package/dist/react/filters/numbers.d.mts +47 -0
  149. package/dist/react/filters/numbers.mjs +151 -0
  150. package/dist/react/filters/operator.mjs +104 -0
  151. package/dist/react/filters/phone.mjs +104 -0
  152. package/dist/react/filters/popover.d.mts +19 -0
  153. package/dist/react/filters/popover.mjs +153 -0
  154. package/dist/react/filters/rules.d.mts +8 -0
  155. package/dist/react/filters/rules.mjs +55 -0
  156. package/dist/react/filters/sheet.mjs +196 -0
  157. package/dist/react/filters/state.mjs +132 -0
  158. package/dist/react/filters/suggest.d.mts +47 -0
  159. package/dist/react/filters/suggest.mjs +97 -0
  160. package/dist/react/filters/values.mjs +166 -0
  161. package/dist/react/filters/words.d.mts +81 -0
  162. package/dist/react/filters/words.mjs +73 -0
  163. package/dist/react/format.mjs +11 -4
  164. package/dist/react/index.d.mts +15 -6
  165. package/dist/react/index.mjs +10 -4
  166. package/dist/react/messages.d.mts +34 -2
  167. package/dist/react/place.mjs +7 -3
  168. package/dist/react/renderers/index.d.mts +3 -21
  169. package/dist/react/renderers/index.mjs +68 -6
  170. package/dist/react/renderers/list.d.mts +2 -1
  171. package/dist/react/renderers/list.mjs +9 -12
  172. package/dist/react/renderers/props.d.mts +26 -0
  173. package/dist/react/scope.d.mts +4 -0
  174. package/dist/react/scope.mjs +19 -2
  175. package/dist/react/series-slots.d.mts +37 -0
  176. package/dist/react/series-slots.mjs +71 -0
  177. package/dist/react/series.d.mts +39 -9
  178. package/dist/react/series.mjs +144 -47
  179. package/dist/react/theme.css +930 -19
  180. package/dist/react/useBoard.d.mts +2 -0
  181. package/dist/react/useDashboard.d.mts +3 -0
  182. package/dist/react/useDashboard.mjs +6 -0
  183. package/dist/react/view-grid.mjs +16 -0
  184. package/dist/recharts/axes.mjs +28 -0
  185. package/dist/recharts/axis.mjs +84 -0
  186. package/dist/recharts/bar.d.mts +7 -0
  187. package/dist/recharts/bar.mjs +141 -0
  188. package/dist/recharts/charts.d.mts +4 -5
  189. package/dist/recharts/charts.mjs +2 -208
  190. package/dist/recharts/index.d.mts +3 -1
  191. package/dist/recharts/index.mjs +4 -1
  192. package/dist/recharts/line.d.mts +2 -0
  193. package/dist/recharts/line.mjs +112 -0
  194. package/dist/recharts/marks.mjs +47 -18
  195. package/dist/recharts/parts.mjs +103 -0
  196. package/dist/recharts/table.mjs +71 -0
  197. package/dist/records-read.mjs +1 -1
  198. package/dist/registry/filter-bar.json +26 -0
  199. package/dist/skills/derive-dashboards/SKILL.md +69 -0
  200. package/dist/store/apply.mjs +3 -1
  201. package/package.json +6 -2
  202. package/dist/react/FilterBar.mjs +0 -119
@@ -24,6 +24,7 @@ function spanOf(range) {
24
24
  /** A column as a selection reads it: its id, member and grain only. */
25
25
  const slim = (c) => ({
26
26
  id: c.id,
27
+ ...c.role === void 0 ? {} : { role: c.role },
27
28
  label: "",
28
29
  type: c.type,
29
30
  ...c.member === void 0 ? {} : { member: c.member },
package/dist/editing.mjs CHANGED
@@ -3,7 +3,7 @@ import { adapterFor } from "./dashboards.mjs";
3
3
  import { HttpError } from "./http.mjs";
4
4
  import { dashboardResource } from "./owner.mjs";
5
5
  import { requestDashboardRow } from "./request-rows.mjs";
6
- import { draftClosed, draftRow } from "./store/rows.mjs";
6
+ import { draftClosed, draftOf, draftRow } from "./store/rows.mjs";
7
7
  import { createStore } from "./store/writer.mjs";
8
8
  import { principalTenant } from "derive-dashboards/core";
9
9
  // src/editing.ts
@@ -109,6 +109,6 @@ async function hasOpenDraft(rt, request, user, id) {
109
109
  const stored = adapter === void 0 ? null : await storedId(rt, request, user, id);
110
110
  if (adapter === void 0 || stored === null) return false;
111
111
  const row = await draftRow(adapter, stored, editorOf(user).author);
112
- return row !== null && row.state === "open";
112
+ return row !== null && row.state === "open" && draftOf(row).changes.length > 0;
113
113
  }
114
114
  export { draftDoc, editorOf, hasOpenDraft, ownUnpublished, rowId, storeFor, storedId, targetOf, unpublishedFor };
@@ -6,7 +6,7 @@ import { docFor } from "../tile-doc.mjs";
6
6
  import { runTile, streamTiles, tileExecution } from "../tiles.mjs";
7
7
  import { viewDashboard } from "./access.mjs";
8
8
  import { memberValues } from "./values.mjs";
9
- import { createDashEndpoint, documentLock } from "derive-dashboards/core";
9
+ import { createDashEndpoint, documentLock, parseMemberId, resolveDimension } from "derive-dashboards/core";
10
10
  // src/endpoints/dashboards.ts
11
11
  /** Which document the request names, as a drill names it. */
12
12
  function documentOf(a) {
@@ -55,7 +55,22 @@ function controlValues(rt, ctx, a) {
55
55
  return memberValues(x, {
56
56
  ...a,
57
57
  member: control.member
58
- });
58
+ }).then((page) => inDeclaredOrder(rt, control.member, page));
59
+ }
60
+ /** A page of values in the order the model declares them, when it declares a list. */
61
+ function inDeclaredOrder(rt, member, page) {
62
+ const source = parseMemberId(member)?.source;
63
+ const def = source === void 0 ? void 0 : resolveDimension(rt.options.model, source, member);
64
+ const declared = def?.dimension.kind === "string" && Array.isArray(def.dimension.values) ? def.dimension.values : void 0;
65
+ if (declared === void 0) return page;
66
+ const rank = (v) => {
67
+ const i = declared.findIndex((d) => d === v);
68
+ return i === -1 ? declared.length : i;
69
+ };
70
+ return {
71
+ ...page,
72
+ values: page.values.toSorted((x, y) => rank(x) - rank(y))
73
+ };
59
74
  }
60
75
  /** Running a dashboard's tiles, records and control values by reference. */
61
76
  function runEndpoints(rt) {
@@ -304,9 +304,11 @@ export declare function coreEndpoints(rt: Runtime): {
304
304
  };
305
305
  }, Omit<Answered, "cuts"> | {
306
306
  drill: import("derive-dashboards/core").AnswerDrill;
307
+ time?: import("derive-dashboards/core").TimeAxis;
307
308
  compare?: {
308
309
  rows: import("derive-dashboards/core").ResultRows;
309
310
  range: import("derive-dashboards/core").ResolvedRange;
311
+ time?: import("derive-dashboards/core").TimeAxis;
310
312
  };
311
313
  rows: import("derive-dashboards/core").ResultRows;
312
314
  columns: readonly import("derive-dashboards/core").ResultColumn[];
@@ -609,11 +611,17 @@ export declare function coreEndpoints(rt: Runtime): {
609
611
  draft?: true;
610
612
  }, import("derive-dashboards/core").ValuesResponse, "POST">;
611
613
  listDashboards: import("derive-dashboards/core").DashEndpoint<"/dashboards/list", Record<string, never>, {
612
- dashboards: {
614
+ dashboards: ({
613
615
  id: string;
614
616
  title: string;
617
+ description?: string;
615
618
  version: number;
616
- }[];
619
+ } | {
620
+ id: string;
621
+ title: string;
622
+ version: number;
623
+ unpublished: true;
624
+ })[];
617
625
  can: {
618
626
  create: boolean;
619
627
  };
@@ -651,6 +659,8 @@ export declare function coreEndpoints(rt: Runtime): {
651
659
  values?: readonly import("derive-dashboards/core").Primitive[] | "lookup";
652
660
  aggregate?: string;
653
661
  unit?: string;
662
+ tones?: Readonly<Record<string, "positive" | "negative" | "warning" | "neutral">>;
663
+ buckets?: readonly number[];
654
664
  }[];
655
665
  dimensions: {
656
666
  id: string;
@@ -659,6 +669,8 @@ export declare function coreEndpoints(rt: Runtime): {
659
669
  values?: readonly import("derive-dashboards/core").Primitive[] | "lookup";
660
670
  aggregate?: string;
661
671
  unit?: string;
672
+ tones?: Readonly<Record<string, "positive" | "negative" | "warning" | "neutral">>;
673
+ buckets?: readonly number[];
662
674
  }[];
663
675
  joins: {
664
676
  name: string;
@@ -672,6 +684,7 @@ export declare function coreEndpoints(rt: Runtime): {
672
684
  command: import("derive-dashboards/core/schema").JsonSchema;
673
685
  query: import("derive-dashboards/core/schema").JsonSchema;
674
686
  picks: import("derive-dashboards/core/schema").JsonSchema;
687
+ display: Record<string, import("derive-dashboards/core/schema").JsonSchema>;
675
688
  }, "GET">;
676
689
  memberValues: import("derive-dashboards/core").DashEndpoint<"/meta/values", {
677
690
  member: string;
@@ -31,7 +31,16 @@ function memberMeta(m) {
31
31
  kind: "dimension",
32
32
  ...base,
33
33
  type: dimensionType(m.def),
34
- ...staticValues(m.def)
34
+ ...staticValues(m.def),
35
+ ...hintsOf(m.def)
36
+ };
37
+ }
38
+ /** The hints a filter or a legend reads: value tones, a number's bucket edges and unit. */
39
+ function hintsOf(def) {
40
+ return {
41
+ ...def.tones === void 0 ? {} : { tones: def.tones },
42
+ ...def.buckets === void 0 ? {} : { buckets: def.buckets },
43
+ ...def.format?.unit === void 0 ? {} : { unit: def.format.unit }
35
44
  };
36
45
  }
37
46
  /** The joins a query can group by: to one row each, never to many. */
package/dist/execute.mjs CHANGED
@@ -4,7 +4,7 @@ import { macHex } from "./cursor-seal.mjs";
4
4
  import { adapterFor } from "./dashboards.mjs";
5
5
  import { withReader } from "./reading.mjs";
6
6
  import { logQuery } from "./store/log.mjs";
7
- import { canonical, isBound, markedRows, resultColumns } from "derive-dashboards/core";
7
+ import { bindQueryViewer, bindViewer, canonical, isBound, markedRows, resultColumns, withTime } from "derive-dashboards/core";
8
8
  import { EngineError, readQuery } from "derive-dashboards/core/engine";
9
9
  // src/execute.ts
10
10
  /** An answer as a client reads it: without what only the server reads. */
@@ -12,9 +12,13 @@ function wire(answer) {
12
12
  const { cuts: _cuts, ...rest } = answer;
13
13
  return rest;
14
14
  }
15
- function boundEntries(entries, what) {
16
- return entries.map((entry) => {
17
- if (!isBound(entry.filter)) throw new EngineError("FILTER_UNBOUND", `A ${what} that uses a viewer value or a variable is not supported yet.`);
15
+ function boundEntries(entries, what, principal) {
16
+ return entries.map((given) => {
17
+ const entry = {
18
+ ...given,
19
+ filter: bindViewer(given.filter, principal)
20
+ };
21
+ if (!isBound(entry.filter)) throw new EngineError("FILTER_UNBOUND", `A ${what} that uses a variable is not supported yet.`);
18
22
  return {
19
23
  ...entry,
20
24
  filter: entry.filter
@@ -30,21 +34,26 @@ function receiptFilter(bound) {
30
34
  ...bound.required.map((e) => e.filter)
31
35
  ] };
32
36
  }
33
- /** The query bound for the engine: no sensitive member, and no viewer value or variable left in the lock or required filters. */
37
+ /**
38
+ * The query bound for the engine: no sensitive member, and the signed-in viewer's values in
39
+ * place of every viewer reference (query, measure, lock and required filters). The bound query
40
+ * is what keys the cache, the receipt and a cursor, so two viewers never share an answer.
41
+ */
34
42
  function bind(x) {
35
43
  const { options } = x.rt;
36
44
  checkSensitive(options, x.principal, x.query);
37
- const lock = boundEntries(x.lock, "lock");
45
+ const query = bindQueryViewer(x.query, x.principal);
46
+ const lock = boundEntries(x.lock, "lock", x.principal);
38
47
  const required = boundEntries(options.compose?.required?.({
39
48
  principal: x.principal,
40
49
  calendar: x.calendar,
41
50
  ...x.dashboardId === void 0 ? {} : { dashboardId: x.dashboardId }
42
- }) ?? [], "required filter");
51
+ }) ?? [], "required filter", x.principal);
43
52
  const maxRows = options.query?.maxRows ?? 5e3;
44
53
  return {
45
54
  input: {
46
55
  model: options.model,
47
- query: x.query,
56
+ query,
48
57
  principal: x.principal,
49
58
  locks: lock,
50
59
  required,
@@ -77,19 +86,25 @@ async function compute(x, bound) {
77
86
  message: `The answer was cut at ${bound.maxRows} rows.`,
78
87
  path: []
79
88
  }] : [];
89
+ const columns = resultColumns(x.rt.options.model, x.query);
90
+ const timed = (rows, range) => withTime(columns, rows, {
91
+ range,
92
+ calendar: x.calendar
93
+ });
94
+ const before = compare === void 0 ? void 0 : {
95
+ ...timed(markedRows(x.query, compare), compare.range),
96
+ range: compare.range
97
+ };
80
98
  return {
81
- columns: resultColumns(x.rt.options.model, x.query),
82
- rows: markedRows(x.query, levels),
83
- ...compare === void 0 ? {} : { compare: {
84
- rows: markedRows(x.query, compare),
85
- range: compare.range
86
- } },
99
+ columns,
100
+ ...timed(markedRows(x.query, levels), value.range),
101
+ ...before === void 0 ? {} : { compare: before },
87
102
  status: truncated === true ? "truncated" : "complete",
88
103
  ...unreadable === true ? { unreadable } : {},
89
104
  ...cuts,
90
105
  receipt: {
91
106
  queryHash: await macHex(await x.rt.macKey, canonical({
92
- query: x.query,
107
+ query: bound.input.query,
93
108
  lock: bound.lock,
94
109
  required: bound.required
95
110
  })),
@@ -137,13 +152,13 @@ function answered(x) {
137
152
  const on = [...bound.lock, ...bound.required].map((e) => e.on);
138
153
  const key = {
139
154
  principal: x.principal,
140
- query: x.query,
155
+ query: bound.input.query,
141
156
  lock: bound.lock,
142
157
  required: bound.required,
143
158
  calendar: x.calendar,
144
159
  maxRows: bound.maxRows,
145
160
  now: x.now.getTime() - x.now.getTime() % quantum,
146
- sources: manifest(options.model, x.query, on)
161
+ sources: manifest(options.model, bound.input.query, on)
147
162
  };
148
163
  return cache.answer(key, () => compute(x, bound));
149
164
  }
package/dist/handler.mjs CHANGED
@@ -30,7 +30,7 @@ function checkOrigin(options, endpoint, request) {
30
30
  const origin = request.headers.get("origin");
31
31
  if (origin === null || origin === new URL(request.url).origin) return;
32
32
  if ((options.trustedOrigins ?? []).includes(origin)) return;
33
- throw new HttpError(403, "FORBIDDEN", `Requests from ${origin} are not trusted.`);
33
+ throw new HttpError(403, "FORBIDDEN", `Requests from ${origin} are not trusted. If that is your app, add it to deriveDashboards({ trustedOrigins: ["${origin}"] }).`);
34
34
  }
35
35
  async function readBody(request) {
36
36
  if (request.method === "GET") return Object.fromEntries(new URL(request.url).searchParams);
@@ -123,6 +123,10 @@ function errorOf(rt, error, request) {
123
123
  code: error.code,
124
124
  message: error.message
125
125
  } });
126
+ if (request.signal.aborted) return json(499, { error: {
127
+ code: "CANCELLED",
128
+ message: BASE_ERROR_CODES.CANCELLED.message
129
+ } });
126
130
  (rt.options.onError ?? console.error)(error, request);
127
131
  return json(500, { error: {
128
132
  code: "INTERNAL",
package/dist/index.mjs CHANGED
@@ -11,7 +11,7 @@ import { postgresConnection } from "./postgres-connection.mjs";
11
11
  import { postgresStore } from "./postgres-store.mjs";
12
12
  import { memoryStorage } from "./storage.mjs";
13
13
  import { SchemaMismatchError, createTables, schemaDiff } from "./store/create-tables.mjs";
14
- import { BASE_ERROR_CODES, defineModel, linkTemplateIssues } from "derive-dashboards/core";
14
+ import { BASE_ERROR_CODES, defineModel, documentDisplayIssues, linkTemplateIssues } from "derive-dashboards/core";
15
15
  import { drillModel } from "derive-dashboards/core/engine";
16
16
  import { loadDocument } from "derive-dashboards/core/schema";
17
17
  // src/index.ts
@@ -26,6 +26,11 @@ function checkedDashboards(options) {
26
26
  const problems = loaded.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
27
27
  throw new Error(`The dashboard "${d.key}" is not a valid document: ${problems}`);
28
28
  }
29
+ const wrong = documentDisplayIssues(loaded.doc);
30
+ if (wrong.length > 0) {
31
+ const problems = wrong.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
32
+ throw new Error(`The dashboard "${d.key}" has display options of the wrong type: ${problems}`);
33
+ }
29
34
  return {
30
35
  key: d.key,
31
36
  document: loaded.doc
package/dist/llms.txt ADDED
@@ -0,0 +1,22 @@
1
+ # Derive Dashboards
2
+
3
+ > Embedded, editable dashboards for TypeScript apps over your own Postgres: a semantic model of your tables, a server handler with tenancy and row policies, React dashboards with drill-in, editing and a built-in filter bar, a CLI, and MCP tools for agents. One npm package: `derive-dashboards`.
4
+
5
+ Install skill for coding agents: `npx skills add derive-to/dashboards --skill derive-dashboards` (skills/derive-dashboards/SKILL.md).
6
+
7
+ ## Docs
8
+
9
+ - [Quick start](https://github.com/derive-to/dashboards/blob/main/docs/quick-start.md): install, describe your data, mount the handler, show a dashboard, drill in.
10
+ - [Concepts](https://github.com/derive-to/dashboards/blob/main/docs/concepts.md): the model, measures, joins, tenancy and row policies, access, documents, drill-in.
11
+ - [Filters](https://github.com/derive-to/dashboards/blob/main/docs/filters.md): the built-in filter bar, theming, options, words, the shadcn copy, custom bars.
12
+ - [React](https://github.com/derive-to/dashboards/blob/main/docs/react.md): provider, Dashboard, editing UI, URL state, drill parts, widget builder.
13
+ - [CLI](https://github.com/derive-to/dashboards/blob/main/docs/cli.md): init, check, generate, create-tables, add, importing from dbt or Cube.
14
+ - [Endpoints](https://github.com/derive-to/dashboards/blob/main/docs/endpoints.md): every handler endpoint, its body and answer.
15
+ - [MCP](https://github.com/derive-to/dashboards/blob/main/docs/mcp.md): tools that let agents query and edit dashboards as themselves.
16
+ - [Store](https://github.com/derive-to/dashboards/blob/main/docs/store.md): where drafts, versions and history live.
17
+ - [A custom data layer](https://github.com/derive-to/dashboards/blob/main/docs/custom-data-layer.md): other databases, with the conformance kit.
18
+ - [Errors](https://github.com/derive-to/dashboards/blob/main/docs/errors.md): every error code and what to do.
19
+
20
+ ## Example
21
+
22
+ - [Acme](https://github.com/derive-to/dashboards/tree/main/examples/acme): a complete host (Hono, PGlite) with tenants, row policies, editing, filters and agents.
@@ -3,33 +3,67 @@ import { EngineError } from "derive-dashboards/core/engine";
3
3
  // src/mcp/format.ts
4
4
  /** The most rows a table shows the model; the rest are counted, and all are in the structured answer. */
5
5
  const SHOWN = 30;
6
- /** A cell as text: exact numbers as their digits, no value as a blank. */
7
- function cellText(cell) {
8
- if (cell === null || cell === void 0) return "";
6
+ /** At most one decimal, without a trailing ".0": 64.3, 12, 0.5. */
7
+ const short = (value) => String(Math.round(value * 10) / 10);
8
+ const DURATION = [
9
+ ["d", 86400],
10
+ ["h", 3600],
11
+ ["min", 60],
12
+ ["s", 1]
13
+ ];
14
+ /** A percent or a duration as a person reads it (64.3%, 3.2 d); anything else as its digits. */
15
+ function formatted(value, column) {
16
+ if (column?.format === "percent") return `${short(column.fraction === true ? value * 100 : value)}%`;
17
+ if (column?.format === "duration") {
18
+ const [unit, size] = DURATION.find(([, n]) => Math.abs(value) >= n) ?? DURATION[3];
19
+ return `${short(value / size)} ${unit}`;
20
+ }
21
+ }
22
+ /** A cell's number, for the formats that read it; undefined for text and blanks. */
23
+ const numberOf = (cell) => {
24
+ const value = typeof cell === "number" ? cell : typeof cell === "object" && cell !== null && "v" in cell ? Number(cell.v) : void 0;
25
+ return value === void 0 || Number.isNaN(value) ? void 0 : value;
26
+ };
27
+ /** A cell as raw text: exact numbers as their digits, no value as "none". */
28
+ function rawText(cell) {
29
+ if (cell === null || cell === void 0) return "none";
9
30
  if (typeof cell === "object" && "v" in cell) return String(cell.v);
10
31
  if (typeof cell === "string") return cell.replaceAll("|", "\\|");
11
32
  if (typeof cell === "number" || typeof cell === "boolean") return String(cell);
12
33
  return JSON.stringify(cell);
13
34
  }
35
+ /** A cell as text: percents and durations as people read them, everything else raw. */
36
+ function cellText(cell, column) {
37
+ const value = numberOf(cell);
38
+ return (value === void 0 ? void 0 : formatted(value, column)) ?? rawText(cell);
39
+ }
14
40
  /** Rows under their column labels, as a Markdown table, cut at SHOWN rows with a count. */
15
- function table(labels, rows) {
41
+ function table(labels, rows, columns) {
16
42
  if (rows.length === 0) return "No rows.";
17
43
  const lines = [
18
44
  `| ${labels.join(" | ")} |`,
19
45
  `| ${labels.map(() => "---").join(" | ")} |`,
20
- ...rows.slice(0, SHOWN).map((row) => `| ${row.map((c) => cellText(c)).join(" | ")} |`)
46
+ ...rows.slice(0, SHOWN).map((row) => `| ${row.map((c, i) => cellText(c, columns?.[i])).join(" | ")} |`)
21
47
  ];
22
48
  if (rows.length > SHOWN) lines.push(`\n${rows.length - SHOWN} more rows are in the structured answer.`);
23
49
  return lines.join("\n");
24
50
  }
51
+ /** An instant as a person reads it: the day alone at midnight, else the day and minute, UTC. */
52
+ function instantText(value) {
53
+ const at = new Date(value);
54
+ if (Number.isNaN(at.getTime())) return value;
55
+ const [day, time = ""] = at.toISOString().split("T");
56
+ const minute = time.slice(0, 5);
57
+ return minute === "00:00" ? day ?? value : `${day} ${minute} UTC`;
58
+ }
25
59
  /** A query's answer: its table, the comparison period's beside it, and whether it was cut. */
26
60
  function answerText(answer) {
27
61
  if (answer.unreadable === true) return "This viewer may not read the rows this question asks about.";
28
62
  const labels = answer.columns.map((c) => c.label);
29
- const parts = [table(labels, answer.rows)];
63
+ const parts = [table(labels, answer.rows, answer.columns)];
30
64
  if (answer.compare !== void 0) {
31
65
  const { from, to } = answer.compare.range;
32
- parts.push(`Compared with ${from} to ${to}:`, table(labels, answer.compare.rows));
66
+ parts.push(`Compared with ${instantText(from)} to ${instantText(to)}:`, table(labels, answer.compare.rows, answer.columns));
33
67
  }
34
68
  if (answer.status === "truncated") parts.push("The answer was cut at its row limit.");
35
69
  return parts.join("\n\n");
@@ -80,4 +114,4 @@ function refused(error, hint, onError = (e) => {
80
114
  isError: true
81
115
  };
82
116
  }
83
- export { answerText, ok, refused, table };
117
+ export { answerText, instantText, ok, refused, table };
@@ -2,11 +2,14 @@ import { HttpError } from "../http.mjs";
2
2
  import { drillRows } from "./drill.mjs";
3
3
  import { answerText, ok, table } from "./format.mjs";
4
4
  import { dashboardOf, resolveQuery, sourceOf } from "./resolve.mjs";
5
- import { drillStateSchema, picksSchema, wireQuerySchema } from "derive-dashboards/core/schema";
5
+ import { drillStateSchema, picksSchema, positional, wireQueryShape } from "derive-dashboards/core/schema";
6
6
  import { z } from "zod";
7
7
  // src/mcp/query.ts
8
8
  /** A question, with `kind` optional since there is only one kind. */
9
- const question = wireQuerySchema.extend({ kind: z.literal("aggregate").optional() });
9
+ const question = wireQueryShape.extend({ kind: z.literal("aggregate").optional() }).transform((query) => positional({
10
+ ...query,
11
+ kind: "aggregate"
12
+ }));
10
13
  const queryInput = z.strictObject({
11
14
  op: z.enum([
12
15
  "describe",
@@ -15,7 +18,7 @@ const queryInput = z.strictObject({
15
18
  "list",
16
19
  "open"
17
20
  ]).describe("describe: what can be asked (sources, measures, fields). ask: answer a question. rows: the records behind a question, or behind a mark (drill). list: the dashboards. open: one dashboard, every tile answered."),
18
- query: question.optional().describe("For ask and rows. Sources, measures and fields may be named by id or label. Ids: measures m0, m1...; dimensions d0, d1..."),
21
+ query: question.optional().describe("For ask and rows. Sources, measures and fields may be named by id or label. Give each measure, dimension and calc an id (m1, d1, c1...) and use those ids in order, rankBy and formulas."),
19
22
  source: z.string().optional().describe("For describe: one source only."),
20
23
  dashboard: z.string().optional().describe("For open: the dashboard's title or id."),
21
24
  filters: picksSchema.optional().describe("For open: values for the dashboard's filters, by control id."),
@@ -34,7 +37,34 @@ async function describe(c, only) {
34
37
  `Fields: ${s.dimensions.map((d) => `${d.label} (${d.id}, ${d.type})`).join("; ")}`,
35
38
  ...s.joins.length === 0 ? [] : [`Joins: ${s.joins.map((j) => `${j.label} (${j.name} to ${j.source})`).join("; ")}`]
36
39
  ].join("\n"));
37
- return ok(text.join("\n\n") || "Nothing this viewer may read.", { sources });
40
+ const example = exampleOf(sources[0]);
41
+ const body = [...text, ...example === void 0 ? [] : [example]].join("\n\n");
42
+ return ok(body || "Nothing this viewer may read.", { sources });
43
+ }
44
+ /**
45
+ * One question to copy: the first source's first measure, by a text field. The first text field
46
+ * usually names each row (one group per row), so a later one is the better grouping.
47
+ */
48
+ function exampleOf(source) {
49
+ const measure = source?.measures[0];
50
+ if (source === void 0 || measure === void 0) return void 0;
51
+ const text = source.dimensions.filter((d) => d.type === "string");
52
+ const group = text[1] ?? text[0];
53
+ const query = {
54
+ source: source.name,
55
+ measures: [{
56
+ id: "m0",
57
+ measure: measure.id
58
+ }],
59
+ ...group === void 0 ? {} : { dimensions: [{
60
+ id: "d0",
61
+ member: group.id
62
+ }] }
63
+ };
64
+ return `Ask like: ${JSON.stringify({
65
+ op: "ask",
66
+ query
67
+ })}`;
38
68
  }
39
69
  /** The question, every name turned into its id. */
40
70
  async function resolved(c, input) {
@@ -55,6 +55,7 @@ function runner(options, run, depth) {
55
55
  * Its `dd_` tables come from `generate` in your own schema, or from `createTables`.
56
56
  */
57
57
  function postgresStore(options) {
58
+ for (const name of ["run", "transaction"]) if (typeof options[name] !== "function") throw new TypeError(`postgresStore needs ${name === "run" ? "a run (a statement to rows as objects)" : "a transaction (fn) => Promise, so every store write is one transaction"}. See docs/quick-start.md, step 4, or use nodePostgres(pool).`);
58
59
  return sqlAdapter("postgres", runner(options, options.run, 0));
59
60
  }
60
61
  export { postgresStore };
@@ -1,7 +1,7 @@
1
1
  import { useDashboards } from "./context.mjs";
2
- import { FilterBar } from "./FilterBar.mjs";
3
2
  import { Grid } from "./Grid.mjs";
4
3
  import { Header } from "./Header.mjs";
4
+ import { Span, sharedSpan, spanKey } from "./Tile.mjs";
5
5
  import { linkTo } from "./view.mjs";
6
6
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
7
  // src/Canvas.tsx
@@ -45,6 +45,29 @@ function EmptyTab({ onAdd }) {
45
45
  })]
46
46
  });
47
47
  }
48
+ /** The zone the server read the tiles in, from any answer's receipt: the host's default included. */
49
+ function answeredZone(results) {
50
+ for (const result of results.values()) if (!("error" in result)) return result.receipt.calendar.timezone;
51
+ }
52
+ /** The host's filter bar (the built-in one by default), told the zone dates are read in. */
53
+ function Filters({ board, doc }) {
54
+ const Bar = useDashboards().components.FilterBar;
55
+ return /* @__PURE__ */ jsx(Bar, {
56
+ controls: doc.controls,
57
+ picks: board.view.picks,
58
+ onChange: board.view.setPicks,
59
+ timezone: doc.scope.timezone ?? answeredZone(board.tiles.results)
60
+ });
61
+ }
62
+ /** The span most tiles cover, said once under the filters; the tiles that cover it leave it out. */
63
+ function DashboardSpan({ results }) {
64
+ const shared = sharedSpan(results);
65
+ const one = [...results.values()].find((result) => spanKey(result) === shared);
66
+ return shared === void 0 || one === void 0 ? null : /* @__PURE__ */ jsx("div", {
67
+ className: "dd-span-all",
68
+ children: /* @__PURE__ */ jsx(Span, { result: one })
69
+ });
70
+ }
48
71
  /** The canvas: header, tabs, filters, and the grid with its marks. */
49
72
  function Canvas(props) {
50
73
  const { board, shown } = props;
@@ -71,11 +94,11 @@ function Canvas(props) {
71
94
  current: shown.tab,
72
95
  onSelect: view.setTab
73
96
  }),
74
- /* @__PURE__ */ jsx(FilterBar, {
75
- controls: shown.doc.controls,
76
- picks: view.picks,
77
- onChange: view.setPicks
97
+ /* @__PURE__ */ jsx(Filters, {
98
+ board,
99
+ doc: shown.doc
78
100
  }),
101
+ /* @__PURE__ */ jsx(DashboardSpan, { results: board.tiles.results }),
79
102
  edit.draft === void 0 || !emptyTab(shown) ? null : /* @__PURE__ */ jsx(EmptyTab, { onAdd: add }),
80
103
  /* @__PURE__ */ jsx(Grid, {
81
104
  doc: shown.doc,
@@ -99,7 +99,8 @@ const Cell = memo(function Cell(props) {
99
99
  loading: props.loading,
100
100
  controlLabels: props.controlLabels,
101
101
  actions,
102
- badge
102
+ badge,
103
+ sharedSpan: props.sharedSpan
103
104
  })]
104
105
  });
105
106
  }, sameCell);
@@ -29,4 +29,8 @@ export type DashboardProps = {
29
29
  /** The link Share copies for a view; by default, this page's address with the view in it. */
30
30
  linkFor?: (view: ViewState) => string;
31
31
  } & DashboardEvents & DashboardDrillProps;
32
+ /**
33
+ * One dashboard. Everything drawn in it, the builder's preview too, shares one book of series
34
+ * colours, kept for as long as this dashboard is shown.
35
+ */
32
36
  export declare function Dashboard(props: DashboardProps): import("react").JSX.Element;
@@ -3,7 +3,7 @@ import { useDashboards } from "./context.mjs";
3
3
  import { DrillScope } from "./drill/board.mjs";
4
4
  import { BuildPage } from "./Editing.mjs";
5
5
  import { Bars, Side } from "./Parts.mjs";
6
- import { ScopeContext } from "./scope.mjs";
6
+ import { ScopeContext, SeriesSlotsContext, useSeriesSlots } from "./scope.mjs";
7
7
  import { useBoard } from "./useBoard.mjs";
8
8
  import { useState } from "react";
9
9
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -15,15 +15,24 @@ function focusOpener(widgetId) {
15
15
  });
16
16
  }
17
17
  /** The dashboard could not be read and there is nothing to show: say so, and offer to try again. */
18
- function LoadFailed({ onRetry }) {
18
+ function LoadFailed({ onRetry, failure }) {
19
19
  const { messages } = useDashboards();
20
+ const refused = failure !== void 0 && failure.status >= 400 && failure.status < 500;
20
21
  return /* @__PURE__ */ jsxs("div", {
21
22
  className: "dd-tile-error",
22
23
  role: "alert",
23
24
  children: [
24
25
  messages.dashboardFailed,
25
26
  " ",
26
- /* @__PURE__ */ jsx("button", {
27
+ refused ? /* @__PURE__ */ jsxs("span", {
28
+ className: "dd-tile-note",
29
+ children: [
30
+ failure.message,
31
+ " (",
32
+ failure.code,
33
+ ")"
34
+ ]
35
+ }) : /* @__PURE__ */ jsx("button", {
27
36
  type: "button",
28
37
  className: "dd-button dd-quiet",
29
38
  onClick: onRetry,
@@ -41,7 +50,18 @@ function Unreachable() {
41
50
  children: messages.dashboardUnreachable
42
51
  });
43
52
  }
53
+ /**
54
+ * One dashboard. Everything drawn in it, the builder's preview too, shares one book of series
55
+ * colours, kept for as long as this dashboard is shown.
56
+ */
44
57
  function Dashboard(props) {
58
+ const slots = useSeriesSlots(props.id);
59
+ return /* @__PURE__ */ jsx(SeriesSlotsContext.Provider, {
60
+ value: slots,
61
+ children: /* @__PURE__ */ jsx(Board, { ...props })
62
+ });
63
+ }
64
+ function Board(props) {
45
65
  const { messages } = useDashboards();
46
66
  const board = useBoard(props);
47
67
  const [building, setBuilding] = useState();
@@ -51,7 +71,10 @@ function Dashboard(props) {
51
71
  className: "dd-tile-state",
52
72
  children: messages.dashboardMissing
53
73
  });
54
- if (error) return /* @__PURE__ */ jsx(LoadFailed, { onRetry: board.refresh });
74
+ if (error) return /* @__PURE__ */ jsx(LoadFailed, {
75
+ onRetry: board.refresh,
76
+ failure: board.failure
77
+ });
55
78
  if (shown?.tab === void 0) return /* @__PURE__ */ jsx("div", {
56
79
  className: "dd-dashboard",
57
80
  "aria-busy": "true"