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
package/README.md CHANGED
@@ -25,7 +25,8 @@ One package. The React UI needs `react`, and the line and bar charts need `recha
25
25
  them only if you use those parts. The `derive-dashboards` command (`npx derive-dashboards init`)
26
26
  comes with it.
27
27
 
28
- Then follow the [quick start](https://github.com/derive-to/dashboards/blob/main/docs/quick-start.md).
28
+ Then follow the [quick start](https://github.com/derive-to/dashboards/blob/main/docs/quick-start.md). Using a coding agent? `npx skills add derive-to/dashboards --skill derive-dashboards`
29
+ gives it the install steps, and [llms.txt](https://github.com/derive-to/dashboards/blob/main/llms.txt) indexes every page (both also ship in the package).
29
30
 
30
31
  ## What is here today
31
32
 
@@ -35,16 +36,17 @@ Embedded dashboards on Postgres, end to end, run by the Acme Tasks sample (`exam
35
36
  | --- | --- |
36
37
  | `derive-dashboards/core` | No I/O and no framework. The model (`defineModel`, `validateModel`), typed member ids, filters and queries, the access kernel (`effectiveFilter`), composition, the oracle every engine must match, the Postgres engine (`/engine`), the document and its schema (`/schema`), and the store's tables as data. |
37
38
  | `derive-dashboards` | `deriveDashboards(options)`: a fetch handler for every endpoint, a Postgres source and store for any driver, the result cache, the query log, `createTables`, and the store contract suite (`/testing`). |
38
- | `derive-dashboards/react` | `Dashboard` with edit mode (Edit, + Add widget, drag and resize, a change count with undo and redo, review before publish, History with in-place preview, Share), `DashboardList` with + New dashboard, `useDraft` and `useReview` for your own edit and review UI, `FilterBar`, `Tile`, drill-in (`DrillPanel`, `DashboardTile`, `useDrill`, and `toSeries` and `rowAt` for any chart kit), the widget builder (`WidgetBuilder`, `useBuilder`) and `theme.css`. |
39
+ | `derive-dashboards/react` | `Dashboard` with edit mode (Edit, + Add widget, drag and resize, a change count with undo and redo, review before publish, History with in-place preview, Share), `DashboardList` with + New dashboard, `useDraft` and `useReview` for your own edit and review UI, the filter bar (`FilterBar`, with chips, a Filter menu, a phone sheet and `filterRules` for your own), `Tile`, drill-in (`DrillPanel`, `DashboardTile`, `useDrill`, and `toSeries` and `rowAt` for any chart kit), the widget builder (`WidgetBuilder`, `useBuilder`) and `theme.css`. |
39
40
  | `derive-dashboards/recharts` | Line and bar tiles, drawn with Recharts, each mark a drill (install `recharts` to use them; any other chart library plugs into `renderers`). |
