derive-dashboards 0.1.1 → 0.2.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 (167) hide show
  1. package/README.md +5 -3
  2. package/dist/cli/add.mjs +130 -0
  3. package/dist/cli/cli.mjs +14 -12
  4. package/dist/cli/config.mjs +12 -1
  5. package/dist/cli/doctor.mjs +147 -0
  6. package/dist/cli/init.mjs +3 -2
  7. package/dist/cli/json.mjs +21 -0
  8. package/dist/cli/layers.mjs +33 -0
  9. package/dist/core/document/layout.mjs +1 -1
  10. package/dist/core/document/view-layout.d.mts +14 -0
  11. package/dist/core/document/view-layout.mjs +157 -0
  12. package/dist/core/engine/filter.mjs +2 -2
  13. package/dist/core/engine/leaf.mjs +9 -4
  14. package/dist/core/engine/members.mjs +1 -1
  15. package/dist/core/engine/version.d.mts +1 -1
  16. package/dist/core/engine/version.mjs +1 -1
  17. package/dist/core/error/codes.d.mts +2 -1
  18. package/dist/core/error/codes.mjs +2 -1
  19. package/dist/core/index.d.mts +5 -3
  20. package/dist/core/index.mjs +5 -3
  21. package/dist/core/model/member.mjs +5 -2
  22. package/dist/core/model/types.d.mts +13 -13
  23. package/dist/core/model/validate/members.mjs +7 -4
  24. package/dist/core/policy/bind-query.d.mts +12 -0
  25. package/dist/core/policy/bind-query.mjs +53 -0
  26. package/dist/core/query/filter.d.mts +6 -0
  27. package/dist/core/query/picks.d.mts +8 -2
  28. package/dist/core/query/picks.mjs +11 -4
  29. package/dist/core/query/segments.mjs +2 -1
  30. package/dist/core/result/columns.mjs +6 -3
  31. package/dist/core/schema/aliases.d.mts +7 -0
  32. package/dist/core/schema/aliases.mjs +77 -0
  33. package/dist/core/schema/answers.d.mts +1 -0
  34. package/dist/core/schema/answers.mjs +1 -0
  35. package/dist/core/schema/index.d.mts +3 -2
  36. package/dist/core/schema/index.mjs +3 -2
  37. package/dist/core/schema/query.d.mts +81 -0
  38. package/dist/core/schema/query.mjs +9 -5
  39. package/dist/core/types/api.d.mts +7 -1
  40. package/dist/core/types/api.mjs +1 -1
  41. package/dist/dashboards.mjs +4 -0
  42. package/dist/editing.mjs +2 -2
  43. package/dist/endpoints/dashboards.mjs +17 -2
  44. package/dist/endpoints/index.d.mts +12 -2
  45. package/dist/endpoints/meta.mjs +10 -1
  46. package/dist/execute.mjs +20 -11
  47. package/dist/handler.mjs +5 -1
  48. package/dist/llms.txt +22 -0
  49. package/dist/mcp/format.mjs +42 -8
  50. package/dist/mcp/query.mjs +34 -4
  51. package/dist/postgres-store.mjs +1 -0
  52. package/dist/react/Canvas.mjs +28 -5
  53. package/dist/react/Cell.mjs +2 -1
  54. package/dist/react/Dashboard.mjs +15 -3
  55. package/dist/react/DashboardList.mjs +22 -22
  56. package/dist/react/DashboardListRow.mjs +49 -0
  57. package/dist/react/Discard.mjs +5 -2
  58. package/dist/react/Editing.mjs +19 -5
  59. package/dist/react/FilterBar.d.mts +7 -9
  60. package/dist/react/Grid.mjs +7 -19
  61. package/dist/react/Header.mjs +1 -1
  62. package/dist/react/History.mjs +5 -0
  63. package/dist/react/ReadFailed.mjs +23 -0
  64. package/dist/react/Spaces.mjs +15 -1
  65. package/dist/react/Tile.d.mts +2 -0
  66. package/dist/react/Tile.mjs +35 -7
  67. package/dist/react/_virtual/_rolldown/runtime.mjs +12 -0
  68. package/dist/react/arrange-steps.mjs +16 -13
  69. package/dist/react/arrange.mjs +10 -3
  70. package/dist/react/builder/Calcs.mjs +35 -11
  71. package/dist/react/builder/FilterEditor.mjs +196 -0
  72. package/dist/react/builder/Filters.mjs +172 -116
  73. package/dist/react/builder/Formula.mjs +82 -0
  74. package/dist/react/builder/Groups.mjs +1 -0
  75. package/dist/react/builder/Preview.mjs +1 -1
  76. package/dist/react/builder/RangeEditor.mjs +184 -0
  77. package/dist/react/builder/Sections.mjs +41 -6
  78. package/dist/react/builder/Time.mjs +138 -60
  79. package/dist/react/builder/Values.mjs +85 -0
  80. package/dist/react/builder/WidgetBuilder.mjs +50 -49
  81. package/dist/react/builder/base.d.mts +5 -0
  82. package/dist/react/builder/base.mjs +33 -8
  83. package/dist/react/builder/calc.mjs +15 -1
  84. package/dist/react/builder/escape.d.mts +1 -0
  85. package/dist/react/builder/escape.mjs +62 -0
  86. package/dist/react/builder/filter-tree.d.mts +9 -0
  87. package/dist/react/builder/filter-tree.mjs +186 -0
  88. package/dist/react/builder/formula-parse.d.mts +18 -0
  89. package/dist/react/builder/formula-parse.mjs +136 -0
  90. package/dist/react/builder/labels.d.mts +1 -1
  91. package/dist/react/builder/state.d.mts +2 -1
  92. package/dist/react/builder/state.mjs +23 -37
  93. package/dist/react/builder/useBuilder.d.mts +12 -1
  94. package/dist/react/builder/useBuilder.mjs +6 -3
  95. package/dist/react/builder/words.d.mts +59 -0
  96. package/dist/react/builder/words.mjs +73 -0
  97. package/dist/react/context.d.mts +13 -0
  98. package/dist/react/context.mjs +9 -3
  99. package/dist/react/drill/useDrill.d.mts +1 -1
  100. package/dist/react/drill/words.d.mts +3 -0
  101. package/dist/react/drill/words.mjs +2 -0
  102. package/dist/react/english.mjs +20 -5
  103. package/dist/react/filters/bar.d.mts +12 -0
  104. package/dist/react/filters/bar.mjs +135 -0
  105. package/dist/react/filters/calendar.mjs +193 -0
  106. package/dist/react/filters/chip.mjs +174 -0
  107. package/dist/react/filters/context.d.mts +22 -0
  108. package/dist/react/filters/context.mjs +78 -0
  109. package/dist/react/filters/dates.mjs +89 -0
  110. package/dist/react/filters/days.d.mts +36 -0
  111. package/dist/react/filters/days.mjs +87 -0
  112. package/dist/react/filters/field-step.mjs +81 -0
  113. package/dist/react/filters/hooks.d.mts +34 -0
  114. package/dist/react/filters/hooks.mjs +94 -0
  115. package/dist/react/filters/listbox.mjs +131 -0
  116. package/dist/react/filters/logic.d.mts +59 -0
  117. package/dist/react/filters/logic.mjs +109 -0
  118. package/dist/react/filters/menu-search.mjs +211 -0
  119. package/dist/react/filters/menu.mjs +85 -0
  120. package/dist/react/filters/number.mjs +127 -0
  121. package/dist/react/filters/numbers.d.mts +47 -0
  122. package/dist/react/filters/numbers.mjs +151 -0
  123. package/dist/react/filters/operator.mjs +104 -0
  124. package/dist/react/filters/phone.mjs +104 -0
  125. package/dist/react/filters/popover.d.mts +19 -0
  126. package/dist/react/filters/popover.mjs +153 -0
  127. package/dist/react/filters/rules.d.mts +8 -0
  128. package/dist/react/filters/rules.mjs +55 -0
  129. package/dist/react/filters/sheet.mjs +196 -0
  130. package/dist/react/filters/state.mjs +132 -0
  131. package/dist/react/filters/suggest.d.mts +47 -0
  132. package/dist/react/filters/suggest.mjs +97 -0
  133. package/dist/react/filters/values.mjs +166 -0
  134. package/dist/react/filters/words.d.mts +81 -0
  135. package/dist/react/filters/words.mjs +73 -0
  136. package/dist/react/format.mjs +11 -4
  137. package/dist/react/index.d.mts +11 -5
  138. package/dist/react/index.mjs +8 -4
  139. package/dist/react/messages.d.mts +34 -2
  140. package/dist/react/place.mjs +7 -3
  141. package/dist/react/renderers/index.mjs +65 -3
  142. package/dist/react/renderers/list.mjs +6 -6
  143. package/dist/react/series.d.mts +25 -8
  144. package/dist/react/series.mjs +135 -39
  145. package/dist/react/theme.css +930 -19
  146. package/dist/react/useBoard.d.mts +2 -0
  147. package/dist/react/useDashboard.d.mts +3 -0
  148. package/dist/react/useDashboard.mjs +6 -0
  149. package/dist/react/view-grid.mjs +16 -0
  150. package/dist/recharts/axes.mjs +28 -0
  151. package/dist/recharts/axis.mjs +84 -0
  152. package/dist/recharts/bar.d.mts +7 -0
  153. package/dist/recharts/bar.mjs +140 -0
  154. package/dist/recharts/charts.d.mts +4 -5
  155. package/dist/recharts/charts.mjs +2 -208
  156. package/dist/recharts/index.d.mts +3 -1
  157. package/dist/recharts/index.mjs +4 -1
  158. package/dist/recharts/line.d.mts +2 -0
  159. package/dist/recharts/line.mjs +111 -0
  160. package/dist/recharts/marks.mjs +47 -18
  161. package/dist/recharts/parts.mjs +88 -0
  162. package/dist/recharts/table.mjs +71 -0
  163. package/dist/records-read.mjs +1 -1
  164. package/dist/registry/filter-bar.json +26 -0
  165. package/dist/skills/derive-dashboards/SKILL.md +69 -0
  166. package/package.json +6 -2
  167. package/dist/react/FilterBar.mjs +0 -119
