derive-dashboards 0.1.0 → 0.1.1

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 (301) hide show
  1. package/README.md +4 -3
  2. package/dist/adapter/sql-adapter.mjs +4 -4
  3. package/dist/body.mjs +11 -1
  4. package/dist/cache.d.mts +1 -1
  5. package/dist/cli/check.mjs +14 -1
  6. package/dist/cli/import/dbt-schema.mjs +2 -2
  7. package/dist/cli/import/index.mjs +2 -2
  8. package/dist/core/conformance/cases.d.mts +3 -0
  9. package/dist/core/conformance/cases.mjs +20 -4
  10. package/dist/core/conformance/check.mjs +6 -3
  11. package/dist/core/conformance/drill-cases.mjs +120 -0
  12. package/dist/core/document/view.d.mts +26 -7
  13. package/dist/core/document/view.mjs +42 -11
  14. package/dist/core/engine/index.d.mts +14 -2
  15. package/dist/core/engine/index.mjs +12 -1
  16. package/dist/core/engine/members.mjs +1 -1
  17. package/dist/core/engine/postgres.mjs +1 -1
  18. package/dist/core/engine/record-layout.d.mts +11 -0
  19. package/dist/core/engine/record-layout.mjs +7 -7
  20. package/dist/core/engine/records.d.mts +3 -2
  21. package/dist/core/engine/records.mjs +2 -1
  22. package/dist/core/engine/segmented.mjs +5 -2
  23. package/dist/core/engine/sql-records.mjs +2 -1
  24. package/dist/core/engine/statement.mjs +37 -3
  25. package/dist/core/engine/types.d.mts +3 -0
  26. package/dist/core/engine/version.d.mts +1 -1
  27. package/dist/core/engine/version.mjs +1 -1
  28. package/dist/core/error/codes.d.mts +31 -0
  29. package/dist/core/error/codes.mjs +28 -1
  30. package/dist/core/index.d.mts +9 -5
  31. package/dist/core/index.mjs +5 -3
  32. package/dist/core/model/catalog/check.mjs +1 -1
  33. package/dist/core/model/hints.d.mts +36 -0
  34. package/dist/core/model/member.d.mts +4 -2
  35. package/dist/core/model/member.mjs +16 -3
  36. package/dist/core/model/types.d.mts +8 -6
  37. package/dist/core/model/validate/drill.mjs +70 -0
  38. package/dist/core/model/validate/index.mjs +3 -0
  39. package/dist/core/model/validate/shape.mjs +150 -0
  40. package/dist/core/model/validate/source.mjs +5 -3
  41. package/dist/core/query/alias.mjs +7 -1
  42. package/dist/core/query/drill/compose.d.mts +22 -0
  43. package/dist/core/query/drill/compose.mjs +85 -0
  44. package/dist/core/query/drill/fields.d.mts +21 -0
  45. package/dist/core/query/drill/fields.mjs +91 -0
  46. package/dist/core/query/drill/internal.d.mts +11 -0
  47. package/dist/core/query/drill/items.d.mts +29 -0
  48. package/dist/core/query/drill/items.mjs +98 -0
  49. package/dist/core/query/drill/line.d.mts +31 -0
  50. package/dist/core/query/drill/line.mjs +183 -0
  51. package/dist/core/query/drill/links.d.mts +33 -0
  52. package/dist/core/query/drill/links.mjs +31 -0
  53. package/dist/core/query/drill/operand.mjs +7 -0
  54. package/dist/core/query/drill/scopes.d.mts +22 -0
  55. package/dist/core/query/drill/scopes.mjs +58 -0
  56. package/dist/core/query/drill/selection.d.mts +37 -0
  57. package/dist/core/query/drill/selection.mjs +144 -0
  58. package/dist/core/query/drill/steps.d.mts +14 -0
  59. package/dist/core/query/drill/steps.mjs +35 -0
  60. package/dist/core/query/drill/synthetic-expr.mjs +85 -0
  61. package/dist/core/query/drill/synthetic.d.mts +22 -0
  62. package/dist/core/query/drill/synthetic.mjs +165 -0
  63. package/dist/core/query/drill/time.d.mts +11 -0
  64. package/dist/core/query/drill/time.mjs +71 -0
  65. package/dist/core/query/drill/types.d.mts +155 -0
  66. package/dist/core/query/drill/types.mjs +4 -0
  67. package/dist/core/query/drill/views.d.mts +62 -0
  68. package/dist/core/query/drill/views.mjs +257 -0
  69. package/dist/core/query/segments.d.mts +12 -2
  70. package/dist/core/query/segments.mjs +3 -1
  71. package/dist/core/result/columns.mjs +17 -4
  72. package/dist/core/result/types.d.mts +5 -1
  73. package/dist/core/schema/answer-parts.mjs +117 -0
  74. package/dist/core/schema/answers.d.mts +2108 -128
  75. package/dist/core/schema/answers.mjs +10 -113
  76. package/dist/core/schema/commands.d.mts +2 -2
  77. package/dist/core/schema/document.d.mts +1 -1
  78. package/dist/core/schema/drill-answers.mjs +179 -0
  79. package/dist/core/schema/drill.d.mts +260 -0
  80. package/dist/core/schema/drill.mjs +107 -0
  81. package/dist/core/schema/index.d.mts +4 -2
  82. package/dist/core/schema/index.mjs +4 -2
  83. package/dist/core/schema/picks.d.mts +35 -0
  84. package/dist/core/schema/picks.mjs +23 -0
  85. package/dist/core/schema/query.d.mts +1 -1
  86. package/dist/core/schema/tools.mjs +1 -1
  87. package/dist/core/schema/view.d.mts +0 -35
  88. package/dist/core/schema/view.mjs +19 -24
  89. package/dist/core/store/schema.d.mts +5 -0
  90. package/dist/core/store/schema.mjs +10 -0
  91. package/dist/core/types/api.d.mts +15 -1
  92. package/dist/core/types/api.mjs +1 -1
  93. package/dist/core/types/drill-api.d.mts +210 -0
  94. package/dist/core/types/options.d.mts +21 -0
  95. package/dist/core/types/viewer.d.mts +5 -0
  96. package/dist/cursor-seal.d.mts +8 -0
  97. package/dist/cursor-seal.mjs +98 -0
  98. package/dist/dashboard-id.mjs +1 -1
  99. package/dist/drill-access.mjs +93 -0
  100. package/dist/drill-change.mjs +76 -0
  101. package/dist/drill-crumbs.mjs +113 -0
  102. package/dist/drill-distinct.mjs +130 -0
  103. package/dist/drill-explain.mjs +64 -0
  104. package/dist/drill-identity.mjs +35 -0
  105. package/dist/drill-item-id.mjs +35 -0
  106. package/dist/drill-items.mjs +132 -0
  107. package/dist/drill-open.mjs +169 -0
  108. package/dist/drill-seal.mjs +170 -0
  109. package/dist/drill-secret.mjs +14 -0
  110. package/dist/drill-share.mjs +53 -0
  111. package/dist/drill-summary.mjs +158 -0
  112. package/dist/drill-targets.mjs +53 -0
  113. package/dist/drill-totals.mjs +8 -0
  114. package/dist/drill-views.mjs +175 -0
  115. package/dist/drill.mjs +157 -0
  116. package/dist/editing.mjs +2 -2
  117. package/dist/endpoints/dashboards.mjs +11 -3
  118. package/dist/endpoints/drill.mjs +55 -0
  119. package/dist/endpoints/index.d.mts +233 -2
  120. package/dist/endpoints/index.mjs +5 -1
  121. package/dist/endpoints/query.mjs +26 -4
  122. package/dist/execute.d.mts +19 -1
  123. package/dist/execute.mjs +15 -17
  124. package/dist/index.d.mts +3 -1
  125. package/dist/index.mjs +29 -2
  126. package/dist/mcp/drill.mjs +61 -0
  127. package/dist/mcp/format.mjs +27 -3
  128. package/dist/mcp/index.d.mts +15 -4
  129. package/dist/mcp/index.mjs +13 -7
  130. package/dist/mcp/query.d.mts +7 -2
  131. package/dist/mcp/query.mjs +7 -3
  132. package/dist/node-postgres.d.mts +8 -4
  133. package/dist/node-postgres.mjs +29 -6
  134. package/dist/owner.mjs +3 -3
  135. package/dist/postgres-connection.d.mts +8 -2
  136. package/dist/postgres-connection.mjs +2 -1
  137. package/dist/react/Dashboard.d.mts +10 -5
  138. package/dist/react/Dashboard.mjs +51 -23
  139. package/dist/react/DashboardList.mjs +30 -2
  140. package/dist/react/Discard.mjs +7 -2
  141. package/dist/react/Grid.mjs +12 -5
  142. package/dist/react/Header.mjs +9 -0
  143. package/dist/react/Parts.mjs +6 -2
  144. package/dist/react/ReviewPanel.mjs +13 -2
  145. package/dist/react/RowBody.d.mts +19 -0
  146. package/dist/react/RowBody.mjs +55 -0
  147. package/dist/react/Tile.d.mts +1 -1
  148. package/dist/react/Tile.mjs +54 -30
  149. package/dist/react/builder/state.d.mts +1 -1
  150. package/dist/react/client.d.mts +2 -0
  151. package/dist/react/client.mjs +1 -0
  152. package/dist/react/context.d.mts +15 -1
  153. package/dist/react/context.mjs +19 -4
  154. package/dist/react/drill/Bars.mjs +179 -0
  155. package/dist/react/drill/Controls.mjs +173 -0
  156. package/dist/react/drill/DashboardTile.d.mts +18 -0
  157. package/dist/react/drill/DashboardTile.mjs +107 -0
  158. package/dist/react/drill/DrillPanel.d.mts +31 -0
  159. package/dist/react/drill/DrillPanel.mjs +104 -0
  160. package/dist/react/drill/DrillTabs.mjs +52 -0
  161. package/dist/react/drill/Header.mjs +131 -0
  162. package/dist/react/drill/Items.d.mts +22 -0
  163. package/dist/react/drill/Items.mjs +164 -0
  164. package/dist/react/drill/ItemsFoot.mjs +60 -0
  165. package/dist/react/drill/Notes.mjs +58 -0
  166. package/dist/react/drill/PanelBody.mjs +74 -0
  167. package/dist/react/drill/PanelStates.mjs +37 -0
  168. package/dist/react/drill/board.d.mts +18 -0
  169. package/dist/react/drill/board.mjs +91 -0
  170. package/dist/react/drill/counts.mjs +14 -0
  171. package/dist/react/drill/host.mjs +26 -0
  172. package/dist/react/drill/item-parts.d.mts +5 -0
  173. package/dist/react/drill/item-parts.mjs +76 -0
  174. package/dist/react/drill/item-type.d.mts +26 -0
  175. package/dist/react/drill/item-type.mjs +7 -0
  176. package/dist/react/drill/lazy.d.mts +6 -0
  177. package/dist/react/drill/lazy.mjs +17 -0
  178. package/dist/react/drill/pages.mjs +48 -0
  179. package/dist/react/drill/panel-focus.mjs +51 -0
  180. package/dist/react/drill/props.d.mts +25 -0
  181. package/dist/react/drill/props.mjs +72 -0
  182. package/dist/react/drill/state.d.mts +18 -0
  183. package/dist/react/drill/state.mjs +68 -0
  184. package/dist/react/drill/useDrill.d.mts +46 -0
  185. package/dist/react/drill/useDrill.mjs +194 -0
  186. package/dist/react/drill/words.d.mts +98 -0
  187. package/dist/react/drill/words.mjs +77 -0
  188. package/dist/react/english.mjs +9 -1
  189. package/dist/react/format.d.mts +3 -3
  190. package/dist/react/format.mjs +34 -12
  191. package/dist/react/index.d.mts +27 -4
  192. package/dist/react/index.mjs +10 -3
  193. package/dist/react/messages.d.mts +14 -1
  194. package/dist/react/renderers/index.d.mts +10 -2
  195. package/dist/react/renderers/index.mjs +54 -14
  196. package/dist/react/renderers/list.d.mts +22 -0
  197. package/dist/react/renderers/list.mjs +118 -0
  198. package/dist/react/review-words.mjs +1 -1
  199. package/dist/react/review.mjs +2 -2
  200. package/dist/react/scope.mjs +2 -7
  201. package/dist/react/series.d.mts +37 -0
  202. package/dist/react/series.mjs +95 -0
  203. package/dist/react/theme.css +1823 -1296
  204. package/dist/react/theme.css.d.ts +1 -0
  205. package/dist/react/tile-store.mjs +15 -3
  206. package/dist/react/useBoard.d.mts +5 -0
  207. package/dist/react/useBoard.mjs +4 -1
  208. package/dist/react/useDashboard.d.mts +1 -0
  209. package/dist/react/useDashboard.mjs +2 -1
  210. package/dist/react/useTiles.mjs +50 -15
  211. package/dist/react/view.d.mts +9 -0
  212. package/dist/react/view.mjs +22 -10
  213. package/dist/reading.d.mts +2 -0
  214. package/dist/reading.mjs +9 -1
  215. package/dist/recharts/charts.d.mts +0 -1
  216. package/dist/recharts/charts.mjs +128 -34
  217. package/dist/recharts/index.d.mts +2 -2
  218. package/dist/recharts/index.mjs +2 -2
  219. package/dist/recharts/marks.mjs +83 -0
  220. package/dist/recharts/series.d.mts +2 -22
  221. package/dist/recharts/series.mjs +1 -64
  222. package/dist/records-read.mjs +44 -0
  223. package/dist/store/apply.mjs +5 -5
  224. package/dist/store/commands.mjs +4 -4
  225. package/dist/store/discard.mjs +7 -7
  226. package/dist/store/drafts.mjs +5 -5
  227. package/dist/store/editor.mjs +1 -1
  228. package/dist/store/publish.mjs +12 -12
  229. package/dist/store/reader.mjs +41 -22
  230. package/dist/store/review.mjs +16 -16
  231. package/dist/store/rows.mjs +20 -20
  232. package/dist/store/undo.mjs +3 -3
  233. package/dist/store/unpublished.mjs +4 -4
  234. package/dist/store/versions.mjs +14 -14
  235. package/dist/testing/adapter-suite.mjs +4 -4
  236. package/dist/tiles.mjs +37 -3
  237. package/package.json +8 -10
  238. package/dist/react/Records.d.mts +0 -12
  239. package/dist/react/Records.mjs +0 -97
  240. package/src/adapter/sql-adapter.ts +0 -95
  241. package/src/adapter/statement.ts +0 -185
  242. package/src/authorize.ts +0 -73
  243. package/src/body.ts +0 -169
  244. package/src/bounded.ts +0 -43
  245. package/src/cache.ts +0 -192
  246. package/src/checks.ts +0 -170
  247. package/src/custom-source.ts +0 -59
  248. package/src/dashboard-id.ts +0 -36
  249. package/src/dashboards.ts +0 -132
  250. package/src/editing.ts +0 -148
  251. package/src/endpoints/access.ts +0 -41
  252. package/src/endpoints/dashboards.ts +0 -92
  253. package/src/endpoints/drafts.ts +0 -138
  254. package/src/endpoints/index.ts +0 -21
  255. package/src/endpoints/meta.ts +0 -137
  256. package/src/endpoints/query.ts +0 -86
  257. package/src/endpoints/read.ts +0 -92
  258. package/src/endpoints/review.ts +0 -89
  259. package/src/endpoints/values.ts +0 -62
  260. package/src/endpoints/versions.ts +0 -104
  261. package/src/execute.ts +0 -207
  262. package/src/handler.ts +0 -232
  263. package/src/http.ts +0 -66
  264. package/src/index.ts +0 -163
  265. package/src/introspect.ts +0 -205
  266. package/src/mcp/api.ts +0 -59
  267. package/src/mcp/format.ts +0 -67
  268. package/src/mcp/index.ts +0 -151
  269. package/src/mcp/query.ts +0 -153
  270. package/src/mcp/resolve.ts +0 -114
  271. package/src/node-postgres.ts +0 -81
  272. package/src/owner.ts +0 -36
  273. package/src/postgres-connection.ts +0 -143
  274. package/src/postgres-store.ts +0 -82
  275. package/src/principal.ts +0 -39
  276. package/src/reading.ts +0 -56
  277. package/src/request-rows.ts +0 -23
  278. package/src/request.ts +0 -22
  279. package/src/storage.ts +0 -63
  280. package/src/store/apply.ts +0 -129
  281. package/src/store/commands.ts +0 -75
  282. package/src/store/conflicts.ts +0 -98
  283. package/src/store/create-tables.ts +0 -104
  284. package/src/store/discard.ts +0 -42
  285. package/src/store/drafts.ts +0 -133
  286. package/src/store/editor.ts +0 -28
  287. package/src/store/log.ts +0 -28
  288. package/src/store/publish.ts +0 -199
  289. package/src/store/publisher.ts +0 -21
  290. package/src/store/reader.ts +0 -139
  291. package/src/store/review.ts +0 -239
  292. package/src/store/rows.ts +0 -250
  293. package/src/store/tenant.ts +0 -28
  294. package/src/store/undo.ts +0 -56
  295. package/src/store/unpublished.ts +0 -33
  296. package/src/store/versions.ts +0 -106
  297. package/src/store/writer.ts +0 -19
  298. package/src/testing/adapter-suite.ts +0 -239
  299. package/src/testing/index.ts +0 -2
  300. package/src/tile-doc.ts +0 -46
  301. package/src/tiles.ts +0 -120
