@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.
@@ -0,0 +1,346 @@
1
+ # The DashSpec v2 document
2
+
3
+ A dashboard is one JSON object. This page describes every part of it. The exact rules
4
+ (types, limits) are the zod schemas in `src/core/schema` of the repository, also
5
+ exported from `@dashspec/renderer/core`; the JSON Schema for editors is
6
+ `@dashspec/renderer/schema.json` (point `"$schema"` at it for autocomplete). A complete
7
+ example that uses every part is `test/compat/v2-everything.json` in the repository.
8
+
9
+ The guides explain each part with examples: [Widgets](widgets.md),
10
+ [Data](data.md), [State and events](state-and-events.md), [Theming](theming.md).
11
+
12
+ ## Shape
13
+
14
+ ```json
15
+ {
16
+ "$schema": "https://dashspec.dev/schema/v2.json",
17
+ "apiVersion": "dashspec.dev/v2",
18
+ "kind": "Dashboard",
19
+ "metadata": { "key": "melting-overview", "name": "Melting overview", "tags": ["ops"] },
20
+ "spec": {
21
+ "display": {},
22
+ "grid": {},
23
+ "connections": {},
24
+ "variables": [],
25
+ "state": {},
26
+ "datasources": {},
27
+ "on": {},
28
+ "actions": {},
29
+ "panels": {},
30
+ "templates": {},
31
+ "modals": {},
32
+ "layouts": [],
33
+ "tour": [],
34
+ "requires": {}
35
+ }
36
+ }
37
+ ```
38
+
39
+ Only `apiVersion`, `kind`, `metadata.key`, `metadata.name`, `spec.panels` and
40
+ `spec.layouts` are required. Everything else is optional.
41
+
42
+ ## Reading rules (forward compatibility)
43
+
44
+ - **Unknown fields and values are warnings**, with a "did you mean" hint for typos. A
45
+ document written for a newer renderer still renders on an older one.
46
+ - **`x-` fields are yours.** Any object may carry `"x-acme-owner": "ops"`; it is kept
47
+ and never warned about.
48
+ - **Namespaced kinds are host extensions.** `acme.Furnace` (widget),
49
+ `acme.notify` (action), `acme.CrewPicker` (filter kind) and custom datasource types
50
+ are accepted as long as the host registers them.
51
+ - **v1 documents are migrated** on load (`loadDocument`); you never need to convert by hand.
52
+
53
+ ## `metadata`
54
+
55
+ | Field | Type | Notes |
56
+ |---|---|---|
57
+ | `key` | id | Stable identifier, used by `openDashboard` |
58
+ | `name` | string | The dashboard's name for people and catalogues (the header shows `display.title`) |
59
+ | `group`, `tags`, `description` | optional | For the host's catalogue |
60
+ | `generator` | `{ name, version? }` | The tool that wrote the document (e.g. the Builder, an MCP). Informational |
61
+
62
+ ## `spec.display`
63
+
64
+ `theme` picks a theme the host registered by name (`"acme-dark"`, see `DashSpecProvider`),
65
+ or is a mode of the host's default theme: `"light"`, `"dark"` or `"auto"`. An unknown name
66
+ keeps the default theme.
67
+
68
+ | Field | Type | Notes |
69
+ |---|---|---|
70
+ | `title`, `description` | template | Shown in the dashboard's header row |
71
+ | `syncedLabel` | template | Small text on the right of the header, e.g. `"Synced ${fmt.ago(datasources.summary.updatedAt)}"` |
72
+ | `theme` | string | See above |
73
+ | `timeZone` | IANA zone | Used for "today", date presets and date helpers, e.g. `"Asia/Kolkata"`. Default: the viewer's |
74
+ | `dayStartsAt` | `"HH:mm"` | When the day starts for "today" and presets (a 06:00 shift day) |
75
+ | `locale` | string | Number and date formatting, e.g. `"de-DE"`, and which `translations` to use. The host's `locale` prop wins |
76
+ | `translations` | `{ locale: { key: text } }` | Text per locale, read in templates as `${t.key}` (below) |
77
+ | `filters` | `"toolbar"` \| `"drawer"` | `"toolbar"` (default): the filter bar. `"drawer"`: a "Filters" button with the number of filters that differ from their default; it opens the same bar in a panel (focus moves in; Escape or × closes it and returns focus). The Builder's edit mode always shows the bar |
78
+ | `filterBar` | object | The filter bar, below |
79
+ | `tv` | `{ rotateViews, every, hideToolbar }` | With the renderer's `mode="tv"`: rotate through these views every `every` (default 60 s), and hide the filter bar |
80
+
81
+ ```json
82
+ "filterBar": { "apply": "change" | "button", "reset": false, "show": true,
83
+ "icon": "sliders" | "filter" | "calendar" | "search" | "none", "look": "card" | "plain" }
84
+ ```
85
+
86
+ `apply: "button"` holds filter changes as drafts until the viewer presses Apply;
87
+ `reset: true` adds a Reset button; `show: false` hides the bar (filters can still be
88
+ placed on the canvas).
89
+
90
+ **Translations.** `${t.revenue}` is the text for the active locale (the host's `locale`
91
+ prop, else `display.locale`). A locale matches exactly (any case), then by language
92
+ (`de-DE` uses `de`); with no match or no locale, the first locale in `translations` is
93
+ used. A key missing in that locale falls back to the first locale, then to the key
94
+ itself, so an untranslated label shows `revenue` rather than nothing. A `state` key
95
+ named `t` would hide it.
96
+
97
+ ```json
98
+ "display": { "locale": "de", "translations": { "en": { "revenue": "Revenue" }, "de": { "revenue": "Umsatz" } } },
99
+ "panels": { "rev": { "kind": "Kpi", "title": "${t.revenue}", "spec": { … } } }
100
+ ```
101
+
102
+ ## `spec.grid`
103
+
104
+ | Field | Default | Notes |
105
+ |---|---|---|
106
+ | `columns` | `12` | `12`, `24` or `60` (60 splits evenly into rows of 2, 3, 4, 5 or 6 cards) |
107
+ | `rowHeight` | `28` | px, 8–200 |
108
+ | `gap` | `12` | px, 0–48 |
109
+
110
+ ## `spec.connections`
111
+
112
+ Named API endpoints: `baseUrl` (a string, or page host → URL with `"*"` as fallback),
113
+ `auth` (`none`, `bearer`, `apiKey`, `cookie`, `headers`), `headers`, `timeout`,
114
+ `retry`, `description`. Tokens never go in the document: `"token": { "from": "host" }`
115
+ asks the host's `getToken`; `localStorage`, `sessionStorage` and `cookie` read a named
116
+ key. Every field is described in [Data: connections](data.md#connections).
117
+
118
+ ## `spec.variables` — the dashboard's filters
119
+
120
+ Each has a `name` (an id), a `kind`, and these optional fields:
121
+
122
+ | Field | Notes |
123
+ |---|---|
124
+ | `label` | Template |
125
+ | `description` | For people |
126
+ | `default` | The starting value (per kind, below) |
127
+ | `persist` | `url` (default: kept in the page URL), `memory` or `none` |
128
+ | `apply` | `immediate` or `button` |
129
+ | `hidden` | Not shown in the filter bar (still usable as a value, or placed with a `Filter` node) |
130
+ | `visibleWhen` | Expression; the filter shows only while it is true |
131
+ | `dependsOn` | Filter names; when one of them changes, this filter goes back to its default |
132
+ | `optionsFilter` | Expression keeping only matching options; `item` is the option's row, e.g. `"item.region == filters.region"` |
133
+
134
+ | Kind | Value | Extra fields |
135
+ |---|---|---|
136
+ | `DateRange` | `{ from, to, preset }` (`YYYY-MM-DD`) | `presets` (`today`, `yesterday`, `last7days`, `last30days`, `last90days`, `thisWeek`, `lastWeek`, `thisMonth`, `lastMonth`, `thisQuarter`, `thisYear`, `lastYear`, `custom`), `default` (a preset name or `{ from, to }`; default `last7days`), `min`, `max`, `maxDays` |
137
+ | `Date` | `YYYY-MM-DD` | `default` (default today), `min`, `max`, `stepper` |
138
+ | `Select` | the option's value | `options`, `searchable`, `stepper` |
139
+ | `MultiSelect` | list of values | `options`, `searchable` |
140
+ | `Chips` | a value, or a list with `multiple` | `options`, `multiple` |
141
+ | `Search` | text | `debounce` (duration), `placeholder` |
142
+ | `Toggle` | boolean | `default` |
143
+ | `ns.Name` | anything | A host filter control registered under `ui.filters`; the whole definition reaches it as `config` ([Design systems](design-systems.md#custom-filter-kinds)) |
144
+
145
+ `options` is a list (`"North"`, `3`, or `{ "value": "N", "label": "North", "count": 12 }`),
146
+ or rows from a datasource: `{ "source": "regions", "path": "results", "value": "id", "label": "name", "count": "orders" }`.
147
+
148
+ Filters show in the filter bar, or anywhere on the canvas as a `Filter` node
149
+ (`{ "kind": "Filter", "spec": { "variable": "plant" } }`).
150
+
151
+ ## `spec.state`
152
+
153
+ Your own values, readable as `${state.x}` (or `${x}`) and writable with `setState`. The
154
+ keys `filters`, `panels`, `view`, `modal`, `highlight`, `datasources` and `context` are
155
+ reserved. See [State and events](state-and-events.md#the-state-tree).
156
+
157
+ ## `spec.datasources`
158
+
159
+ | Type | Use |
160
+ |---|---|
161
+ | `http` | `connection`, `path` or `url`, `method`, `query`, `headers`, `body`, `select` |
162
+ | `graphql` | Accepted by the schema (`query`, `variables`, `select`), but this version sends it as a plain request; use `http` with a POST body for now ([Data](data.md#graphql)) |
163
+ | `sse`, `websocket` | Live streams: `event` (SSE), `send` (WebSocket), `merge` (`replace` / `append`), `keep`. They reconnect after a drop (1 s, 2 s, 4 s… up to 30 s); `reconnect: false` or `{ "maxDelay": "10s" }` changes that |
164
+ | `static` | `data` inline |
165
+ | `host` | `key` — data passed by the host in the `data` prop |
166
+ | derived | `from` another datasource + `transform` steps (`filter`, `map`, `groupBy` + aggregates, `pivot`, `sort`, `limit`, `pick`, `fn`) |
167
+ | any other `type` | A host datasource type registered with the `datasourceTypes` prop ([Data](data.md#custom-datasource-types)) |
168
+
169
+ Every type also takes `load` (`onLoad` / `lazy` / `manual`), `refresh`
170
+ (`every`, `whenVisible`, `when`, `onFocus`), `cache: { staleTime }`, `transform`,
171
+ `forEach`, `timeout`, `retry`, `onError` (`keepLast` / `clear`), `omitEmpty` and
172
+ `description`. Modals may declare their own `datasources` too.
173
+
174
+ Any value can use `${…}` templates such as `${filters.period.from}`; a datasource
175
+ refetches when a value it reads changes. Every field is described in
176
+ [Data](data.md#datasources).
177
+
178
+ ## `spec.panels` — the nodes
179
+
180
+ Every widget on the dashboard is a node, keyed by id:
181
+
182
+ ```json
183
+ "kpi": {
184
+ "kind": "Kpi",
185
+ "version": 1,
186
+ "spec": { "title": "Heats", "data": { "source": "overview", "path": "kpis.heats" }, "target": 24 },
187
+ "style": { "padding": "compact", "shadow": "sm", "radius": 12 },
188
+ "slots": { "header": ["kpiBadge"], "footer": ["kpiNote"] },
189
+ "on": { "click": ["openHeat"] },
190
+ "watch": [{ "path": "filters.plant", "do": [{ "do": "refresh", "source": "overview" }] }],
191
+ "visibleWhen": "view == 'main'",
192
+ "messages": { "empty": "No heats yet" }
193
+ }
194
+ ```
195
+
196
+ - `kind` — a built-in widget or a host `ns.Name` widget. `spec` holds that widget's
197
+ own props, checked against its schema.
198
+ - `spec.data` — where the node's data comes from: `{ source, path }`, `{ panel, path }`,
199
+ `{ state }` or `{ value }`. A node without `data` uses its parent's, and can read
200
+ `${parent.*}`.
201
+ - `slots` — child node ids by slot name, in order, at any depth. Header and footer
202
+ slots exist on every node; containers use `items`, Card `body`, Tabs one slot per tab
203
+ key, Repeater `item` (children read `${item}` and `${index}`). A node sits in at most
204
+ one place.
205
+ - `version` — the widget's props version the node was saved with (default 1); older
206
+ ones are upgraded by the widget's migrations.
207
+ - `style` — the card's look (table below).
208
+ - `on` — event → actions. `watch` — state path → actions, with a loop guard. See
209
+ [State and events](state-and-events.md).
210
+ - `visibleWhen` — an expression; the node shows only while it is true.
211
+ - `drill` — `{ "levels": [{ name, label?, x?, query?, source?, do? }] }`, drill-down
212
+ levels ([State and events](state-and-events.md#drill-down)).
213
+ - `controls` — small inputs that belong to this node, with the same fields as filters,
214
+ read as `${panel.controls.<name>}`.
215
+ - `messages` — `empty`, `error` and `loading` text (templates). `loading` is shown over the
216
+ loading skeleton (a `status` region with `aria-busy`) and passed as `message` to the
217
+ host's `renderLoading` and design-system `Loading`.
218
+ - `description` — for people.
219
+
220
+ | `style` field | Values |
221
+ |---|---|
222
+ | `tone` | `default`, `subtle`, `accent`, `plain` |
223
+ | `padding` | `none`, `compact`, `normal`, `roomy`, or px (0–64) |
224
+ | `hideHeader` | Hide the node's header row |
225
+ | `minHeight` | px |
226
+ | `background`, `borderColor` | A theme token name (`"status-good-bg"`, `"surface-sunken"`) or a CSS colour |
227
+ | `borderWidth` | px, 0–8 |
228
+ | `radius` | px, 0–40 |
229
+ | `shadow` | `none`, `sm`, `md`, `lg` |
230
+ | `flex`, `minWidth`, `maxWidth`, `align` | As a child of a container: flex grow / basis, width limits, `start` / `center` / `end` / `stretch` |
231
+
232
+ Built-in kinds: `Kpi`, `Tiles`, `BarChart`, `LineChart`, `PieChart`, `Scatter`,
233
+ `Gauge`, `Breakdown`, `MatrixChart`, `Table`, `StageTracker`, `StateTimeline`,
234
+ `Status`, `CardGrid`, `ImageMap`, `Sparkline`, `Content`, `Image`, `Container`,
235
+ `Row`, `Column`, `Card`, `Tabs`, `Repeater`, `Filter`, `Text`, `Value`, `Progress`,
236
+ `Icon`, `Divider`. Their props are in [Widgets](widgets.md#built-in-widgets).
237
+
238
+ ## Events and actions
239
+
240
+ `on` exists on the dashboard (`load`, `variableChange`, …) and on each node (`click`,
241
+ `rowClick`, `change`, `hover`, `legendClick`, …). A handler is a list of steps; a
242
+ step is an action object or the name of a named action from `spec.actions`:
243
+
244
+ ```json
245
+ "on": { "rowClick": [{ "do": "setState", "path": "selectedHeat", "value": "${event.datum.id}" }, "notify"] }
246
+ ```
247
+
248
+ Actions: `setVariable`, `setState`, `setSelection`, `clearSelection`, `openModal`,
249
+ `closeModal`, `setView`, `drillDown`, `drillUp`, `drillReset`, `show`, `hide`,
250
+ `toggle`, `refresh`, `fetch`, `http`, `navigate`, `openDashboard`, `highlight`,
251
+ `toggleSeries`, `toast`, `export`, `download`, `fullscreen`, `emit`, `call`,
252
+ `sequence`, `script`, and host `ns.name` actions. Any step may have `when` (a condition).
253
+ Each action's fields and an example are in
254
+ [State and events](state-and-events.md#actions).
255
+
256
+ `spec.actions` holds named actions: an action object, or a callback string
257
+ `"(event, state, api) => { … }"`.
258
+
259
+ ## Expressions and templates
260
+
261
+ `${…}` inside strings, and bare expressions in `visibleWhen`, `when`, `refresh.when`,
262
+ `optionsFilter` and transform `filter` steps. They read `filters`, `state`,
263
+ `datasources.<id>`, `panels.<id>` (a widget's selection, page, …), `panel`, `view`,
264
+ `modal.args`, `highlight`, `event`, `drill`, `parent`, `item`, `index`, `context`,
265
+ `t` (translations), and
266
+ have helpers for numbers, dates and text. They cannot run arbitrary code. The full
267
+ language is in [Data: expressions](data.md#expressions).
268
+
269
+ ## `spec.templates`
270
+
271
+ Saved node subtrees (a metric card, a filter row) with a `label`, a `root` id and
272
+ their `nodes`. Editors insert copies; the renderer doesn't draw them.
273
+
274
+ ## `spec.modals`
275
+
276
+ Pop-ups opened by `openModal` (or by an `open` template turning true), keyed by id:
277
+
278
+ | Field | Notes |
279
+ |---|---|
280
+ | `title` | Template |
281
+ | `size` | `sm`, `md` (default), `lg`, `xl`, `full` |
282
+ | `presentation` | `modal` (default) or `drawer` (slides in from the side) |
283
+ | `open` | Template; the modal opens when it becomes true, e.g. `"${state.showOrder}"` |
284
+ | `datasources` | Datasources only this modal uses; they load when it opens |
285
+ | `panels` | Its own nodes (required) |
286
+ | `layout` | Layout items `{ panel, x, y, w, h }` for its nodes (required) |
287
+ | `on` | `close`: actions run when the viewer closes it |
288
+
289
+ Its nodes read the arguments as `${modal.args.*}`.
290
+
291
+ ```json
292
+ "modals": {
293
+ "order": {
294
+ "title": "Order ${modal.args.id}",
295
+ "size": "lg",
296
+ "datasources": { "orderDetail": { "type": "http", "connection": "api", "path": "/orders/${modal.args.id}" } },
297
+ "panels": { "orderLines": { "kind": "Table", "spec": { "data": { "source": "orderDetail", "path": "lines" } } } },
298
+ "layout": [{ "panel": "orderLines", "x": 0, "y": 0, "w": 12, "h": 8 }]
299
+ }
300
+ }
301
+ ```
302
+
303
+ ## `spec.layouts`
304
+
305
+ One entry per view and breakpoint. Either `items` (`{ panel, x, y, w, h, minW?, minH? }`
306
+ on the grid) or `auto`: `"flow"` (wrap in order, heights fit the content; phones use this
307
+ when there is no mobile layout) or `"stack"` (one column at desktop heights). Only
308
+ top-level nodes appear here; nested nodes live in slots.
309
+
310
+ | Field | Notes |
311
+ |---|---|
312
+ | `view` | The view this layout belongs to. The first `view` named in `layouts` is the starting view; `setView` switches |
313
+ | `breakpoint` | `desktop` (default, ≥ 1100 px), `tablet` (≥ 700 px), `mobile`, `tv` (≥ 1800 px). A missing breakpoint uses the desktop layout |
314
+ | `label` | The view's name for people |
315
+ | `items` / `auto` | Exactly one |
316
+
317
+ ```json
318
+ "layouts": [
319
+ { "view": "main", "breakpoint": "desktop", "items": [{ "panel": "kpi", "x": 0, "y": 0, "w": 15, "h": 5 }] },
320
+ { "view": "main", "breakpoint": "mobile", "auto": "flow" }
321
+ ]
322
+ ```
323
+
324
+ ## `spec.tour`
325
+
326
+ Optional guided tour: steps with a `panel` (optional), `title` (optional) and `text`
327
+ (both templates). When there is at least one step, the header shows a **Tour** button
328
+ (not in the Builder's edit mode, nor with `hideHeader`). Each step outlines its panel and
329
+ shows a small dialog with the step's title, text, "n / total", and Back / Next / Done.
330
+ Focus moves into the dialog; Escape, Close or Done ends the tour and returns focus to
331
+ the button. A step whose panel isn't on screen (another view, hidden) shows its text
332
+ without a highlight.
333
+
334
+ ```json
335
+ "tour": [
336
+ { "panel": "kpi", "title": "Today", "text": "Output for ${filters.plant}" },
337
+ { "panel": "trend", "text": "${t.trendHelp}" }
338
+ ]
339
+ ```
340
+
341
+ ## `spec.requires`
342
+
343
+ What the document needs to show fully: `{ "renderer": ">=0.2.0" }` (a version range of
344
+ `@dashspec/renderer`; `^`, `~`, `>=`, `<` and several separated by spaces). A renderer
345
+ that doesn't match still shows the document and warns that some parts may not show.
346
+
@@ -0,0 +1,141 @@
1
+ # Security
2
+
3
+ ## Threat model: documents are untrusted input
4
+
5
+ Dashboard documents are often written by people other than your developers: analysts,
6
+ customer-success teams, a visual builder, an AI agent, or a customer. Treat a document
7
+ like any user-generated content. The renderer is designed so that a document, the data
8
+ it loads, and values in the URL **cannot**:
9
+
10
+ - run code in your page,
11
+ - read or send your users' credentials to a server of its choosing,
12
+ - open `javascript:` or other dangerous links,
13
+ - break out of the dashboard's markup or styles,
14
+ - take your page down when it is broken.
15
+
16
+ This page lists what the renderer guarantees, and what your app must do in return.
17
+
18
+ ## What the renderer guarantees
19
+
20
+ **No code from documents runs in your page by default.** Callbacks, `script` actions,
21
+ `fn` transforms and `fn` props run in a QuickJS WebAssembly sandbox (`scripts="sandbox"`,
22
+ the default). The code sees only `event`, `state` and the `api` object (or `rows`, or
23
+ its parameters): no `window`, DOM, `fetch`, storage, cookies or tokens. Values cross the
24
+ boundary as JSON. Each run has a time limit (1 s synchronous, 50 ms per fn prop call,
25
+ 30 s per callback) and the VM a memory limit (32 MB). The host bridge is hidden from the
26
+ code, and the shared VM's built-ins are frozen so one script can't change what the next
27
+ sees. The sandbox loads only when a document contains code.
28
+
29
+ **Expressions can't reach JavaScript.** `${…}` templates and conditions use a small
30
+ expression language with no assignment, no `new`, no function bodies and no globals. It
31
+ reads own properties only, refuses `__proto__`, `prototype` and `constructor`, and can
32
+ call only its built-in helpers.
33
+
34
+ **Links are checked after templates are filled.** The `navigate` action, Table link
35
+ columns and Markdown links go through `safeLink`: only `http:`, `https:`, `mailto:` and
36
+ same-site paths pass, after removing the tabs, newlines and control characters a
37
+ browser would ignore (so `java\nscript:` is caught). `//host` and `/\host` are refused.
38
+ A refused `navigate` reports `unsafe-url` to `onError`. Image sources (Image, ImageMap,
39
+ Table image columns) allow only `http(s)`, paths and `data:image/`.
40
+
41
+ **Credentials go only where you allow.** Tokens never appear in documents: auth names a
42
+ token *source* (`{ "from": "host" }`), and validation rejects literal tokens and
43
+ passwords (`secret`). Auth is attached only to requests that name the connection and go
44
+ to that connection's own origin. Stored credentials (tokens in localStorage,
45
+ sessionStorage or cookies, `cookie` auth, and a token refresh written in the JSON) are
46
+ sent only to the page's origin, connections your app passes, and origins in
47
+ `trustedOrigins`. A token refresh written in the JSON may only call the connection's own
48
+ origin.
49
+
50
+ **Values in request paths are URL-encoded.** A value filled into a datasource's or
51
+ action's `path` or `url` can't add path segments or query parameters: `../admin`
52
+ becomes `..%2Fadmin`.
53
+
54
+ **Lookups by name use own properties only.** Datasource, panel, action, modal, function
55
+ and host-action names from a document are looked up with own-property checks, and
56
+ connections are null-prototype objects, so a document naming `constructor` or
57
+ `toString` finds nothing and a polluted `Object.prototype` can't redirect a request.
58
+ State paths never read or write prototype keys.
59
+
60
+ **Markdown values are escaped.** In the `Content` widget, every `${…}` value filled
61
+ into `markdown` is escaped, so data, filters or URL values can't add links, `action:`
62
+ buttons or headings. No raw HTML is ever rendered.
63
+
64
+ **Theme values can't inject CSS.** `themeStylesheet` drops tokens whose name or value
65
+ could end a rule (`;`, braces, `<`, `>`, line breaks, `\`). Node `style` colours accept
66
+ only token names and plain CSS colours.
67
+
68
+ **State stays consistent.** Writes from actions, scripts and widgets can't replace the
69
+ runtime's own parts (`datasources`, `context` are read-only; `filters`, `panels`,
70
+ `highlight` stay objects). A refused write is reported; the store never breaks.
71
+
72
+ **Failures stay local.** An invalid document shows a message instead of throwing; a
73
+ failing datasource, widget or control costs only that part. Responses are capped at
74
+ 10 MB (`maxResponseBytes`), transforms at 100 000 rows, polling at once per second, and
75
+ runaway `watch` loops are stopped.
76
+
77
+ ## What your app must do
78
+
79
+ **Give tokens through `getToken`.** Write connections as
80
+ `"token": { "from": "host" }` and return the token from your app. Your callback decides
81
+ which connection gets which token; return `null` for connections you don't recognise.
82
+
83
+ ```tsx
84
+ <DashSpecProvider getToken={(connection) => (connection === "api" ? auth.token() : null)}>
85
+ ```
86
+
87
+ **Keep `trustedOrigins` short.** Only list origins that should receive tokens stored in
88
+ the browser. Prefer `getToken` to storage-based tokens for documents you didn't write.
89
+
90
+ **Keep `scripts` on its default.** `"sandbox"` is safe for untrusted documents.
91
+ `scripts="trusted"` runs document code with `new Function` and full access to your page:
92
+ use it only when every document is written by people you trust as much as your own
93
+ developers. `scripts="off"` is the strictest: no document code runs at all.
94
+
95
+ **Pass only what documents may read in `context` and `data`.** Anything there is readable
96
+ by every document as `${context.*}` and can be sent in a request.
97
+
98
+ **Restrict where requests and images can go.** A document can send requests (without
99
+ your credentials) and load images from any URL, including values from your state. If
100
+ that matters, limit it with your Content Security Policy (`connect-src`, `img-src`) or
101
+ route requests through your own `transport`.
102
+
103
+ **Handle `onNavigate`.** Links are checked, but you may want to send same-site paths
104
+ through your router and confirm external ones.
105
+
106
+ **Validate on save.** Run `loadDocument` (from `@dashspec/renderer/core`) where
107
+ documents are saved, and refuse those with errors, so invalid or secret-bearing JSON
108
+ never reaches storage.
109
+
110
+ ## Content Security Policy
111
+
112
+ The renderer needs no `'unsafe-inline'` scripts and no `'unsafe-eval'` in its default
113
+ mode. What to allow:
114
+
115
+ | Feature | Directive |
116
+ |---|---|
117
+ | The injected stylesheet and inline token variables | `style-src 'unsafe-inline'` (the renderer renders a `<style>` element and `style` attributes) |
118
+ | The script sandbox (documents with code, `scripts="sandbox"`) | `script-src 'wasm-unsafe-eval'` to compile the QuickJS WebAssembly, and `connect-src` allowing the origin the `.wasm` file is served from (usually `'self'`) |
119
+ | `scripts="trusted"` | `script-src 'unsafe-eval'` (it uses `new Function`). Not recommended |
120
+ | Datasources, `http` and `download` actions | `connect-src` for your API origins; `ws:` / `wss:` URLs for WebSocket datasources |
121
+ | Images in documents | `img-src` for the hosts you allow, plus `data:` for inline images |
122
+
123
+ A policy for a dashboard that calls `https://api.example.com` and may contain scripts:
124
+
125
+ ```
126
+ Content-Security-Policy:
127
+ default-src 'self';
128
+ script-src 'self' 'wasm-unsafe-eval';
129
+ style-src 'self' 'unsafe-inline';
130
+ connect-src 'self' https://api.example.com;
131
+ img-src 'self' data: https://cdn.example.com;
132
+ ```
133
+
134
+ Without `'wasm-unsafe-eval'`, a document with code shows "Could not start the script
135
+ sandbox" and documents without code work normally.
136
+
137
+ ## Reporting a vulnerability
138
+
139
+ Please don't open a public issue. Follow the instructions in
140
+ [SECURITY.md](https://github.com/vaskar-nowpurchase/dashspec-renderer/blob/main/SECURITY.md)
141
+ at the root of the repository to report it privately.
@@ -0,0 +1,126 @@
1
+ # Server rendering
2
+
3
+ The renderer works with server-side rendering (SSR) and React Server Components. The
4
+ React entry draws on the server and hydrates in the browser; data always loads in the
5
+ browser. The `/core` entry has no React and runs anywhere, so your server can validate
6
+ documents before sending them.
7
+
8
+ ## The two entries on the server
9
+
10
+ | Entry | On the server |
11
+ |---|---|
12
+ | `@dashspec/renderer` | Marked `"use client"` (the directive is the first line of the built file). In the Next.js App Router it is a client module: render it from a Client Component, or from a Server Component with serializable props only |
13
+ | `@dashspec/renderer/core` | Plain ESM without React or DOM: use it in Server Components, route handlers, API servers, edge functions, CI |
14
+
15
+ ## Next.js App Router
16
+
17
+ Callbacks such as `getToken` and `onError` are functions, which can't cross from a Server
18
+ Component to a Client Component. Put the renderer and its settings in a Client Component
19
+ of your own:
20
+
21
+ ```tsx
22
+ // app/dashboards/[key]/Dashboard.tsx
23
+ "use client";
24
+
25
+ import { DashboardRenderer, DashSpecProvider } from "@dashspec/renderer";
26
+ import { getAccessToken } from "@/lib/auth-client";
27
+
28
+ export function Dashboard({ id, document }: { id: string; document: unknown }) {
29
+ return (
30
+ <DashSpecProvider getToken={() => getAccessToken()} trustedOrigins={["https://api.example.com"]}>
31
+ <DashboardRenderer id={id} document={document} onError={(e) => console.error(e)} />
32
+ </DashSpecProvider>
33
+ );
34
+ }
35
+ ```
36
+
37
+ Load and validate the document on the server with `/core`, and pass plain JSON down:
38
+
39
+ ```tsx
40
+ // app/dashboards/[key]/page.tsx (a Server Component)
41
+ import { notFound } from "next/navigation";
42
+ import { builtInWidgetChecks, loadDocument } from "@dashspec/renderer/core";
43
+ import { getDashboardJson } from "@/lib/dashboards";
44
+ import { Dashboard } from "./Dashboard";
45
+
46
+ export default async function Page({ params }: { params: Promise<{ key: string }> }) {
47
+ const { key } = await params;
48
+ const json = await getDashboardJson(key);
49
+ if (!json) notFound();
50
+
51
+ const result = loadDocument(json, { widgets: builtInWidgetChecks });
52
+ if (result.status === "invalid") {
53
+ console.error(result.problems);
54
+ return <p>This dashboard has errors.</p>;
55
+ }
56
+ return <Dashboard id={key} document={json} />;
57
+ }
58
+ ```
59
+
60
+ Pass the stored JSON (`json`), not `result.document`: the parsed document leaves out
61
+ unknown and `x-` fields, which your own widgets and filter kinds may read, and the
62
+ renderer migrates and validates again in the browser anyway. With
63
+ `builtInWidgetChecks` (React-free, from `/core`), `loadDocument` on the server checks the
64
+ document's structure, its links and the props of every built-in widget. Your own
65
+ widgets' props are checked by the renderer in the browser, or on the server with
66
+ `widgetChecks` (see [API: validateDocument](api.md#validatedocument)).
67
+
68
+ A `DashSpecProvider` with your design systems, widgets and actions usually sits once in
69
+ a client layout component near the root, so every dashboard page shares it.
70
+
71
+ ## Other SSR frameworks
72
+
73
+ Nothing is specific to Next.js. Any SSR setup (Remix / React Router, Vite SSR, a custom
74
+ `renderToString`) can render `DashboardRenderer` on the server: it needs no `window`
75
+ during render, injects its stylesheet inline, and starts loading data only after
76
+ hydration.
77
+
78
+ ## Hydration
79
+
80
+ The renderer makes its first browser render match the server HTML:
81
+
82
+ - **No data on the server.** The runtime starts in an effect, so the server renders the
83
+ layout with loading placeholders and the browser fetches. Nothing is fetched twice.
84
+ - **URL filters after mount.** Filter values in the URL are applied in an effect right
85
+ after hydration, before the first fetch, so the first request already uses them.
86
+ - **Auto dark mode.** With mode `"auto"`, the server and the first client render use
87
+ the light colours, then switch to dark if the viewer prefers it. To avoid that flash,
88
+ choose the mode yourself (for example from a cookie) and pass a theme with
89
+ `mode: "light"` or `"dark"` (see [Theming](theming.md#light-dark-and-auto)).
90
+ - **Styles.** The stylesheet is rendered inline in the same way on server and client.
91
+ - **Dates.** Default filter dates ("today", "last 7 days") are computed during render
92
+ in the document's `display.timeZone`, or the machine's own time zone without one. Set
93
+ `display.timeZone` so the server and the browser agree on "today".
94
+ - **Scripts.** A document with code in `"sandbox"` mode renders a loading placeholder
95
+ until the sandbox has loaded in the browser.
96
+
97
+ ## Several dashboards on one page
98
+
99
+ Give each `DashboardRenderer` its own `id`:
100
+
101
+ ```tsx
102
+ <DashboardRenderer id="sales" document={salesDoc} />
103
+ <DashboardRenderer id="support" document={supportDoc} />
104
+ ```
105
+
106
+ The `id`:
107
+
108
+ - prefixes the dashboard's URL keys (`sales.region`, `support.region`), so the two
109
+ don't overwrite each other's filters. Without ids, only the first mounted dashboard
110
+ keeps its filters in the URL and the others skip URL sync (with a development
111
+ warning);
112
+ - is the name [`useDashboardState`](api.md#usedashboardstate) and
113
+ [`useDashboardActions`](api.md#usedashboardactions) use. Two mounted dashboards with
114
+ the same `id` log a warning and the hooks see the later one.
115
+
116
+ Each dashboard has its own state, data and requests. Settings from a shared
117
+ `DashSpecProvider` apply to all of them.
118
+
119
+ ## The script sandbox and bundlers
120
+
121
+ The sandbox (`@dashspec/renderer/sandbox`) is a separate chunk that the renderer
122
+ imports only when a document contains code. It loads a QuickJS WebAssembly file of about
123
+ 500 KB, referenced with `new URL("emscripten-module.wasm", import.meta.url)`; bundlers
124
+ that understand that pattern emit the file next to your assets. Make sure it is served
125
+ (with the `application/wasm` type) from your site, and allowed by your Content Security
126
+ Policy (see [Security](security.md#content-security-policy)).