40
41
  | `derive-dashboards/mcp` | Two tools for the MCP server you already run (`addDashboardTools`): `dashboards_query` to ask and read, `dashboards_api` for everything else. See [MCP](https://github.com/derive-to/dashboards/blob/main/docs/mcp.md). |
41
- | `derive-dashboards/cli` | `defineConfig` for `derive-dashboards.config.ts`; the `derive-dashboards` command runs `init`, `check`, `generate`, `create-tables`. |
42
+ | `derive-dashboards/cli` | `defineConfig` for `derive-dashboards.config.ts`; the `derive-dashboards` command runs `init`, `doctor`, `check`, `generate`, `create-tables`. |
42
43
 
43
44
  Tenancy and row policy are opt-in. An app of one tenant leaves them out; once the model has
44
45
  tenant keys, every source must say how it is tied to them. A viewer who can read no row of a
45
46
  tile's source gets "no access", never zeros.
46
47
 
47
48
  Start with the [quick start](https://github.com/derive-to/dashboards/blob/main/docs/quick-start.md), then [concepts](https://github.com/derive-to/dashboards/blob/main/docs/concepts.md),
49
+ [filters](https://github.com/derive-to/dashboards/blob/main/docs/filters.md) (the built-in filter bar, how to theme it, and `npx derive-dashboards add filter-bar` to own its code),
48
50
  [endpoints](https://github.com/derive-to/dashboards/blob/main/docs/endpoints.md), [the store](https://github.com/derive-to/dashboards/blob/main/docs/store.md) and [the CLI](https://github.com/derive-to/dashboards/blob/main/docs/cli.md). To run
49
51
  your own data layer (ClickHouse, an API, your own SQL), see
50
52
  [a custom data layer](https://github.com/derive-to/dashboards/blob/main/docs/custom-data-layer.md). The
@@ -0,0 +1,130 @@
1
+ import { ComponentsJson, PackageJson, readJson } from "./json.mjs";
2
+ import { LAYER_LINE, layerOrder } from "./layers.mjs";
3
+ import { spawnSync } from "node:child_process";
4
+ import { existsSync } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ // src/add.ts
8
+ /** The shadcn CLI version the registry item is tested with. */
9
+ const SHADCN = "shadcn@4.23.0";
10
+ /** The React version installed in the app, when it is: what will run, not what the range allows. */
11
+ function installedReact(cwd) {
12
+ try {
13
+ return readJson(join(cwd, "node_modules/react/package.json"), PackageJson).version;
14
+ } catch {
15
+ return;
16
+ }
17
+ }
18
+ /**
19
+ * Why this folder is not an app to add the bar to, or undefined when it is: it needs its own
20
+ * package.json (so no package manager walks up into a parent project), React 19, and the library.
21
+ */
22
+ function notAnApp(cwd) {
23
+ const file = join(cwd, "package.json");
24
+ if (!existsSync(file)) return `There is no package.json in ${cwd}. Run this in your React app's folder (where its package.json is), or pass --cwd <folder>.`;
25
+ let manifest;
26
+ try {
27
+ manifest = readJson(file, PackageJson);
28
+ } catch {
29
+ return `${file} is not valid JSON.`;
30
+ }
31
+ const deps = {
32
+ ...manifest.devDependencies,
33
+ ...manifest.dependencies
34
+ };
35
+ if (deps["derive-dashboards"] === void 0) return `${file} does not list derive-dashboards. Install it first: npm install derive-dashboards`;
36
+ const react = installedReact(cwd) ?? deps["react"];
37
+ if (react === void 0) return `${file} does not list react. The filter bar is a React component.`;
38
+ const major = /(\d+)/u.exec(react)?.[1];
39
+ if (major !== void 0 && Number(major) < 19) return `The filter bar needs React 19; ${file} has react ${react}. Upgrade React, or keep the built-in bar.`;
40
+ }
41
+ /** The shadcn bases the copied bar is written for: its triggers render as plain buttons on both. */
42
+ const BASES = /* @__PURE__ */ new Set(["radix", "base"]);
43
+ /**
44
+ * Which primitive library a shadcn app is on, from components.json: its `base`, else the prefix of
45
+ * its `style` ("radix-nova", "base-nova"), else Radix for older apps that name neither.
46
+ */
47
+ function shadcnBase(cwd) {
48
+ try {
49
+ const config = readJson(join(cwd, "components.json"), ComponentsJson);
50
+ return config.base ?? /^([a-z]+)-/u.exec(config.style ?? "")?.[1] ?? "radix";
51
+ } catch {
52
+ return "radix";
53
+ }
54
+ }
55
+ /** Why the copy cannot go into this shadcn app, or undefined when it can. */
56
+ function unsupportedBase(cwd) {
57
+ const base = shadcnBase(cwd);
58
+ if (BASES.has(base)) return void 0;
59
+ return `This app's shadcn components are on ${base === "aria" ? "React Aria" : base}; the filter bar copy is written for Base UI and Radix. Keep the built-in bar (it needs no UI kit), or add a Base UI or Radix popover and command to copy it.`;
60
+ }
61
+ /** The registry item inside this package: dist/cli/add.mjs → dist/registry/filter-bar.json. */
62
+ const registryItem = () => fileURLToPath(new URL("../registry/filter-bar.json", import.meta.url));
63
+ const SHADCN_LINE = `import { DashboardFilterBar } from "@/components/filter-bar";
64
+
65
+ <DashboardsProvider client={client} components={{ FilterBar: DashboardFilterBar }}>`;
66
+ /** Runs (or, for a dry run, prints) the shadcn CLI on the packaged item; false when it failed. */
67
+ function runShadcn(io, dryRun, overwrite) {
68
+ const args = [
69
+ SHADCN,
70
+ "add",
71
+ registryItem(),
72
+ ...overwrite ? ["--overwrite", "--yes"] : []
73
+ ];
74
+ if (dryRun) {
75
+ io.out(`npx ${args.join(" ")}`);
76
+ return true;
77
+ }
78
+ const result = spawnSync("npx", args, {
79
+ cwd: io.cwd,
80
+ stdio: "inherit",
81
+ shell: false
82
+ });
83
+ if (result.status === 0) return true;
84
+ io.err(`npx shadcn failed${result.error ? `: ${result.error.message}` : ""}.`);
85
+ return false;
86
+ }
87
+ /**
88
+ * `derive-dashboards add filter-bar`: the Linear-style filter bar as your own code. Every
89
+ * dashboard already draws it (the built-in bar); in a shadcn app this copies the shadcn version
90
+ * into your components, styled by your tokens. Without shadcn there is nothing to add.
91
+ * `--dry-run` prints the command instead of running it; `--overwrite` replaces a copy you have.
92
+ */
93
+ function add(io, item, dryRun, overwrite = false) {
94
+ const shadcn = existsSync(join(io.cwd, "components.json"));
95
+ const problem = refusal(io.cwd, item, shadcn);
96
+ if (problem !== void 0) {
97
+ io.err(problem);
98
+ return 2;
99
+ }
100
+ if (!shadcn) {
101
+ io.out("Every dashboard already has the filter bar: the built-in one, styled by derive-dashboards/react/theme.css and your own CSS (see docs/filters.md).\nTo own its code instead, set up shadcn/ui (npx shadcn@latest init) and run this again.");
102
+ return 0;
103
+ }
104
+ const base = shadcnBase(io.cwd) === "base" ? "Base UI" : "Radix";
105
+ io.out(`Found components.json (shadcn on ${base}): adding the shadcn filter bar to your components.`);
106
+ if (!runShadcn(io, dryRun, overwrite)) return 1;
107
+ lastSteps(io, overwrite);
108
+ return 0;
109
+ }
110
+ /** Why `add` cannot go ahead here: an unknown item, not an app, or an unsupported shadcn base. */
111
+ function refusal(cwd, item, shadcn) {
112
+ if (item !== "filter-bar") return `add knows one item: filter-bar.${item === void 0 ? "" : ` Not "${item}".`}`;
113
+ return notAnApp(cwd) ?? (shadcn ? unsupportedBase(cwd) : void 0);
114
+ }
115
+ /** What is left after the copy: an existing copy kept, and the one provider line. */
116
+ function lastSteps(io, overwrite) {
117
+ if (!overwrite && existsSync(join(io.cwd, "components/filter-bar.tsx"))) io.out("components/filter-bar.tsx was already there and shadcn keeps it unless you say yes. To update it to this version, commit, run again with --overwrite, and use git diff to put back your own changes.");
118
+ const layers = layerOrder(io.cwd);
119
+ if (layers?.ok === false) io.out(`\nFirst, at the top of ${layers.file}, so the theme sits above Tailwind's reset:\n\n${LAYER_LINE}`);
120
+ io.out(`\nLast step, where you render dashboards (a client component in Next.js):\n\n${SHADCN_LINE}\n\nMore: https://github.com/derive-to/dashboards/blob/main/docs/filters.md`);
121
+ }
122
+ /** The CLI's `add` command: `--cwd` picks the app's folder, `--dry-run` and `--overwrite` pass on. */
123
+ function addCommand(flags, io) {
124
+ const cwd = flags.cwd === void 0 ? io.cwd : resolve(io.cwd, flags.cwd);
125
+ return add({
126
+ ...io,
127
+ cwd
128
+ }, flags.args?.[0], flags["dry-run"] === true, flags.overwrite === true);
129
+ }
130
+ export { BASES, addCommand, shadcnBase };
package/dist/cli/cli.mjs CHANGED
@@ -1,10 +1,10 @@
1
+ import { addCommand } from "./add.mjs";
1
2
  import { checkModel } from "./check.mjs";
2
- import { loadConfig } from "./config.mjs";
3
+ import { configFor } from "./config.mjs";
3
4
  import { checkHost } from "./conformance.mjs";
5
+ import { doctor } from "./doctor.mjs";
4
6
  import { init, writeNew } from "./init.mjs";
5
7
  import { renderDrizzle, renderKysely, renderSql, renderStatements } from "./render.mjs";
6
- import { existsSync } from "node:fs";
7
- import { resolve } from "node:path";
8
8
  import { parseArgs } from "node:util";
9
9
  import { createTables, schemaDiff } from "derive-dashboards";
10
10
  // src/cli.ts
@@ -16,6 +16,9 @@ const USAGE = `Usage: derive-dashboards <command> [options]
16
16
  Import a model from dbt's semantic layer (target/semantic_manifest.json, or the project
17
17
  folder) or Cube's YAML data model (a file or folder); exact storage from the config's
18
18
  connection when there is one, then checked against it.
19
+ doctor
20
+ Look over the setup and say what is missing, each with its fix: the config, model,
21
+ connection and store tables, DASHBOARDS_SECRET, the React peers and the shadcn base.
19
22
  check
20
23
  Prove the config's model against the database: tables, columns, keys, types.
21
24
  check --conformance <module>
@@ -27,6 +30,9 @@ const USAGE = `Usage: derive-dashboards <command> [options]
27
30
  Write the library's tables for your own tool (drizzle-kit, SQL files).
28
31
  generate --orm sql --diff --out <file>
29
32
  Write only what the config's database lacks: new tables, columns, keys, indexes.
33
+ add filter-bar [--cwd <folder>] [--overwrite] [--dry-run]
34
+ Copy the filter bar into a shadcn app as your own code (dashboards already draw the
35
+ built-in one). Prints the one line left to change. --overwrite replaces your copy.
30
36
 
31
37
  --config <file> defaults to derive-dashboards.config.ts
32
38
  -h, --help this text`;
@@ -43,6 +49,8 @@ function need(value, what) {
43
49
  }
44
50
  const COMMANDS = {
45
51
  init,
52
+ add: (_config, flags, io) => Promise.resolve(addCommand(flags, io)),
53
+ doctor: (_config, flags, io) => doctor(io, flags),
46
54
  check(config, flags, io) {
47
55
  if (flags.conformance !== void 0) return checkHost(io, flags.conformance);
48
56
  return checkModel(config, need(config.model, "model"), io);
@@ -71,15 +79,6 @@ const COMMANDS = {
71
79
  return 0;
72
80
  }
73
81
  };
74
- /**
75
- * The config a command reads: none for generating files or checking a custom source; for an
76
- * import, the config when there is one (its connection gives exact storage), else none.
77
- */
78
- function configFor(command, flags, cwd) {
79
- if (command === "generate" && flags.diff !== true || flags.conformance !== void 0) return Promise.resolve({});
80
- if (command === "init" && flags.from !== void 0 && !existsSync(resolve(cwd, flags.config ?? "derive-dashboards.config.ts"))) return Promise.resolve({});
81
- return loadConfig(cwd, flags.config);
82
- }
83
82
  const OPTIONS = {
84
83
  config: { type: "string" },
85
84
  tenant: {
@@ -93,6 +92,9 @@ const OPTIONS = {
93
92
  dialect: { type: "string" },
94
93
  diff: { type: "boolean" },
95
94
  conformance: { type: "string" },
95
+ "dry-run": { type: "boolean" },
96
+ cwd: { type: "string" },
97
+ overwrite: { type: "boolean" },
96
98
  help: {
97
99
  type: "boolean",
98
100
  short: "h"
@@ -1,4 +1,6 @@
1
1
  import { loadModule } from "./load.mjs";
2
+ import { existsSync } from "node:fs";
3
+ import { resolve } from "node:path";
2
4
  // src/config.ts
3
5
  function defineConfig(config) {
4
6
  return config;
@@ -11,4 +13,13 @@ async function loadConfig(cwd, path = "derive-dashboards.config.ts") {
11
13
  if (!isConfig(config)) throw new Error(`${path} must export its config as the default export.`);
12
14
  return config;
13
15
  }
14
- export { defineConfig, loadConfig };
16
+ /**
17
+ * The config a command reads: none for generating files or checking a custom source; for an
18
+ * import, the config when there is one (its connection gives exact storage), else none.
19
+ */
20
+ function configFor(command, flags, cwd) {
21
+ if (command === "add" || command === "doctor" || command === "generate" && flags.diff !== true || flags.conformance !== void 0) return Promise.resolve({});
22
+ if (command === "init" && flags.from !== void 0 && !existsSync(resolve(cwd, flags.config ?? "derive-dashboards.config.ts"))) return Promise.resolve({});
23
+ return loadConfig(cwd, flags.config);
24
+ }
25
+ export { configFor, defineConfig, loadConfig };
@@ -0,0 +1,147 @@
1
+ import { BASES, shadcnBase } from "./add.mjs";
2
+ import { introspects } from "./check.mjs";
3
+ import { loadConfig } from "./config.mjs";
4
+ import { PackageJson, readJson } from "./json.mjs";
5
+ import { LAYER_LINE, layerOrder } from "./layers.mjs";
6
+ import { schemaDiff } from "derive-dashboards";
7
+ import { existsSync } from "node:fs";
8
+ import { join, resolve } from "node:path";
9
+ import { validateModel } from "derive-dashboards/core";
10
+ // src/doctor.ts
11
+ const ok = (what) => ({
12
+ ok: true,
13
+ what
14
+ });
15
+ const bad = (what, fix) => ({
16
+ ok: false,
17
+ what,
18
+ fix
19
+ });
20
+ /** A package's version as installed in the app, else the range it lists, else undefined. */
21
+ function versionOf(cwd, name, listed) {
22
+ try {
23
+ const file = join(cwd, "node_modules", name, "package.json");
24
+ return readJson(file, PackageJson).version;
25
+ } catch {
26
+ return listed[name];
27
+ }
28
+ }
29
+ const plural = (n, word) => `${String(n)} ${word}${n === 1 ? "" : "s"}`;
30
+ const major = (version) => Number(/(\d+)/u.exec(version)?.[1] ?? "0");
31
+ /** The app's own dependencies, as its package.json lists them; undefined with no package.json. */
32
+ function dependenciesOf(cwd) {
33
+ const file = join(cwd, "package.json");
34
+ if (!existsSync(file)) return void 0;
35
+ const manifest = readJson(file, PackageJson);
36
+ return {
37
+ ...manifest.devDependencies,
38
+ ...manifest.dependencies
39
+ };
40
+ }
41
+ /** The peers the React parts need, at the majors they are built for, each when it is used. */
42
+ function peers(cwd) {
43
+ const deps = dependenciesOf(cwd);
44
+ if (deps === void 0) return [bad("No package.json here", "Run this in your app's folder.")];
45
+ if (deps["derive-dashboards"] === void 0) return [bad("derive-dashboards is not installed", "npm install derive-dashboards")];
46
+ return [
47
+ [
48
+ "react",
49
+ 19,
50
+ "derive-dashboards/react"
51
+ ],
52
+ [
53
+ "react-dom",
54
+ 19,
55
+ "derive-dashboards/react"
56
+ ],
57
+ [
58
+ "recharts",
59
+ 3,
60
+ "derive-dashboards/recharts (the built-in charts)"
61
+ ]
62
+ ].flatMap(([name, want, by]) => {
63
+ const version = versionOf(cwd, name, deps);
64
+ if (version === void 0) return name === "react" ? [ok("No React: server only")] : [];
65
+ if (major(version) === want) return [ok(`${name} ${version}`)];
66
+ const what = major(version) < want ? `older than ${by} needs` : `newer than the major ${by} is built for`;
67
+ return [bad(`${name} ${version} is ${what}`, `npm install ${name}@^${String(want)}`)];
68
+ });
69
+ }
70
+ /** The shadcn base, when the app has components.json: one the copied filter bar is written for. */
71
+ function shadcn(cwd) {
72
+ if (!existsSync(join(cwd, "components.json"))) return [];
73
+ const base = shadcnBase(cwd);
74
+ return BASES.has(base) ? [ok(`shadcn on ${base === "base" ? "Base UI" : "Radix"}`)] : [bad(`shadcn on ${base}`, "The copied filter bar needs Radix or Base UI; keep the built-in bar.")];
75
+ }
76
+ /** A Tailwind app's layer order, so Tailwind's reset does not undo the theme. */
77
+ function layers(cwd) {
78
+ const found = layerOrder(cwd);
79
+ if (found === void 0) return [];
80
+ return found.ok ? [ok(`${found.file} puts the theme above Tailwind's reset`)] : [bad(`${found.file} does not name the layer order`, `Add at its top: ${LAYER_LINE}`)];
81
+ }
82
+ /** The seal secret the server reads (quick start step 4), long enough to be a key. */
83
+ function secret(env) {
84
+ const value = env["DASHBOARDS_SECRET"];
85
+ if (value === void 0 || value === "") return bad("DASHBOARDS_SECRET is not set", "Set it to the same long random value on every instance (openssl rand -base64 32), and pass it as deriveDashboards({ secret }).");
86
+ return value.length >= 32 ? ok("DASHBOARDS_SECRET is set") : bad("DASHBOARDS_SECRET is shorter than 32 characters", "Use openssl rand -base64 32.");
87
+ }
88
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
89
+ /** Whether the connection answers: it reads the database's catalog, as check does. */
90
+ async function reachable(config) {
91
+ const connection = config.connection ?? Object.values(config.connections ?? {}).find((c) => introspects(c));
92
+ if (connection === void 0) return config.connections === void 0 ? bad("The config has no connection", "Add connection: nodePostgres(pool).connection.") : ok("Connections are custom sources (derive-dashboards check --conformance checks them)");
93
+ try {
94
+ await connection.introspect();
95
+ return ok("Connection answers (derive-dashboards check proves the model against it)");
96
+ } catch (error) {
97
+ return bad("Connection does not answer", messageOf(error));
98
+ }
99
+ }
100
+ /** The config's model, connection and store, each checked as far as reading allows. */
101
+ async function configured(config) {
102
+ const model = config.model;
103
+ const issues = model === void 0 ? [] : validateModel(model);
104
+ const found = [model === void 0 ? bad("The config has no model", "derive-dashboards init writes one.") : issues.length === 0 ? ok(`Model: ${plural(Object.keys(model.sources).length, "source")}`) : bad(`Model: ${String(issues.length)} problems`, "derive-dashboards check lists them."), await reachable(config)];
105
+ if (config.database === void 0) return [...found, ok("No store: viewing works; editing needs one (docs/store.md)")];
106
+ let missing;
107
+ try {
108
+ const diff = await schemaDiff(config.database);
109
+ missing = diff.tables.length + diff.columns.length;
110
+ } catch (error) {
111
+ return [...found, bad("Store: could not read its tables", messageOf(error))];
112
+ }
113
+ return [...found, missing === 0 ? ok("Store: every dd_ table and column is there") : bad(`Store: ${String(missing)} tables or columns missing`, "derive-dashboards create-tables")];
114
+ }
115
+ /** The config, or what is wrong with it as a finding. */
116
+ async function configOrFinding(cwd, path) {
117
+ const file = path ?? "derive-dashboards.config.ts";
118
+ if (!existsSync(resolve(cwd, file))) return bad(`No ${file}`, "Make one that default-exports defineConfig({ ... }); see docs/cli.md.");
119
+ try {
120
+ return await loadConfig(cwd, path);
121
+ } catch (error) {
122
+ return bad(`${file} does not load`, messageOf(error));
123
+ }
124
+ }
125
+ /**
126
+ * Looks over a setup and says what is missing, each with its fix: the config, its model,
127
+ * connection and store, the seal secret, the React peers and the shadcn base. It only reads. The
128
+ * exit code is 0 when everything is in place, 1 when something needs fixing.
129
+ */
130
+ async function doctor(io, flags, env = process.env) {
131
+ const config = await configOrFinding(io.cwd, flags.config);
132
+ const findings = [
133
+ ..."ok" in config ? [config] : await configured(config),
134
+ secret(env),
135
+ ...peers(io.cwd),
136
+ ...shadcn(io.cwd),
137
+ ...layers(io.cwd)
138
+ ];
139
+ for (const f of findings) if (f.ok) io.out(` ok ${f.what}`);
140
+ else io.out(` fix ${f.what}\n → ${f.fix}`);
141
+ const left = findings.filter((f) => !f.ok).length;
142
+ io.out(left === 0 ? "Everything here is in place." : `${String(left)} to fix.`);
143
+ io.out("Not checked here: where the handler is mounted and the React provider. Open the app: a wrong mount says NO_HANDLER, a page from another origin names trustedOrigins.");
144
+ if ("close" in config) await config.close?.();
145
+ return left === 0 ? 0 : 1;
146
+ }
147
+ export { configured, doctor };
package/dist/cli/init.mjs CHANGED
@@ -5,9 +5,9 @@ import { catalogOf } from "./import/catalog.mjs";
5
5
  import { proposeModel } from "./propose.mjs";
6
6
  import { renderModel } from "./render.mjs";
7
7
  import { existsSync } from "node:fs";
8
- import { resolve } from "node:path";
8
+ import { dirname, resolve } from "node:path";
9
9
  import { validateModel } from "derive-dashboards/core";
10
- import { writeFile } from "node:fs/promises";
10
+ import { mkdir, writeFile } from "node:fs/promises";
11
11
  // src/init.ts
12
12
  /** The tenant keys and their columns; none for an app of one tenant. */
13
13
  function tenantOf(pairs) {
@@ -20,6 +20,7 @@ function tenantOf(pairs) {
20
20
  async function writeNew(io, file, text, force) {
21
21
  const path = resolve(io.cwd, file);
22
22
  if (existsSync(path) && !force) throw new Error(`${file} exists. Pass --force to overwrite it.`);
23
+ await mkdir(dirname(path), { recursive: true });
23
24
  await writeFile(path, text);
24
25
  io.out(`Wrote ${file}.`);
25
26
  }
@@ -0,0 +1,21 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { z } from "zod";
3
+ // src/json.ts
4
+ /** A JSON file read as `schema` says it is; throws when it is not JSON or not that shape. */
5
+ function readJson(file, schema) {
6
+ return schema.parse(JSON.parse(readFileSync(file, "utf8")));
7
+ }
8
+ const deps = z.record(z.string(), z.string()).optional();
9
+ /** The parts of a package.json the CLI reads. */
10
+ const PackageJson = z.object({
11
+ version: z.string().optional(),
12
+ dependencies: deps,
13
+ devDependencies: deps
14
+ });
15
+ /** The parts of a shadcn app's components.json the CLI reads. */
16
+ const ComponentsJson = z.object({
17
+ base: z.string().optional(),
18
+ style: z.string().optional(),
19
+ tailwind: z.object({ css: z.string().optional() }).optional()
20
+ });
21
+ export { ComponentsJson, PackageJson, readJson };
@@ -0,0 +1,33 @@
1
+ import { ComponentsJson, readJson } from "./json.mjs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ // src/layers.ts
5
+ /** The cascade layer order a Tailwind app names once, so the theme sits above Tailwind's reset. */
6
+ const LAYER_LINE = "@layer theme, base, derive-dashboards, components, utilities;";
7
+ /** The app's Tailwind stylesheet, from components.json (`tailwind.css`), when it has one. */
8
+ function stylesheetOf(cwd) {
9
+ try {
10
+ const css = readJson(join(cwd, "components.json"), ComponentsJson).tailwind?.css;
11
+ return css !== void 0 && existsSync(join(cwd, css)) ? css : void 0;
12
+ } catch {
13
+ return;
14
+ }
15
+ }
16
+ /**
17
+ * Whether a Tailwind app's stylesheet names the layer order with the theme between Tailwind's
18
+ * reset and its utilities: undefined when the app has no Tailwind stylesheet to read.
19
+ */
20
+ function layerOrder(cwd) {
21
+ const file = stylesheetOf(cwd);
22
+ if (file === void 0) return void 0;
23
+ const text = readFileSync(join(cwd, file), "utf8");
24
+ if (!text.includes("tailwindcss")) return void 0;
25
+ const order = /@layer\s+([\w\s,-]+);/u.exec(text)?.[1]?.split(",").map((s) => s.trim());
26
+ const at = (name) => order?.indexOf(name) ?? -1;
27
+ const dd = at("derive-dashboards");
28
+ return {
29
+ file,
30
+ ok: dd > at("base") && at("base") >= 0 && (at("utilities") < 0 || dd < at("utilities"))
31
+ };
32
+ }
33
+ export { LAYER_LINE, layerOrder };
@@ -225,4 +225,4 @@ function repairLayout(doc) {
225
225
  }]
226
226
  };
227
227
  }
228
- export { GRID_COLUMNS, closeGaps, closeGapsCommands, compact, freeSpot, layoutGaps, packInto, placeItem, repairLayout };
228
+ export { GRID_COLUMNS, closeGaps, closeGapsCommands, compact, freeSpot, layoutGaps, overlaps, packInto, placeItem, repairLayout };
@@ -0,0 +1,14 @@
1
+ import { LayoutItem } from "./types.mjs";
2
+ /** The smallest a tile of this kind can be; a kind the kit does not know gets the number's size. */
3
+ export declare const smallestFor: (kind: string | undefined) => {
4
+ w: number;
5
+ h: number;
6
+ };
7
+ /**
8
+ * The layout as a viewer sees it, whatever was saved: every tile at least the size its kind
9
+ * reads at, nothing overlapping, no empty rows, no gap in the middle of a row, each row using
10
+ * the grid's whole width (its spare columns shared between its tiles), and a tile beside a
11
+ * taller one as tall as it. The saved layout is never changed; an editor draws it as saved.
12
+ * The order of tiles is kept.
13
+ */
14
+ export declare function viewLayout(layout: readonly LayoutItem[], kindOf: (widget: string) => string | undefined): LayoutItem[];
@@ -0,0 +1,157 @@
1
+ import { closeGaps, compact, layoutGaps, overlaps, packInto } from "./layout.mjs";
2
+ // src/document/view-layout.ts
3
+ /** The smallest each kind of tile reads at: a chart needs room for its axes, a table for rows. */
4
+ const SMALLEST = {
5
+ number: {
6
+ w: 2,
7
+ h: 2
8
+ },
9
+ line: {
10
+ w: 4,
11
+ h: 3
12
+ },
13
+ bar: {
14
+ w: 4,
15
+ h: 3
16
+ },
17
+ table: {
18
+ w: 4,
19
+ h: 3
20
+ },
21
+ list: {
22
+ w: 3,
23
+ h: 3
24
+ }
25
+ };
26
+ /** The smallest a tile of this kind can be; a kind the kit does not know gets the number's size. */
27
+ const smallestFor = (kind) => (kind === void 0 ? void 0 : SMALLEST[kind]) ?? {
28
+ w: 2,
29
+ h: 2
30
+ };
31
+ /**
32
+ * The tiles of one row band: items that start on the same row, are the same height and nothing
33
+ * else shares their rows. Their free columns at the right are shared out between them.
34
+ */
35
+ function rowBands(layout) {
36
+ const byRow = /* @__PURE__ */ new Map();
37
+ for (const item of layout) {
38
+ const key = `${String(item.y)}:${String(item.h)}`;
39
+ byRow.set(key, [...byRow.get(key) ?? [], item]);
40
+ }
41
+ return [...byRow.values()].map((band) => band.toSorted((a, b) => a.x - b.x)).filter((band) => {
42
+ const [first] = band;
43
+ if (first === void 0) return false;
44
+ const ids = new Set(band.map((i) => i.widget));
45
+ const rows = {
46
+ ...first,
47
+ x: 0,
48
+ w: 12
49
+ };
50
+ return !layout.some((other) => !ids.has(other.widget) && overlaps(other, rows));
51
+ });
52
+ }
53
+ /** A band's free columns at the right, shared out between its tiles, the leftmost first. */
54
+ function widened(band) {
55
+ const spare = 12 - band.reduce((sum, item) => sum + item.w, 0);
56
+ if (spare <= 0) return [...band];
57
+ const each = Math.floor(spare / band.length);
58
+ const extra = spare % band.length;
59
+ let x = 0;
60
+ return band.map((item, i) => {
61
+ const w = item.w + each + (i < extra ? 1 : 0);
62
+ const at = {
63
+ ...item,
64
+ x,
65
+ w
66
+ };
67
+ x += w;
68
+ return at;
69
+ });
70
+ }
71
+ /** A tile with free columns at its right that nothing else uses grows into them. */
72
+ function grownRight(layout) {
73
+ let current = [...layout];
74
+ for (const item of layout.toSorted((a, b) => a.y - b.y || b.x - a.x)) {
75
+ const at = current.find((i) => i.widget === item.widget);
76
+ if (at === void 0) continue;
77
+ const others = current.filter((i) => i.widget !== item.widget);
78
+ let w = at.w;
79
+ while (at.x + w < 12 && !others.some((o) => overlaps(o, {
80
+ ...at,
81
+ w: w + 1
82
+ }))) w += 1;
83
+ if (w !== at.w) current = current.map((i) => i.widget === at.widget ? {
84
+ ...at,
85
+ w
86
+ } : i);
87
+ }
88
+ return current;
89
+ }
90
+ /** A tile beside a taller one that starts on its row grows down to match it, into free space. */
91
+ function grownDown(layout) {
92
+ let current = [...layout];
93
+ for (const item of layout) {
94
+ const at = current.find((i) => i.widget === item.widget);
95
+ if (at === void 0) continue;
96
+ const bottom = Math.max(...current.filter((i) => i.y === at.y).map((i) => i.y + i.h));
97
+ const others = current.filter((i) => i.widget !== item.widget);
98
+ let h = at.h;
99
+ while (at.y + h < bottom && !others.some((o) => overlaps(o, {
100
+ ...at,
101
+ h: h + 1
102
+ }))) h += 1;
103
+ if (h !== at.h) current = current.map((i) => i.widget === at.widget ? {
104
+ ...at,
105
+ h
106
+ } : i);
107
+ }
108
+ return current;
109
+ }
110
+ /** Each tile, top to bottom, rises into free space above it, so no hole sits over a tile. */
111
+ function risen(layout) {
112
+ let current = [...layout];
113
+ for (const item of layout.toSorted((a, b) => a.y - b.y || a.x - b.x)) {
114
+ const at = current.find((i) => i.widget === item.widget);
115
+ if (at === void 0) continue;
116
+ const others = current.filter((i) => i.widget !== item.widget);
117
+ let y = at.y;
118
+ while (y > 0 && !others.some((o) => overlaps(o, {
119
+ ...at,
120
+ y: y - 1
121
+ }))) y -= 1;
122
+ if (y !== at.y) current = current.map((i) => i.widget === at.widget ? {
123
+ ...at,
124
+ y
125
+ } : i);
126
+ }
127
+ return current;
128
+ }
129
+ /** Holes closed until none is left: closing one can open room beside a tile it passed. */
130
+ function gapless(layout) {
131
+ let current = risen(layout);
132
+ for (let n = 0; n < 48 && layoutGaps(current).length > 0; n += 1) current = risen(closeGaps(current).layout);
133
+ return compact(current);
134
+ }
135
+ /**
136
+ * The layout as a viewer sees it, whatever was saved: every tile at least the size its kind
137
+ * reads at, nothing overlapping, no empty rows, no gap in the middle of a row, each row using
138
+ * the grid's whole width (its spare columns shared between its tiles), and a tile beside a
139
+ * taller one as tall as it. The saved layout is never changed; an editor draws it as saved.
140
+ * The order of tiles is kept.
141
+ */
142
+ function viewLayout(layout, kindOf) {
143
+ const sized = layout.map((item) => {
144
+ const least = smallestFor(kindOf(item.widget));
145
+ return {
146
+ ...item,
147
+ w: Math.max(item.w, least.w),
148
+ h: Math.max(item.h, least.h)
149
+ };
150
+ });
151
+ const closed = gapless(packInto([], sized));
152
+ const bands = new Map(rowBands(closed).flatMap((band) => widened(band).map((item) => [item.widget, item])));
153
+ const filled = gapless(grownDown(grownRight(closed.map((item) => bands.get(item.widget) ?? item))));
154
+ const order = new Map(layout.map((item, i) => [item.widget, i]));
155
+ return filled.toSorted((a, b) => (order.get(a.widget) ?? 0) - (order.get(b.widget) ?? 0));
156
+ }
157
+ export { smallestFor, viewLayout };