derive-dashboards 0.1.0 → 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 (410) hide show
  1. package/README.md +8 -5
  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/add.mjs +130 -0
  6. package/dist/cli/check.mjs +14 -1
  7. package/dist/cli/cli.mjs +14 -12
  8. package/dist/cli/config.mjs +12 -1
  9. package/dist/cli/doctor.mjs +147 -0
  10. package/dist/cli/import/dbt-schema.mjs +2 -2
  11. package/dist/cli/import/index.mjs +2 -2
  12. package/dist/cli/init.mjs +3 -2
  13. package/dist/cli/json.mjs +21 -0
  14. package/dist/cli/layers.mjs +33 -0
  15. package/dist/core/conformance/cases.d.mts +3 -0
  16. package/dist/core/conformance/cases.mjs +20 -4
  17. package/dist/core/conformance/check.mjs +6 -3
  18. package/dist/core/conformance/drill-cases.mjs +120 -0
  19. package/dist/core/document/layout.mjs +1 -1
  20. package/dist/core/document/view-layout.d.mts +14 -0
  21. package/dist/core/document/view-layout.mjs +157 -0
  22. package/dist/core/document/view.d.mts +26 -7
  23. package/dist/core/document/view.mjs +42 -11
  24. package/dist/core/engine/filter.mjs +2 -2
  25. package/dist/core/engine/index.d.mts +14 -2
  26. package/dist/core/engine/index.mjs +12 -1
  27. package/dist/core/engine/leaf.mjs +9 -4
  28. package/dist/core/engine/members.mjs +2 -2
  29. package/dist/core/engine/postgres.mjs +1 -1
  30. package/dist/core/engine/record-layout.d.mts +11 -0
  31. package/dist/core/engine/record-layout.mjs +7 -7
  32. package/dist/core/engine/records.d.mts +3 -2
  33. package/dist/core/engine/records.mjs +2 -1
  34. package/dist/core/engine/segmented.mjs +5 -2
  35. package/dist/core/engine/sql-records.mjs +2 -1
  36. package/dist/core/engine/statement.mjs +37 -3
  37. package/dist/core/engine/types.d.mts +3 -0
  38. package/dist/core/engine/version.d.mts +1 -1
  39. package/dist/core/engine/version.mjs +1 -1
  40. package/dist/core/error/codes.d.mts +33 -1
  41. package/dist/core/error/codes.mjs +30 -2
  42. package/dist/core/index.d.mts +13 -7
  43. package/dist/core/index.mjs +9 -5
  44. package/dist/core/model/catalog/check.mjs +1 -1
  45. package/dist/core/model/hints.d.mts +36 -0
  46. package/dist/core/model/member.d.mts +4 -2
  47. package/dist/core/model/member.mjs +19 -3
  48. package/dist/core/model/types.d.mts +21 -19
  49. package/dist/core/model/validate/drill.mjs +70 -0
  50. package/dist/core/model/validate/index.mjs +3 -0
  51. package/dist/core/model/validate/members.mjs +7 -4
  52. package/dist/core/model/validate/shape.mjs +150 -0
  53. package/dist/core/model/validate/source.mjs +5 -3
  54. package/dist/core/policy/bind-query.d.mts +12 -0
  55. package/dist/core/policy/bind-query.mjs +53 -0
  56. package/dist/core/query/alias.mjs +7 -1
  57. package/dist/core/query/drill/compose.d.mts +22 -0
  58. package/dist/core/query/drill/compose.mjs +85 -0
  59. package/dist/core/query/drill/fields.d.mts +21 -0
  60. package/dist/core/query/drill/fields.mjs +91 -0
  61. package/dist/core/query/drill/internal.d.mts +11 -0
  62. package/dist/core/query/drill/items.d.mts +29 -0
  63. package/dist/core/query/drill/items.mjs +98 -0
  64. package/dist/core/query/drill/line.d.mts +31 -0
  65. package/dist/core/query/drill/line.mjs +183 -0
  66. package/dist/core/query/drill/links.d.mts +33 -0
  67. package/dist/core/query/drill/links.mjs +31 -0
  68. package/dist/core/query/drill/operand.mjs +7 -0
  69. package/dist/core/query/drill/scopes.d.mts +22 -0
  70. package/dist/core/query/drill/scopes.mjs +58 -0
  71. package/dist/core/query/drill/selection.d.mts +37 -0
  72. package/dist/core/query/drill/selection.mjs +144 -0
  73. package/dist/core/query/drill/steps.d.mts +14 -0
  74. package/dist/core/query/drill/steps.mjs +35 -0
  75. package/dist/core/query/drill/synthetic-expr.mjs +85 -0
  76. package/dist/core/query/drill/synthetic.d.mts +22 -0
  77. package/dist/core/query/drill/synthetic.mjs +165 -0
  78. package/dist/core/query/drill/time.d.mts +11 -0
  79. package/dist/core/query/drill/time.mjs +71 -0
  80. package/dist/core/query/drill/types.d.mts +155 -0
  81. package/dist/core/query/drill/types.mjs +4 -0
  82. package/dist/core/query/drill/views.d.mts +62 -0
  83. package/dist/core/query/drill/views.mjs +257 -0
  84. package/dist/core/query/filter.d.mts +6 -0
  85. package/dist/core/query/picks.d.mts +8 -2
  86. package/dist/core/query/picks.mjs +11 -4
  87. package/dist/core/query/segments.d.mts +12 -2
  88. package/dist/core/query/segments.mjs +5 -2
  89. package/dist/core/result/columns.mjs +20 -4
  90. package/dist/core/result/types.d.mts +5 -1
  91. package/dist/core/schema/aliases.d.mts +7 -0
  92. package/dist/core/schema/aliases.mjs +77 -0
  93. package/dist/core/schema/answer-parts.mjs +117 -0
  94. package/dist/core/schema/answers.d.mts +2109 -128
  95. package/dist/core/schema/answers.mjs +11 -113
  96. package/dist/core/schema/commands.d.mts +2 -2
  97. package/dist/core/schema/document.d.mts +1 -1
  98. package/dist/core/schema/drill-answers.mjs +179 -0
  99. package/dist/core/schema/drill.d.mts +260 -0
  100. package/dist/core/schema/drill.mjs +107 -0
  101. package/dist/core/schema/index.d.mts +6 -3
  102. package/dist/core/schema/index.mjs +6 -3
  103. package/dist/core/schema/picks.d.mts +35 -0
  104. package/dist/core/schema/picks.mjs +23 -0
  105. package/dist/core/schema/query.d.mts +82 -1
  106. package/dist/core/schema/query.mjs +9 -5
  107. package/dist/core/schema/tools.mjs +1 -1
  108. package/dist/core/schema/view.d.mts +0 -35
  109. package/dist/core/schema/view.mjs +19 -24
  110. package/dist/core/store/schema.d.mts +5 -0
  111. package/dist/core/store/schema.mjs +10 -0
  112. package/dist/core/types/api.d.mts +21 -1
  113. package/dist/core/types/api.mjs +1 -1
  114. package/dist/core/types/drill-api.d.mts +210 -0
  115. package/dist/core/types/options.d.mts +21 -0
  116. package/dist/core/types/viewer.d.mts +5 -0
  117. package/dist/cursor-seal.d.mts +8 -0
  118. package/dist/cursor-seal.mjs +98 -0
  119. package/dist/dashboard-id.mjs +1 -1
  120. package/dist/dashboards.mjs +4 -0
  121. package/dist/drill-access.mjs +93 -0
  122. package/dist/drill-change.mjs +76 -0
  123. package/dist/drill-crumbs.mjs +113 -0
  124. package/dist/drill-distinct.mjs +130 -0
  125. package/dist/drill-explain.mjs +64 -0
  126. package/dist/drill-identity.mjs +35 -0
  127. package/dist/drill-item-id.mjs +35 -0
  128. package/dist/drill-items.mjs +132 -0
  129. package/dist/drill-open.mjs +169 -0
  130. package/dist/drill-seal.mjs +170 -0
  131. package/dist/drill-secret.mjs +14 -0
  132. package/dist/drill-share.mjs +53 -0
  133. package/dist/drill-summary.mjs +158 -0
  134. package/dist/drill-targets.mjs +53 -0
  135. package/dist/drill-totals.mjs +8 -0
  136. package/dist/drill-views.mjs +175 -0
  137. package/dist/drill.mjs +157 -0
  138. package/dist/editing.mjs +3 -3
  139. package/dist/endpoints/dashboards.mjs +28 -5
  140. package/dist/endpoints/drill.mjs +55 -0
  141. package/dist/endpoints/index.d.mts +245 -4
  142. package/dist/endpoints/index.mjs +5 -1
  143. package/dist/endpoints/meta.mjs +10 -1
  144. package/dist/endpoints/query.mjs +26 -4
  145. package/dist/execute.d.mts +19 -1
  146. package/dist/execute.mjs +34 -27
  147. package/dist/handler.mjs +5 -1
  148. package/dist/index.d.mts +3 -1
  149. package/dist/index.mjs +29 -2
  150. package/dist/llms.txt +22 -0
  151. package/dist/mcp/drill.mjs +61 -0
  152. package/dist/mcp/format.mjs +69 -11
  153. package/dist/mcp/index.d.mts +15 -4
  154. package/dist/mcp/index.mjs +13 -7
  155. package/dist/mcp/query.d.mts +7 -2
  156. package/dist/mcp/query.mjs +40 -6
  157. package/dist/node-postgres.d.mts +8 -4
  158. package/dist/node-postgres.mjs +29 -6
  159. package/dist/owner.mjs +3 -3
  160. package/dist/postgres-connection.d.mts +8 -2
  161. package/dist/postgres-connection.mjs +2 -1
  162. package/dist/postgres-store.mjs +1 -0
  163. package/dist/react/Canvas.mjs +28 -5
  164. package/dist/react/Cell.mjs +2 -1
  165. package/dist/react/Dashboard.d.mts +10 -5
  166. package/dist/react/Dashboard.mjs +62 -22
  167. package/dist/react/DashboardList.mjs +52 -24
  168. package/dist/react/DashboardListRow.mjs +49 -0
  169. package/dist/react/Discard.mjs +12 -4
  170. package/dist/react/Editing.mjs +19 -5
  171. package/dist/react/FilterBar.d.mts +7 -9
  172. package/dist/react/Grid.mjs +19 -24
  173. package/dist/react/Header.mjs +10 -1
  174. package/dist/react/History.mjs +5 -0
  175. package/dist/react/Parts.mjs +6 -2
  176. package/dist/react/ReadFailed.mjs +23 -0
  177. package/dist/react/ReviewPanel.mjs +13 -2
  178. package/dist/react/RowBody.d.mts +19 -0
  179. package/dist/react/RowBody.mjs +55 -0
  180. package/dist/react/Spaces.mjs +15 -1
  181. package/dist/react/Tile.d.mts +3 -1
  182. package/dist/react/Tile.mjs +84 -32
  183. package/dist/react/_virtual/_rolldown/runtime.mjs +12 -0
  184. package/dist/react/arrange-steps.mjs +16 -13
  185. package/dist/react/arrange.mjs +10 -3
  186. package/dist/react/builder/Calcs.mjs +35 -11
  187. package/dist/react/builder/FilterEditor.mjs +196 -0
  188. package/dist/react/builder/Filters.mjs +172 -116
  189. package/dist/react/builder/Formula.mjs +82 -0
  190. package/dist/react/builder/Groups.mjs +1 -0
  191. package/dist/react/builder/Preview.mjs +1 -1
  192. package/dist/react/builder/RangeEditor.mjs +184 -0
  193. package/dist/react/builder/Sections.mjs +41 -6
  194. package/dist/react/builder/Time.mjs +138 -60
  195. package/dist/react/builder/Values.mjs +85 -0
  196. package/dist/react/builder/WidgetBuilder.mjs +50 -49
  197. package/dist/react/builder/base.d.mts +5 -0
  198. package/dist/react/builder/base.mjs +33 -8
  199. package/dist/react/builder/calc.mjs +15 -1
  200. package/dist/react/builder/escape.d.mts +1 -0
  201. package/dist/react/builder/escape.mjs +62 -0
  202. package/dist/react/builder/filter-tree.d.mts +9 -0
  203. package/dist/react/builder/filter-tree.mjs +186 -0
  204. package/dist/react/builder/formula-parse.d.mts +18 -0
  205. package/dist/react/builder/formula-parse.mjs +136 -0
  206. package/dist/react/builder/labels.d.mts +1 -1
  207. package/dist/react/builder/state.d.mts +2 -1
  208. package/dist/react/builder/state.mjs +23 -37
  209. package/dist/react/builder/useBuilder.d.mts +12 -1
  210. package/dist/react/builder/useBuilder.mjs +6 -3
  211. package/dist/react/builder/words.d.mts +59 -0
  212. package/dist/react/builder/words.mjs +73 -0
  213. package/dist/react/client.d.mts +2 -0
  214. package/dist/react/client.mjs +1 -0
  215. package/dist/react/context.d.mts +28 -1
  216. package/dist/react/context.mjs +25 -4
  217. package/dist/react/drill/Bars.mjs +179 -0
  218. package/dist/react/drill/Controls.mjs +173 -0
  219. package/dist/react/drill/DashboardTile.d.mts +18 -0
  220. package/dist/react/drill/DashboardTile.mjs +107 -0
  221. package/dist/react/drill/DrillPanel.d.mts +31 -0
  222. package/dist/react/drill/DrillPanel.mjs +104 -0
  223. package/dist/react/drill/DrillTabs.mjs +52 -0
  224. package/dist/react/drill/Header.mjs +131 -0
  225. package/dist/react/drill/Items.d.mts +22 -0
  226. package/dist/react/drill/Items.mjs +164 -0
  227. package/dist/react/drill/ItemsFoot.mjs +60 -0
  228. package/dist/react/drill/Notes.mjs +58 -0
  229. package/dist/react/drill/PanelBody.mjs +74 -0
  230. package/dist/react/drill/PanelStates.mjs +37 -0
  231. package/dist/react/drill/board.d.mts +18 -0
  232. package/dist/react/drill/board.mjs +91 -0
  233. package/dist/react/drill/counts.mjs +14 -0
  234. package/dist/react/drill/host.mjs +26 -0
  235. package/dist/react/drill/item-parts.d.mts +5 -0
  236. package/dist/react/drill/item-parts.mjs +76 -0
  237. package/dist/react/drill/item-type.d.mts +26 -0
  238. package/dist/react/drill/item-type.mjs +7 -0
  239. package/dist/react/drill/lazy.d.mts +6 -0
  240. package/dist/react/drill/lazy.mjs +17 -0
  241. package/dist/react/drill/pages.mjs +48 -0
  242. package/dist/react/drill/panel-focus.mjs +51 -0
  243. package/dist/react/drill/props.d.mts +25 -0
  244. package/dist/react/drill/props.mjs +72 -0
  245. package/dist/react/drill/state.d.mts +18 -0
  246. package/dist/react/drill/state.mjs +68 -0
  247. package/dist/react/drill/useDrill.d.mts +46 -0
  248. package/dist/react/drill/useDrill.mjs +194 -0
  249. package/dist/react/drill/words.d.mts +101 -0
  250. package/dist/react/drill/words.mjs +79 -0
  251. package/dist/react/english.mjs +29 -6
  252. package/dist/react/filters/bar.d.mts +12 -0
  253. package/dist/react/filters/bar.mjs +135 -0
  254. package/dist/react/filters/calendar.mjs +193 -0
  255. package/dist/react/filters/chip.mjs +174 -0
  256. package/dist/react/filters/context.d.mts +22 -0
  257. package/dist/react/filters/context.mjs +78 -0
  258. package/dist/react/filters/dates.mjs +89 -0
  259. package/dist/react/filters/days.d.mts +36 -0
  260. package/dist/react/filters/days.mjs +87 -0
  261. package/dist/react/filters/field-step.mjs +81 -0
  262. package/dist/react/filters/hooks.d.mts +34 -0
  263. package/dist/react/filters/hooks.mjs +94 -0
  264. package/dist/react/filters/listbox.mjs +131 -0
  265. package/dist/react/filters/logic.d.mts +59 -0
  266. package/dist/react/filters/logic.mjs +109 -0
  267. package/dist/react/filters/menu-search.mjs +211 -0
  268. package/dist/react/filters/menu.mjs +85 -0
  269. package/dist/react/filters/number.mjs +127 -0
  270. package/dist/react/filters/numbers.d.mts +47 -0
  271. package/dist/react/filters/numbers.mjs +151 -0
  272. package/dist/react/filters/operator.mjs +104 -0
  273. package/dist/react/filters/phone.mjs +104 -0
  274. package/dist/react/filters/popover.d.mts +19 -0
  275. package/dist/react/filters/popover.mjs +153 -0
  276. package/dist/react/filters/rules.d.mts +8 -0
  277. package/dist/react/filters/rules.mjs +55 -0
  278. package/dist/react/filters/sheet.mjs +196 -0
  279. package/dist/react/filters/state.mjs +132 -0
  280. package/dist/react/filters/suggest.d.mts +47 -0
  281. package/dist/react/filters/suggest.mjs +97 -0
  282. package/dist/react/filters/values.mjs +166 -0
  283. package/dist/react/filters/words.d.mts +81 -0
  284. package/dist/react/filters/words.mjs +73 -0
  285. package/dist/react/format.d.mts +3 -3
  286. package/dist/react/format.mjs +45 -16
  287. package/dist/react/index.d.mts +34 -5
  288. package/dist/react/index.mjs +15 -4
  289. package/dist/react/messages.d.mts +47 -2
  290. package/dist/react/place.mjs +7 -3
  291. package/dist/react/renderers/index.d.mts +10 -2
  292. package/dist/react/renderers/index.mjs +116 -14
  293. package/dist/react/renderers/list.d.mts +22 -0
  294. package/dist/react/renderers/list.mjs +118 -0
  295. package/dist/react/review-words.mjs +1 -1
  296. package/dist/react/review.mjs +2 -2
  297. package/dist/react/scope.mjs +2 -7
  298. package/dist/react/series.d.mts +54 -0
  299. package/dist/react/series.mjs +191 -0
  300. package/dist/react/theme.css +2734 -1296
  301. package/dist/react/theme.css.d.ts +1 -0
  302. package/dist/react/tile-store.mjs +15 -3
  303. package/dist/react/useBoard.d.mts +7 -0
  304. package/dist/react/useBoard.mjs +4 -1
  305. package/dist/react/useDashboard.d.mts +4 -0
  306. package/dist/react/useDashboard.mjs +8 -1
  307. package/dist/react/useTiles.mjs +50 -15
  308. package/dist/react/view-grid.mjs +16 -0
  309. package/dist/react/view.d.mts +9 -0
  310. package/dist/react/view.mjs +22 -10
  311. package/dist/reading.d.mts +2 -0
  312. package/dist/reading.mjs +9 -1
  313. package/dist/recharts/axes.mjs +28 -0
  314. package/dist/recharts/axis.mjs +84 -0
  315. package/dist/recharts/bar.d.mts +7 -0
  316. package/dist/recharts/bar.mjs +140 -0
  317. package/dist/recharts/charts.d.mts +4 -6
  318. package/dist/recharts/charts.mjs +2 -114
  319. package/dist/recharts/index.d.mts +5 -3
  320. package/dist/recharts/index.mjs +6 -3
  321. package/dist/recharts/line.d.mts +2 -0
  322. package/dist/recharts/line.mjs +111 -0
  323. package/dist/recharts/marks.mjs +112 -0
  324. package/dist/recharts/parts.mjs +88 -0
  325. package/dist/recharts/series.d.mts +2 -22
  326. package/dist/recharts/series.mjs +1 -64
  327. package/dist/recharts/table.mjs +71 -0
  328. package/dist/records-read.mjs +44 -0
  329. package/dist/registry/filter-bar.json +26 -0
  330. package/dist/skills/derive-dashboards/SKILL.md +69 -0
  331. package/dist/store/apply.mjs +5 -5
  332. package/dist/store/commands.mjs +4 -4
  333. package/dist/store/discard.mjs +7 -7
  334. package/dist/store/drafts.mjs +5 -5
  335. package/dist/store/editor.mjs +1 -1
  336. package/dist/store/publish.mjs +12 -12
  337. package/dist/store/reader.mjs +41 -22
  338. package/dist/store/review.mjs +16 -16
  339. package/dist/store/rows.mjs +20 -20
  340. package/dist/store/undo.mjs +3 -3
  341. package/dist/store/unpublished.mjs +4 -4
  342. package/dist/store/versions.mjs +14 -14
  343. package/dist/testing/adapter-suite.mjs +4 -4
  344. package/dist/tiles.mjs +37 -3
  345. package/package.json +12 -10
  346. package/dist/react/FilterBar.mjs +0 -119
  347. package/dist/react/Records.d.mts +0 -12
  348. package/dist/react/Records.mjs +0 -97
  349. package/src/adapter/sql-adapter.ts +0 -95
  350. package/src/adapter/statement.ts +0 -185
  351. package/src/authorize.ts +0 -73
  352. package/src/body.ts +0 -169
  353. package/src/bounded.ts +0 -43
  354. package/src/cache.ts +0 -192
  355. package/src/checks.ts +0 -170
  356. package/src/custom-source.ts +0 -59
  357. package/src/dashboard-id.ts +0 -36
  358. package/src/dashboards.ts +0 -132
  359. package/src/editing.ts +0 -148
  360. package/src/endpoints/access.ts +0 -41
  361. package/src/endpoints/dashboards.ts +0 -92
  362. package/src/endpoints/drafts.ts +0 -138
  363. package/src/endpoints/index.ts +0 -21
  364. package/src/endpoints/meta.ts +0 -137
  365. package/src/endpoints/query.ts +0 -86
  366. package/src/endpoints/read.ts +0 -92
  367. package/src/endpoints/review.ts +0 -89
  368. package/src/endpoints/values.ts +0 -62
  369. package/src/endpoints/versions.ts +0 -104
  370. package/src/execute.ts +0 -207
  371. package/src/handler.ts +0 -232
  372. package/src/http.ts +0 -66
  373. package/src/index.ts +0 -163
  374. package/src/introspect.ts +0 -205
  375. package/src/mcp/api.ts +0 -59
  376. package/src/mcp/format.ts +0 -67
  377. package/src/mcp/index.ts +0 -151
  378. package/src/mcp/query.ts +0 -153
  379. package/src/mcp/resolve.ts +0 -114
  380. package/src/node-postgres.ts +0 -81
  381. package/src/owner.ts +0 -36
  382. package/src/postgres-connection.ts +0 -143
  383. package/src/postgres-store.ts +0 -82
  384. package/src/principal.ts +0 -39
  385. package/src/reading.ts +0 -56
  386. package/src/request-rows.ts +0 -23
  387. package/src/request.ts +0 -22
  388. package/src/storage.ts +0 -63
  389. package/src/store/apply.ts +0 -129
  390. package/src/store/commands.ts +0 -75
  391. package/src/store/conflicts.ts +0 -98
  392. package/src/store/create-tables.ts +0 -104
  393. package/src/store/discard.ts +0 -42
  394. package/src/store/drafts.ts +0 -133
  395. package/src/store/editor.ts +0 -28
  396. package/src/store/log.ts +0 -28
  397. package/src/store/publish.ts +0 -199
  398. package/src/store/publisher.ts +0 -21
  399. package/src/store/reader.ts +0 -139
  400. package/src/store/review.ts +0 -239
  401. package/src/store/rows.ts +0 -250
  402. package/src/store/tenant.ts +0 -28
  403. package/src/store/undo.ts +0 -56
  404. package/src/store/unpublished.ts +0 -33
  405. package/src/store/versions.ts +0 -106
  406. package/src/store/writer.ts +0 -19
  407. package/src/testing/adapter-suite.ts +0 -239
  408. package/src/testing/index.ts +0 -2
  409. package/src/tile-doc.ts +0 -46
  410. package/src/tiles.ts +0 -120
