@dashspec/renderer 0.0.0-stage → 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/docs/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # `@dashspec/renderer` documentation
2
+
3
+ `@dashspec/renderer` is a React library that draws a complete, interactive dashboard
4
+ (layout, filters, data, widgets, events) from one JSON document with
5
+ `apiVersion: "dashspec.dev/v2"`.
6
+
7
+ ## Guides
8
+
9
+ | Page | What it covers |
10
+ |---|---|
11
+ | [Getting started](getting-started.md) | Install, a first dashboard, loading JSON from your API, validating with `loadDocument`, what viewers see for invalid documents |
12
+ | [Widgets](widgets.md) | The 30 built-in widgets and their props, nesting with slots, and writing your own with `wrapComponent`, `defineWidget` and `lazyWidget` |
13
+ | [Data](data.md) | Connections and auth, every datasource type, transforms, refresh and cache, `${…}` templates, the expression language and its helpers, custom datasource types, errors |
14
+ | [State and events](state-and-events.md) | The state tree, widget events, every action with an example, named actions, `watch`, host actions, scripts, driving a dashboard from your app, URL sync |
15
+ | [Design systems](design-systems.md) | Bringing your own components, filter controls, empty / error / loading states and custom filter kinds; combining design systems; aliasing built-ins |
16
+ | [Theming](theming.md) | Tokens, `createTheme`, light / dark / auto, named themes, `--ds-*` CSS variables, `themeStylesheet`, charts |
17
+ | [Server rendering](server-rendering.md) | SSR, the Next.js App Router, hydration, several dashboards on one page |
18
+ | [Security](security.md) | The threat model, what the renderer guarantees, what your app must do, Content Security Policy |
19
+
20
+ ## Reference
21
+
22
+ | Page | What it covers |
23
+ |---|---|
24
+ | [JSON format](json-format.md) | Every part of the v2 document, field by field |
25
+ | [API reference](api.md) | Every export of `@dashspec/renderer`, `/core` and `/sandbox`: props, hooks, functions, problem codes |
package/docs/api.md ADDED
@@ -0,0 +1,513 @@
1
+ # API reference
2
+
3
+ Every public export of `@dashspec/renderer`, grouped by purpose. Anything not listed
4
+ here is internal and may change without notice.
5
+
6
+ | Entry point | Import | Notes |
7
+ |---|---|---|
8
+ | React | `@dashspec/renderer` | Marked `"use client"`. Re-exports everything in `/core` too |
9
+ | Core | `@dashspec/renderer/core` | No React, no DOM: works on servers and in workers |
10
+ | Sandbox | `@dashspec/renderer/sandbox` | The QuickJS script sandbox, loaded only when needed |
11
+ | JSON Schema | `@dashspec/renderer/schema.json` | For editor autocomplete via `"$schema"` |
12
+
13
+ ## Contents
14
+
15
+ - [Rendering](#rendering): `DashboardRenderer`, `DashSpecProvider`, `DashboardHandle`, hooks
16
+ - [Documents](#documents): `loadDocument`, `validateDocument`, problem codes, migration, versions
17
+ - [Expressions and links](#expressions-and-links): `interpolate`, `interpolateUrl`, `evaluate`, `safeLink`
18
+ - [Widgets](#widgets): `defineWidget`, `wrapComponent`, `lazyWidget`, `checkWidget`
19
+ - [Design systems](#design-systems): `defineDesignSystem`, `combineDesignSystems`
20
+ - [Theme](#theme): `createTheme`, `themeStylesheet`, CSS variables
21
+ - [Scripts](#scripts): `createSandboxRunner`, `trustedRunner`, `offRunner`
22
+ - [Data and HTTP](#data-and-http): `DataError`, `applyTransform`, `createHttpClient`
23
+ - [Schema](#schema): zod schemas and constants
24
+ - [Building blocks](#building-blocks): lower-level components and the headless runtime
25
+
26
+ ## Rendering
27
+
28
+ ### `DashboardRenderer`
29
+
30
+ ```tsx
31
+ import { DashboardRenderer } from "@dashspec/renderer";
32
+
33
+ <DashboardRenderer document={doc} getToken={getToken} />;
34
+ ```
35
+
36
+ Draws a dashboard. Only `document` is required. It accepts a `ref` of type
37
+ [`DashboardHandle`](#dashboardhandle). Props set on a surrounding
38
+ [`DashSpecProvider`](#dashspecprovider) apply too; the renderer's own props win.
39
+
40
+ #### Document and identity
41
+
42
+ | Prop | Type | Default | What it does |
43
+ |---|---|---|---|
44
+ | `document` | `unknown` | (required) | The dashboard JSON. Older formats are migrated, then it is validated. See [Getting started](getting-started.md#validate-with-loaddocument) |
45
+ | `id` | `string` | none | Names this dashboard for [`useDashboardState`](#usedashboardstate) / [`useDashboardActions`](#usedashboardactions) and prefixes its URL keys (`<id>.plant`). Give each dashboard on a page its own `id` |
46
+ | `mode` | `"view" \| "preview" \| "tv"` | `"view"` | `"tv"` turns on the document's `display.tv` settings: rotating views and hiding the filter bar |
47
+ | `urlSync` | `boolean` | `true` (unless `editable`) | Keep filter values and the current view in the page URL |
48
+ | `hideHeader` | `boolean` | `false` | Hide the dashboard's title row |
49
+
50
+ #### What the JSON can refer to
51
+
52
+ | Prop | Type | Default | What it does |
53
+ |---|---|---|---|
54
+ | `widgets` | `AnyWidgetDefinition[]` | `[]` | Your own widgets, used in JSON as `"kind": "acme.Gauge"`. See [Widgets](widgets.md#write-your-own-widget) |
55
+ | `designSystems` | `DesignSystem[]` | `[]` | Packaged widgets, controls and theme. See [Design systems](design-systems.md) |
56
+ | `ui` | `UIComponents` | none | Replaces DashSpec's own controls one by one (filters, empty / error / loading); wins over `designSystems` |
57
+ | `aliases` | `Record<string, string>` | `{}` | Points a kind at another widget, e.g. `{ "Table": "acme.Table" }`, so existing JSON switches widget unchanged |
58
+ | `actions` | `Record<string, (action, { event, api }) => unknown>` | none | Your own actions by namespaced name, used in JSON as `{ "do": "acme.notify" }`. See [State and events](state-and-events.md#host-actions) |
59
+ | `functions` | `Record<string, (args) => unknown>` | `{}` | Functions the `call` action and a script's `api.call` can run |
60
+ | `datasourceTypes` | `DatasourceType[]` | none | Your own datasource types. See [Data](data.md#custom-datasource-types) |
61
+ | `theme` | `Theme` | the design system's theme, else the default | The look. Build one with [`createTheme`](theming.md#createtheme) |
62
+ | `themes` | `Record<string, Theme>` | none | Named themes a document picks with `"display": { "theme": "<name>" }` |
63
+ | `context` | `Record<string, unknown>` | `{}` | Values documents read as `${context.*}`: user, roles, tenant… Read-only for the document |
64
+ | `data` | `Record<string, unknown>` | none | Data for `host` datasources, by `key` |
65
+ | `locale` | `string` | the document's `display.locale` | Locale for number and date formatting; wins over the document's |
66
+ | `scripts` | `"sandbox" \| "trusted" \| "off"` | `"sandbox"` | How code in a document runs. See [Scripts](state-and-events.md#scripts) and [Security](security.md) |
67
+
68
+ #### Network (`NetworkOptions`)
69
+
70
+ | Prop | Type | Default | What it does |
71
+ |---|---|---|---|
72
+ | `connections` | `Record<string, ConnectionSpec>` | none | Connections from the host, merged over the document's by name; host values win and its headers are merged |
73
+ | `connectionMap` | `Record<string, string>` | none | Document connection name → host connection name |
74
+ | `getToken` | `(connection) => string \| null \| undefined \| Promise<…>` | none | Returns the token for connections whose auth says `{ "from": "host" }` |
75
+ | `refreshToken` | `(connection) => Promise<string \| null \| undefined>` | none | Called on a 401 when a bearer connection says `"refresh": { "from": "host" }`; the request is retried once |
76
+ | `trustedOrigins` | `string[]` | `[]` | Origins a document's own connections may send stored credentials to (tokens from localStorage, sessionStorage or cookies, cookie auth, a token refresh written in the JSON). The page's origin and host `connections` are always trusted |
77
+ | `transport` | `(request, signal) => Promise<unknown>` | none | Replaces HTTP entirely (tests, native bridges, your own client). No auth, refresh or size check is applied |
78
+ | `onRequest` | `(request) => void` | none | Called before every request, with the final URL |
79
+ | `onResponse` | `(response, request) => void` | none | Called after every response with `{ status, data }` |
80
+ | `fetch` | `typeof fetch` | global `fetch` | The fetch implementation |
81
+ | `pageHost` | `string` | `window.location.host` | Host used to pick a connection's `baseUrl` and the page origin |
82
+ | `storage` | `{ local?, session?, cookie? }` | browser storage | Where stored tokens are read from |
83
+ | `maxResponseBytes` | `number` | `10485760` (10 MB) | Larger responses fail with `too-large` |
84
+ | `sleep` | `(ms) => Promise<void>` | `setTimeout` | Wait between retries (replace in tests) |
85
+
86
+ #### Callbacks
87
+
88
+ | Prop | Type | When it fires |
89
+ |---|---|---|
90
+ | `onLoad` | `() => void` | The dashboard started (document valid, runtime ready) |
91
+ | `onError` | `(e: { code, message, panel?, datasource? }) => void` | A datasource failed (`DataError` codes), an action failed (`action`, `script`, `unsafe-url`, `loop`, `export`), the render crashed (`render`), or `display.theme` names an unregistered theme (`unknown-theme`) |
92
+ | `onEvent` | `(e: DashEvent) => void` | A widget emitted an event (click, rowClick…), or the `emit` action ran (`{ type: <event name>, value: <payload> }`) |
93
+ | `onStateChange` | `(tree: Tree) => void` | Any state changed |
94
+ | `onVariableChange` | `(name, value) => void` | A filter value changed |
95
+ | `onSelectionChange` | `(panel, selection) => void` | A panel's selection changed |
96
+ | `onNavigate` | `(to, { newTab }) => void` | The `navigate` action ran. Default: `window.location.assign`, or `window.open(…, "noopener")` for `newTab` |
97
+ | `onOpenDashboard` | `(key, filters, { newTab }) => void` | The `openDashboard` action ran. Nothing happens without it |
98
+ | `onToast` | `(message, tone?) => void` | The `toast` action ran. Default: `console.info` |
99
+
100
+ #### Controlled values
101
+
102
+ | Prop | Type | What it does |
103
+ |---|---|---|
104
+ | `variables` | `Record<string, unknown>` | Filter values by name. Applied on start and whenever the object's JSON changes; only differing values are written |
105
+ | `state` | `Record<string, unknown>` | State values by path (`{ "selectedHeat": "H-12" }`), same rules |
106
+ | `view` | `string \| null` | The current view (which `layouts` entry is shown) |
107
+
108
+ See [State and events](state-and-events.md#drive-a-dashboard-from-your-app).
109
+
110
+ #### Rendering hooks
111
+
112
+ | Prop | Type | What it does |
113
+ |---|---|---|
114
+ | `renderEmpty` | `(panel) => ReactNode` | A panel's "no data" state |
115
+ | `renderError` | `(error: { code, message }, panel?) => ReactNode` | A panel's error state; without `panel`, the invalid-document message |
116
+ | `renderLoading` | `(panel, message?) => ReactNode` | A panel's loading state; `message` is its `messages.loading`, filled |
117
+
118
+ #### Builder props
119
+
120
+ `editable`, `selectedPanel`, `onPanelSelect`, `canDropOn`, `onDropOnPanel`,
121
+ `onDragPanelStart`, `onFilterSelect`, `selectedFilter`, `onLayoutChange`, `onDropWidget`,
122
+ `dropSize` and `breakpoint` exist for visual editors built on the renderer. A host that
123
+ only displays dashboards never sets them.
124
+
125
+ ### `DashSpecProvider`
126
+
127
+ Registers settings once for every `DashboardRenderer` inside it, so a document can
128
+ refer to your widgets, actions and themes by name.
129
+
130
+ ```tsx
131
+ import { DashSpecProvider, createTheme } from "@dashspec/renderer";
132
+
133
+ <DashSpecProvider
134
+ designSystems={[acmeDesignSystem]}
135
+ actions={{ "acme.notify": (a) => notify(String(a.message)) }}
136
+ themes={{ "acme-dark": createTheme({ mode: "dark", colors: { primary: "#7c5cff" } }) }}
137
+ getToken={getToken}
138
+ trustedOrigins={["https://api.example.com"]}
139
+ >
140
+ <App />
141
+ </DashSpecProvider>;
142
+ ```
143
+
144
+ `DashSpecSettings` (its props) is this subset of `DashboardRendererProps`:
145
+ `designSystems`, `widgets`, `ui`, `aliases`, `actions`, `functions`, `datasourceTypes`,
146
+ `themes`, `theme`, `locale`, `scripts`, `context`, `data`, `connections`,
147
+ `connectionMap`, `getToken`, `refreshToken`, `trustedOrigins`, `transport`, `fetch`,
148
+ `pageHost`, `storage`, `maxResponseBytes`, `onRequest`, `onResponse`, `onError`,
149
+ `onEvent`, `onNavigate`, `onOpenDashboard`, `onToast`, `renderEmpty`, `renderError`,
150
+ `renderLoading`.
151
+
152
+ **Merge rules.** Providers nest, and a renderer's own props sit on top of the innermost
153
+ provider. For each setting:
154
+
155
+ | Kind of setting | Settings | Rule |
156
+ |---|---|---|
157
+ | Lists | `designSystems`, `widgets`, `datasourceTypes`, `trustedOrigins` | Combined, outer first |
158
+ | Maps | `aliases`, `actions`, `functions`, `themes`, `context`, `data`, `connections`, `connectionMap` | Merged by key; inner wins |
159
+ | `ui` | `ui` | Merged by control; `ui.filters` merged one level deeper by kind |
160
+ | Everything else | `theme`, `getToken`, `scripts`, `onError`, … | Taken from the innermost place that sets it |
161
+
162
+ `useDashSpecSettings()` returns the merged settings of the nearest provider (an empty
163
+ object without one).
164
+
165
+ ### `DashboardHandle`
166
+
167
+ The `ref` of a `DashboardRenderer`.
168
+
169
+ ```tsx
170
+ import { useRef } from "react";
171
+ import { DashboardRenderer, type DashboardHandle } from "@dashspec/renderer";
172
+
173
+ const ref = useRef<DashboardHandle>(null);
174
+ <DashboardRenderer ref={ref} document={doc} />;
175
+
176
+ ref.current?.setVariable("region", "North");
177
+ ref.current?.refresh("sales");
178
+ ```
179
+
180
+ | Method | What it does |
181
+ |---|---|
182
+ | `getState(): Tree` | The current [state tree](state-and-events.md#the-state-tree) |
183
+ | `setState(patch)` | Writes each `path → value` of `patch` (`{ "selectedHeat": "H-12" }`) |
184
+ | `setVariable(name, value)` | Sets a filter |
185
+ | `refresh(source?)` | Reloads one datasource id, a list, or every loaded one when omitted |
186
+ | `reset()` | Puts filters and the view back to their defaults and closes any modal |
187
+ | `run(action): Promise<void>` | Runs an action object or the name of a named action |
188
+ | `exportData(panel, format?)` | Downloads the panel's rows; `format` is `"csv"` (default) or `"xlsx"` (needs an add-on; reports `export` to `onError`) |
189
+
190
+ ### `useDashboardState`
191
+
192
+ ```ts
193
+ function useDashboardState<T>(id: string, select: (tree: Tree) => T): T | undefined;
194
+ ```
195
+
196
+ Reads part of the state of the dashboard with that `id`, from anywhere in your app (it
197
+ does not need to be inside the renderer). Returns `undefined` until that dashboard is
198
+ mounted.
199
+
200
+ ```tsx
201
+ const region = useDashboardState("sales", (t) => t.filters.region);
202
+ ```
203
+
204
+ ### `useDashboardActions`
205
+
206
+ ```ts
207
+ function useDashboardActions(id: string): {
208
+ ready: boolean;
209
+ setVariable(name: string, value: unknown): void;
210
+ setState(path: string, value: unknown): void;
211
+ setView(view: string): void;
212
+ run(action: unknown): Promise<void> | undefined;
213
+ refresh(source?: string | string[]): void;
214
+ };
215
+ ```
216
+
217
+ Drives the dashboard with that `id` from anywhere in your app. `ready` is false until it
218
+ is mounted; the functions do nothing until then.
219
+
220
+ ## Documents
221
+
222
+ From `@dashspec/renderer/core` (also re-exported by the React entry).
223
+
224
+ ### `loadDocument`
225
+
226
+ ```ts
227
+ function loadDocument(input: unknown, options?: LoadOptions): LoadResult;
228
+
229
+ type LoadResult =
230
+ | { status: "valid"; document: Dashboard; problems: Problem[]; migration: { from: "v1" | "v2"; notes: string[]; changed: boolean } }
231
+ | { status: "invalid"; problems: Problem[]; migration?: { from: "v1" | "v2"; notes: string[]; changed: boolean } };
232
+ ```
233
+
234
+ Migrates (older formats to v2, then each widget's `migrations`), then validates. This is
235
+ what the renderer does with every document. `migration.changed` tells you the stored
236
+ document is in an older shape; `migration.notes` lists anything a person should finish
237
+ by hand. The input is never modified.
238
+
239
+ `LoadOptions` extends `ValidateOptions` (below); its `widgets` entries may also carry
240
+ `steps` (the widget's `migrations`).
241
+
242
+ ### `validateDocument`
243
+
244
+ ```ts
245
+ function validateDocument(input: unknown, options?: ValidateOptions): ValidationResult;
246
+
247
+ interface ValidateOptions {
248
+ widgets?: WidgetCheck[]; // check panels against these widgets; omit to skip widget checks
249
+ hostConnections?: string[]; // connection names the host provides through `connections`
250
+ datasourceTypes?: { type: string; schema?: ZodTypeAny }[];
251
+ rendererVersion?: string; // checked against spec.requires.renderer; default RENDERER_VERSION
252
+ }
253
+ interface ValidationResult { valid: boolean; problems: Problem[]; document?: Dashboard }
254
+ interface Problem { severity: "error" | "warning"; path: string; code: string; message: string }
255
+ ```
256
+
257
+ Validates a v2 document without migrating it. Prefer `loadDocument` unless you know the
258
+ input is already v2. `valid` means "no problem with severity `error`".
259
+
260
+ To also check widget props, pass the widgets. `builtInWidgetChecks` covers the 30
261
+ built-in widgets and comes from `/core`, so it works without React: in React Server
262
+ Components, edge functions, API servers and CI.
263
+
264
+ ```ts
265
+ import { builtInWidgetChecks, loadDocument } from "@dashspec/renderer/core";
266
+
267
+ const result = loadDocument(json, { widgets: builtInWidgetChecks });
268
+ ```
269
+
270
+ To include your own widgets, build the list from the registry with `widgetChecks`
271
+ (main entry, so it loads your widget components too):
272
+
273
+ ```ts
274
+ import { builtInWidgets, createWidgetRegistry, loadDocument, widgetChecks } from "@dashspec/renderer";
275
+
276
+ const widgets = widgetChecks(createWidgetRegistry(builtInWidgets, myWidgets));
277
+ const result = loadDocument(json, { widgets });
278
+ ```
279
+
280
+ ### Problem codes
281
+
282
+ | Code | Severity | Meaning |
283
+ |---|---|---|
284
+ | `schema` | error | The document doesn't match the format (wrong type, missing required field, wrong `apiVersion`) |
285
+ | `migration` | error | The input isn't a document this version can read (not an object, unsupported `apiVersion`) |
286
+ | `unknown-field` | warning | A field this version doesn't know; ignored, with a "did you mean" hint |
287
+ | `unknown-value` | warning | A choice value, `do`, datasource `type`, filter `kind` or transform step this version doesn't know; the default is used or only that item fails |
288
+ | `requires-renderer` | warning | `spec.requires.renderer` doesn't include this renderer's version |
289
+ | `requires-unreadable` | warning | `spec.requires.renderer` isn't a version range this version can read |
290
+ | `duplicate` | error | A filter defined twice, a panel placed twice in one layout, or two layouts for the same view and breakpoint |
291
+ | `unknown-datasource` | error | A reference to a datasource that doesn't exist |
292
+ | `unknown-variable` | error | A reference to a filter that doesn't exist (`dependsOn`, `setVariable`) |
293
+ | `unknown-filter` | error | A `Filter` widget names a filter that doesn't exist |
294
+ | `unknown-connection` | error | A datasource or action uses a connection that is neither in the document nor in the host's `connections` |
295
+ | `missing-connection` | error | A datasource has a `path` but no `connection`, and the document has more than one connection |
296
+ | `unknown-datasource-type` | warning (error when `datasourceTypes` is passed) | A datasource `type` that isn't built in or registered |
297
+ | `unknown-action` | error | A handler names an action that isn't in `spec.actions` |
298
+ | `unknown-modal` | error | `openModal` names a modal that doesn't exist |
299
+ | `unknown-view` | error | `setView` or `display.tv.rotateViews` names a view no layout has |
300
+ | `unknown-panel` | error | A reference to a panel that doesn't exist (layouts, slots, actions, data bindings, tour) |
301
+ | `cycle` | error | Datasources, dependent filters or nested nodes refer to each other in a loop |
302
+ | `reserved` | error | `spec.state` uses a key the runtime owns |
303
+ | `data-binding` | error | A panel's `spec.data` isn't one of `{ source, path? }`, `{ panel, path? }`, `{ state }`, `{ value }` |
304
+ | `out-of-grid` | error | A layout item is wider than `grid.columns` |
305
+ | `not-placed` | warning | A panel is in no layout and no slot |
306
+ | `two-places` | error | A node is on the grid and in a slot, or in two slots |
307
+ | `unknown-slot` | warning | A slot name the widget doesn't have |
308
+ | `slot-full` | error | More children than the slot's `max` |
309
+ | `slot-accepts` | error | A child the slot doesn't accept (for example a chart in a header) |
310
+ | `unknown-widget` | warning | No widget is registered for the panel's `kind`; it shows "Unknown widget" |
311
+ | `widget-version` | warning | The panel was saved with a newer widget `version` than this renderer has |
312
+ | `widget-spec` | error | A widget prop fails the widget's schema (the renderer then drops just that prop) |
313
+ | `secret` | error | A literal token or password in the JSON |
314
+
315
+ ### `migrateDocument`
316
+
317
+ ```ts
318
+ function migrateDocument(input: unknown, widgets?: WidgetMigrations[]): MigrateResult;
319
+ // MigrateResult: { document, from: "v1" | "v2", notes: string[], changed: boolean }
320
+ ```
321
+
322
+ The migration step of `loadDocument` on its own. Throws `MigrationError` for input it
323
+ can't read. Types: `PanelMigration`, `WidgetMigrations`, `MigrateResult`.
324
+
325
+ ### `RENDERER_VERSION` and `satisfies`
326
+
327
+ ```ts
328
+ import { RENDERER_VERSION, satisfies } from "@dashspec/renderer/core";
329
+
330
+ RENDERER_VERSION; // "0.1.0": this package's version
331
+ satisfies("0.2.3", "^0.2"); // true
332
+ satisfies("0.1.0", ">=0.2.0"); // false
333
+ satisfies("1.0.0", "banana"); // undefined: the range can't be read
334
+ ```
335
+
336
+ `satisfies(version, range)` supports `1.2.3` (same as `^`), `^`, `~`, `>=`, `>`, `<=`,
337
+ `<`, `=` and several parts separated by spaces (all must hold). Documents use it through
338
+ `spec.requires.renderer`.
339
+
340
+ ## Expressions and links
341
+
342
+ ### `interpolate` and `scope`
343
+
344
+ ```ts
345
+ import { interpolate, scope } from "@dashspec/renderer/core";
346
+
347
+ interpolate("Hello ${user.name}", scope({ user: { name: "Ada" } })); // "Hello Ada"
348
+ interpolate("${n}", scope({ n: 1234.5 })); // 1234.5 (a number)
349
+ ```
350
+
351
+ Fills `${…}` placeholders. A template that is exactly one placeholder keeps the value's
352
+ type; mixed text joins values as strings. `scope(...layers)` builds the lookup scope from
353
+ objects, searched in order. An optional third argument encodes each filled value.
354
+ `resolve(value, scope)` does the same for every string inside a JSON value.
355
+
356
+ ### `interpolateUrl`
357
+
358
+ ```ts
359
+ import { interpolateUrl, scope } from "@dashspec/renderer/core";
360
+
361
+ interpolateUrl("/plants/${id}", scope({ id: "a/b c" })); // "/plants/a%2Fb%20c"
362
+ ```
363
+
364
+ Like `interpolate`, but URL-encodes each value filled into literal text, so a value
365
+ can't add path segments or query parameters. A template that is exactly one placeholder
366
+ (a whole URL from data) is used as is. `resolveRequest(request, scope)` applies it to a
367
+ request's `url` and `path` and `resolve` to its other fields.
368
+
369
+ ### `evaluate`
370
+
371
+ ```ts
372
+ import { evaluate, evaluateSafe, createHelpers, scope } from "@dashspec/renderer/core";
373
+
374
+ evaluate("fmt.number(n, 1)", scope({ n: 1234.5 }, createHelpers({ locale: "en-US" }))); // "1,234.5"
375
+ evaluateSafe("a.b.c(", scope({}), null); // null instead of throwing
376
+ ```
377
+
378
+ Runs one expression of the [expression language](data.md#expressions). Also exported:
379
+ `parse`, `compile` (to an AST `Node`), `ExpressionError`, `createHelpers`,
380
+ `parseDuration` (`"8h"` → ms), `plantDate`, `plantDayStart`, and the reference finders
381
+ `placeholders`, `templateReferences`, `expressionReferences`, `collectReferences`.
382
+ Types: `Scope`, `Helpers`, `TimeSettings`, `DateRange`, `Node`, `Reference`, `RefRoot`.
383
+
384
+ ### `safeLink` and `isSafeUrl`
385
+
386
+ ```ts
387
+ import { safeLink } from "@dashspec/renderer/core";
388
+
389
+ safeLink("https://example.com/x"); // "https://example.com/x"
390
+ safeLink("/orders/42"); // "/orders/42"
391
+ safeLink("javascript:alert(1)"); // undefined
392
+ safeLink("//evil.example"); // undefined
393
+ ```
394
+
395
+ Returns the link only when a dashboard may open it: `http:`, `https:`, `mailto:` or a
396
+ path on the same site, after removing the tabs, newlines and control characters a
397
+ browser would ignore. Use it on any link built from document or API data.
398
+ `isSafeUrl(url)` is the looser check used while validating, where `${…}` templates are
399
+ allowed.
400
+
401
+ ## Widgets
402
+
403
+ See [Widgets](widgets.md) for a guide.
404
+
405
+ | Export | What it is |
406
+ |---|---|
407
+ | `defineWidget(def)` | Declares a widget (`WidgetDefinition`). Checks the kind and version, returns it typed |
408
+ | `wrapComponent(Component, options)` | Turns any React component into a widget by mapping props, events, state writes and slots (`WrapOptions`) |
409
+ | `lazyWidget(def)` | A widget whose code downloads only when a dashboard uses it (`load: () => import(…)`, optional `fallback`) |
410
+ | `checkWidget(def)` | Returns a list of contract problems (empty when fine). Use it in your tests |
411
+ | `builtInWidgets` | The 30 built-in widget definitions |
412
+ | `createWidgetRegistry(builtIns, extra, aliases)` | Builds the kind → widget map the renderer uses (throws on un-namespaced or duplicate kinds). `WidgetRegistry` type |
413
+
414
+ Types: `WidgetDefinition`, `AnyWidgetDefinition` (for lists of widgets with different
415
+ props), `WidgetProps`, `WidgetStore`, `WidgetMeta`, `SlotDefinition`, `Emit`,
416
+ `WrapOptions`.
417
+
418
+ ## Design systems
419
+
420
+ See [Design systems](design-systems.md).
421
+
422
+ | Export | What it is |
423
+ |---|---|
424
+ | `defineDesignSystem({ name, widgets?, ui?, theme? })` | Packages a design system. Throws without a `name`; widgets without `meta.category` get the system's name |
425
+ | `combineDesignSystems(list)` | `{ widgets, ui, theme }` of several: all widgets; later ones win for controls and theme; `ui.filters` merged by kind |
426
+
427
+ Types: `DesignSystem`, `UIComponents`, `UISelectProps`, `UIMultiSelectProps`,
428
+ `UIDateProps`, `UIDateRangeProps`, `UISearchProps`, `UIToggleProps`, `UIChipsProps`,
429
+ `UICustomFilterProps`, `UIStateProps`.
430
+
431
+ ## Theme
432
+
433
+ See [Theming](theming.md).
434
+
435
+ | Export | What it is |
436
+ |---|---|
437
+ | `createTheme(input?)` | Builds a `Theme` from the short form (`colors`, `font`, `radius`, `density`) and full `scale` / `light` / `dark` overrides (`ThemeInput`) |
438
+ | `defaultTheme` | The built-in theme (mode `auto`) |
439
+ | `themeCssVars(theme, mode)` | Every token as a `--ds-*` variable for one mode, as an object |
440
+ | `themeStylesheet(theme, selector?)` | The same as a CSS string: light on `selector` (default `.ds-root`), dark under `[data-ds-theme="dark"]` |
441
+ | `echartsTheme(theme, mode)` | An ECharts theme object built from the tokens |
442
+ | `ThemeScope` | Sets a theme's variables on one `.ds-root` element (`ThemeScopeProps`) |
443
+ | `useThemeTokens()` | `{ theme, mode }` inside a `ThemeScope`, for code that needs values instead of CSS variables |
444
+ | `ThemeContext` | The context behind `useThemeTokens` |
445
+ | `mergeDeep(base, patch)` | Deep merge used by `createTheme`; never mutates, arrays replace |
446
+ | `resolveMode(theme, prefersDark)` | `"light"` or `"dark"` for a theme whose mode may be `"auto"` |
447
+
448
+ Types: `Theme`, `ThemeMode`, `ColorTokens`, `ScaleTokens`, `StatusColors`, `TypeRole`,
449
+ `StatusTone`, `DeepPartial`.
450
+
451
+ ## Scripts
452
+
453
+ | Export | Entry | What it is |
454
+ |---|---|---|
455
+ | `createSandboxRunner(options?)` | `/sandbox` | Creates the QuickJS runner. Options (`SandboxOptions`): `syncTimeoutMs` (default 1000), `fnPropTimeoutMs` (50), `asyncTimeoutMs` (30000), `memoryBytes` (32 MB) |
456
+ | `trustedRunner()` | React | Runs code with `new Function`. Only for documents from trusted authors |
457
+ | `offRunner()` | React | Callbacks and function props do nothing; `fn` transforms fail |
458
+
459
+ `DashboardRenderer` loads the sandbox by itself when a document contains code and
460
+ `scripts` is `"sandbox"`; you only need `createSandboxRunner` with the headless runtime.
461
+ Types: `ScriptMode`, `ScriptRunner`, `CallbackApi`.
462
+
463
+ ## Data and HTTP
464
+
465
+ From `/core`. See [Data](data.md).
466
+
467
+ | Export | What it is |
468
+ |---|---|
469
+ | `DataError` | The error every failed request becomes: `code` (`DataErrorCode`), `message`, `status?`, `datasource?`, `toJSON()` |
470
+ | `applyTransform(data, steps, scope, options?)` | Runs datasource `transform` steps (`TransformOptions`: `runFn`, `maxRows`, default 100 000). Throws `TransformError` with the failing `step` |
471
+ | `createHttpClient(connections, options?)` | The HTTP client the renderer uses: `send`, `streamTarget`, `connections` (`HttpClient`) |
472
+ | `mergeConnections`, `resolveBaseUrl`, `buildUrl`, `buildRequestUrl` | The URL and connection helpers behind it |
473
+
474
+ Types: `NetworkOptions`, `ConnectionSpec`, `ResolvedRequest`, `DataErrorCode`.
475
+
476
+ ## Schema
477
+
478
+ From `/core`. The zod schemas the validator uses, for building forms or your own checks.
479
+
480
+ | Export | What it is |
481
+ |---|---|
482
+ | `Dashboard`, `Spec`, `Metadata`, `Display`, `Requires` | The document and its top-level parts. `Dashboard` / `DashboardInput` types |
483
+ | `Panel`, `DataBinding`, `Drill`, `Modal`, `Layout`, `LayoutItem`, `Grid` | Nodes, layouts, modals |
484
+ | `Variable`, `PanelControl` | Filters and panel controls |
485
+ | `Datasource`, `TransformStep`, `Connection`, `Auth`, `TokenSource` | Data |
486
+ | `Action`, `ActionRef`, `Handler`, `EventHandler`, `EventMap`, `NamedAction` | Actions and handlers |
487
+ | `ACTION_SCHEMAS`, `ACTION_KINDS` | Each built-in action's schema by `do`, and the list of names |
488
+ | `Id`, `Template`, `Expression`, `Duration`, `Callback`, `FnProp`, `JsonValue`, `StatusTone` | Primitives |
489
+ | `isCallbackSource(s)` | Whether a string is callback source (`(event, state, api) => …`) |
490
+ | `dashboardJsonSchema({ widgets? })` | The JSON Schema; with widgets, panel specs are checked per kind |
491
+ | `API_VERSION` (`"dashspec.dev/v2"`), `SCHEMA_URL` | Format identifiers |
492
+ | `RESERVED_STATE_KEYS`, `BUILT_IN_DATASOURCE_TYPES`, `VARIABLE_KINDS`, `DATE_PRESETS`, `BREAKPOINTS` | Constants |
493
+
494
+ Types: `Problem`, `Severity`, `ValidateOptions`, `ValidationResult`, `WidgetCheck`,
495
+ `LoadOptions`, `LoadResult`.
496
+
497
+ ## Building blocks
498
+
499
+ Lower-level exports used by the renderer itself and by visual editors. Most apps never
500
+ need them.
501
+
502
+ | Export | What it is |
503
+ |---|---|
504
+ | `createDashboardRuntime(doc, options)` | The dashboard without React: store, data engine, actions (`RuntimeOptions`, `DashboardRuntime`) |
505
+ | `timeSettingsFor`, `panelRows`, `presetRange` | Runtime helpers: time settings, a panel's rows, a date preset's range |
506
+ | `DashboardContext`, `useDashboard`, `useTree` | Context and selector hook inside a renderer |
507
+ | `Grid`, `layoutsForView`, `PanelFrame`, `Slot`, `useNodeScope`, `FilterBar`, `ControlField`, `ModalHost` | The renderer's own components |
508
+ | `SelectControl`, `MultiSelectControl`, `DateControl`, `DateRangeControl` | DashSpec's own filter controls |
509
+ | `BAR`, `BAR_ICONS` | Filter bar constants |
510
+ | `RENDERER_CSS` | The stylesheet the renderer injects |
511
+
512
+ Types: `Tree`, `PanelState`, `SourceState`, `DashEvent`, `HostHooks`, `DatasourceType`,
513
+ `NodeScope`, `Option`, `Breakpoint`, `LayoutSpec`, `GridChangeItem`.