@@ -1,129 +0,0 @@
1
- import {
2
- type Author,
3
- type Command,
4
- type CommandBody,
5
- type CommandId,
6
- canonical,
7
- type DashAdapter,
8
- type Draft,
9
- type Row,
10
- reduceAll,
11
- type Tenant,
12
- } from "@derive-to/dashboards-core";
13
- import { sha256 } from "../cache";
14
- import { HttpError } from "../http";
15
- import { writeCommands } from "./commands";
16
- import {
17
- advanceDraft,
18
- draftOf,
19
- expectRevision,
20
- inTransaction,
21
- namedOf,
22
- now,
23
- openDraft,
24
- } from "./rows";
25
-
26
- /** Applying edits to a draft: each batch all or nothing, each command once. */
27
-
28
- const bodyOf = ({ commandId: _id, ...body }: Command): CommandBody => body;
29
- const digestOf = (command: Command) => sha256(canonical(bodyOf(command)));
30
-
31
- /**
32
- * Commands this draft already applied, found in one read: by id, a retry with the same body is
33
- * acknowledged; the same id with another body is refused.
34
- */
35
- async function newCommands(
36
- tx: DashAdapter,
37
- draftId: unknown,
38
- commands: readonly Command[],
39
- ): Promise<{ fresh: Command[]; acknowledged: CommandId[] }> {
40
- // Only this batch's ids: an edit reads none of the draft's other commands.
41
- const seen = await tx.findMany({
42
- table: "dd_dashboard_draft_command",
43
- where: [
44
- { field: "draft_id", value: draftId },
45
- { field: "command_id", op: "in", value: commands.map((c) => c.commandId) },
46
- ],
47
- });
48
- const digests = new Map(seen.map((r) => [String(r["command_id"]), String(r["digest"])]));
49
- const fresh: Command[] = [];
50
- const acknowledged: CommandId[] = [];
51
- for (const command of commands) {
52
- const stored = digests.get(command.commandId);
53
- // oxlint-disable-next-line no-await-in-loop -- a digest is a hash of this one command
54
- const same = stored !== undefined && stored === (await digestOf(command));
55
- if (stored === undefined) fresh.push(command);
56
- else if (same) acknowledged.push(command.commandId);
57
- else
58
- throw new HttpError(
59
- 409,
60
- "DUPLICATE_COMMAND_ID",
61
- `The command id "${command.commandId}" was used for another edit.`,
62
- );
63
- }
64
- return { fresh, acknowledged };
65
- }
66
-
67
- /** The draft row's summary after one more edit: a step more, the widgets it names, the next sequence. */
68
- function summed(row: Row, current: Draft, fresh: readonly Command[]) {
69
- const moved = fresh.flatMap((c) => {
70
- const body = bodyOf(c);
71
- return body.type === "widget.move" ? [body.id] : [];
72
- });
73
- const named = new Set([...namedOf(row), ...moved]);
74
- return {
75
- steps: current.steps + 1,
76
- named: [...named].toSorted(),
77
- next_seq: Number(row["next_seq"]) + fresh.length,
78
- };
79
- }
80
-
81
- /**
82
- * Applies a batch of commands to the author's open draft, made against `expectedRevision`: all or
83
- * nothing, a refused command refuses the batch with its reason. The commands are kept, in
84
- * order, so a publish on top of someone else's version can replay them.
85
- */
86
- export function applyDraft(
87
- db: DashAdapter,
88
- a: {
89
- tenant: Tenant;
90
- id: string;
91
- author: Author;
92
- expectedRevision: number;
93
- commands: readonly Command[];
94
- },
95
- ): Promise<{ draft: Draft; acknowledged: readonly CommandId[] }> {
96
- return inTransaction(db, async (tx) => {
97
- const { row } = await openDraft(tx, a);
98
- const { fresh, acknowledged } = await newCommands(tx, row["id"], a.commands);
99
- const current = draftOf(row);
100
- // A retry of a batch already applied is acknowledged whatever revision it names: the
101
- // client that lost the answer still holds the revision it sent the batch against.
102
- if (fresh.length === 0) return { draft: current, acknowledged };
103
- expectRevision(row, a.expectedRevision);
104
- const outcome = reduceAll(
105
- current.doc,
106
- fresh.map((c) => bodyOf(c)),
107
- );
108
- if (!outcome.ok)
109
- throw new HttpError(400, "EDIT_REFUSED", outcome.issue.message, {
110
- issues: [outcome.issue],
111
- });
112
- const revision = current.revision + 1;
113
- const at = now();
114
- const first = Number(row["next_seq"]);
115
- const set = { spec: outcome.doc, revision, ...summed(row, current, fresh), updated_at: at };
116
- await advanceDraft(tx, row, set);
117
- const added = await Promise.all(
118
- fresh.map(async (c) => ({
119
- commandId: c.commandId,
120
- body: bodyOf(c),
121
- revision,
122
- digest: await digestOf(c),
123
- })),
124
- );
125
- await writeCommands(tx, { draftId: row["id"], commands: added, first, at });
126
- const draft = draftOf({ ...row, ...set });
127
- return { draft, acknowledged };
128
- });
129
- }
@@ -1,75 +0,0 @@
1
- import type { CommandBody, DashAdapter, Recorded } from "@derive-to/dashboards-core";
2
- import { now } from "./rows";
3
-
4
- /** A draft's commands as it keeps them: each with the edit (revision) it came in. */
5
-
6
- export type Kept = Recorded & { revision: number; digest: string };
7
-
8
- /** The draft's commands in the order they were applied. */
9
- export async function keptCommands(tx: DashAdapter, draftId: unknown): Promise<Kept[]> {
10
- const rows = await tx.findMany({
11
- table: "dd_dashboard_draft_command",
12
- where: [{ field: "draft_id", value: draftId }],
13
- orderBy: [{ field: "seq", direction: "asc" }],
14
- });
15
- return rows.map((r) => ({
16
- commandId: String(r["command_id"]),
17
- // The bodies were checked by the command schema when they were applied.
18
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion
19
- body: r["body"] as CommandBody,
20
- revision: Number(r["revision"]),
21
- digest: String(r["digest"]),
22
- }));
23
- }
24
-
25
- /** A draft's commands as rows, numbered from `first`; written in one statement where the store can. */
26
- export async function writeCommands(
27
- tx: DashAdapter,
28
- a: { draftId: unknown; commands: readonly Kept[]; first: number; at: string },
29
- ): Promise<void> {
30
- const rows = a.commands.map((k, i) => ({
31
- draft_id: a.draftId,
32
- command_id: k.commandId,
33
- digest: k.digest,
34
- body: k.body,
35
- revision: k.revision,
36
- seq: a.first + i,
37
- created_at: a.at,
38
- }));
39
- if (rows.length === 0) return;
40
- if (tx.createMany !== undefined) {
41
- await tx.createMany({ table: "dd_dashboard_draft_command", rows });
42
- return;
43
- }
44
- // oxlint-disable-next-line no-await-in-loop -- a store without createMany, one row at a time
45
- for (const data of rows) await tx.create({ table: "dd_dashboard_draft_command", data });
46
- }
47
-
48
- /** Replaces a draft's kept commands with these, in order. */
49
- export async function rewriteCommands(
50
- tx: DashAdapter,
51
- draftId: unknown,
52
- kept: readonly Kept[],
53
- ): Promise<void> {
54
- await tx.deleteMany({
55
- table: "dd_dashboard_draft_command",
56
- where: [{ field: "draft_id", value: draftId }],
57
- });
58
- await writeCommands(tx, { draftId, commands: kept, first: 0, at: now() });
59
- }
60
-
61
- /** How many edits Undo can step back through: one per revision that applied commands. */
62
- const stepsIn = (kept: readonly Kept[]) => new Set(kept.map((k) => k.revision)).size;
63
-
64
- /**
65
- * The widgets a draft's commands move, so a move of any other is read as room made: a title
66
- * edit names a widget, but a push from another tile's resize is still not its own move.
67
- */
68
- const namedBy = (kept: readonly Recorded[]) =>
69
- new Set(kept.flatMap((k) => (k.body.type === "widget.move" ? [k.body.id] : [])));
70
-
71
- /** The draft row's columns that sum up its kept commands, for a write that has them all. */
72
- export const keptColumns = (kept: readonly Kept[]) => ({
73
- steps: stepsIn(kept),
74
- named: [...namedBy(kept)].toSorted(),
75
- });
@@ -1,98 +0,0 @@
1
- import {
2
- type Change,
3
- commandWidget,
4
- type Doc,
5
- type OverlapPart,
6
- type Preview,
7
- type Refusal,
8
- reduceAll,
9
- type replay,
10
- widgetDiff,
11
- } from "@derive-to/dashboards-core";
12
- import type { Kept } from "./commands";
13
-
14
- /** What a review says about a draft replayed on a newer version: what no longer applies, and what both changed. */
15
-
16
- /** The changes that no longer apply, each with its reason and the widget it needs by its title. */
17
- export function refusalsOf(
18
- kept: readonly Kept[],
19
- merged: ReturnType<typeof replay>,
20
- titles: Doc[],
21
- ) {
22
- return merged.outcomes.flatMap((o, i): Refusal[] => {
23
- const k = kept[i];
24
- if (o.applied || k === undefined) return [];
25
- const title = titles.map((d) => d.widgets[o.widget ?? ""]?.title).find((t) => t !== undefined);
26
- return [
27
- {
28
- commandId: o.commandId,
29
- body: k.body,
30
- issue: { code: o.issue.code, message: o.issue.message },
31
- ...(o.widget === undefined ? {} : { widget: { id: o.widget, title: title ?? o.widget } }),
32
- },
33
- ];
34
- });
35
- }
36
-
37
- /** What changes touched, as "widget part": each part of it edited, its place, or all of it. */
38
- const touchedBy = (changes: readonly Change[]) =>
39
- changes.flatMap((c) => {
40
- if (c.kind === "widget.edited") return c.parts.map((part) => `${c.widget} ${part}`);
41
- if (c.kind === "widget.moved") return [`${c.widget} place`];
42
- return c.kind === "widget.removed" ? [`${c.widget} removed`] : [];
43
- });
44
-
45
- /** The parts of a widget a change of the person's touched that the newer version's changes did too. */
46
- function shared(
47
- mine: readonly string[],
48
- theirs: ReadonlySet<string>,
49
- widget: string,
50
- ): OverlapPart[] {
51
- const parts = mine.flatMap((t): OverlapPart[] => {
52
- const part = t.slice(widget.length + 1);
53
- if (part === "removed")
54
- return [...theirs].some((x) => x.startsWith(`${widget} `)) ? ["removed"] : [];
55
- return theirs.has(t) && isOverlapPart(part) ? [part] : [];
56
- });
57
- return [...new Set(parts)];
58
- }
59
-
60
- const OVERLAP_PARTS: ReadonlySet<string> = new Set([
61
- "title",
62
- "kind",
63
- "display",
64
- "query",
65
- "place",
66
- "removed",
67
- ]);
68
- const isOverlapPart = (part: string): part is OverlapPart => OVERLAP_PARTS.has(part);
69
-
70
- /**
71
- * The person's applied changes to a part of a widget (its title, kind, display, query or
72
- * place) that someone else changed since the draft started, or that remove a widget they
73
- * changed: nothing refuses them, so without this the other person's edit would go quietly.
74
- * Each change is read by what it did to its own widget on top of the newer version, so a
75
- * change to another part of the same widget does not count.
76
- */
77
- export function overlapsOf(
78
- kept: readonly Kept[],
79
- merged: ReturnType<typeof replay>,
80
- since: readonly Change[],
81
- head: Doc,
82
- ): Preview["overlaps"] {
83
- const theirs = new Set(touchedBy(since));
84
- if (theirs.size === 0) return [];
85
- let current = head;
86
- return kept.flatMap((k, i) => {
87
- const widget = commandWidget(k.body);
88
- const step = merged.outcomes[i]?.applied === true ? reduceAll(current, [k.body]) : undefined;
89
- if (step === undefined || !step.ok) return [];
90
- const before = current;
91
- current = step.doc;
92
- if (widget === undefined) return [];
93
- const parts = shared(touchedBy(widgetDiff(before, step.doc, widget)), theirs, widget);
94
- if (parts.length === 0) return [];
95
- const title = head.widgets[widget]?.title ?? widget;
96
- return [{ commandId: k.commandId, widget: { id: widget, title }, parts }];
97
- });
98
- }
@@ -1,104 +0,0 @@
1
- import { type DashAdapter, schemaChecks } from "@derive-to/dashboards-core";
2
- import { inTransaction } from "./rows";
3
-
4
- /** Thrown when a `dd_` table lacks a required column with no default: rows there would have no value. */
5
- export class SchemaMismatchError extends Error {
6
- constructor(table: string, column: string, cause?: unknown) {
7
- super(
8
- `The table ${table} lacks the required column ${column}, which has no default to give rows already there. It was made by an early pre-release: drop the dd_ tables (they hold only dashboards) and run createTables again.`,
9
- { cause },
10
- );
11
- this.name = "SchemaMismatchError";
12
- }
13
- }
14
-
15
- /** What it takes to bring a database to this schema, in the order to run it. */
16
- export type SchemaDiff = { tables: string[]; columns: string[]; indexes: string[] };
17
-
18
- /**
19
- * The columns each `dd_` table has, read from the database's catalog, and the schema they are
20
- * all in, if they share one: a table a newer release adds is made beside them, so a host's grants
21
- * and backups on that schema cover it.
22
- */
23
- async function present(
24
- adapter: DashAdapter,
25
- ): Promise<{ have: Map<string, Set<string>>; home?: string }> {
26
- const have = new Map<string, Set<string>>();
27
- const schemas = new Set<string | undefined>();
28
- for (const { table, column, schema } of await adapter.schema.columns()) {
29
- const columns = have.get(table) ?? new Set<string>();
30
- columns.add(column);
31
- have.set(table, columns);
32
- schemas.add(schema);
33
- }
34
- const [home] = schemas;
35
- return schemas.size === 1 && home !== undefined ? { have, home } : { have };
36
- }
37
-
38
- /**
39
- * The difference between a database and this schema, read from its catalog: the tables it
40
- * lacks, the columns an older table lacks (nullable, or with a default, so rows there are kept),
41
- * and every key and index (made only if missing). It only reads. `createTables` runs it;
42
- * `generate --diff` writes it for a host's own migration tool.
43
- */
44
- export async function schemaDiff(adapter: DashAdapter): Promise<SchemaDiff> {
45
- const { have, home } = await present(adapter);
46
- const diff: SchemaDiff = { tables: [], columns: [], indexes: [] };
47
- for (const check of schemaChecks(adapter.schema.dialect, home)) {
48
- const [table = "", ...keys] = check.create;
49
- diff.indexes.push(...keys);
50
- const columns = have.get(check.table);
51
- if (columns === undefined) {
52
- diff.tables.push(table);
53
- continue;
54
- }
55
- for (const column of check.columns) {
56
- if (columns.has(column.name)) continue;
57
- if (column.add === undefined) throw new SchemaMismatchError(check.table, column.name);
58
- diff.columns.push(column.add);
59
- }
60
- }
61
- return diff;
62
- }
63
-
64
- /** Runs a diff: new tables in one transaction, columns one by one, then keys and indexes. */
65
- async function apply(adapter: DashAdapter, diff: SchemaDiff): Promise<void> {
66
- const run = async (db: DashAdapter, statements: readonly string[]) => {
67
- for (const statement of statements) {
68
- // oxlint-disable-next-line no-await-in-loop -- DDL runs in order, one statement at a time
69
- await db.schema.execute(statement);
70
- }
71
- };
72
- await inTransaction(adapter, (tx) => run(tx, diff.tables));
73
- await run(adapter, diff.columns);
74
- await inTransaction(adapter, (tx) => run(tx, diff.indexes));
75
- }
76
-
77
- /**
78
- * Makes the library's `dd_` tables, keys and indexes, and brings older ones up to this
79
- * schema: there is one schema, no migration history. Tables that are missing are made; a
80
- * table an older release made gets the columns this release added (a release only adds
81
- * columns that are nullable or have a default, so rows are kept), then any keys and indexes
82
- * it lacks. Safe to run on every start, from every instance: when another instance makes the
83
- * same thing first, the database is read again and only what is still missing is run. For a
84
- * host with its own schema tool, `generate` writes the same tables, and `generate --diff` only
85
- * what a database lacks.
86
- */
87
- export async function createTables(adapter: DashAdapter): Promise<void> {
88
- const diff = await schemaDiff(adapter);
89
- try {
90
- await apply(adapter, diff);
91
- } catch (first) {
92
- // Another instance may have made a table or index between the read and the write; read
93
- // again. A failure that is not that one fails again here, and is thrown with the first.
94
- try {
95
- await apply(adapter, await schemaDiff(adapter));
96
- } catch (second) {
97
- throw new AggregateError(
98
- [first, second],
99
- `createTables failed, and again after reading the database once more: ${second instanceof Error ? second.message : String(second)}`,
100
- { cause: second },
101
- );
102
- }
103
- }
104
- }
@@ -1,42 +0,0 @@
1
- import type { Author, DashAdapter, Tenant } from "@derive-to/dashboards-core";
2
- import { advanceDraft, expectRevision, inTransaction, now, openDraft } from "./rows";
3
-
4
- /**
5
- * Drops the author's open draft. A dashboard that was never published, and that nobody else
6
- * is editing, goes with it: a new one disappears, and a built-in serves its code document.
7
- */
8
- export function discardDraft(
9
- db: DashAdapter,
10
- a: { tenant: Tenant; id: string; author: Author; expectedRevision: number },
11
- ): Promise<{ removed: boolean }> {
12
- return inTransaction(db, async (tx) => {
13
- const { row, dashboard } = await openDraft(tx, a);
14
- expectRevision(row, a.expectedRevision);
15
- await tx.deleteMany({
16
- table: "dd_dashboard_draft_command",
17
- where: [{ field: "draft_id", value: row["id"] }],
18
- });
19
- const others = await tx.count({
20
- table: "dd_dashboard_draft",
21
- where: [
22
- { field: "dashboard_id", value: dashboard["id"] },
23
- { field: "state", value: "open" },
24
- { field: "id", op: "ne", value: row["id"] },
25
- ],
26
- });
27
- if (dashboard["current_version"] === null && others === 0) {
28
- await tx.deleteMany({
29
- table: "dd_dashboard_draft",
30
- where: [{ field: "dashboard_id", value: dashboard["id"] }],
31
- });
32
- await tx.deleteMany({
33
- table: "dd_dashboard",
34
- where: [{ field: "id", value: dashboard["id"] }],
35
- });
36
- // A built-in still serves its code document: only a new dashboard is gone.
37
- return { removed: dashboard["default_of"] === null };
38
- }
39
- await advanceDraft(tx, row, { state: "closed", updated_at: now() });
40
- return { removed: false };
41
- });
42
- }
@@ -1,133 +0,0 @@
1
- import type {
2
- Author,
3
- DashAdapter,
4
- Doc,
5
- Draft,
6
- DraftTarget,
7
- Row,
8
- Tenant,
9
- } from "@derive-to/dashboards-core";
10
- import { HttpError } from "../http";
11
- import {
12
- dashboardRow,
13
- docDigest,
14
- draftAuthorId,
15
- draftOf,
16
- draftRow,
17
- headDoc,
18
- insertDashboard,
19
- inTransaction,
20
- now,
21
- } from "./rows";
22
- import { tenantHash } from "./tenant";
23
-
24
- /**
25
- * The new dashboard a retried create already made, by the maker's request id; the same id
26
- * sent for a different dashboard is refused rather than answered with the first one.
27
- */
28
- async function madeBefore(
29
- db: DashAdapter,
30
- a: { tenant: Tenant; author: Author; target: { create: Doc; requestId?: string } },
31
- ): Promise<Row | null> {
32
- const { requestId } = a.target;
33
- if (requestId === undefined) return null;
34
- const made = await db.findOne({
35
- table: "dd_dashboard",
36
- where: [
37
- { field: "tenant_hash", value: await tenantHash(a.tenant) },
38
- { field: "owner_kind", value: a.author.kind ?? "user" },
39
- { field: "owner_id", value: a.author.id },
40
- { field: "request_id", value: requestId },
41
- { field: "archived_at", op: "isNull" },
42
- ],
43
- });
44
- if (made !== null && made["request_digest"] !== (await docDigest(a.target.create)))
45
- throw new HttpError(
46
- 409,
47
- "REQUEST_REUSED",
48
- `The request id "${requestId}" already made "${String(made["title"])}". Send a new one for another dashboard.`,
49
- );
50
- return made;
51
- }
52
-
53
- /** The dashboard row a draft edits, made for a built-in or a new dashboard the first time. */
54
- async function targetRow(
55
- db: DashAdapter,
56
- a: { tenant: Tenant; author: Author; target: DraftTarget },
57
- ): Promise<{ row: Row; base: Doc | undefined }> {
58
- const { target } = a;
59
- if ("id" in target) {
60
- const row = await dashboardRow(db, a.tenant, { id: target.id });
61
- if (row === null)
62
- throw new HttpError(404, "NOT_FOUND", `There is no dashboard "${target.id}".`);
63
- return { row, base: undefined };
64
- }
65
- if ("builtIn" in target) {
66
- const found = await dashboardRow(db, a.tenant, { key: target.builtIn });
67
- const row =
68
- found ?? (await insertDashboard(db, { ...a, doc: target.doc, key: target.builtIn }));
69
- return { row, base: target.doc };
70
- }
71
- const made = await madeBefore(db, { ...a, target });
72
- const row =
73
- made ??
74
- (await insertDashboard(db, {
75
- ...a,
76
- doc: target.create,
77
- ...(target.requestId === undefined ? {} : { requestId: target.requestId }),
78
- }));
79
- return { row, base: target.create };
80
- }
81
-
82
- /**
83
- * The author's open draft of the target, or a new one from its current document: the latest
84
- * published version, else the built-in's code document or the new dashboard's first one.
85
- */
86
- export function startDraft(
87
- db: DashAdapter,
88
- a: { tenant: Tenant; author: Author; target: DraftTarget },
89
- ): Promise<Draft> {
90
- return inTransaction(db, async (tx) => {
91
- const { row, base } = await targetRow(tx, a);
92
- const id = String(row["id"]);
93
- const existing = await draftRow(tx, id, a.author);
94
- if (existing?.["state"] === "open") return draftOf(existing);
95
- const head = await headDoc(tx, row);
96
- const doc = head.doc ?? base;
97
- if (doc === undefined)
98
- throw new HttpError(404, "NOT_FOUND", `The dashboard "${id}" has no document to edit.`);
99
- const fresh = {
100
- state: "open",
101
- closed_by: null,
102
- revision: 0,
103
- base_version: head.version,
104
- spec: doc,
105
- base_spec: doc,
106
- for_id: a.author.kind === "agent" ? (a.author.for ?? null) : null,
107
- steps: 0,
108
- named: [],
109
- next_seq: 0,
110
- updated_at: now(),
111
- };
112
- if (existing === null) {
113
- const data = {
114
- id: crypto.randomUUID(),
115
- dashboard_id: id,
116
- tenant_hash: await tenantHash(a.tenant),
117
- author_id: draftAuthorId(a.author),
118
- author_kind: a.author.kind ?? "user",
119
- generation: 1,
120
- ...fresh,
121
- };
122
- await tx.create({ table: "dd_dashboard_draft", data });
123
- return draftOf(data);
124
- }
125
- const generation = Number(existing["generation"]) + 1;
126
- await tx.updateMany({
127
- table: "dd_dashboard_draft",
128
- where: [{ field: "id", value: existing["id"] }],
129
- set: { ...fresh, generation },
130
- });
131
- return draftOf({ ...existing, ...fresh, generation });
132
- });
133
- }
@@ -1,28 +0,0 @@
1
- import type { DashAdapter, DashboardStore } from "@derive-to/dashboards-core";
2
- import { applyDraft } from "./apply";
3
- import { discardDraft } from "./discard";
4
- import { startDraft } from "./drafts";
5
- import { dashboardRow, draftOf, draftRow } from "./rows";
6
- import { undo } from "./undo";
7
- import { unpublished } from "./unpublished";
8
-
9
- type Editing = Pick<
10
- DashboardStore,
11
- "getDraft" | "startDraft" | "applyDraft" | "discardDraft" | "unpublished" | "undo"
12
- >;
13
-
14
- /** A person's or an agent's own draft: opened, edited, stepped back, dropped. */
15
- export function draftMethods(db: DashAdapter): Editing {
16
- return {
17
- getDraft: async (a) => {
18
- const dashboard = await dashboardRow(db, a.tenant, { id: a.id });
19
- const row = dashboard === null ? null : await draftRow(db, a.id, a.author);
20
- return row === null || row["state"] !== "open" ? null : draftOf(row);
21
- },
22
- startDraft: (a) => startDraft(db, a),
23
- applyDraft: (a) => applyDraft(db, a),
24
- discardDraft: (a) => discardDraft(db, a),
25
- unpublished: (a) => unpublished(db, a),
26
- undo: (a) => undo(db, a),
27
- };
28
- }
package/src/store/log.ts DELETED
@@ -1,28 +0,0 @@
1
- import type { DashAdapter, Principal } from "@derive-to/dashboards-core";
2
- import { principalTenant } from "@derive-to/dashboards-core";
3
- import type { Answered } from "../execute";
4
- import { tenantHash } from "./tenant";
5
-
6
- /** One `dd_query_log` row for an answered query: who, what (by hash), how long, how many rows, from where. */
7
- export async function logQuery(
8
- adapter: DashAdapter,
9
- principal: Principal,
10
- source: string,
11
- answer: Answered,
12
- ): Promise<void> {
13
- const { receipt } = answer;
14
- await adapter.create({
15
- table: "dd_query_log",
16
- data: {
17
- id: crypto.randomUUID(),
18
- tenant_hash: await tenantHash(principalTenant(principal)),
19
- viewer_id: principal.channel === "user" ? principal.viewer.id : null,
20
- query_hash: receipt.queryHash,
21
- source,
22
- duration_ms: receipt.durationMs,
23
- rows: receipt.rowsReturned,
24
- cache: receipt.cache,
25
- at: receipt.computedAt,
26
- },
27
- });
28
- }