package/src/mcp/api.ts DELETED
@@ -1,59 +0,0 @@
1
- // dashboards_api: every endpoint by path, as the signed-in person. Edits, publishing, history,
2
- // and each plugin's endpoints, with nothing to keep in step: the paths come from the server,
3
- // and GET /meta/schemas gives each body's JSON Schema when the agent needs it.
4
- import type { Viewer } from "@derive-to/dashboards-core";
5
- import { z } from "zod";
6
- import { ok, type ToolResult } from "./format";
7
- import type { Callable } from "./query";
8
-
9
- /** The longest answer handed back as text; the whole answer is always in the structured content. */
10
- const MOST_TEXT = 20_000;
11
-
12
- export type ApiServer = Callable & { routes: readonly { path: string; method: "GET" | "POST" }[] };
13
-
14
- /** The tool's input: one of the server's paths, and the body it takes. */
15
- export function apiInput(routes: ApiServer["routes"]) {
16
- const paths = routes.map((r) => r.path);
17
- const [first, ...rest] = paths;
18
- if (first === undefined) throw new Error("The dashboards server has no endpoints.");
19
- return z.object({
20
- path: z.enum([first, ...rest]).describe("The endpoint to call."),
21
- body: z
22
- .record(z.string(), z.unknown())
23
- .optional()
24
- .describe(
25
- "The endpoint's body (none for a GET). GET /meta/schemas lists every body's JSON Schema.",
26
- ),
27
- });
28
- }
29
-
30
- /** What the tool says it does: how editing goes, then every path with its method. */
31
- export function apiDescription(routes: ApiServer["routes"]): string {
32
- return [
33
- "Calls any dashboards endpoint as the signed-in person, with their access. For questions and reading dashboards, prefer dashboards_query.",
34
- "Editing: POST /dashboards/new or /dashboards/draft/start opens your own draft; /dashboards/draft/apply applies commands (each answer gives the revision the next names); /dashboards/draft/preview shows what would go live; /dashboards/draft/publish puts it live. Nothing is live until publish.",
35
- "Paths:",
36
- ...routes.map((r) => `${r.method} ${r.path}`),
37
- ].join("\n");
38
- }
39
-
40
- /** Calls one endpoint as the viewer; the answer comes back as JSON text and structured content. */
41
- export async function runApi(
42
- dashboards: ApiServer,
43
- viewer: Viewer,
44
- input: { path: string; body?: Record<string, unknown> | undefined },
45
- ): Promise<ToolResult> {
46
- const route = dashboards.routes.find((r) => r.path === input.path);
47
- const body = route?.method === "GET" ? undefined : (input.body ?? {});
48
- const answer = await dashboards.call(input.path, {
49
- ...(body === undefined ? {} : { body }),
50
- viewer,
51
- });
52
- const text = JSON.stringify(answer ?? null, null, 1);
53
- return ok(
54
- text.length > MOST_TEXT
55
- ? `${text.slice(0, MOST_TEXT)}\n... cut; the whole answer is in the structured content.`
56
- : text,
57
- answer,
58
- );
59
- }
package/src/mcp/format.ts DELETED
@@ -1,67 +0,0 @@
1
- // How tool answers read to a model: a short table it can quote, a sentence when there is
2
- // nothing to show, and every refusal as the code, the reason and what to do instead.
3
- import type { QueryAnswer } from "@derive-to/dashboards-core";
4
- import { HttpError } from "../http";
5
-
6
- /** What a tool call answers: text for the model, and the whole answer as structured content. */
7
- export type ToolResult = {
8
- content: { type: "text"; text: string }[];
9
- structuredContent?: Record<string, unknown>;
10
- isError?: true;
11
- };
12
-
13
- /** The most rows a table shows the model; the rest are counted, and all are in the structured answer. */
14
- const SHOWN = 30;
15
-
16
- /** A cell as text: exact numbers as their digits, no value as a blank. */
17
- function cellText(cell: unknown): string {
18
- if (cell === null || cell === undefined) return "";
19
- if (typeof cell === "object" && "v" in cell) return String(cell.v);
20
- if (typeof cell === "string") return cell.replaceAll("|", "\\|");
21
- if (typeof cell === "number" || typeof cell === "boolean") return String(cell);
22
- return JSON.stringify(cell);
23
- }
24
-
25
- /** Rows under their column labels, as a Markdown table, cut at SHOWN rows with a count. */
26
- export function table(labels: readonly string[], rows: readonly (readonly unknown[])[]): string {
27
- if (rows.length === 0) return "No rows.";
28
- const lines = [
29
- `| ${labels.join(" | ")} |`,
30
- `| ${labels.map(() => "---").join(" | ")} |`,
31
- ...rows.slice(0, SHOWN).map((row) => `| ${row.map((c) => cellText(c)).join(" | ")} |`),
32
- ];
33
- if (rows.length > SHOWN)
34
- lines.push(`\n${rows.length - SHOWN} more rows are in the structured answer.`);
35
- return lines.join("\n");
36
- }
37
-
38
- /** A query's answer: its table, the comparison period's beside it, and whether it was cut. */
39
- export function answerText(answer: QueryAnswer): string {
40
- if (answer.unreadable === true)
41
- return "This viewer may not read the rows this question asks about.";
42
- const labels = answer.columns.map((c) => c.label);
43
- const parts = [table(labels, answer.rows)];
44
- if (answer.compare !== undefined) {
45
- const { from, to } = answer.compare.range;
46
- parts.push(`Compared with ${from} to ${to}:`, table(labels, answer.compare.rows));
47
- }
48
- if (answer.status === "truncated") parts.push("The answer was cut at its row limit.");
49
- return parts.join("\n\n");
50
- }
51
-
52
- export const ok = (text: string, data?: unknown): ToolResult => ({
53
- content: [{ type: "text", text }],
54
- ...(data === undefined ? {} : { structuredContent: { result: data } }),
55
- });
56
-
57
- /** A refusal the model can act on: the code, the reason, each problem with the input, and a hint. */
58
- export function refused(error: unknown, hint?: string): ToolResult {
59
- if (!(error instanceof HttpError)) throw error;
60
- const issues = (error.issues ?? []).map((i) => `- ${i.path.join(".") || "input"}: ${i.message}`);
61
- const text = [
62
- `${error.code}: ${error.message}`,
63
- ...issues,
64
- ...(hint === undefined ? [] : [hint]),
65
- ];
66
- return { content: [{ type: "text", text: text.join("\n") }], isError: true };
67
- }
package/src/mcp/index.ts DELETED
@@ -1,151 +0,0 @@
1
- // Dashboards in an MCP server, or any agent framework: two tools. dashboards_query reads
2
- // (questions, the rows behind them, dashboards read out) and is marked read only, so clients
3
- // can run it without asking; dashboards_api reaches every endpoint, edits included, which go to
4
- // the agent's own draft until it publishes. Both run as the viewer the host names, so an agent
5
- // can do what its person can and nothing more.
6
- import type { Viewer } from "@derive-to/dashboards-core";
7
- import { z } from "zod";
8
- import { HttpError } from "../http";
9
- import { type ApiServer, apiDescription, apiInput, runApi } from "./api";
10
- import { refused, type ToolResult } from "./format";
11
- import { queryInput, runQuery } from "./query";
12
-
13
- export type { ToolResult } from "./format";
14
-
15
- /** MCP's tool annotations: what a client may assume about a tool before it runs it. */
16
- export type ToolAnnotations = {
17
- readOnlyHint?: boolean;
18
- destructiveHint?: boolean;
19
- idempotentHint?: boolean;
20
- openWorldHint?: boolean;
21
- };
22
-
23
- /** One tool as plain data, for MCP or any agent framework. */
24
- export type DashboardTool = {
25
- name: string;
26
- title: string;
27
- description: string;
28
- inputSchema: z.ZodObject;
29
- annotations: ToolAnnotations;
30
- /**
31
- * Runs the tool as `viewer`, checking its input against `inputSchema` first. A refusal comes
32
- * back as an error result saying why and what to do.
33
- */
34
- run: (input: unknown, viewer: Viewer) => Promise<ToolResult>;
35
- };
36
-
37
- export type DashboardToolsOptions = {
38
- /** Put before each tool's name; `dashboards_` by default. */
39
- prefix?: string;
40
- /** False leaves out dashboards_api, so an agent can read but never change anything. */
41
- api?: boolean;
42
- /** The link to a dashboard in your app, given with every dashboard the agent opens. */
43
- linkFor?: (dashboardId: string) => string;
44
- };
45
-
46
- /** An agent acts for its person: marked so, its edits are its own draft and history says an agent made them. */
47
- const asAgent = (viewer: Viewer): Viewer =>
48
- viewer.agent === undefined ? { ...viewer, agent: { for: viewer.id } } : viewer;
49
-
50
- const HINT =
51
- "Fix the input and call again; dashboards_query with op describe lists what can be asked.";
52
-
53
- /**
54
- * A tool's run: the input checked against its schema (an agent framework may not check it),
55
- * then run as the agent acting for the viewer. A refusal becomes a result the model can act on;
56
- * anything else is a bug and throws.
57
- */
58
- function guarded<S extends z.ZodObject>(
59
- schema: S,
60
- run: (input: z.infer<S>, viewer: Viewer) => Promise<ToolResult>,
61
- ): DashboardTool["run"] {
62
- return async (raw, viewer) => {
63
- const parsed = schema.safeParse(raw);
64
- if (!parsed.success)
65
- return refused(new HttpError(400, "BODY_INVALID", z.prettifyError(parsed.error)), HINT);
66
- try {
67
- return await run(parsed.data, asAgent(viewer));
68
- } catch (error) {
69
- return refused(error, HINT);
70
- }
71
- };
72
- }
73
-
74
- /** The two tools, as plain data: `name`, `description`, `inputSchema` (Zod), `annotations`, `run(input, viewer)`. */
75
- export function dashboardTools(
76
- dashboards: ApiServer,
77
- options: DashboardToolsOptions = {},
78
- ): DashboardTool[] {
79
- const prefix = options.prefix ?? "dashboards_";
80
- const query: DashboardTool = {
81
- name: `${prefix}query`,
82
- title: "Ask about the data",
83
- description:
84
- "Answers questions from the data, as the signed-in person: describe what can be asked, ask a question (measures by groups over a time range, top N, compared with the period before), list the rows behind it, list dashboards, or open one with every tile answered. Start with op describe when unsure what exists.",
85
- inputSchema: queryInput,
86
- annotations: { readOnlyHint: true, openWorldHint: false },
87
- run: guarded(queryInput, (input, viewer) =>
88
- runQuery({ dashboards, viewer, linkFor: options.linkFor }, input),
89
- ),
90
- };
91
- if (options.api === false) return [query];
92
- const api = apiInput(dashboards.routes);
93
- const apiTool: DashboardTool = {
94
- name: `${prefix}api`,
95
- title: "Dashboards API",
96
- description: apiDescription(dashboards.routes),
97
- inputSchema: api,
98
- annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
99
- run: guarded(api, (input, viewer) => runApi(dashboards, viewer, input)),
100
- };
101
- return [query, apiTool];
102
- }
103
-
104
- /** What a tool call carries besides its input, as the MCP SDK passes it: the caller's auth. */
105
- export type McpCallExtra = {
106
- authInfo?: { token: string; clientId: string; scopes: string[]; extra?: Record<string, unknown> };
107
- sessionId?: string;
108
- };
109
-
110
- /** What `addDashboardTools` needs of an MCP server: `McpServer` from `@modelcontextprotocol/sdk` has it. */
111
- export type McpServerLike = {
112
- registerTool(
113
- name: string,
114
- config: {
115
- title?: string;
116
- description?: string;
117
- inputSchema?: z.ZodObject;
118
- annotations?: ToolAnnotations;
119
- },
120
- callback: (input: Record<string, unknown>, extra: McpCallExtra) => Promise<ToolResult>,
121
- ): unknown;
122
- };
123
-
124
- /**
125
- * Adds the two tools to an MCP server you already run. `viewer` reads the person from the
126
- * call (`extra.authInfo` from your MCP auth); none refuses the call.
127
- */
128
- export function addDashboardTools(
129
- server: McpServerLike,
130
- dashboards: ApiServer,
131
- options: DashboardToolsOptions & {
132
- viewer: (extra: McpCallExtra) => Viewer | null | Promise<Viewer | null>;
133
- },
134
- ): void {
135
- for (const tool of dashboardTools(dashboards, options)) {
136
- const { name, title, description, inputSchema, annotations } = tool;
137
- const callback = async (
138
- input: Record<string, unknown>,
139
- extra: McpCallExtra,
140
- ): Promise<ToolResult> => {
141
- const viewer = await options.viewer(extra);
142
- if (viewer === null)
143
- return {
144
- content: [{ type: "text", text: "UNAUTHORIZED: sign in to use dashboards." }],
145
- isError: true,
146
- };
147
- return tool.run(input, viewer);
148
- };
149
- server.registerTool(name, { title, description, inputSchema, annotations }, callback);
150
- }
151
- }
package/src/mcp/query.ts DELETED
@@ -1,153 +0,0 @@
1
- // dashboards_query: the read-only tool. Five ops cover what an agent asks of dashboards: what
2
- // can be asked, a question, the rows behind it, which dashboards there are, and one read out.
3
- import type { DashOptions, TileLine, Viewer } from "@derive-to/dashboards-core";
4
- import { picksSchema, wireQuerySchema } from "@derive-to/dashboards-core/schema";
5
- import { z } from "zod";
6
- import { HttpError } from "../http";
7
- import type { DashServer } from "../index";
8
- import { answerText, ok, type ToolResult, table } from "./format";
9
- import { dashboardOf, resolveQuery, sourceOf } from "./resolve";
10
-
11
- /** What the tools need of `deriveDashboards(...)`: its calls, by name and by path. */
12
- export type Callable = Pick<DashServer<DashOptions>, "api" | "call" | "routes">;
13
-
14
- export type QueryContext = {
15
- dashboards: Callable;
16
- viewer: Viewer;
17
- /** The link to a dashboard in the host's app, added to what `open` answers. */
18
- linkFor?: ((dashboardId: string) => string) | undefined;
19
- };
20
-
21
- /** A question, with `kind` optional since there is only one kind. */
22
- const question = wireQuerySchema.extend({ kind: z.literal("aggregate").optional() });
23
-
24
- export const queryInput = z.object({
25
- op: z
26
- .enum(["describe", "ask", "rows", "list", "open"])
27
- .describe(
28
- "describe: what can be asked (sources, measures, fields). ask: answer a question. rows: the records behind a question. list: the dashboards. open: one dashboard, every tile answered.",
29
- ),
30
- query: question
31
- .optional()
32
- .describe(
33
- "For ask and rows. Sources, measures and fields may be named by id or label. Ids: measures m0, m1...; dimensions d0, d1...",
34
- ),
35
- source: z.string().optional().describe("For describe: one source only."),
36
- dashboard: z.string().optional().describe("For open: the dashboard's title or id."),
37
- filters: picksSchema
38
- .optional()
39
- .describe("For open: values for the dashboard's filters, by control id."),
40
- limit: z
41
- .number()
42
- .int()
43
- .min(1)
44
- .max(200)
45
- .optional()
46
- .describe("For rows: how many (50 by default)."),
47
- });
48
- export type QueryInput = z.infer<typeof queryInput>;
49
-
50
- const meta = (c: QueryContext) => c.dashboards.api.meta({ viewer: c.viewer });
51
- const listed = (c: QueryContext) => c.dashboards.api.listDashboards({ viewer: c.viewer });
52
-
53
- async function describe(c: QueryContext, only?: string): Promise<ToolResult> {
54
- const all = await meta(c);
55
- const sources = only === undefined ? all.sources : [sourceOf(all, only)];
56
- const text = sources.map((s) =>
57
- [
58
- `## ${s.label} (${s.name})`,
59
- `Measures: ${s.measures.map((m) => `${m.label} (${m.id}${m.aggregate === undefined ? "" : `, ${m.aggregate}`})`).join("; ")}`,
60
- `Fields: ${s.dimensions.map((d) => `${d.label} (${d.id}, ${d.type})`).join("; ")}`,
61
- ...(s.joins.length === 0
62
- ? []
63
- : [`Joins: ${s.joins.map((j) => `${j.label} (${j.name} to ${j.source})`).join("; ")}`]),
64
- ].join("\n"),
65
- );
66
- return ok(text.join("\n\n") || "Nothing this viewer may read.", { sources });
67
- }
68
-
69
- /** The question, every name turned into its id. */
70
- async function resolved(c: QueryContext, input: QueryInput) {
71
- if (input.query === undefined)
72
- throw new HttpError(
73
- 400,
74
- "QUERY_INVALID",
75
- `${input.op} needs a query: a source and at least one measure.`,
76
- );
77
- return resolveQuery(await meta(c), { ...input.query, kind: "aggregate" as const });
78
- }
79
-
80
- async function ask(c: QueryContext, input: QueryInput): Promise<ToolResult> {
81
- const query = await resolved(c, input);
82
- const answer = await c.dashboards.api.queryRun({ body: { query }, viewer: c.viewer });
83
- return ok(answerText(answer), answer);
84
- }
85
-
86
- async function rows(c: QueryContext, input: QueryInput): Promise<ToolResult> {
87
- const query = await resolved(c, input);
88
- const body = { query, limit: input.limit ?? 50 };
89
- const page = await c.dashboards.api.queryRecords({ body, viewer: c.viewer });
90
- const labels = page.columns.map((col) => col.label);
91
- return ok(table(labels, page.rows), page);
92
- }
93
-
94
- async function list(c: QueryContext): Promise<ToolResult> {
95
- const all = await listed(c);
96
- const rowsOf = all.dashboards.map((d) => [
97
- d.title,
98
- d.id,
99
- "unpublished" in d ? "draft" : `v${d.version}`,
100
- ]);
101
- return ok(table(["Dashboard", "Id", "Version"], rowsOf), all);
102
- }
103
-
104
- /** Every line a streamed answer gives, read to its end. */
105
- async function collect<T>(stream: AsyncIterable<T>): Promise<T[]> {
106
- const lines: T[] = [];
107
- for await (const line of stream) lines.push(line);
108
- return lines;
109
- }
110
-
111
- /** One tile's part of the read-out: its title, then its answer or why it has none. */
112
- function tileText(title: string, line: TileLine | undefined): string {
113
- if (line === undefined || "done" in line) return `### ${title}\nNo answer.`;
114
- if (!line.ok) return `### ${title}\n${line.error.code}: ${line.error.message}`;
115
- return `### ${title}\n${answerText(line.result)}`;
116
- }
117
-
118
- /** One dashboard read out: each tile's title and answer, in layout order, and its link. */
119
- async function open(c: QueryContext, input: QueryInput): Promise<ToolResult> {
120
- const { id } = dashboardOf((await listed(c)).dashboards, input.dashboard ?? "");
121
- const got = await c.dashboards.api.getDashboard({ body: { dashboardId: id }, viewer: c.viewer });
122
- const widgets = got.document.tabs
123
- .flatMap((t) => t.layout.map((item) => item.widget))
124
- .slice(0, 50);
125
- const body = {
126
- dashboardId: id,
127
- version: got.version,
128
- tiles: widgets.map((widgetId) => ({ widgetId })),
129
- ...(input.filters === undefined ? {} : { picks: input.filters }),
130
- };
131
- const lines =
132
- widgets.length === 0
133
- ? []
134
- : await collect(await c.dashboards.api.tiles({ body, viewer: c.viewer }));
135
- const tiles = widgets.map((widgetId, i) =>
136
- tileText(
137
- got.document.widgets[widgetId]?.title ?? widgetId,
138
- lines.find((l) => "i" in l && l.i === i),
139
- ),
140
- );
141
- const link = c.linkFor?.(id);
142
- const head = `# ${got.document.meta.title}${link === undefined ? "" : `\n${link}`}`;
143
- return ok([head, ...tiles].join("\n\n"), { dashboard: got, tiles: lines });
144
- }
145
-
146
- /** Runs one op of dashboards_query as the viewer. */
147
- export function runQuery(c: QueryContext, input: QueryInput): Promise<ToolResult> {
148
- if (input.op === "describe") return describe(c, input.source);
149
- if (input.op === "ask") return ask(c, input);
150
- if (input.op === "rows") return rows(c, input);
151
- if (input.op === "list") return list(c);
152
- return open(c, input);
153
- }
@@ -1,114 +0,0 @@
1
- // Agents name things the way people do: "Signups", "Plan", "Tasks". A question may name a
2
- // source, measure or field by its id, its short name or its label; each is turned into its id
3
- // here, and a name that matches nothing is refused with the names that would have worked.
4
- import type { MetaResponse } from "@derive-to/dashboards-core";
5
- import { HttpError } from "../http";
6
-
7
- type Source = MetaResponse["sources"][number];
8
- type Named = { id: string; label: string };
9
-
10
- const fold = (text: string) => text.trim().toLowerCase();
11
-
12
- /** The one entry `name` names, by id, by the part after the source, or by label. */
13
- function pick<T extends Named>(entries: readonly T[], name: string): T | undefined {
14
- const wanted = fold(name);
15
- return (
16
- entries.find((e) => e.id === name) ??
17
- entries.find((e) => fold(e.id.split(".").slice(1).join(".")) === wanted) ??
18
- entries.find((e) => fold(e.label) === wanted)
19
- );
20
- }
21
-
22
- const unknown = (what: string, name: string, choices: readonly Named[]) =>
23
- new HttpError(
24
- 400,
25
- "QUERY_INVALID",
26
- `There is no ${what} "${name}". Use one of: ${choices
27
- .slice(0, 40)
28
- .map((c) => `${c.label} (${c.id})`)
29
- .join(", ")}.`,
30
- );
31
-
32
- /** The source a question reads, by name or label. */
33
- export function sourceOf(meta: MetaResponse, name: string): Source {
34
- const found = pick(
35
- meta.sources.map((s) => ({ ...s, id: s.name })),
36
- name,
37
- );
38
- if (found === undefined)
39
- throw unknown(
40
- "source",
41
- name,
42
- meta.sources.map((s) => ({ id: s.name, label: s.label })),
43
- );
44
- return found;
45
- }
46
-
47
- /** A field's id: one of the source's own, by any of its names, or a joined one already by id. */
48
- function memberId(source: Source, name: string): string {
49
- if (name.split(".").length > 2) return name;
50
- const found = pick(source.dimensions, name);
51
- if (found === undefined) throw unknown("field", name, source.dimensions);
52
- return found.id;
53
- }
54
-
55
- function measureId(source: Source, name: string): string {
56
- const found = pick(source.measures, name);
57
- if (found === undefined) throw unknown("measure", name, source.measures);
58
- return found.id;
59
- }
60
-
61
- /** Every `member` in a filter tree, by id; the tree is otherwise as given. */
62
- function filterIds(source: Source, filter: unknown): unknown {
63
- if (Array.isArray(filter)) return filter.map((f) => filterIds(source, f));
64
- if (typeof filter !== "object" || filter === null) return filter;
65
- return Object.fromEntries(
66
- Object.entries(filter).map(([key, value]) =>
67
- key === "member" && typeof value === "string"
68
- ? [key, memberId(source, value)]
69
- : [key, filterIds(source, value)],
70
- ),
71
- );
72
- }
73
-
74
- type Loose = {
75
- source: string;
76
- measures: readonly { measure: string }[];
77
- dimensions?: readonly { member: string }[];
78
- time?: { dimension: string };
79
- filters?: unknown;
80
- };
81
-
82
- /** The question with every source, measure and field named by its id. */
83
- export function resolveQuery<Q extends Loose>(meta: MetaResponse, query: Q): Q {
84
- const source = sourceOf(meta, query.source);
85
- return {
86
- ...query,
87
- source: source.name,
88
- measures: query.measures.map((m) => ({ ...m, measure: measureId(source, m.measure) })),
89
- ...(query.dimensions === undefined
90
- ? {}
91
- : {
92
- dimensions: query.dimensions.map((d) => ({ ...d, member: memberId(source, d.member) })),
93
- }),
94
- ...(query.time === undefined
95
- ? {}
96
- : { time: { ...query.time, dimension: memberId(source, query.time.dimension) } }),
97
- ...(query.filters === undefined ? {} : { filters: filterIds(source, query.filters) }),
98
- };
99
- }
100
-
101
- /** A dashboard named by id or title, from those the viewer can open. */
102
- export function dashboardOf(
103
- listed: readonly { id: string; title: string }[],
104
- name: string,
105
- ): { id: string; title: string } {
106
- const found =
107
- listed.find((d) => d.id === name) ?? listed.find((d) => fold(d.title) === fold(name));
108
- if (found !== undefined) return found;
109
- throw new HttpError(
110
- 404,
111
- "NOT_FOUND",
112
- `There is no dashboard "${name}". Open one of: ${listed.map((d) => `${d.title} (${d.id})`).join(", ")}.`,
113
- );
114
- }
@@ -1,81 +0,0 @@
1
- import type { IntrospectingConnection } from "@derive-to/dashboards-core";
2
- import { postgresConnection, type RunSql } from "./postgres-connection";
3
- import { postgresStore, type RunRows } from "./postgres-store";
4
-
5
- /** What `nodePostgres` uses of a node-postgres client: its `query` with a config object. */
6
- export type PgQueryable = {
7
- query(config: { text: string; values?: unknown[]; rowMode?: "array" }): Promise<{
8
- rows: unknown[];
9
- }>;
10
- };
11
-
12
- /** What `nodePostgres` uses of a node-postgres `Pool`: `query`, and `connect` for a transaction. */
13
- export type PgPool = PgQueryable & {
14
- connect(): Promise<PgQueryable & { release(destroy?: boolean | Error): void }>;
15
- };
16
-
17
- /** Rows as arrays in select order, for queries; as objects by column, for the store. */
18
- const arrays =
19
- (client: PgQueryable): RunSql =>
20
- async (text, params) =>
21
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- rowMode "array" returns arrays
22
- (await client.query({ text, values: [...params], rowMode: "array" })).rows as unknown[][];
23
- const objects =
24
- (client: PgQueryable): RunRows =>
25
- async (text, params) =>
26
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- without rowMode, rows are objects
27
- (await client.query({ text, values: [...params] })).rows as Record<string, unknown>[];
28
-
29
- /**
30
- * One client of the pool for `fn`, inside a transaction `begin` starts: committed when `fn`
31
- * resolves, rolled back when it throws, and the client always given back (dropped from the pool
32
- * when even the rollback failed).
33
- */
34
- async function inTransaction<T>(
35
- pool: PgPool,
36
- begin: string,
37
- fn: (client: PgQueryable) => Promise<T>,
38
- ): Promise<T> {
39
- const client = await pool.connect();
40
- let broken = false;
41
- try {
42
- await client.query({ text: begin });
43
- const value = await fn(client);
44
- await client.query({ text: "COMMIT" });
45
- return value;
46
- } catch (error) {
47
- await client.query({ text: "ROLLBACK" }).catch(() => {
48
- broken = true;
49
- });
50
- throw error;
51
- } finally {
52
- client.release(broken);
53
- }
54
- }
55
-
56
- /**
57
- * The query connection and the store for a node-postgres `Pool`, set up the safe way: each
58
- * request's queries read one snapshot on one pooled client, begun in one round trip with the
59
- * request's statement timeout (so a slow query stops in the database), and every store write
60
- * is one transaction. Works the same behind PgBouncer in transaction mode.
61
- *
62
- * const { connection, store } = nodePostgres(pool);
63
- * deriveDashboards({ ..., connections: { main: connection }, database: store });
64
- */
65
- export function nodePostgres(
66
- pool: PgPool,
67
- options: { id?: string } = {},
68
- ): { connection: IntrospectingConnection; store: ReturnType<typeof postgresStore> } {
69
- return {
70
- connection: postgresConnection({
71
- ...(options.id === undefined ? {} : { id: options.id }),
72
- run: arrays(pool),
73
- sendsBegin: true,
74
- transaction: (fn, begin) => inTransaction(pool, begin, (client) => fn(arrays(client))),
75
- }),
76
- store: postgresStore({
77
- run: objects(pool),
78
- transaction: (fn) => inTransaction(pool, "BEGIN", (client) => fn(objects(client))),
79
- }),
80
- };
81
- }
package/src/owner.ts DELETED
@@ -1,36 +0,0 @@
1
- import {
2
- type DashOptions,
3
- type Principal,
4
- principalTenant,
5
- type Resource,
6
- type Row,
7
- } from "@derive-to/dashboards-core";
8
- import { parseDashboardId } from "./dashboard-id";
9
- import { adapterFor } from "./dashboards";
10
- import { requestDashboardRow } from "./request-rows";
11
-
12
- /** Who made a stored dashboard, as `can` receives it. */
13
- const ownerOf = (row: Row): { id: string; kind: "user" | "agent" } => ({
14
- id: String(row["owner_id"]),
15
- kind: row["owner_kind"] === "agent" ? "agent" : "user",
16
- });
17
-
18
- /**
19
- * A dashboard as `can` sees it: its id, and who made it when it is stored, so a host's rule
20
- * such as "people edit what they made" needs no table of its own. A built-in has no owner,
21
- * customized or not.
22
- */
23
- export async function dashboardResource(
24
- options: DashOptions,
25
- request: Request,
26
- principal: Principal,
27
- id: string,
28
- ): Promise<Resource> {
29
- const adapter = adapterFor(options, request);
30
- if (adapter === undefined || id === "") return { kind: "dashboard", id };
31
- const tenant = principalTenant(principal);
32
- const row = await requestDashboardRow(request, adapter, tenant, parseDashboardId(id));
33
- // A built-in's stored copy belongs to nobody: it was made by whoever first pressed Edit.
34
- if (row === null || row["default_of"] !== null) return { kind: "dashboard", id };
35
- return { kind: "dashboard", id, owner: ownerOf(row) };
36
- }