@@ -2,6 +2,87 @@ import { WireFilter } from "../query/filter.mjs";
2
2
  import { FormulaNode, WireQuery } from "../query/types.mjs";
3
3
  import { Issue } from "../types/primitives.mjs";
4
4
  import { z } from "zod";
5
+ /** The query's fields, before its ids are checked against each other; extend this, not the schema. */
6
+ export declare const wireQueryShape: z.ZodObject<{
7
+ kind: z.ZodLiteral<"aggregate">;
8
+ source: z.ZodString;
9
+ measures: z.ZodReadonly<z.ZodArray<z.ZodObject<{
10
+ id: z.ZodTemplateLiteral<`m${number}`>;
11
+ measure: z.ZodString;
12
+ filter: z.ZodExactOptional<z.ZodType<WireFilter, unknown, z.core.$ZodTypeInternals<WireFilter, unknown>>>;
13
+ label: z.ZodExactOptional<z.ZodString>;
14
+ }, z.core.$strict>>>;
15
+ dimensions: z.ZodExactOptional<z.ZodReadonly<z.ZodArray<z.ZodObject<{
16
+ id: z.ZodTemplateLiteral<`d${number}`>;
17
+ member: z.ZodString;
18
+ limit: z.ZodExactOptional<z.ZodNumber>;
19
+ other: z.ZodExactOptional<z.ZodBoolean>;
20
+ rankBy: z.ZodExactOptional<z.ZodObject<{
21
+ by: z.ZodUnion<readonly [z.ZodTemplateLiteral<`m${number}`>, z.ZodTemplateLiteral<`c${number}`>]>;
22
+ dir: z.ZodEnum<{
23
+ asc: "asc";
24
+ desc: "desc";
25
+ }>;
26
+ }, z.core.$strict>>;
27
+ }, z.core.$strict>>>>;
28
+ time: z.ZodExactOptional<z.ZodObject<{
29
+ dimension: z.ZodString;
30
+ grain: z.ZodExactOptional<z.ZodEnum<{
31
+ hour: "hour";
32
+ day: "day";
33
+ week: "week";
34
+ month: "month";
35
+ quarter: "quarter";
36
+ year: "year";
37
+ }>>;
38
+ range: z.ZodUnion<readonly [z.ZodObject<{
39
+ last: z.ZodNumber;
40
+ unit: z.ZodEnum<{
41
+ hour: "hour";
42
+ day: "day";
43
+ week: "week";
44
+ month: "month";
45
+ quarter: "quarter";
46
+ year: "year";
47
+ }>;
48
+ includeCurrent: z.ZodBoolean;
49
+ }, z.core.$strict>, z.ZodObject<{
50
+ from: z.ZodString;
51
+ to: z.ZodString;
52
+ }, z.core.$strict>]>;
53
+ compare: z.ZodExactOptional<z.ZodEnum<{
54
+ previous_period: "previous_period";
55
+ previous_year: "previous_year";
56
+ }>>;
57
+ }, z.core.$strict>>;
58
+ filters: z.ZodExactOptional<z.ZodType<WireFilter, unknown, z.core.$ZodTypeInternals<WireFilter, unknown>>>;
59
+ calc: z.ZodExactOptional<z.ZodReadonly<z.ZodArray<z.ZodObject<{
60
+ id: z.ZodTemplateLiteral<`c${number}`>;
61
+ formula: z.ZodType<FormulaNode, unknown, z.core.$ZodTypeInternals<FormulaNode, unknown>>;
62
+ format: z.ZodExactOptional<z.ZodEnum<{
63
+ number: "number";
64
+ percent: "percent";
65
+ currency: "currency";
66
+ duration: "duration";
67
+ }>>;
68
+ label: z.ZodExactOptional<z.ZodString>;
69
+ }, z.core.$strict>>>>;
70
+ order: z.ZodExactOptional<z.ZodReadonly<z.ZodArray<z.ZodObject<{
71
+ by: z.ZodUnion<readonly [z.ZodTemplateLiteral<`m${number}`>, z.ZodTemplateLiteral<`c${number}`>, z.ZodTemplateLiteral<`d${number}`>]>;
72
+ dir: z.ZodEnum<{
73
+ asc: "asc";
74
+ desc: "desc";
75
+ }>;
76
+ }, z.core.$strict>>>>;
77
+ limit: z.ZodExactOptional<z.ZodNumber>;
78
+ other: z.ZodExactOptional<z.ZodBoolean>;
79
+ total: z.ZodExactOptional<z.ZodBoolean>;
80
+ fill: z.ZodExactOptional<z.ZodEnum<{
81
+ none: "none";
82
+ zero: "zero";
83
+ }>>;
84
+ }, z.core.$strict>;
85
+ /** A query from outside: its fields, then each id checked to be its entry's position. */
5
86
  export declare const wireQuerySchema: z.ZodObject<{
6
87
  kind: z.ZodLiteral<"aggregate">;
7
88
  source: z.ZodString;
@@ -1,5 +1,6 @@
1
1
  import { NEGATIVE_OPS, NULL_OPS, POSITIVE_OPS } from "../query/filter.mjs";
2
2
  import { parseDate, parseTextTime } from "../time/instant.mjs";
3
+ import { checkPositions } from "./aliases.mjs";
3
4
  import { z } from "zod";
4
5
  // src/schema/query.ts
5
6
  /**
@@ -61,9 +62,9 @@ const filter = z.lazy(() => z.union([
61
62
  where: filter
62
63
  }) })
63
64
  ]));
64
- const measureAlias = z.templateLiteral(["m", z.number().int().nonnegative()], { error: "A measure's id in a query is m and a number: m0, m1." });
65
- const dimensionAlias = z.templateLiteral(["d", z.number().int().nonnegative()], { error: "A dimension's id in a query is d and a number: d0, d1." });
66
- const calcAlias = z.templateLiteral(["c", z.number().int().nonnegative()], { error: "A calculation's id in a query is c and a number: c0, c1." });
65
+ const measureAlias = z.templateLiteral(["m", z.number().int().nonnegative()], { error: "A measure's id in a query is m and a number: m1, m2." });
66
+ const dimensionAlias = z.templateLiteral(["d", z.number().int().nonnegative()], { error: "A dimension's id in a query is d and a number: d1, d2." });
67
+ const calcAlias = z.templateLiteral(["c", z.number().int().nonnegative()], { error: "A calculation's id in a query is c and a number: c1, c2." });
67
68
  const formula = z.lazy(() => z.union([
68
69
  z.strictObject({
69
70
  ref: z.union([measureAlias, calcAlias]),
@@ -105,7 +106,8 @@ const range = z.union([z.strictObject({
105
106
  from: rangeEnd,
106
107
  to: rangeEnd
107
108
  })]);
108
- const wireQuerySchema = z.strictObject({
109
+ /** The query's fields, before its ids are checked against each other; extend this, not the schema. */
110
+ const wireQueryShape = z.strictObject({
109
111
  kind: z.literal("aggregate"),
110
112
  source: name,
111
113
  measures: z.array(z.strictObject({
@@ -155,6 +157,8 @@ const wireQuerySchema = z.strictObject({
155
157
  total: z.boolean().exactOptional(),
156
158
  fill: z.enum(["zero", "none"]).exactOptional()
157
159
  });
160
+ /** A query from outside: its fields, then each id checked to be its entry's position. */
161
+ const wireQuerySchema = wireQueryShape.superRefine(checkPositions);
158
162
  /** Checks an untrusted query. Every problem is reported, with the path to it. */
159
163
  function parseWireQuery(input) {
160
164
  const result = wireQuerySchema.safeParse(input);
@@ -171,4 +175,4 @@ function parseWireQuery(input) {
171
175
  }))
172
176
  };
173
177
  }
174
- export { grain, idSchema, name, op, parseWireQuery, primitive, range, viewerRef, wireQuerySchema };
178
+ export { grain, idSchema, name, op, parseWireQuery, primitive, range, viewerRef, wireQuerySchema, wireQueryShape };
@@ -19,6 +19,10 @@ export type MetaMember = {
19
19
  /** On a measure: how it aggregates ("count", "sum", "ratio" and so on) and its unit. */
20
20
  aggregate?: string;
21
21
  unit?: string;
22
+ /** On a dimension: the tone of each value, from the model's hints. */
23
+ tones?: Readonly<Record<string, "positive" | "negative" | "warning" | "neutral">>;
24
+ /** On a number dimension: its bucket edges, ascending, from the model's hints. */
25
+ buckets?: readonly number[];
22
26
  };
23
27
  /** A join a query can group by: `<source>.<join>.<dimension>` names a dimension of `source`. */
24
28
  export type MetaJoin = {
@@ -41,6 +45,8 @@ export type DashboardListResponse = {
41
45
  dashboards: {
42
46
  id: string;
43
47
  title: string;
48
+ /** What the dashboard shows, in a sentence, when it has one. */
49
+ description?: string;
44
50
  version: number;
45
51
  unpublished?: true;
46
52
  }[];
@@ -338,4 +344,4 @@ export type CoreContract = {
338
344
  * than reading a shape it does not know. A test recomputes it from the answer schemas, so a
339
345
  * change to an answer fails until this is updated.
340
346
  */
341
- export declare const CONTRACT_VERSION = "1a5793ca2a46d9e9";
347
+ export declare const CONTRACT_VERSION = "f999ff7ebd6624b2";
@@ -5,5 +5,5 @@
5
5
  * than reading a shape it does not know. A test recomputes it from the answer schemas, so a
6
6
  * change to an answer fails until this is updated.
7
7
  */
8
- const CONTRACT_VERSION = "1a5793ca2a46d9e9";
8
+ const CONTRACT_VERSION = "f999ff7ebd6624b2";
9
9
  export { CONTRACT_VERSION };
@@ -30,6 +30,8 @@ function adapterFor(options, request) {
30
30
  const { database } = options;
31
31
  return typeof database === "function" ? database(request) : database;
32
32
  }
33
+ /** A description the list carries only when there is one to show. */
34
+ const described = (description) => description === void 0 || description.trim() === "" ? {} : { description };
33
35
  async function listDashboards(options, request, principal) {
34
36
  const adapter = adapterFor(options, request);
35
37
  const stored = adapter === void 0 ? [] : await allStored(adapter, principalTenant(principal));
@@ -37,11 +39,13 @@ async function listDashboards(options, request, principal) {
37
39
  const defaults = (options.dashboards ?? []).filter((d) => !customized.has(d.key)).map((d) => ({
38
40
  id: builtInId(d.key),
39
41
  title: d.document.meta.title,
42
+ ...described(d.document.meta.description),
40
43
  version: 0
41
44
  }));
42
45
  return [...stored.map((d) => ({
43
46
  id: d.defaultOf === void 0 ? d.id : builtInId(d.defaultOf),
44
47
  title: d.title,
48
+ ...described(d.description),
45
49
  version: d.currentVersion,
46
50
  ...d.defaultOf === void 0 ? { owner: {
47
51
  id: d.ownerId,
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) {
@@ -609,11 +609,17 @@ export declare function coreEndpoints(rt: Runtime): {
609
609
  draft?: true;
610
610
  }, import("derive-dashboards/core").ValuesResponse, "POST">;
611
611
  listDashboards: import("derive-dashboards/core").DashEndpoint<"/dashboards/list", Record<string, never>, {
612
- dashboards: {
612
+ dashboards: ({
613
613
  id: string;
614
614
  title: string;
615
+ description?: string;
615
616
  version: number;
616
- }[];
617
+ } | {
618
+ id: string;
619
+ title: string;
620
+ version: number;
621
+ unpublished: true;
622
+ })[];
617
623
  can: {
618
624
  create: boolean;
619
625
  };
@@ -651,6 +657,8 @@ export declare function coreEndpoints(rt: Runtime): {
651
657
  values?: readonly import("derive-dashboards/core").Primitive[] | "lookup";
652
658
  aggregate?: string;
653
659
  unit?: string;
660
+ tones?: Readonly<Record<string, "positive" | "negative" | "warning" | "neutral">>;
661
+ buckets?: readonly number[];
654
662
  }[];
655
663
  dimensions: {
656
664
  id: string;
@@ -659,6 +667,8 @@ export declare function coreEndpoints(rt: Runtime): {
659
667
  values?: readonly import("derive-dashboards/core").Primitive[] | "lookup";
660
668
  aggregate?: string;
661
669
  unit?: string;
670
+ tones?: Readonly<Record<string, "positive" | "negative" | "warning" | "neutral">>;
671
+ buckets?: readonly number[];
662
672
  }[];
663
673
  joins: {
664
674
  name: 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 } 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,
@@ -89,7 +98,7 @@ async function compute(x, bound) {
89
98
  ...cuts,
90
99
  receipt: {
91
100
  queryHash: await macHex(await x.rt.macKey, canonical({
92
- query: x.query,
101
+ query: bound.input.query,
93
102
  lock: bound.lock,
94
103
  required: bound.required
95
104
  })),
@@ -137,13 +146,13 @@ function answered(x) {
137
146
  const on = [...bound.lock, ...bound.required].map((e) => e.on);
138
147
  const key = {
139
148
  principal: x.principal,
140
- query: x.query,
149
+ query: bound.input.query,
141
150
  lock: bound.lock,
142
151
  required: bound.required,
143
152
  calendar: x.calendar,
144
153
  maxRows: bound.maxRows,
145
154
  now: x.now.getTime() - x.now.getTime() % quantum,
146
- sources: manifest(options.model, x.query, on)
155
+ sources: manifest(options.model, bound.input.query, on)
147
156
  };
148
157
  return cache.answer(key, () => compute(x, bound));
149
158
  }
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/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);