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.
- package/README.md +4 -3
- package/dist/adapter/sql-adapter.mjs +4 -4
- package/dist/body.mjs +11 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cli/check.mjs +14 -1
- package/dist/cli/import/dbt-schema.mjs +2 -2
- package/dist/cli/import/index.mjs +2 -2
- package/dist/core/conformance/cases.d.mts +3 -0
- package/dist/core/conformance/cases.mjs +20 -4
- package/dist/core/conformance/check.mjs +6 -3
- package/dist/core/conformance/drill-cases.mjs +120 -0
- package/dist/core/document/view.d.mts +26 -7
- package/dist/core/document/view.mjs +42 -11
- package/dist/core/engine/index.d.mts +14 -2
- package/dist/core/engine/index.mjs +12 -1
- package/dist/core/engine/members.mjs +1 -1
- package/dist/core/engine/postgres.mjs +1 -1
- package/dist/core/engine/record-layout.d.mts +11 -0
- package/dist/core/engine/record-layout.mjs +7 -7
- package/dist/core/engine/records.d.mts +3 -2
- package/dist/core/engine/records.mjs +2 -1
- package/dist/core/engine/segmented.mjs +5 -2
- package/dist/core/engine/sql-records.mjs +2 -1
- package/dist/core/engine/statement.mjs +37 -3
- package/dist/core/engine/types.d.mts +3 -0
- package/dist/core/engine/version.d.mts +1 -1
- package/dist/core/engine/version.mjs +1 -1
- package/dist/core/error/codes.d.mts +31 -0
- package/dist/core/error/codes.mjs +28 -1
- package/dist/core/index.d.mts +9 -5
- package/dist/core/index.mjs +5 -3
- package/dist/core/model/catalog/check.mjs +1 -1
- package/dist/core/model/hints.d.mts +36 -0
- package/dist/core/model/member.d.mts +4 -2
- package/dist/core/model/member.mjs +16 -3
- package/dist/core/model/types.d.mts +8 -6
- package/dist/core/model/validate/drill.mjs +70 -0
- package/dist/core/model/validate/index.mjs +3 -0
- package/dist/core/model/validate/shape.mjs +150 -0
- package/dist/core/model/validate/source.mjs +5 -3
- package/dist/core/query/alias.mjs +7 -1
- package/dist/core/query/drill/compose.d.mts +22 -0
- package/dist/core/query/drill/compose.mjs +85 -0
- package/dist/core/query/drill/fields.d.mts +21 -0
- package/dist/core/query/drill/fields.mjs +91 -0
- package/dist/core/query/drill/internal.d.mts +11 -0
- package/dist/core/query/drill/items.d.mts +29 -0
- package/dist/core/query/drill/items.mjs +98 -0
- package/dist/core/query/drill/line.d.mts +31 -0
- package/dist/core/query/drill/line.mjs +183 -0
- package/dist/core/query/drill/links.d.mts +33 -0
- package/dist/core/query/drill/links.mjs +31 -0
- package/dist/core/query/drill/operand.mjs +7 -0
- package/dist/core/query/drill/scopes.d.mts +22 -0
- package/dist/core/query/drill/scopes.mjs +58 -0
- package/dist/core/query/drill/selection.d.mts +37 -0
- package/dist/core/query/drill/selection.mjs +144 -0
- package/dist/core/query/drill/steps.d.mts +14 -0
- package/dist/core/query/drill/steps.mjs +35 -0
- package/dist/core/query/drill/synthetic-expr.mjs +85 -0
- package/dist/core/query/drill/synthetic.d.mts +22 -0
- package/dist/core/query/drill/synthetic.mjs +165 -0
- package/dist/core/query/drill/time.d.mts +11 -0
- package/dist/core/query/drill/time.mjs +71 -0
- package/dist/core/query/drill/types.d.mts +155 -0
- package/dist/core/query/drill/types.mjs +4 -0
- package/dist/core/query/drill/views.d.mts +62 -0
- package/dist/core/query/drill/views.mjs +257 -0
- package/dist/core/query/segments.d.mts +12 -2
- package/dist/core/query/segments.mjs +3 -1
- package/dist/core/result/columns.mjs +17 -4
- package/dist/core/result/types.d.mts +5 -1
- package/dist/core/schema/answer-parts.mjs +117 -0
- package/dist/core/schema/answers.d.mts +2108 -128
- package/dist/core/schema/answers.mjs +10 -113
- package/dist/core/schema/commands.d.mts +2 -2
- package/dist/core/schema/document.d.mts +1 -1
- package/dist/core/schema/drill-answers.mjs +179 -0
- package/dist/core/schema/drill.d.mts +260 -0
- package/dist/core/schema/drill.mjs +107 -0
- package/dist/core/schema/index.d.mts +4 -2
- package/dist/core/schema/index.mjs +4 -2
- package/dist/core/schema/picks.d.mts +35 -0
- package/dist/core/schema/picks.mjs +23 -0
- package/dist/core/schema/query.d.mts +1 -1
- package/dist/core/schema/tools.mjs +1 -1
- package/dist/core/schema/view.d.mts +0 -35
- package/dist/core/schema/view.mjs +19 -24
- package/dist/core/store/schema.d.mts +5 -0
- package/dist/core/store/schema.mjs +10 -0
- package/dist/core/types/api.d.mts +15 -1
- package/dist/core/types/api.mjs +1 -1
- package/dist/core/types/drill-api.d.mts +210 -0
- package/dist/core/types/options.d.mts +21 -0
- package/dist/core/types/viewer.d.mts +5 -0
- package/dist/cursor-seal.d.mts +8 -0
- package/dist/cursor-seal.mjs +98 -0
- package/dist/dashboard-id.mjs +1 -1
- package/dist/drill-access.mjs +93 -0
- package/dist/drill-change.mjs +76 -0
- package/dist/drill-crumbs.mjs +113 -0
- package/dist/drill-distinct.mjs +130 -0
- package/dist/drill-explain.mjs +64 -0
- package/dist/drill-identity.mjs +35 -0
- package/dist/drill-item-id.mjs +35 -0
- package/dist/drill-items.mjs +132 -0
- package/dist/drill-open.mjs +169 -0
- package/dist/drill-seal.mjs +170 -0
- package/dist/drill-secret.mjs +14 -0
- package/dist/drill-share.mjs +53 -0
- package/dist/drill-summary.mjs +158 -0
- package/dist/drill-targets.mjs +53 -0
- package/dist/drill-totals.mjs +8 -0
- package/dist/drill-views.mjs +175 -0
- package/dist/drill.mjs +157 -0
- package/dist/editing.mjs +2 -2
- package/dist/endpoints/dashboards.mjs +11 -3
- package/dist/endpoints/drill.mjs +55 -0
- package/dist/endpoints/index.d.mts +233 -2
- package/dist/endpoints/index.mjs +5 -1
- package/dist/endpoints/query.mjs +26 -4
- package/dist/execute.d.mts +19 -1
- package/dist/execute.mjs +15 -17
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +29 -2
- package/dist/mcp/drill.mjs +61 -0
- package/dist/mcp/format.mjs +27 -3
- package/dist/mcp/index.d.mts +15 -4
- package/dist/mcp/index.mjs +13 -7
- package/dist/mcp/query.d.mts +7 -2
- package/dist/mcp/query.mjs +7 -3
- package/dist/node-postgres.d.mts +8 -4
- package/dist/node-postgres.mjs +29 -6
- package/dist/owner.mjs +3 -3
- package/dist/postgres-connection.d.mts +8 -2
- package/dist/postgres-connection.mjs +2 -1
- package/dist/react/Dashboard.d.mts +10 -5
- package/dist/react/Dashboard.mjs +51 -23
- package/dist/react/DashboardList.mjs +30 -2
- package/dist/react/Discard.mjs +7 -2
- package/dist/react/Grid.mjs +12 -5
- package/dist/react/Header.mjs +9 -0
- package/dist/react/Parts.mjs +6 -2
- package/dist/react/ReviewPanel.mjs +13 -2
- package/dist/react/RowBody.d.mts +19 -0
- package/dist/react/RowBody.mjs +55 -0
- package/dist/react/Tile.d.mts +1 -1
- package/dist/react/Tile.mjs +54 -30
- package/dist/react/builder/state.d.mts +1 -1
- package/dist/react/client.d.mts +2 -0
- package/dist/react/client.mjs +1 -0
- package/dist/react/context.d.mts +15 -1
- package/dist/react/context.mjs +19 -4
- package/dist/react/drill/Bars.mjs +179 -0
- package/dist/react/drill/Controls.mjs +173 -0
- package/dist/react/drill/DashboardTile.d.mts +18 -0
- package/dist/react/drill/DashboardTile.mjs +107 -0
- package/dist/react/drill/DrillPanel.d.mts +31 -0
- package/dist/react/drill/DrillPanel.mjs +104 -0
- package/dist/react/drill/DrillTabs.mjs +52 -0
- package/dist/react/drill/Header.mjs +131 -0
- package/dist/react/drill/Items.d.mts +22 -0
- package/dist/react/drill/Items.mjs +164 -0
- package/dist/react/drill/ItemsFoot.mjs +60 -0
- package/dist/react/drill/Notes.mjs +58 -0
- package/dist/react/drill/PanelBody.mjs +74 -0
- package/dist/react/drill/PanelStates.mjs +37 -0
- package/dist/react/drill/board.d.mts +18 -0
- package/dist/react/drill/board.mjs +91 -0
- package/dist/react/drill/counts.mjs +14 -0
- package/dist/react/drill/host.mjs +26 -0
- package/dist/react/drill/item-parts.d.mts +5 -0
- package/dist/react/drill/item-parts.mjs +76 -0
- package/dist/react/drill/item-type.d.mts +26 -0
- package/dist/react/drill/item-type.mjs +7 -0
- package/dist/react/drill/lazy.d.mts +6 -0
- package/dist/react/drill/lazy.mjs +17 -0
- package/dist/react/drill/pages.mjs +48 -0
- package/dist/react/drill/panel-focus.mjs +51 -0
- package/dist/react/drill/props.d.mts +25 -0
- package/dist/react/drill/props.mjs +72 -0
- package/dist/react/drill/state.d.mts +18 -0
- package/dist/react/drill/state.mjs +68 -0
- package/dist/react/drill/useDrill.d.mts +46 -0
- package/dist/react/drill/useDrill.mjs +194 -0
- package/dist/react/drill/words.d.mts +98 -0
- package/dist/react/drill/words.mjs +77 -0
- package/dist/react/english.mjs +9 -1
- package/dist/react/format.d.mts +3 -3
- package/dist/react/format.mjs +34 -12
- package/dist/react/index.d.mts +27 -4
- package/dist/react/index.mjs +10 -3
- package/dist/react/messages.d.mts +14 -1
- package/dist/react/renderers/index.d.mts +10 -2
- package/dist/react/renderers/index.mjs +54 -14
- package/dist/react/renderers/list.d.mts +22 -0
- package/dist/react/renderers/list.mjs +118 -0
- package/dist/react/review-words.mjs +1 -1
- package/dist/react/review.mjs +2 -2
- package/dist/react/scope.mjs +2 -7
- package/dist/react/series.d.mts +37 -0
- package/dist/react/series.mjs +95 -0
- package/dist/react/theme.css +1823 -1296
- package/dist/react/theme.css.d.ts +1 -0
- package/dist/react/tile-store.mjs +15 -3
- package/dist/react/useBoard.d.mts +5 -0
- package/dist/react/useBoard.mjs +4 -1
- package/dist/react/useDashboard.d.mts +1 -0
- package/dist/react/useDashboard.mjs +2 -1
- package/dist/react/useTiles.mjs +50 -15
- package/dist/react/view.d.mts +9 -0
- package/dist/react/view.mjs +22 -10
- package/dist/reading.d.mts +2 -0
- package/dist/reading.mjs +9 -1
- package/dist/recharts/charts.d.mts +0 -1
- package/dist/recharts/charts.mjs +128 -34
- package/dist/recharts/index.d.mts +2 -2
- package/dist/recharts/index.mjs +2 -2
- package/dist/recharts/marks.mjs +83 -0
- package/dist/recharts/series.d.mts +2 -22
- package/dist/recharts/series.mjs +1 -64
- package/dist/records-read.mjs +44 -0
- package/dist/store/apply.mjs +5 -5
- package/dist/store/commands.mjs +4 -4
- package/dist/store/discard.mjs +7 -7
- package/dist/store/drafts.mjs +5 -5
- package/dist/store/editor.mjs +1 -1
- package/dist/store/publish.mjs +12 -12
- package/dist/store/reader.mjs +41 -22
- package/dist/store/review.mjs +16 -16
- package/dist/store/rows.mjs +20 -20
- package/dist/store/undo.mjs +3 -3
- package/dist/store/unpublished.mjs +4 -4
- package/dist/store/versions.mjs +14 -14
- package/dist/testing/adapter-suite.mjs +4 -4
- package/dist/tiles.mjs +37 -3
- package/package.json +8 -10
- package/dist/react/Records.d.mts +0 -12
- package/dist/react/Records.mjs +0 -97
- package/src/adapter/sql-adapter.ts +0 -95
- package/src/adapter/statement.ts +0 -185
- package/src/authorize.ts +0 -73
- package/src/body.ts +0 -169
- package/src/bounded.ts +0 -43
- package/src/cache.ts +0 -192
- package/src/checks.ts +0 -170
- package/src/custom-source.ts +0 -59
- package/src/dashboard-id.ts +0 -36
- package/src/dashboards.ts +0 -132
- package/src/editing.ts +0 -148
- package/src/endpoints/access.ts +0 -41
- package/src/endpoints/dashboards.ts +0 -92
- package/src/endpoints/drafts.ts +0 -138
- package/src/endpoints/index.ts +0 -21
- package/src/endpoints/meta.ts +0 -137
- package/src/endpoints/query.ts +0 -86
- package/src/endpoints/read.ts +0 -92
- package/src/endpoints/review.ts +0 -89
- package/src/endpoints/values.ts +0 -62
- package/src/endpoints/versions.ts +0 -104
- package/src/execute.ts +0 -207
- package/src/handler.ts +0 -232
- package/src/http.ts +0 -66
- package/src/index.ts +0 -163
- package/src/introspect.ts +0 -205
- package/src/mcp/api.ts +0 -59
- package/src/mcp/format.ts +0 -67
- package/src/mcp/index.ts +0 -151
- package/src/mcp/query.ts +0 -153
- package/src/mcp/resolve.ts +0 -114
- package/src/node-postgres.ts +0 -81
- package/src/owner.ts +0 -36
- package/src/postgres-connection.ts +0 -143
- package/src/postgres-store.ts +0 -82
- package/src/principal.ts +0 -39
- package/src/reading.ts +0 -56
- package/src/request-rows.ts +0 -23
- package/src/request.ts +0 -22
- package/src/storage.ts +0 -63
- package/src/store/apply.ts +0 -129
- package/src/store/commands.ts +0 -75
- package/src/store/conflicts.ts +0 -98
- package/src/store/create-tables.ts +0 -104
- package/src/store/discard.ts +0 -42
- package/src/store/drafts.ts +0 -133
- package/src/store/editor.ts +0 -28
- package/src/store/log.ts +0 -28
- package/src/store/publish.ts +0 -199
- package/src/store/publisher.ts +0 -21
- package/src/store/reader.ts +0 -139
- package/src/store/review.ts +0 -239
- package/src/store/rows.ts +0 -250
- package/src/store/tenant.ts +0 -28
- package/src/store/undo.ts +0 -56
- package/src/store/unpublished.ts +0 -33
- package/src/store/versions.ts +0 -106
- package/src/store/writer.ts +0 -19
- package/src/testing/adapter-suite.ts +0 -239
- package/src/testing/index.ts +0 -2
- package/src/tile-doc.ts +0 -46
- package/src/tiles.ts +0 -120
package/src/execute.ts
DELETED
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
type BoundFilter,
|
|
3
|
-
type Calendar,
|
|
4
|
-
canonical,
|
|
5
|
-
type DashOptions,
|
|
6
|
-
type Issue,
|
|
7
|
-
isBound,
|
|
8
|
-
type LockEntry,
|
|
9
|
-
markedRows,
|
|
10
|
-
type Principal,
|
|
11
|
-
type RecordsResponse,
|
|
12
|
-
type Result,
|
|
13
|
-
recordColumns,
|
|
14
|
-
resultColumns,
|
|
15
|
-
type ScopeCoverage,
|
|
16
|
-
type WireFilter,
|
|
17
|
-
type WireQuery,
|
|
18
|
-
} from "@derive-to/dashboards-core";
|
|
19
|
-
import {
|
|
20
|
-
EngineError,
|
|
21
|
-
type EngineInput,
|
|
22
|
-
type Reader,
|
|
23
|
-
readQuery,
|
|
24
|
-
readRecords,
|
|
25
|
-
} from "@derive-to/dashboards-core/engine";
|
|
26
|
-
import { checkSensitive } from "./authorize";
|
|
27
|
-
import { type Cache, manifest, sha256 } from "./cache";
|
|
28
|
-
import { adapterFor } from "./dashboards";
|
|
29
|
-
import { withReader } from "./reading";
|
|
30
|
-
import { logQuery } from "./store/log";
|
|
31
|
-
|
|
32
|
-
/** The runtime's state for one handler: its options and its result cache. */
|
|
33
|
-
export type Runtime = { options: DashOptions; cache: Cache | undefined };
|
|
34
|
-
|
|
35
|
-
/** What one query needs to run: the request around it, and the query as composed. */
|
|
36
|
-
export type Execution = {
|
|
37
|
-
rt: Runtime;
|
|
38
|
-
request: Request;
|
|
39
|
-
principal: Principal;
|
|
40
|
-
now: Date;
|
|
41
|
-
calendar: Calendar;
|
|
42
|
-
query: WireQuery;
|
|
43
|
-
lock: readonly LockEntry[];
|
|
44
|
-
coverage: ScopeCoverage;
|
|
45
|
-
/** The dashboard the query belongs to; absent for a free query. */
|
|
46
|
-
dashboardId?: string;
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
export type Answered = Result & { unreadable?: true };
|
|
50
|
-
|
|
51
|
-
const DEFAULT_QUANTUM = 60;
|
|
52
|
-
|
|
53
|
-
function boundEntries<E extends { filter: WireFilter }>(
|
|
54
|
-
entries: readonly E[],
|
|
55
|
-
what: string,
|
|
56
|
-
): (E & { filter: BoundFilter })[] {
|
|
57
|
-
return entries.map((entry) => {
|
|
58
|
-
if (!isBound(entry.filter)) {
|
|
59
|
-
throw new EngineError(
|
|
60
|
-
"FILTER_UNBOUND",
|
|
61
|
-
`A ${what} that uses a viewer value or a variable is not supported yet.`,
|
|
62
|
-
);
|
|
63
|
-
}
|
|
64
|
-
return { ...entry, filter: entry.filter };
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** The filters that decided an answer, as the viewer may see them: the query's, each lock's, each required filter's. */
|
|
69
|
-
function receiptFilter(bound: Bound): BoundFilter {
|
|
70
|
-
const { query } = bound.input;
|
|
71
|
-
return {
|
|
72
|
-
all: [
|
|
73
|
-
...(query.filters !== undefined && isBound(query.filters) ? [query.filters] : []),
|
|
74
|
-
...bound.lock.map((e) => e.filter),
|
|
75
|
-
...bound.required.map((e) => e.filter),
|
|
76
|
-
],
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/** The query bound for the engine: no sensitive member, and no viewer value or variable left in the lock or required filters. */
|
|
81
|
-
function bind(x: Execution) {
|
|
82
|
-
const { options } = x.rt;
|
|
83
|
-
checkSensitive(options, x.principal, x.query);
|
|
84
|
-
const lock = boundEntries(x.lock, "lock");
|
|
85
|
-
const required = boundEntries(
|
|
86
|
-
options.compose?.required?.({
|
|
87
|
-
principal: x.principal,
|
|
88
|
-
calendar: x.calendar,
|
|
89
|
-
...(x.dashboardId === undefined ? {} : { dashboardId: x.dashboardId }),
|
|
90
|
-
}) ?? [],
|
|
91
|
-
"required filter",
|
|
92
|
-
);
|
|
93
|
-
const maxRows = options.query?.maxRows ?? 5000;
|
|
94
|
-
const input: EngineInput = {
|
|
95
|
-
model: options.model,
|
|
96
|
-
query: x.query,
|
|
97
|
-
principal: x.principal,
|
|
98
|
-
locks: lock,
|
|
99
|
-
required,
|
|
100
|
-
now: x.now,
|
|
101
|
-
calendar: x.calendar,
|
|
102
|
-
maxRows,
|
|
103
|
-
quantumSeconds: options.cache?.quantum ?? DEFAULT_QUANTUM,
|
|
104
|
-
};
|
|
105
|
-
return { input, lock, required, maxRows };
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
type Bound = ReturnType<typeof bind>;
|
|
109
|
-
|
|
110
|
-
/** Reads through the query's connection, under the request's deadline and abort. */
|
|
111
|
-
const reading = <T>(x: Execution, maxRows: number, fn: (reader: Reader) => Promise<T>) =>
|
|
112
|
-
withReader({ options: x.rt.options, request: x.request, source: x.query.source, maxRows }, fn);
|
|
113
|
-
|
|
114
|
-
/** Runs the engine and shapes its answer as the plan's `Result`, with a receipt of what was read. */
|
|
115
|
-
async function compute(x: Execution, bound: Bound): Promise<Answered> {
|
|
116
|
-
const started = performance.now();
|
|
117
|
-
const computedAt = new Date().toISOString();
|
|
118
|
-
const { value, consistency, custom } = await reading(x, bound.maxRows, (reader) =>
|
|
119
|
-
readQuery(bound.input, reader),
|
|
120
|
-
);
|
|
121
|
-
const { truncated, unreadable, compare, ...levels } = value.answer;
|
|
122
|
-
const warnings: Issue[] =
|
|
123
|
-
truncated === true
|
|
124
|
-
? [{ code: "ROW_CAP", message: `The answer was cut at ${bound.maxRows} rows.`, path: [] }]
|
|
125
|
-
: [];
|
|
126
|
-
return {
|
|
127
|
-
columns: resultColumns(x.rt.options.model, x.query),
|
|
128
|
-
rows: markedRows(x.query, levels),
|
|
129
|
-
...(compare === undefined
|
|
130
|
-
? {}
|
|
131
|
-
: { compare: { rows: markedRows(x.query, compare), range: compare.range } }),
|
|
132
|
-
status: truncated === true ? "truncated" : "complete",
|
|
133
|
-
...(unreadable === true ? { unreadable } : {}),
|
|
134
|
-
receipt: {
|
|
135
|
-
queryHash: await sha256(
|
|
136
|
-
canonical({ query: x.query, lock: bound.lock, required: bound.required }),
|
|
137
|
-
),
|
|
138
|
-
// A custom source's rows come from the host's own code, not the library's SQL.
|
|
139
|
-
provider: custom ? "custom" : "builtin",
|
|
140
|
-
trust: custom ? "external" : "builtin",
|
|
141
|
-
sources: value.sources,
|
|
142
|
-
answeredBy: "base",
|
|
143
|
-
cache: "off",
|
|
144
|
-
...(value.range === undefined ? {} : { range: value.range }),
|
|
145
|
-
calendar: x.calendar,
|
|
146
|
-
dataThrough: computedAt,
|
|
147
|
-
computedAt,
|
|
148
|
-
consistency,
|
|
149
|
-
durationMs: Math.round(performance.now() - started),
|
|
150
|
-
rowsReturned: levels.rows.length,
|
|
151
|
-
filter: receiptFilter(bound),
|
|
152
|
-
coverage: x.coverage,
|
|
153
|
-
warnings,
|
|
154
|
-
},
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* Runs one composed query under the viewer's access and returns the plan's `Result`: rows
|
|
160
|
-
* described by their columns, `complete` or `truncated`, and a receipt. With a cache, an equal
|
|
161
|
-
* request (same bound query, policies, calendar and source epochs) is answered from it.
|
|
162
|
-
*/
|
|
163
|
-
export async function execute(x: Execution): Promise<Answered> {
|
|
164
|
-
const answer = await answered(x);
|
|
165
|
-
record(x, answer);
|
|
166
|
-
return answer;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/** With `queryLog`, one row per answer, written where the host runs background work; never fails a request. */
|
|
170
|
-
function record(x: Execution, answer: Answered): void {
|
|
171
|
-
const { options } = x.rt;
|
|
172
|
-
const adapter = options.queryLog === true ? adapterFor(options, x.request) : undefined;
|
|
173
|
-
if (adapter === undefined) return;
|
|
174
|
-
const task = logQuery(adapter, x.principal, x.query.source, answer).catch(() => null);
|
|
175
|
-
options.advanced?.backgroundTasks?.handler(task);
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
function answered(x: Execution): Promise<Answered> {
|
|
179
|
-
const bound = bind(x);
|
|
180
|
-
const { cache, options } = x.rt;
|
|
181
|
-
if (cache === undefined) return compute(x, bound);
|
|
182
|
-
const quantum = (options.cache?.quantum ?? DEFAULT_QUANTUM) * 1000;
|
|
183
|
-
const on = [...bound.lock, ...bound.required].map((e) => e.on);
|
|
184
|
-
const key = {
|
|
185
|
-
principal: x.principal,
|
|
186
|
-
query: x.query,
|
|
187
|
-
lock: bound.lock,
|
|
188
|
-
required: bound.required,
|
|
189
|
-
calendar: x.calendar,
|
|
190
|
-
maxRows: bound.maxRows,
|
|
191
|
-
now: x.now.getTime() - (x.now.getTime() % quantum),
|
|
192
|
-
sources: manifest(options.model, x.query, on),
|
|
193
|
-
};
|
|
194
|
-
return cache.answer(key, () => compute(x, bound));
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/** A page of the rows behind a query, under the same access, filters and range as its answer. */
|
|
198
|
-
export async function executeRecords(
|
|
199
|
-
x: Execution,
|
|
200
|
-
page: { limit: number; after?: string },
|
|
201
|
-
): Promise<RecordsResponse> {
|
|
202
|
-
const bound = bind(x);
|
|
203
|
-
const { value } = await reading(x, page.limit, (reader) =>
|
|
204
|
-
readRecords(bound.input, page, reader),
|
|
205
|
-
);
|
|
206
|
-
return { ...value, columns: recordColumns(x.rt.options.model, x.query.source, value.columns) };
|
|
207
|
-
}
|
package/src/handler.ts
DELETED
|
@@ -1,232 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
BASE_ERROR_CODES,
|
|
3
|
-
CONTRACT_VERSION,
|
|
4
|
-
type DashEndpoint,
|
|
5
|
-
type DashHook,
|
|
6
|
-
type DashOptions,
|
|
7
|
-
type HeadersLike,
|
|
8
|
-
type HookContext,
|
|
9
|
-
type Principal,
|
|
10
|
-
type Viewer,
|
|
11
|
-
} from "@derive-to/dashboards-core";
|
|
12
|
-
import { EngineError } from "@derive-to/dashboards-core/engine";
|
|
13
|
-
import { addRoute, createRouter, findRoute } from "rou3";
|
|
14
|
-
import { coreEndpoints } from "./endpoints/index";
|
|
15
|
-
import type { Runtime } from "./execute";
|
|
16
|
-
import { errorResponse, HttpError, json, ndjson } from "./http";
|
|
17
|
-
import { dashboardResource } from "./owner";
|
|
18
|
-
import { checkTenant, principalOf } from "./principal";
|
|
19
|
-
|
|
20
|
-
/** Engine refusals the caller can fix are 400s; a plan that fails its own check is a 500. */
|
|
21
|
-
function engineStatus(error: EngineError): number {
|
|
22
|
-
if (error.code === "PLAN_ASSERTION" || error.code === "NUMERIC_STORAGE") return 500;
|
|
23
|
-
return error.code === "TENANT_MISSING" ? 403 : 400;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
async function authorize(
|
|
27
|
-
options: DashOptions,
|
|
28
|
-
endpoint: DashEndpoint,
|
|
29
|
-
ctx: { body: unknown; principal: Principal | null; request: Request },
|
|
30
|
-
) {
|
|
31
|
-
const { access } = endpoint;
|
|
32
|
-
if (access.kind === "public") return;
|
|
33
|
-
if (ctx.principal?.channel !== "user") throw new HttpError(401, "UNAUTHORIZED", "Sign in first.");
|
|
34
|
-
checkTenant(options, ctx.principal);
|
|
35
|
-
if (access.kind === "signed_in") return;
|
|
36
|
-
const named = access.resource(ctx.body);
|
|
37
|
-
const resource =
|
|
38
|
-
named.kind === "dashboard"
|
|
39
|
-
? await dashboardResource(options, ctx.request, ctx.principal, named.id)
|
|
40
|
-
: named;
|
|
41
|
-
const allowed = await options.access.can(ctx.principal.viewer, access.verb, resource);
|
|
42
|
-
if (!allowed) throw new HttpError(403, "FORBIDDEN", BASE_ERROR_CODES.FORBIDDEN.message);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* A browser sends its page's origin with every POST. One that is neither this server's nor a
|
|
47
|
-
* trusted one is refused, so another site cannot drive a signed-in viewer's session.
|
|
48
|
-
*/
|
|
49
|
-
function checkOrigin(options: DashOptions, endpoint: DashEndpoint, request: Request): void {
|
|
50
|
-
if (request.method === "GET" || endpoint.access.kind === "public") return;
|
|
51
|
-
const origin = request.headers.get("origin");
|
|
52
|
-
if (origin === null || origin === new URL(request.url).origin) return;
|
|
53
|
-
if ((options.trustedOrigins ?? []).includes(origin)) return;
|
|
54
|
-
throw new HttpError(403, "FORBIDDEN", `Requests from ${origin} are not trusted.`);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async function readBody(request: Request): Promise<unknown> {
|
|
58
|
-
if (request.method === "GET") return Object.fromEntries(new URL(request.url).searchParams);
|
|
59
|
-
try {
|
|
60
|
-
return await request.json();
|
|
61
|
-
} catch {
|
|
62
|
-
throw new HttpError(400, "BODY_INVALID", "The body is not JSON. Send a JSON object.");
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
type Hooks = { before: readonly DashHook[]; after: readonly DashHook[] };
|
|
67
|
-
|
|
68
|
-
async function runHooks(hooks: readonly DashHook[], path: string, ctx: HookContext) {
|
|
69
|
-
for (const hook of hooks.filter((h) => h.matcher(path))) {
|
|
70
|
-
// Hooks run in plugin order, each after the one before.
|
|
71
|
-
// oxlint-disable-next-line eslint/no-await-in-loop
|
|
72
|
-
await hook.handler(ctx);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/** One endpoint for one request: the viewer, access, the body, hooks, then the handler's answer. */
|
|
77
|
-
async function run(
|
|
78
|
-
rt: Runtime,
|
|
79
|
-
hooks: Hooks,
|
|
80
|
-
endpoint: DashEndpoint,
|
|
81
|
-
call: { request: Request; viewer?: Viewer | undefined },
|
|
82
|
-
) {
|
|
83
|
-
const { request } = call;
|
|
84
|
-
const principal = await principalOf(rt.options, request, call.viewer);
|
|
85
|
-
const raw = await readBody(request);
|
|
86
|
-
await authorize(rt.options, endpoint, { body: raw, principal, request });
|
|
87
|
-
const body = endpoint.parse(raw);
|
|
88
|
-
const ctx = { body, principal, request };
|
|
89
|
-
await runHooks(hooks.before, endpoint.path, { ...ctx, path: endpoint.path });
|
|
90
|
-
const output = await endpoint.handler(ctx);
|
|
91
|
-
const answered =
|
|
92
|
-
endpoint.respond === "ndjson"
|
|
93
|
-
? { ...ctx, path: endpoint.path }
|
|
94
|
-
: { ...ctx, path: endpoint.path, result: output };
|
|
95
|
-
await runHooks(hooks.after, endpoint.path, answered);
|
|
96
|
-
return output;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
async function dispatch(
|
|
100
|
-
rt: Runtime,
|
|
101
|
-
hooks: Hooks,
|
|
102
|
-
endpoint: DashEndpoint,
|
|
103
|
-
request: Request,
|
|
104
|
-
): Promise<Response> {
|
|
105
|
-
checkOrigin(rt.options, endpoint, request);
|
|
106
|
-
const output = await run(rt, hooks, endpoint, { request });
|
|
107
|
-
return endpoint.respond === "ndjson" ? ndjson(output) : json(200, output);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Calls an endpoint from the host's own server, as better-auth's `auth.api` does: through the
|
|
112
|
-
* same viewer, access check, body schema and hooks as over HTTP, and answers with the value
|
|
113
|
-
* itself. Pass the incoming `request`: the call runs on its URL and headers, so a host that
|
|
114
|
-
* reads the viewer or tenant from the cookie, a header or the host name gets the same answer as
|
|
115
|
-
* over HTTP. `headers` alone works too, on a placeholder URL. Or name the `viewer` outright,
|
|
116
|
-
* as an MCP server or a job does with no request to read one from: every check still runs as
|
|
117
|
-
* that viewer. A refusal throws `HttpError` with its code. There is no browser, so no origin to
|
|
118
|
-
* check.
|
|
119
|
-
*/
|
|
120
|
-
export function serverCall(rt: Runtime, endpoint: DashEndpoint) {
|
|
121
|
-
const hooks = hooksOf(rt);
|
|
122
|
-
const base = rt.options.basePath ?? "/api/dashboards";
|
|
123
|
-
return (
|
|
124
|
-
input: { body?: unknown; headers?: HeadersLike; request?: Request; viewer?: Viewer } = {},
|
|
125
|
-
) => {
|
|
126
|
-
const headers = new Headers(input.request?.headers);
|
|
127
|
-
for (const [name, value] of new Headers(input.headers)) headers.set(name, value);
|
|
128
|
-
headers.set("content-type", "application/json");
|
|
129
|
-
const get = endpoint.method === "GET";
|
|
130
|
-
const origin =
|
|
131
|
-
input.request === undefined ? "http://server.call" : new URL(input.request.url).origin;
|
|
132
|
-
const request = new Request(`${origin}${base}${endpoint.path}`, {
|
|
133
|
-
method: endpoint.method,
|
|
134
|
-
headers,
|
|
135
|
-
...(get ? {} : { body: JSON.stringify(input.body ?? {}) }),
|
|
136
|
-
});
|
|
137
|
-
return run(rt, hooks, endpoint, { request, viewer: input.viewer });
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
* A refusal answers with its own code; what it keeps for the host alone goes to `onError`.
|
|
143
|
-
* Anything else is the library's or the host's bug: it
|
|
144
|
-
* goes to `onError` (the console by default) and answers 500 `INTERNAL`, never a stack.
|
|
145
|
-
*/
|
|
146
|
-
function errorOf(rt: Runtime, error: unknown, request: Request): Response {
|
|
147
|
-
if (error instanceof HttpError) {
|
|
148
|
-
// oxlint-disable-next-line no-console -- the host's logger, or the console without one
|
|
149
|
-
if (error.cause !== undefined) (rt.options.onError ?? console.error)(error.cause, request);
|
|
150
|
-
return errorResponse(error);
|
|
151
|
-
}
|
|
152
|
-
if (error instanceof EngineError)
|
|
153
|
-
return json(engineStatus(error), { error: { code: error.code, message: error.message } });
|
|
154
|
-
// The default when the host gives no logger: an unexpected error must be seen somewhere.
|
|
155
|
-
// oxlint-disable-next-line no-console
|
|
156
|
-
(rt.options.onError ?? console.error)(error, request);
|
|
157
|
-
return json(500, { error: { code: "INTERNAL", message: BASE_ERROR_CODES.INTERNAL.message } });
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** Each plugin's hooks, in plugin order. */
|
|
161
|
-
function hooksOf(rt: Runtime): Hooks {
|
|
162
|
-
const plugins = rt.options.plugins ?? [];
|
|
163
|
-
return {
|
|
164
|
-
before: plugins.flatMap((p) => p.hooks?.before ?? []),
|
|
165
|
-
after: plugins.flatMap((p) => p.hooks?.after ?? []),
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/** Every endpoint, the core's and each plugin's; two at one method and path refuse to start. */
|
|
170
|
-
function routes(rt: Runtime) {
|
|
171
|
-
const base = rt.options.basePath ?? "/api/dashboards";
|
|
172
|
-
const router = createRouter<DashEndpoint>();
|
|
173
|
-
const plugins = rt.options.plugins ?? [];
|
|
174
|
-
const endpoints: DashEndpoint[] = [
|
|
175
|
-
...Object.values(coreEndpoints(rt)),
|
|
176
|
-
...plugins.flatMap((p) => Object.values(p.endpoints ?? {})),
|
|
177
|
-
];
|
|
178
|
-
for (const endpoint of endpoints) {
|
|
179
|
-
const path = `${base}${endpoint.path}`;
|
|
180
|
-
if (findRoute(router, endpoint.method, path) !== undefined)
|
|
181
|
-
throw new Error(`Two endpoints answer ${endpoint.method} ${endpoint.path}.`);
|
|
182
|
-
addRoute(router, endpoint.method, path, endpoint);
|
|
183
|
-
}
|
|
184
|
-
return { router, hooks: hooksOf(rt) };
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* No endpoint answers this: say the method and path, and where the handler is mounted, since
|
|
189
|
-
* the usual cause is mounting it somewhere other than `basePath`.
|
|
190
|
-
*/
|
|
191
|
-
function notFound(
|
|
192
|
-
rt: Runtime,
|
|
193
|
-
router: Parameters<typeof findRoute<DashEndpoint>>[0],
|
|
194
|
-
method: string,
|
|
195
|
-
path: string,
|
|
196
|
-
): HttpError {
|
|
197
|
-
const base = rt.options.basePath ?? "/api/dashboards";
|
|
198
|
-
const other = ["GET", "POST"].find(
|
|
199
|
-
(m) => m !== method && findRoute(router, m, path) !== undefined,
|
|
200
|
-
);
|
|
201
|
-
if (other !== undefined)
|
|
202
|
-
return new HttpError(404, "NOT_FOUND", `${path} answers ${other}, not ${method}.`);
|
|
203
|
-
const where = path.startsWith(base)
|
|
204
|
-
? `No endpoint answers ${method} ${path}.`
|
|
205
|
-
: `${method} ${path} is outside basePath "${base}". Mount the handler there, or set basePath to where it is mounted.`;
|
|
206
|
-
return new HttpError(404, "NOT_FOUND", where);
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/** Every answer says which contract it keeps, so a client from another release can tell. */
|
|
210
|
-
function stamped(response: Response): Response {
|
|
211
|
-
response.headers.set("dd-contract", CONTRACT_VERSION);
|
|
212
|
-
return response;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/**
|
|
216
|
-
* The fetch handler: mount it at `basePath` (default `/api/dashboards`) in any framework
|
|
217
|
-
* that speaks Request and Response.
|
|
218
|
-
*/
|
|
219
|
-
export function createHandler(rt: Runtime): (request: Request) => Promise<Response> {
|
|
220
|
-
const { router, hooks } = routes(rt);
|
|
221
|
-
return async (request) => {
|
|
222
|
-
const { pathname } = new URL(request.url);
|
|
223
|
-
const match = findRoute(router, request.method, pathname);
|
|
224
|
-
if (match === undefined)
|
|
225
|
-
return stamped(errorResponse(notFound(rt, router, request.method, pathname)));
|
|
226
|
-
try {
|
|
227
|
-
return stamped(await dispatch(rt, hooks, match.data, request));
|
|
228
|
-
} catch (error) {
|
|
229
|
-
return stamped(errorOf(rt, error, request));
|
|
230
|
-
}
|
|
231
|
-
};
|
|
232
|
-
}
|
package/src/http.ts
DELETED
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import type { Issue, RuntimeErrorCode } from "@derive-to/dashboards-core";
|
|
2
|
-
|
|
3
|
-
/** A refusal the handler turns into a JSON error response. */
|
|
4
|
-
export class HttpError extends Error {
|
|
5
|
-
readonly status: number;
|
|
6
|
-
readonly code: RuntimeErrorCode;
|
|
7
|
-
readonly issues: readonly Issue[] | undefined;
|
|
8
|
-
/**
|
|
9
|
-
* `issues`: what was wrong, item by item. `cause`: what only the host should see (a
|
|
10
|
-
* database's own message, which can echo stored values); it goes to `onError`, never into
|
|
11
|
-
* the answer.
|
|
12
|
-
*/
|
|
13
|
-
constructor(
|
|
14
|
-
status: number,
|
|
15
|
-
code: HttpError["code"],
|
|
16
|
-
message: string,
|
|
17
|
-
more: { issues?: readonly Issue[]; cause?: unknown } = {},
|
|
18
|
-
) {
|
|
19
|
-
const { issues, cause } = more;
|
|
20
|
-
super(message, cause === undefined ? undefined : { cause });
|
|
21
|
-
this.name = "HttpError";
|
|
22
|
-
this.status = status;
|
|
23
|
-
this.code = code;
|
|
24
|
-
this.issues = issues;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export function json(status: number, body: unknown): Response {
|
|
29
|
-
return new Response(JSON.stringify(body), {
|
|
30
|
-
status,
|
|
31
|
-
headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function errorResponse(error: HttpError): Response {
|
|
36
|
-
const issues = error.issues === undefined ? {} : { issues: error.issues };
|
|
37
|
-
return json(error.status, { error: { code: error.code, message: error.message, ...issues } });
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {
|
|
41
|
-
return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Streams each value of `lines` as one line of JSON, written as soon as it is ready. The stream
|
|
46
|
-
* stops reading when the client goes away.
|
|
47
|
-
*/
|
|
48
|
-
export function ndjson(lines: unknown): Response {
|
|
49
|
-
if (!isAsyncIterable(lines)) throw new Error("An ndjson endpoint must return an async iterable.");
|
|
50
|
-
const iterator = lines[Symbol.asyncIterator]();
|
|
51
|
-
const encoder = new TextEncoder();
|
|
52
|
-
const body = new ReadableStream<Uint8Array>({
|
|
53
|
-
async pull(controller) {
|
|
54
|
-
const next = await iterator.next();
|
|
55
|
-
if (next.done === true) controller.close();
|
|
56
|
-
else controller.enqueue(encoder.encode(`${JSON.stringify(next.value)}\n`));
|
|
57
|
-
},
|
|
58
|
-
async cancel() {
|
|
59
|
-
await iterator.return?.();
|
|
60
|
-
},
|
|
61
|
-
});
|
|
62
|
-
return new Response(body, {
|
|
63
|
-
status: 200,
|
|
64
|
-
headers: { "content-type": "application/x-ndjson; charset=utf-8", "cache-control": "no-store" },
|
|
65
|
-
});
|
|
66
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,163 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
type Awaitable,
|
|
3
|
-
BASE_ERROR_CODES,
|
|
4
|
-
type CodeDashboard,
|
|
5
|
-
type Dash,
|
|
6
|
-
type DashEndpoint,
|
|
7
|
-
type DashOptions,
|
|
8
|
-
type DashPlugin,
|
|
9
|
-
defineModel,
|
|
10
|
-
type ServerCallInput,
|
|
11
|
-
type SourceName,
|
|
12
|
-
type UniqueIds,
|
|
13
|
-
type ViewerFor,
|
|
14
|
-
} from "@derive-to/dashboards-core";
|
|
15
|
-
import { loadDocument } from "@derive-to/dashboards-core/schema";
|
|
16
|
-
import { createCache } from "./cache";
|
|
17
|
-
import { coreEndpoints } from "./endpoints/index";
|
|
18
|
-
import { createHandler, serverCall } from "./handler";
|
|
19
|
-
import { HttpError } from "./http";
|
|
20
|
-
import { isSource } from "./reading";
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Code-defined dashboards are checked when the handler is made, not when a viewer opens one: an
|
|
24
|
-
* invalid document stops the server with every problem named, and a layout is repaired once.
|
|
25
|
-
*/
|
|
26
|
-
function checkedDashboards(options: DashOptions): CodeDashboard[] {
|
|
27
|
-
return (options.dashboards ?? []).map((d) => {
|
|
28
|
-
const loaded = loadDocument(d.document);
|
|
29
|
-
if (!loaded.ok) {
|
|
30
|
-
const problems = loaded.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
|
|
31
|
-
throw new Error(`The dashboard "${d.key}" is not a valid document: ${problems}`);
|
|
32
|
-
}
|
|
33
|
-
return { key: d.key, document: loaded.doc };
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Every connection the model's sources read is given, and each one given as it is (not per
|
|
39
|
-
* request) is a connection, or the server does not start.
|
|
40
|
-
*/
|
|
41
|
-
function checkConnections(options: DashOptions): void {
|
|
42
|
-
const missing = [...new Set(Object.values(options.model.sources).map((s) => s.in))].filter(
|
|
43
|
-
(id) => !Object.hasOwn(options.connections, id),
|
|
44
|
-
);
|
|
45
|
-
if (missing.length > 0)
|
|
46
|
-
throw new Error(
|
|
47
|
-
`The model reads ${missing.map((m) => `"${m}"`).join(", ")}, which \`connections\` does not have. Add each as a key of \`connections\`.`,
|
|
48
|
-
);
|
|
49
|
-
const wrong = Object.entries(options.connections).find(
|
|
50
|
-
([, c]) => typeof c !== "function" && !isSource(c),
|
|
51
|
-
);
|
|
52
|
-
if (wrong !== undefined)
|
|
53
|
-
throw new Error(
|
|
54
|
-
`\`connections.${wrong[0]}\` is not a connection. Wrap your database client, postgresConnection({ run, transaction }), or your own data layer, customSource({ answer, records }).`,
|
|
55
|
-
);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Two plugins with one id would answer each other's paths, and a plugin named like one of the
|
|
60
|
-
* library's calls would hide it under `api`: refuse to start.
|
|
61
|
-
*/
|
|
62
|
-
function checkPluginIds(options: DashOptions, taken: readonly string[]): void {
|
|
63
|
-
const ids = (options.plugins ?? []).map((p) => p.id);
|
|
64
|
-
const twice = ids.find((id, i) => ids.indexOf(id) !== i);
|
|
65
|
-
if (twice !== undefined) throw new Error(`Two plugins have the id "${twice}".`);
|
|
66
|
-
const clash = ids.find((id) => taken.includes(id));
|
|
67
|
-
if (clash !== undefined)
|
|
68
|
-
throw new Error(`A plugin's id "${clash}" is a name the library uses under \`api\`.`);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** Whether an endpoint's answer is a stream of lines (`ndjson`) rather than one value. */
|
|
72
|
-
function isStream(output: unknown): output is AsyncIterable<unknown> {
|
|
73
|
-
return (
|
|
74
|
-
typeof output === "object" &&
|
|
75
|
-
output !== null &&
|
|
76
|
-
typeof Reflect.get(output, Symbol.asyncIterator) === "function"
|
|
77
|
-
);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/** One endpoint by path; a streamed answer is read to its end and comes back as its lines. */
|
|
81
|
-
async function callPath(
|
|
82
|
-
byPath: ReadonlyMap<string, (input?: ServerCallInput) => Promise<unknown>>,
|
|
83
|
-
path: string,
|
|
84
|
-
input?: ServerCallInput,
|
|
85
|
-
): Promise<unknown> {
|
|
86
|
-
const call = byPath.get(path);
|
|
87
|
-
if (call === undefined)
|
|
88
|
-
throw new HttpError(404, "NOT_FOUND", `There is no endpoint at ${path}. routes lists them.`);
|
|
89
|
-
const output = await call(input);
|
|
90
|
-
if (!isStream(output)) return output;
|
|
91
|
-
const lines: unknown[] = [];
|
|
92
|
-
for await (const line of output) lines.push(line);
|
|
93
|
-
return lines;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/** What `deriveDashboards` returns: `api` calls every endpoint; `$Infer.Endpoints` types a client. */
|
|
97
|
-
export type DashServer<O extends DashOptions> = Dash<O, ReturnType<typeof coreEndpoints>>;
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Embedded dashboards for your product. Pass the model, how to read the viewer, who may see
|
|
101
|
-
* what, and the connections the model reads; mount the returned handler. Everything it
|
|
102
|
-
* returns is typed from the options: `$Infer.Member` and `$Infer.Query` from the model,
|
|
103
|
-
* `$ERROR_CODES` from the plugins, and `api`: every endpoint, the library's by name and each
|
|
104
|
-
* plugin's under its id, as a server-side call.
|
|
105
|
-
*/
|
|
106
|
-
export function deriveDashboards<const O extends DashOptions>(
|
|
107
|
-
options: O & {
|
|
108
|
-
plugins?: UniqueIds<O["plugins"]>;
|
|
109
|
-
/** Typed from the model: with tenant keys, the viewer must carry a value for each. */
|
|
110
|
-
viewer: (request: Request) => Awaitable<ViewerFor<O["model"]> | null>;
|
|
111
|
-
},
|
|
112
|
-
): DashServer<O> {
|
|
113
|
-
defineModel(options.model);
|
|
114
|
-
checkConnections(options);
|
|
115
|
-
const checked = { ...options, dashboards: checkedDashboards(options) };
|
|
116
|
-
const rt = { options: checked, cache: createCache(checked) };
|
|
117
|
-
const library = coreEndpoints(rt);
|
|
118
|
-
checkPluginIds(options, ["cache", ...Object.keys(library)]);
|
|
119
|
-
const plugins: readonly DashPlugin[] = options.plugins ?? [];
|
|
120
|
-
const invalidate = async (a: {
|
|
121
|
-
tenant: Record<string, string>;
|
|
122
|
-
sources?: readonly SourceName[];
|
|
123
|
-
}) => {
|
|
124
|
-
await rt.cache?.invalidate(a.tenant, a.sources);
|
|
125
|
-
};
|
|
126
|
-
const calls = (record: Record<string, DashEndpoint>) =>
|
|
127
|
-
Object.fromEntries(Object.entries(record).map(([name, e]) => [name, serverCall(rt, e)]));
|
|
128
|
-
const core = calls(library);
|
|
129
|
-
const endpoints = Object.fromEntries(plugins.map((p) => [p.id, calls(p.endpoints ?? {})]));
|
|
130
|
-
const all = [library, ...plugins.map((p) => p.endpoints ?? {})].flatMap((r) => Object.values(r));
|
|
131
|
-
const byPath = new Map(all.map((e) => [e.path, serverCall(rt, e)]));
|
|
132
|
-
const codes: Record<string, unknown> = { ...BASE_ERROR_CODES };
|
|
133
|
-
for (const p of plugins) Object.assign(codes, p.$ERROR_CODES);
|
|
134
|
-
// Built from the same plugin tuple the types read; `$Infer` carries types only.
|
|
135
|
-
/* oxlint-disable typescript/no-unsafe-type-assertion */
|
|
136
|
-
return {
|
|
137
|
-
handler: createHandler(rt),
|
|
138
|
-
api: { cache: { invalidate }, ...core, ...endpoints } as DashServer<O>["api"],
|
|
139
|
-
$ERROR_CODES: codes as DashServer<O>["$ERROR_CODES"],
|
|
140
|
-
call: (path, input) => callPath(byPath, path, input),
|
|
141
|
-
routes: all.map((e) => ({ path: e.path, method: e.method })),
|
|
142
|
-
$Infer: {} as DashServer<O>["$Infer"],
|
|
143
|
-
options,
|
|
144
|
-
};
|
|
145
|
-
/* oxlint-enable typescript/no-unsafe-type-assertion */
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
export { type CustomSourceOptions, customSource } from "./custom-source";
|
|
149
|
-
export { HttpError } from "./http";
|
|
150
|
-
export { nodePostgres, type PgPool, type PgQueryable } from "./node-postgres";
|
|
151
|
-
export {
|
|
152
|
-
type PostgresConnectionOptions,
|
|
153
|
-
postgresConnection,
|
|
154
|
-
type RunSql,
|
|
155
|
-
} from "./postgres-connection";
|
|
156
|
-
export { type PostgresStoreOptions, postgresStore, type RunRows } from "./postgres-store";
|
|
157
|
-
export { memoryStorage } from "./storage";
|
|
158
|
-
export {
|
|
159
|
-
createTables,
|
|
160
|
-
type SchemaDiff,
|
|
161
|
-
SchemaMismatchError,
|
|
162
|
-
schemaDiff,
|
|
163
|
-
} from "./store/create-tables";
|