@zeyos/zx 5.5.0 → 5.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +210 -0
- package/README.md +73 -7
- package/bin/zx-css.js +328 -0
- package/dist/types/components/account-menu/account-menu.d.ts +4 -2
- package/dist/types/components/activity-list/activity-list.d.ts +14 -8
- package/dist/types/components/agent-thread/ag-ui.d.ts +340 -0
- package/dist/types/components/agent-thread/agent-thread.d.ts +711 -0
- package/dist/types/components/agent-thread/ui-message-stream.d.ts +401 -0
- package/dist/types/components/app-sidebar/app-sidebar.d.ts +14 -8
- package/dist/types/components/approval-card/approval-card.d.ts +596 -0
- package/dist/types/components/avatar/avatar.d.ts +91 -4
- package/dist/types/components/block-view/block-view.d.ts +205 -0
- package/dist/types/components/breadcrumb/breadcrumb.d.ts +3 -3
- package/dist/types/components/calendar/calendar-model.d.ts +9 -2
- package/dist/types/components/calendar/calendar.d.ts +12 -4
- package/dist/types/components/chart/chart.d.ts +25 -13
- package/dist/types/components/code-editor/code-editor.d.ts +7 -2
- package/dist/types/components/composer/composer.d.ts +938 -0
- package/dist/types/components/composer/queue.d.ts +76 -0
- package/dist/types/components/copy/copy-button.d.ts +6 -4
- package/dist/types/components/copy/copy-input.d.ts +10 -6
- package/dist/types/components/datebox/date-range-box.d.ts +33 -0
- package/dist/types/components/datebox/placeholder.d.ts +7 -0
- package/dist/types/components/dock/dock.d.ts +12 -3
- package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
- package/dist/types/components/field-upload/field-upload.d.ts +3 -2
- package/dist/types/components/file-item/file-item.d.ts +3 -2
- package/dist/types/components/file-list/file-list.d.ts +14 -8
- package/dist/types/components/filter/filter-model.d.ts +31 -1
- package/dist/types/components/filter/filter.d.ts +20 -2
- package/dist/types/components/finder/finder.d.ts +14 -6
- package/dist/types/components/flag/flag.d.ts +99 -0
- package/dist/types/components/grid/grid.d.ts +1 -1
- package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
- package/dist/types/components/launcher/launcher.d.ts +2 -0
- package/dist/types/components/multi-value-editor/multi-value-editor.d.ts +3 -2
- package/dist/types/components/number-field/number-field.d.ts +17 -6
- package/dist/types/components/prompt-starters/prompt-starters.d.ts +107 -0
- package/dist/types/components/prose/prose.d.ts +9 -6
- package/dist/types/components/questionnaire/conditions.d.ts +270 -0
- package/dist/types/components/questionnaire/items.d.ts +52 -30
- package/dist/types/components/questionnaire/questionnaire.d.ts +44 -4
- package/dist/types/components/rating/rating.d.ts +5 -3
- package/dist/types/components/run-status/run-status.d.ts +393 -0
- package/dist/types/components/run-trace/run-trace.d.ts +624 -0
- package/dist/types/components/select/country.d.ts +106 -0
- package/dist/types/components/select/field-adapter.d.ts +2 -1
- package/dist/types/components/select/locale.d.ts +102 -0
- package/dist/types/components/select/select.d.ts +41 -2
- package/dist/types/components/slider/slider.d.ts +1 -0
- package/dist/types/components/sort-control/sort-control.d.ts +7 -3
- package/dist/types/components/source-list/source-list.d.ts +179 -0
- package/dist/types/components/split-view/split-view.d.ts +5 -3
- package/dist/types/components/surface/catalog.d.ts +260 -0
- package/dist/types/components/surface/elicit.d.ts +81 -0
- package/dist/types/components/surface/mcp.d.ts +165 -0
- package/dist/types/components/surface/schema.d.ts +314 -0
- package/dist/types/components/surface/stream.d.ts +118 -0
- package/dist/types/components/surface/surface.d.ts +718 -0
- package/dist/types/components/surface/text.d.ts +277 -0
- package/dist/types/components/surface/validate.d.ts +339 -0
- package/dist/types/components/table/table.d.ts +55 -3
- package/dist/types/components/table/window.d.ts +203 -0
- package/dist/types/components/toolbar/toolbar.d.ts +10 -6
- package/dist/types/components/tooltip/tooltip.d.ts +2 -2
- package/dist/types/components/tree/tree.d.ts +20 -13
- package/dist/types/core/component.d.ts +10 -0
- package/dist/types/core/date.d.ts +8 -1
- package/dist/types/core/dom.d.ts +1 -0
- package/dist/types/core/http.d.ts +10 -0
- package/dist/types/core/i18n.d.ts +38 -0
- package/dist/types/core/messages.d.ts +479 -1
- package/dist/types/core/storage.d.ts +7 -2
- package/dist/types/elements/define.d.ts +21 -46
- package/dist/types/elements/definitions.d.ts +147 -0
- package/dist/types/elements/kit.d.ts +7 -0
- package/dist/types/elements/reflect.d.ts +6 -3
- package/dist/types/index.d.ts +18 -1
- package/dist/types/internal/agent-model.d.ts +587 -0
- package/dist/types/internal/date-locale.d.ts +7 -0
- package/dist/types/internal/highlight.d.ts +24 -0
- package/dist/types/internal/json-patch.d.ts +146 -0
- package/dist/types/internal/presence-loop.d.ts +148 -0
- package/dist/types/locales/de.d.ts +13 -0
- package/dist/types/locales/en.d.ts +2 -0
- package/dist/types/locales/index.d.ts +823 -0
- package/dist/types/zeyos/view.d.ts +8 -1
- package/dist/zx-zeyos.esm.js +20505 -18748
- package/dist/zx-zeyos.esm.min.js +5 -5
- package/dist/zx.core.css +1276 -0
- package/dist/zx.core.min.css +1 -0
- package/dist/zx.css +2424 -134
- package/dist/zx.esm.js +46167 -28468
- package/dist/zx.esm.min.js +40 -8
- package/dist/zx.global.js +46167 -28468
- package/dist/zx.global.min.js +40 -8
- package/dist/zx.layered.css +17302 -0
- package/dist/zx.layered.min.css +1 -0
- package/dist/zx.min.css +1 -1
- package/docs/agent-catalog.json +12501 -0
- package/docs/agent-surfaces.md +340 -0
- package/docs/api.json +2057 -166
- package/docs/llms.md +1458 -58
- package/docs/llms.txt +38 -8
- package/package.json +29 -6
- package/src/components/account-menu/account-menu.js +6 -3
- package/src/components/activity-item/activity-item.js +2 -1
- package/src/components/activity-list/activity-list.js +16 -10
- package/src/components/agent-thread/ag-ui.js +1439 -0
- package/src/components/agent-thread/agent-thread.css +417 -0
- package/src/components/agent-thread/agent-thread.js +1670 -0
- package/src/components/agent-thread/ui-message-stream.js +1281 -0
- package/src/components/app-sidebar/app-sidebar.js +18 -8
- package/src/components/approval-card/approval-card.css +289 -0
- package/src/components/approval-card/approval-card.js +1378 -0
- package/src/components/avatar/avatar.css +56 -1
- package/src/components/avatar/avatar.js +148 -26
- package/src/components/block-view/block-view.css +300 -0
- package/src/components/block-view/block-view.js +524 -0
- package/src/components/breadcrumb/breadcrumb.js +8 -5
- package/src/components/calendar/calendar-model.js +8 -2
- package/src/components/calendar/calendar.js +53 -18
- package/src/components/chart/chart.js +54 -23
- package/src/components/code-editor/code-editor.js +45 -8
- package/src/components/code-editor/field-adapter.js +1 -1
- package/src/components/composer/composer.css +482 -0
- package/src/components/composer/composer.js +1815 -0
- package/src/components/composer/queue.js +78 -0
- package/src/components/context-menu/context-menu.js +12 -1
- package/src/components/copy/copy-button.js +9 -7
- package/src/components/copy/copy-input.js +10 -6
- package/src/components/date-picker/date-picker.js +2 -1
- package/src/components/date-picker/date-range-picker.js +8 -7
- package/src/components/datebox/date-range-box.js +3 -9
- package/src/components/datebox/datebox.js +18 -21
- package/src/components/datebox/placeholder.js +18 -0
- package/src/components/dialog/dialog.js +1 -1
- package/src/components/dock/dock.js +34 -13
- package/src/components/entity-ref/entity-ref.js +16 -5
- package/src/components/field-upload/field-upload.js +81 -38
- package/src/components/file-item/file-item.js +70 -40
- package/src/components/file-list/file-list.js +15 -9
- package/src/components/filter/filter-model.js +46 -8
- package/src/components/filter/filter.css +3 -3
- package/src/components/filter/filter.js +29 -10
- package/src/components/filter-panel/filter-panel.js +13 -5
- package/src/components/finder/finder.js +50 -26
- package/src/components/flag/flag.css +40 -0
- package/src/components/flag/flag.js +177 -0
- package/src/components/form/form.js +1 -1
- package/src/components/grid/grid.js +22 -8
- package/src/components/kanban-view/kanban-view.js +51 -81
- package/src/components/launcher/launcher.js +17 -2
- package/src/components/list-toolbar/list-toolbar.js +2 -1
- package/src/components/master-panel/master-panel.js +1 -1
- package/src/components/menu-button/menu-button.js +4 -0
- package/src/components/message/message.js +3 -0
- package/src/components/multi-value-editor/multi-value-editor.js +10 -9
- package/src/components/navigation-bar/navigation-bar.js +3 -3
- package/src/components/number-field/number-field.js +29 -13
- package/src/components/prompt-starters/prompt-starters.css +91 -0
- package/src/components/prompt-starters/prompt-starters.js +206 -0
- package/src/components/prose/prose.js +14 -10
- package/src/components/questionnaire/conditions.js +666 -0
- package/src/components/questionnaire/items.js +150 -41
- package/src/components/questionnaire/questionnaire.js +126 -32
- package/src/components/rating/rating.js +5 -4
- package/src/components/run-status/run-status.css +208 -0
- package/src/components/run-status/run-status.js +782 -0
- package/src/components/run-trace/run-trace.css +443 -0
- package/src/components/run-trace/run-trace.js +1209 -0
- package/src/components/select/country.js +136 -0
- package/src/components/select/field-adapter.js +7 -2
- package/src/components/select/locale.js +219 -0
- package/src/components/select/select.css +20 -22
- package/src/components/select/select.js +94 -12
- package/src/components/sheet/sheet-stack.js +10 -1
- package/src/components/slider/slider.js +7 -2
- package/src/components/sort-control/sort-control.js +15 -5
- package/src/components/source-list/source-list.css +208 -0
- package/src/components/source-list/source-list.js +358 -0
- package/src/components/split-view/split-view.js +5 -3
- package/src/components/surface/catalog.js +1334 -0
- package/src/components/surface/elicit.js +107 -0
- package/src/components/surface/mcp.js +243 -0
- package/src/components/surface/schema.js +644 -0
- package/src/components/surface/stream.js +245 -0
- package/src/components/surface/surface.css +308 -0
- package/src/components/surface/surface.js +2291 -0
- package/src/components/surface/text.js +513 -0
- package/src/components/surface/validate.js +2218 -0
- package/src/components/tabbox/tabbox.js +9 -0
- package/src/components/table/table.css +63 -3
- package/src/components/table/table.js +167 -28
- package/src/components/table/window.js +317 -0
- package/src/components/toolbar/toolbar.js +12 -7
- package/src/components/tooltip/tooltip.css +2 -3
- package/src/components/tooltip/tooltip.js +32 -5
- package/src/components/tree/tree.js +53 -23
- package/src/core/component.js +25 -1
- package/src/core/date.js +62 -16
- package/src/core/dom.js +22 -2
- package/src/core/format.js +15 -13
- package/src/core/http.js +29 -20
- package/src/core/i18n.js +83 -10
- package/src/core/keyboard.js +79 -8
- package/src/core/messages.js +519 -2
- package/src/core/overlay-host.js +1 -0
- package/src/core/storage.js +59 -6
- package/src/elements/define.js +178 -130
- package/src/elements/definitions.js +229 -0
- package/src/elements/kit.js +444 -0
- package/src/elements/reflect.js +8 -3
- package/src/index.js +18 -1
- package/src/internal/agent-model.js +488 -0
- package/src/internal/date-locale.js +11 -0
- package/src/internal/highlight.js +104 -0
- package/src/internal/json-patch.js +405 -0
- package/src/internal/presence-loop.js +343 -0
- package/src/locales/de.js +911 -0
- package/src/locales/en.js +2 -0
- package/src/locales/index.js +7 -0
- package/src/zeyos/calendar.js +2 -1
- package/src/zeyos/form.js +2 -1
- package/src/zeyos/launcher.js +7 -6
- package/src/zeyos/module-bar.js +2 -1
- package/src/zeyos/schema.js +37 -23
- package/src/zeyos/select.js +4 -3
- package/src/zeyos/table.js +2 -13
- package/src/zeyos/view.js +57 -17
- package/styles/core.css +11 -0
- package/styles/tokens/semantic.css +1 -0
- package/styles/zeyos.css +2 -0
- package/styles/zx.css +11 -8
- package/styles/zx.layered.css +1 -0
|
@@ -0,0 +1,2218 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Validates surface operations and documents.
|
|
4
|
+
*
|
|
5
|
+
* Rendering is tolerant and reporting strict: an invalid property is dropped, an invalid node is
|
|
6
|
+
* kept only as its id and type (the surface draws a quiet fallback for it), and every problem is
|
|
7
|
+
* listed as an error an application can hand back to the model that wrote the surface. Three shape
|
|
8
|
+
* mistakes that can only mean one thing are repaired, and reported with `repaired: true`:
|
|
9
|
+
*
|
|
10
|
+
* - `root` or `children` given as one id string is wrapped in a list;
|
|
11
|
+
* - a non-empty `$data` pointer without its leading `/` gets one;
|
|
12
|
+
* - a child given inline as a whole node with an `id` and a `type` is lifted out as its own
|
|
13
|
+
* `node` operation and replaced by its id.
|
|
14
|
+
*
|
|
15
|
+
* Nothing else is guessed at. The module touches no DOM, so a server can validate what its model
|
|
16
|
+
* wrote before it forwards it, and again when a reply comes back.
|
|
17
|
+
*/
|
|
18
|
+
import { safeHref } from '../../core/dom.js';
|
|
19
|
+
import { getPointer, parsePointer } from '../../internal/json-patch.js';
|
|
20
|
+
import { checkCondition, checkNext, checkRuleList, MAX_CONDITION_DEPTH, NEXT_REVIEW, NEXT_SUBMIT } from '../questionnaire/conditions.js';
|
|
21
|
+
import {
|
|
22
|
+
assertCatalog, CATALOG, FORBIDDEN_KEYS, HREF_PATTERN, ICON_PATTERN, ID_PATTERN, LIMITS, NAME_PATTERN, PLACEMENTS, RESERVED_ACTIONS, SURFACE_VERSION
|
|
23
|
+
} from './catalog.js';
|
|
24
|
+
import { unsupported } from './schema.js';
|
|
25
|
+
|
|
26
|
+
/** @typedef {import('./catalog.js').SurfaceCatalog} SurfaceCatalog */
|
|
27
|
+
/** @typedef {import('./catalog.js').CatalogNode} CatalogNode */
|
|
28
|
+
/** @typedef {import('./catalog.js').CatalogProp} CatalogProp */
|
|
29
|
+
/** @typedef {import('./catalog.js').SurfaceIntent} SurfaceIntent */
|
|
30
|
+
/** @typedef {import('./catalog.js').SurfacePlacement} SurfacePlacement */
|
|
31
|
+
/** @typedef {import('../questionnaire/conditions.js').Condition} Condition */
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* What went wrong. Codes are stable; messages are English and written for the model.
|
|
35
|
+
* - `invalid-op`: the operation is not an object.
|
|
36
|
+
* - `unknown-op`: `op` is not one of the operations.
|
|
37
|
+
* - `version`: `zx` is not `surface/1`; the surface is refused.
|
|
38
|
+
* - `no-begin`, `duplicate-begin`, `ended`: an operation out of order; it is refused.
|
|
39
|
+
* - `unknown-intent`: the intent is unknown or outside the catalog; the surface draws no controls.
|
|
40
|
+
* - `unknown-type`: the node type is unknown or outside the catalog; the node is a fallback.
|
|
41
|
+
* - `not-allowed`: the node or property does not belong in this surface.
|
|
42
|
+
* - `unknown-node`: a `patch`, `append` or `remove` names a node that does not exist.
|
|
43
|
+
* - `unknown-key`: a key the format does not have; dropped.
|
|
44
|
+
* - `token-refused`: a `token`, which only the application can set; dropped.
|
|
45
|
+
* - `confirmation-ignored`: an action trying to set its own confirmation; dropped.
|
|
46
|
+
* - `forbidden-key`: `__proto__`, `constructor` or `prototype`; dropped at any depth.
|
|
47
|
+
* - `not-finite`: a number that is not finite; dropped.
|
|
48
|
+
* - `limit`: over one of the limits; dropped.
|
|
49
|
+
* - `invalid-value`: the wrong type or a value outside its choices; dropped.
|
|
50
|
+
* - `missing`: something required is absent.
|
|
51
|
+
* - `link-refused`: a link that is not a plain `https:` address.
|
|
52
|
+
* - `ref-refused`: a record whose entity the application does not offer.
|
|
53
|
+
* - `pointer-invalid`: a malformed JSON Pointer.
|
|
54
|
+
* - `data-path`: a `data` path that runs through a value that is not an object or a list, or
|
|
55
|
+
* whose parent does not exist.
|
|
56
|
+
* - `condition`: a `visible`, `when` or `next` that breaks the condition grammar, nests too deep or
|
|
57
|
+
* names an input that does not come earlier; dropped, so the node stays visible.
|
|
58
|
+
* - `unsupported-schema`: a schema construct outside the input subset; dropped.
|
|
59
|
+
* - `untitled-property`: a schema property without a `title`.
|
|
60
|
+
* - `duplicate-name`: an input name used twice; the later one is dropped.
|
|
61
|
+
* - `draw-failed`: a node or the surface could not be drawn; the rest stands, and it still replies.
|
|
62
|
+
* - `cycle`: a child that is the node itself or one of its ancestors, or already placed elsewhere.
|
|
63
|
+
* - `missing-node`: a child id that never arrived by `end`.
|
|
64
|
+
* - `unreachable`: a node that no list of children reaches from `root`.
|
|
65
|
+
* - `needs`: the intent lacks the node it needs.
|
|
66
|
+
* - `wrapped-list`, `pointer-slash`, `lifted-child`: the three repairs, with `repaired: true`.
|
|
67
|
+
* @typedef {'invalid-op'|'unknown-op'|'version'|'no-begin'|'duplicate-begin'|'ended'|'unknown-intent'
|
|
68
|
+
* |'unknown-type'|'not-allowed'|'unknown-node'|'unknown-key'|'token-refused'|'confirmation-ignored'
|
|
69
|
+
* |'forbidden-key'|'not-finite'|'limit'|'invalid-value'|'missing'|'link-refused'|'ref-refused'
|
|
70
|
+
* |'pointer-invalid'|'data-path'|'condition'|'unsupported-schema'|'untitled-property'|'duplicate-name'
|
|
71
|
+
* |'cycle'|'missing-node'|'unreachable'|'needs'|'wrapped-list'|'pointer-slash'|'lifted-child'
|
|
72
|
+
* |'draw-failed'} SurfaceErrorCode
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* One problem, in a shape an application can return to the model as it is.
|
|
77
|
+
* @typedef {Object} SurfaceError
|
|
78
|
+
* @property {SurfaceErrorCode} code What went wrong.
|
|
79
|
+
* @property {string} message What went wrong, for the model.
|
|
80
|
+
* @property {string} [surface] The surface it concerns.
|
|
81
|
+
* @property {string} [id] The node or action it concerns.
|
|
82
|
+
* @property {string} [path] JSON Pointer to the problem inside the operation line, or inside the
|
|
83
|
+
* document for `validateDocument()`.
|
|
84
|
+
* @property {true} [repaired] Present when the problem was repaired rather than dropped.
|
|
85
|
+
*/
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A node: its id, its type, its properties, and optionally `visible` and `children`.
|
|
89
|
+
* @typedef {{id: string, type: string, visible?: Condition, children?: string[], [key: string]: unknown}} SurfaceNode
|
|
90
|
+
*/
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* One operation line, after validation. Every line names its `surface`.
|
|
94
|
+
* @typedef {{op: 'begin', zx: string, surface: string, intent: SurfaceIntent|null, title?: string, author?: string, root: string[], placement?: SurfacePlacement, description?: string}
|
|
95
|
+
* | ({op: 'node', surface: string} & SurfaceNode)
|
|
96
|
+
* | {op: 'patch', surface: string, id: string, props: Record<string, unknown>}
|
|
97
|
+
* | {op: 'append', surface: string, id: string, text: string}
|
|
98
|
+
* | {op: 'remove', surface: string, id: string}
|
|
99
|
+
* | {op: 'data', surface: string, path: string, value?: unknown, remove?: true}
|
|
100
|
+
* | {op: 'actions', surface: string, items: SurfaceAction[]}
|
|
101
|
+
* | {op: 'end', surface: string, sources?: SurfaceSource[]}} SurfaceOp
|
|
102
|
+
*/
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* An action of the surface's own. What it needs before it runs is the application's decision.
|
|
106
|
+
* @typedef {Object} SurfaceAction
|
|
107
|
+
* @property {string} id Reported as the reply's `action`.
|
|
108
|
+
* @property {string} label The button text.
|
|
109
|
+
* @property {'primary'|'secondary'|'danger'} [kind] How it looks; `danger` is presentation only.
|
|
110
|
+
* @property {string} [tool] The tool the action triggers, for the application's policy.
|
|
111
|
+
* @property {string} [description] A supporting line.
|
|
112
|
+
*/
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* A source a surface's citation markers refer to.
|
|
116
|
+
* @typedef {Object} SurfaceSource
|
|
117
|
+
* @property {number} n The marker's number, `[n]`.
|
|
118
|
+
* @property {string} [title] What the source is.
|
|
119
|
+
* @property {string} [call] The trace step it came from.
|
|
120
|
+
* @property {{$ref: string, id: string}} [ref] The record it is.
|
|
121
|
+
*/
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The document form: a whole surface as one object, the shape the `show_surface` and `ask_user`
|
|
125
|
+
* tools take and `Surface({document})` renders. It mirrors the operations: the `begin` members,
|
|
126
|
+
* then every `node`, the `data`, the `actions` and the `end`'s `sources`. A key whose value is
|
|
127
|
+
* `null` counts as absent, so arguments written for strict structured output are read as given.
|
|
128
|
+
* @typedef {Object} SurfaceDocument
|
|
129
|
+
* @property {'surface/1'} zx The format version.
|
|
130
|
+
* @property {string} surface The surface's id.
|
|
131
|
+
* @property {SurfaceIntent|null} intent The intent; `null` after validation when it was invalid.
|
|
132
|
+
* @property {string} [title] What the surface is about; also its accessible name.
|
|
133
|
+
* @property {string} [author] Who composed it, a key into the application's authors.
|
|
134
|
+
* @property {string[]} root The ids of the top-level nodes, in order.
|
|
135
|
+
* @property {SurfacePlacement} [placement] Where the surface asks to be placed.
|
|
136
|
+
* @property {string} [description] A supporting line under the title.
|
|
137
|
+
* @property {SurfaceNode[]} nodes Every node, each once.
|
|
138
|
+
* @property {Record<string, unknown>} [data] Data that `{"$data": "/pointer"}` properties bind to.
|
|
139
|
+
* @property {SurfaceAction[]} [actions] The surface's own actions.
|
|
140
|
+
* @property {SurfaceSource[]} [sources] The sources of its citation markers.
|
|
141
|
+
*/
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* What `validateOp()` returns. Apply `ops` in order: the operation itself, preceded or followed by
|
|
145
|
+
* what validation adds — lifted inline children after the node that held them, and at `end` the
|
|
146
|
+
* patches that drop what the whole surface showed to be invalid.
|
|
147
|
+
* @typedef {Object} OpResult
|
|
148
|
+
* @property {SurfaceOp|null} op The operation as it may be applied, or `null` when it is refused.
|
|
149
|
+
* @property {SurfaceError[]} errors Everything found, repairs included.
|
|
150
|
+
* @property {SurfaceOp[]} ops Every operation to apply, in order.
|
|
151
|
+
*/
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Options of `createValidationState()` and `validateDocument()`.
|
|
155
|
+
* @typedef {Object} ValidationSettings
|
|
156
|
+
* @property {Iterable<string>|null} [entities=null] The record entities `{"$ref": …}` may name, as
|
|
157
|
+
* the Surface's `resolve.entities`. Without them every record is refused.
|
|
158
|
+
*/
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* What the validator knows of the surfaces of one stream. Create it with
|
|
162
|
+
* `createValidationState()`, pass it to every `validateOp()` of the stream, and read a surface back
|
|
163
|
+
* with `stateToDocument()`. Opaque otherwise.
|
|
164
|
+
* @typedef {Object} ValidationState
|
|
165
|
+
* @property {Set<string>|null} entities The entities records may name.
|
|
166
|
+
* @property {Map<string, SurfaceTrack>} surfaces The surfaces begun so far.
|
|
167
|
+
*/
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* @typedef {Object} SurfaceTrack
|
|
171
|
+
* @property {string} id
|
|
172
|
+
* @property {SurfaceIntent|null} intent
|
|
173
|
+
* @property {string} [title]
|
|
174
|
+
* @property {string} [author]
|
|
175
|
+
* @property {SurfacePlacement} [placement]
|
|
176
|
+
* @property {string} [description]
|
|
177
|
+
* @property {string[]} root
|
|
178
|
+
* @property {Map<string, SurfaceNode>} nodes
|
|
179
|
+
* @property {Map<string, number>} seq Arrival order of each node id.
|
|
180
|
+
* @property {number} counter
|
|
181
|
+
* @property {Map<string, string>} parent Parent id of each child id; `ROOT` for the top level.
|
|
182
|
+
* @property {Map<string, {owner: string, seq: number}>} names Input names and the node holding them.
|
|
183
|
+
* @property {Record<string, unknown>} data
|
|
184
|
+
* @property {number} dataSize Characters of `data` written as JSON.
|
|
185
|
+
* @property {SurfaceAction[]|null} actions
|
|
186
|
+
* @property {SurfaceSource[]|null} sources
|
|
187
|
+
* @property {boolean} ended
|
|
188
|
+
*/
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* @typedef {Object} Context
|
|
192
|
+
* @property {string} surface
|
|
193
|
+
* @property {SurfaceError[]} errors
|
|
194
|
+
* @property {(path: string) => string} at Maps a path inside the operation to the reported path.
|
|
195
|
+
* @property {Set<string>|null} entities
|
|
196
|
+
*/
|
|
197
|
+
|
|
198
|
+
const ROOT = '\u0000root';
|
|
199
|
+
const OPS = new Set(['begin', 'node', 'patch', 'append', 'remove', 'data', 'actions', 'end']);
|
|
200
|
+
const FORBIDDEN = new Set(FORBIDDEN_KEYS);
|
|
201
|
+
const ID = new RegExp(ID_PATTERN);
|
|
202
|
+
const NAME = new RegExp(NAME_PATTERN);
|
|
203
|
+
const ICON = new RegExp(ICON_PATTERN);
|
|
204
|
+
const HREF = new RegExp(HREF_PATTERN);
|
|
205
|
+
const ASSET = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
|
|
206
|
+
const CONFIRMATION_KEYS = new Set(['confirmation', 'confirm', 'confirmText', 'confirmed', 'policy', 'skipConfirmation', 'noConfirm', 'requireConfirmation', 'requiresConfirmation']);
|
|
207
|
+
const VALUELESS = new Set(['empty', 'filled']);
|
|
208
|
+
/** Properties that define inputs, so names, limits and conditions can be checked: never bound to data. */
|
|
209
|
+
const UNBOUND_PROPS = new Set(['name', 'schema', 'steps']);
|
|
210
|
+
/** An array index as RFC 6901 writes it. */
|
|
211
|
+
const ARRAY_INDEX = /^(?:0|[1-9][0-9]*)$/;
|
|
212
|
+
const INPUT_INTENTS_EXCLUDED = new Set(['show', 'confirm']);
|
|
213
|
+
/** The columns a list of changes is drawn with. */
|
|
214
|
+
const DIFF_COLUMNS = 3;
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Creates the state one stream's operations are validated against.
|
|
218
|
+
* @param {ValidationSettings} [options]
|
|
219
|
+
* @returns {ValidationState}
|
|
220
|
+
*/
|
|
221
|
+
export function createValidationState(options = {}) {
|
|
222
|
+
const entities = options.entities == null ? null : new Set([...options.entities].filter((entity) => typeof entity === 'string'));
|
|
223
|
+
return { entities, surfaces: new Map() };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Validates one operation against the stream's state and the catalog, and records it in the state.
|
|
228
|
+
* @param {unknown} op The operation, as parsed from its line.
|
|
229
|
+
* @param {ValidationState} state From `createValidationState()`.
|
|
230
|
+
* @param {SurfaceCatalog} [catalog=CATALOG] The catalog, or a narrowed one.
|
|
231
|
+
* @returns {OpResult}
|
|
232
|
+
* @throws {TypeError} When the state or the catalog is not one of the library's.
|
|
233
|
+
*/
|
|
234
|
+
export function validateOp(op, state, catalog = CATALOG) {
|
|
235
|
+
if (!state || !(state.surfaces instanceof Map)) throw new TypeError('validateOp() needs a state from createValidationState()');
|
|
236
|
+
assertCatalog(catalog);
|
|
237
|
+
return validateOpAt(op, state, catalog, (path) => path);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Validates a whole document. The result is the document as it may be rendered: repairs applied,
|
|
242
|
+
* inline children lifted, invalid parts dropped, `null` members removed.
|
|
243
|
+
* @param {unknown} document The document.
|
|
244
|
+
* @param {SurfaceCatalog} [catalog=CATALOG] The catalog, or a narrowed one.
|
|
245
|
+
* @param {ValidationSettings} [options]
|
|
246
|
+
* @returns {{document: SurfaceDocument|null, errors: SurfaceError[]}} `document` is `null` when
|
|
247
|
+
* the document could not be read as a surface at all.
|
|
248
|
+
* @throws {TypeError} When the catalog is not one of the library's.
|
|
249
|
+
*/
|
|
250
|
+
export function validateDocument(document, catalog = CATALOG, options = {}) {
|
|
251
|
+
assertCatalog(catalog);
|
|
252
|
+
/** @type {SurfaceError[]} */
|
|
253
|
+
const errors = [];
|
|
254
|
+
if (!isObject(document)) {
|
|
255
|
+
errors.push({ code: 'invalid-op', message: 'A surface document must be an object', path: '' });
|
|
256
|
+
return { document: null, errors };
|
|
257
|
+
}
|
|
258
|
+
const state = createValidationState(options);
|
|
259
|
+
const surface = document.surface;
|
|
260
|
+
/** @param {SurfaceError} error */
|
|
261
|
+
const report = (error) => errors.push(typeof surface === 'string' ? { surface, ...error } : error);
|
|
262
|
+
const known = new Set(['zx', 'surface', 'intent', 'title', 'author', 'root', 'placement', 'description', 'nodes', 'data', 'actions', 'sources']);
|
|
263
|
+
for (const key of Object.keys(document)) {
|
|
264
|
+
if (known.has(key) || document[key] === null) continue;
|
|
265
|
+
if (key === 'token') report({ code: 'token-refused', message: 'A surface cannot set its own token; only the application gives one', path: '/token' });
|
|
266
|
+
else report({ code: FORBIDDEN.has(key) ? 'forbidden-key' : 'unknown-key', message: `Unknown key "${key}"`, path: `/${escapeKey(key)}` });
|
|
267
|
+
}
|
|
268
|
+
/** @param {unknown} op @param {(path: string) => string} at */
|
|
269
|
+
const run = (op, at) => {
|
|
270
|
+
const result = validateOpAt(op, state, catalog, at);
|
|
271
|
+
errors.push(...result.errors);
|
|
272
|
+
return result;
|
|
273
|
+
};
|
|
274
|
+
/** @type {Record<string, unknown>} */
|
|
275
|
+
const begin = { op: 'begin' };
|
|
276
|
+
for (const key of ['zx', 'surface', 'intent', 'title', 'author', 'root', 'placement', 'description']) {
|
|
277
|
+
if (Object.hasOwn(document, key)) begin[key] = document[key];
|
|
278
|
+
}
|
|
279
|
+
if (!run(begin, (path) => path).op) return { document: null, errors };
|
|
280
|
+
const id = /** @type {string} */ (surface);
|
|
281
|
+
|
|
282
|
+
if (present(document.data)) {
|
|
283
|
+
run({ op: 'data', surface: id, path: '', value: document.data }, (path) => path.replace(/^\/value/, '/data'));
|
|
284
|
+
}
|
|
285
|
+
if (present(document.nodes)) {
|
|
286
|
+
if (!Array.isArray(document.nodes)) {
|
|
287
|
+
report({ code: 'invalid-value', message: '"nodes" must be a list of nodes', path: '/nodes' });
|
|
288
|
+
} else {
|
|
289
|
+
if (document.nodes.length > LIMITS.nodes) {
|
|
290
|
+
report({ code: 'limit', message: `A surface has at most ${LIMITS.nodes} nodes; the rest were dropped`, path: '/nodes' });
|
|
291
|
+
}
|
|
292
|
+
document.nodes.slice(0, LIMITS.nodes).forEach((node, index) => {
|
|
293
|
+
const at = (/** @type {string} */ path) => `/nodes/${index}${path}`;
|
|
294
|
+
if (!isObject(node)) {
|
|
295
|
+
report({ code: 'invalid-value', message: 'A node must be an object', path: at('') });
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (Object.hasOwn(node, 'op') || Object.hasOwn(node, 'surface')) {
|
|
299
|
+
report({ code: 'unknown-key', message: 'A node in a document carries no "op" or "surface"', path: at('') });
|
|
300
|
+
}
|
|
301
|
+
run({ ...node, op: 'node', surface: id }, at);
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
} else {
|
|
305
|
+
report({ code: 'missing', message: 'A document needs "nodes", even an empty list', path: '/nodes' });
|
|
306
|
+
}
|
|
307
|
+
if (present(document.actions)) run({ op: 'actions', surface: id, items: document.actions }, (path) => path.replace(/^\/items/, '/actions'));
|
|
308
|
+
/** @type {Record<string, unknown>} */
|
|
309
|
+
const end = { op: 'end', surface: id };
|
|
310
|
+
if (present(document.sources)) end.sources = document.sources;
|
|
311
|
+
run(end, (path) => path);
|
|
312
|
+
return { document: stateToDocument(state, id), errors };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Reads one surface back from a validation state as a document.
|
|
317
|
+
* @param {ValidationState} state
|
|
318
|
+
* @param {string} surface The surface's id.
|
|
319
|
+
* @returns {SurfaceDocument|null} `null` when the surface has not begun.
|
|
320
|
+
*/
|
|
321
|
+
export function stateToDocument(state, surface) {
|
|
322
|
+
const track = state?.surfaces?.get(surface);
|
|
323
|
+
if (!track) return null;
|
|
324
|
+
/** @type {Record<string, unknown>} */
|
|
325
|
+
const out = { zx: SURFACE_VERSION, surface: track.id, intent: track.intent };
|
|
326
|
+
if (track.title !== undefined) out.title = track.title;
|
|
327
|
+
if (track.author !== undefined) out.author = track.author;
|
|
328
|
+
out.root = [...track.root];
|
|
329
|
+
if (track.placement !== undefined) out.placement = track.placement;
|
|
330
|
+
if (track.description !== undefined) out.description = track.description;
|
|
331
|
+
out.nodes = [...track.nodes.values()]
|
|
332
|
+
.sort((a, b) => (track.seq.get(a.id) ?? 0) - (track.seq.get(b.id) ?? 0))
|
|
333
|
+
.map((node) => clone(node));
|
|
334
|
+
if (Object.keys(track.data).length) out.data = clone(track.data);
|
|
335
|
+
if (track.actions) out.actions = clone(track.actions);
|
|
336
|
+
if (track.sources) out.sources = clone(track.sources);
|
|
337
|
+
return /** @type {SurfaceDocument} */ (out);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* The cells a node draws as a table, for the budget of `LIMITS.cells`. Rows bound to data count
|
|
342
|
+
* for every node they are drawn in.
|
|
343
|
+
* @param {SurfaceNode} node @param {unknown} data The surface's data.
|
|
344
|
+
* @returns {number} `0` for anything that is not a table, or has no rows yet.
|
|
345
|
+
*/
|
|
346
|
+
export function tableCells(node, data) {
|
|
347
|
+
if (node.type !== 'table' && node.type !== 'diff') return 0;
|
|
348
|
+
const rows = boundValue(node.rows, data);
|
|
349
|
+
if (!Array.isArray(rows)) return 0;
|
|
350
|
+
const count = Math.min(rows.length, LIMITS.rows);
|
|
351
|
+
if (node.type === 'diff') return count * DIFF_COLUMNS;
|
|
352
|
+
const columns = boundValue(node.columns, data);
|
|
353
|
+
return Array.isArray(columns) ? count * Math.min(columns.length, LIMITS.columns) : 0;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* @param {string} id A table's node id.
|
|
358
|
+
* @returns {string} What a table past the budget is told, here and by the surface drawing it.
|
|
359
|
+
*/
|
|
360
|
+
export function cellLimitMessage(id) {
|
|
361
|
+
return `The tables of a surface hold at most ${LIMITS.cells.toLocaleString('en-US')} cells, each binding counted where it is used; the rows of "${id}" were dropped`;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** @param {unknown} value @param {unknown} data @returns {unknown} The value, a binding read from the data. */
|
|
365
|
+
function boundValue(value, data) {
|
|
366
|
+
if (!isBinding(value)) return value;
|
|
367
|
+
try {
|
|
368
|
+
return getPointer(data, /** @type {string} */ (value.$data));
|
|
369
|
+
} catch {
|
|
370
|
+
return undefined;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Checks a value bound with `{"$data": …}` once it is resolved, as it would have been checked had
|
|
376
|
+
* the model written it into the node.
|
|
377
|
+
* @param {string} type The node type.
|
|
378
|
+
* @param {string} prop The property.
|
|
379
|
+
* @param {unknown} value The resolved value.
|
|
380
|
+
* @param {ValidationSettings & {node?: SurfaceNode}} [options] `node` gives a table's columns, for
|
|
381
|
+
* rows written as lists.
|
|
382
|
+
* @returns {{value: unknown, errors: SurfaceError[]}} `value` is `undefined` when it was dropped.
|
|
383
|
+
*/
|
|
384
|
+
export function validateValue(type, prop, value, options = {}) {
|
|
385
|
+
/** @type {Context} */
|
|
386
|
+
const ctx = {
|
|
387
|
+
surface: '',
|
|
388
|
+
errors: [],
|
|
389
|
+
at: (path) => path,
|
|
390
|
+
entities: options.entities == null ? null : new Set(options.entities)
|
|
391
|
+
};
|
|
392
|
+
const node = typeof type === 'string' && Object.hasOwn(CATALOG.nodes, type) ? CATALOG.nodes[type] : null;
|
|
393
|
+
const entry = node && typeof prop === 'string' && Object.hasOwn(node.props, prop) ? node.props[prop] : null;
|
|
394
|
+
if (!entry) {
|
|
395
|
+
ctx.errors.push({ code: 'unknown-key', message: `"${type}" nodes have no "${prop}"`, path: '' });
|
|
396
|
+
return { value: undefined, errors: ctx.errors };
|
|
397
|
+
}
|
|
398
|
+
if (UNBOUND_PROPS.has(prop)) {
|
|
399
|
+
ctx.errors.push({ code: 'not-allowed', message: `"${prop}" cannot be bound to data`, path: '' });
|
|
400
|
+
return { value: undefined, errors: ctx.errors };
|
|
401
|
+
}
|
|
402
|
+
const clean = sanitize(value, '', 2, ctx);
|
|
403
|
+
if (clean === undefined) return { value: undefined, errors: ctx.errors.map(stripSurface) };
|
|
404
|
+
const checked = checkProp(entry, prop, clean, ctx, '', options.node ?? null);
|
|
405
|
+
return { value: checked, errors: ctx.errors.map(stripSurface) };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/* ------------------------------------------------------------------------------------------------
|
|
409
|
+
* Operations
|
|
410
|
+
* --------------------------------------------------------------------------------------------- */
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* @param {unknown} raw @param {ValidationState} state @param {SurfaceCatalog} catalog
|
|
414
|
+
* @param {(path: string) => string} at
|
|
415
|
+
* @returns {OpResult}
|
|
416
|
+
*/
|
|
417
|
+
function validateOpAt(raw, state, catalog, at) {
|
|
418
|
+
/** @type {SurfaceError[]} */
|
|
419
|
+
const errors = [];
|
|
420
|
+
/** @type {OpResult} */
|
|
421
|
+
const refused = { op: null, errors, ops: [] };
|
|
422
|
+
if (!isObject(raw)) {
|
|
423
|
+
errors.push({ code: 'invalid-op', message: 'An operation must be a JSON object', path: at('') });
|
|
424
|
+
return refused;
|
|
425
|
+
}
|
|
426
|
+
const surface = raw.surface;
|
|
427
|
+
/** @type {Context} */
|
|
428
|
+
const ctx = { surface: typeof surface === 'string' ? surface : '', errors, at, entities: state.entities };
|
|
429
|
+
if (typeof raw.op !== 'string' || !OPS.has(raw.op)) {
|
|
430
|
+
report(ctx, 'unknown-op', `Unknown operation ${describeValue(raw.op)}; use one of ${[...OPS].join(', ')}`, { path: '/op' });
|
|
431
|
+
return refused;
|
|
432
|
+
}
|
|
433
|
+
if (typeof surface !== 'string' || !ID.test(surface)) {
|
|
434
|
+
report(ctx, 'invalid-value', 'Every operation names its "surface" with an id of letters, digits, "_", ".", ":" or "-"', { path: '/surface' });
|
|
435
|
+
return refused;
|
|
436
|
+
}
|
|
437
|
+
const op = raw.op;
|
|
438
|
+
const track = state.surfaces.get(surface);
|
|
439
|
+
if (op === 'begin') {
|
|
440
|
+
if (track) {
|
|
441
|
+
report(ctx, 'duplicate-begin', `The surface "${surface}" has already begun`, { path: '/op' });
|
|
442
|
+
return refused;
|
|
443
|
+
}
|
|
444
|
+
return validateBegin(raw, state, catalog, ctx);
|
|
445
|
+
}
|
|
446
|
+
if (!track) {
|
|
447
|
+
report(ctx, 'no-begin', `The surface "${surface}" has not begun; send "begin" first`, { path: '/op' });
|
|
448
|
+
return refused;
|
|
449
|
+
}
|
|
450
|
+
if (track.ended) {
|
|
451
|
+
report(ctx, 'ended', `The surface "${surface}" has ended`, { path: '/op' });
|
|
452
|
+
return refused;
|
|
453
|
+
}
|
|
454
|
+
switch (op) {
|
|
455
|
+
case 'node': return validateNodeOp(raw, track, catalog, ctx);
|
|
456
|
+
case 'patch': return validatePatch(raw, track, catalog, ctx);
|
|
457
|
+
case 'append': return validateAppend(raw, track, ctx);
|
|
458
|
+
case 'remove': return validateRemove(raw, track, ctx);
|
|
459
|
+
case 'data': return validateData(raw, track, ctx);
|
|
460
|
+
case 'actions': return validateActions(raw, track, ctx);
|
|
461
|
+
default: return validateEnd(raw, track, catalog, ctx);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* @param {Record<string, unknown>} raw @param {ValidationState} state @param {SurfaceCatalog} catalog
|
|
467
|
+
* @param {Context} ctx @returns {OpResult}
|
|
468
|
+
*/
|
|
469
|
+
function validateBegin(raw, state, catalog, ctx) {
|
|
470
|
+
const input = sanitizeOp(raw, ctx);
|
|
471
|
+
checkKeys(input, ['op', 'zx', 'surface', 'intent', 'title', 'author', 'root', 'placement', 'description'], ctx, '');
|
|
472
|
+
if (input.zx !== SURFACE_VERSION) {
|
|
473
|
+
report(ctx, 'version', `"zx" must be "${SURFACE_VERSION}"`, { path: '/zx' });
|
|
474
|
+
return { op: null, errors: ctx.errors, ops: [] };
|
|
475
|
+
}
|
|
476
|
+
/** @type {SurfaceTrack} */
|
|
477
|
+
const track = {
|
|
478
|
+
id: ctx.surface, intent: null, root: [], nodes: new Map(), seq: new Map(), counter: 0, parent: new Map(),
|
|
479
|
+
names: new Map(), data: {}, dataSize: 2, actions: null, sources: null, ended: false
|
|
480
|
+
};
|
|
481
|
+
if (typeof input.intent === 'string' && Object.hasOwn(catalog.intents, input.intent)) {
|
|
482
|
+
track.intent = /** @type {SurfaceIntent} */ (input.intent);
|
|
483
|
+
} else {
|
|
484
|
+
const allowed = Object.keys(catalog.intents);
|
|
485
|
+
report(ctx, 'unknown-intent', `Unknown intent ${JSON.stringify(input.intent ?? null)}; this surface may use ${allowed.join(', ')}. Without an intent it shows no controls.`, { path: '/intent' });
|
|
486
|
+
}
|
|
487
|
+
track.title = text(input, 'title', LIMITS.label, ctx, { required: true });
|
|
488
|
+
const author = text(input, 'author', LIMITS.name, ctx, { required: true });
|
|
489
|
+
if (author !== undefined && !NAME.test(author)) report(ctx, 'invalid-value', '"author" is a key: letters, digits, "_", "." or "-"', { path: '/author' });
|
|
490
|
+
else track.author = author;
|
|
491
|
+
track.description = text(input, 'description', LIMITS.description, ctx);
|
|
492
|
+
if (present(input.placement)) {
|
|
493
|
+
if (PLACEMENTS.includes(/** @type {SurfacePlacement} */ (input.placement))) track.placement = /** @type {SurfacePlacement} */ (input.placement);
|
|
494
|
+
else report(ctx, 'invalid-value', `"placement" must be one of ${PLACEMENTS.join(', ')}`, { path: '/placement' });
|
|
495
|
+
}
|
|
496
|
+
state.surfaces.set(ctx.surface, track);
|
|
497
|
+
/** @type {SurfaceOp[]} */
|
|
498
|
+
const lifted = [];
|
|
499
|
+
if (present(input.root)) {
|
|
500
|
+
track.root = childList(input.root, ROOT, track, catalog, ctx, '/root', lifted);
|
|
501
|
+
} else {
|
|
502
|
+
report(ctx, 'missing', '"begin" needs "root", the list of top-level node ids', { path: '/root' });
|
|
503
|
+
}
|
|
504
|
+
/** @type {SurfaceOp} */
|
|
505
|
+
const op = { op: 'begin', zx: SURFACE_VERSION, surface: ctx.surface, intent: track.intent, root: [...track.root] };
|
|
506
|
+
for (const key of /** @type {const} */ (['title', 'author', 'placement', 'description'])) {
|
|
507
|
+
if (track[key] !== undefined) /** @type {Record<string, unknown>} */ (op)[key] = track[key];
|
|
508
|
+
}
|
|
509
|
+
return { op, errors: ctx.errors, ops: [op, ...lifted] };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* @param {Record<string, unknown>} raw @param {SurfaceTrack} track @param {SurfaceCatalog} catalog
|
|
514
|
+
* @param {Context} ctx @returns {OpResult}
|
|
515
|
+
*/
|
|
516
|
+
function validateNodeOp(raw, track, catalog, ctx) {
|
|
517
|
+
const input = sanitizeOp(raw, ctx);
|
|
518
|
+
/** @type {SurfaceOp[]} */
|
|
519
|
+
const lifted = [];
|
|
520
|
+
const node = validateNode(input, track, catalog, ctx, '', lifted);
|
|
521
|
+
if (!node) return { op: null, errors: ctx.errors, ops: [] };
|
|
522
|
+
const op = /** @type {SurfaceOp} */ ({ op: 'node', surface: ctx.surface, ...node });
|
|
523
|
+
return { op, errors: ctx.errors, ops: [op, ...lifted] };
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Validates a node and records it. Returns the node as it may be applied, or null when refused.
|
|
528
|
+
* @param {Record<string, unknown>} input Sanitized node, possibly still carrying `op` and `surface`.
|
|
529
|
+
* @param {SurfaceTrack} track @param {SurfaceCatalog} catalog @param {Context} ctx
|
|
530
|
+
* @param {string} path Where the node is inside the operation.
|
|
531
|
+
* @param {SurfaceOp[]} lifted Receives the node operations of lifted inline children.
|
|
532
|
+
* @returns {SurfaceNode|null}
|
|
533
|
+
*/
|
|
534
|
+
function validateNode(input, track, catalog, ctx, path, lifted) {
|
|
535
|
+
const id = input.id;
|
|
536
|
+
if (typeof id !== 'string' || !ID.test(id)) {
|
|
537
|
+
report(ctx, typeof id === 'string' ? 'invalid-value' : 'missing', 'A node needs an "id" of letters, digits, "_", ".", ":" or "-"', { path: `${path}/id` });
|
|
538
|
+
return null;
|
|
539
|
+
}
|
|
540
|
+
const exists = track.nodes.has(id);
|
|
541
|
+
if (!exists && track.nodes.size >= LIMITS.nodes) {
|
|
542
|
+
report(ctx, 'limit', `A surface has at most ${LIMITS.nodes} nodes`, { id, path });
|
|
543
|
+
return null;
|
|
544
|
+
}
|
|
545
|
+
const type = input.type;
|
|
546
|
+
/** @type {SurfaceNode} */
|
|
547
|
+
const node = { id, type: typeof type === 'string' ? type : '' };
|
|
548
|
+
const entry = typeof type === 'string' && Object.hasOwn(catalog.nodes, type) ? catalog.nodes[type] : undefined;
|
|
549
|
+
|
|
550
|
+
const release = () => {
|
|
551
|
+
if (!exists) return;
|
|
552
|
+
for (const [name, owner] of track.names) if (owner.owner === id) track.names.delete(name);
|
|
553
|
+
for (const [child, parent] of track.parent) if (parent === id) track.parent.delete(child);
|
|
554
|
+
};
|
|
555
|
+
const record = () => {
|
|
556
|
+
release();
|
|
557
|
+
track.nodes.set(id, node);
|
|
558
|
+
if (!track.seq.has(id)) track.seq.set(id, track.counter++);
|
|
559
|
+
};
|
|
560
|
+
|
|
561
|
+
if (!entry) {
|
|
562
|
+
const known = typeof type === 'string' && Object.hasOwn(CATALOG.nodes, type);
|
|
563
|
+
report(ctx, typeof type === 'string' ? 'unknown-type' : 'missing', typeof type !== 'string'
|
|
564
|
+
? 'A node needs a "type"'
|
|
565
|
+
: known ? `The node type "${type}" is not available in this surface` : `Unknown node type "${type}"; use one of ${Object.keys(catalog.nodes).join(', ')}`, { id, path: `${path}/type` });
|
|
566
|
+
record();
|
|
567
|
+
return node;
|
|
568
|
+
}
|
|
569
|
+
if (entry.intentOnly && entry.intentOnly !== track.intent) {
|
|
570
|
+
report(ctx, 'not-allowed', `A "${entry.type}" node belongs only in a "${entry.intentOnly}" surface`, { id, path: `${path}/type` });
|
|
571
|
+
record();
|
|
572
|
+
return node;
|
|
573
|
+
}
|
|
574
|
+
const inputsBarred = track.intent !== null && INPUT_INTENTS_EXCLUDED.has(track.intent);
|
|
575
|
+
if (entry.input && entry.type !== 'table' && inputsBarred) {
|
|
576
|
+
report(ctx, 'not-allowed', `A "${track.intent}" surface takes no inputs; "${entry.type}" is one`, { id, path: `${path}/type` });
|
|
577
|
+
record();
|
|
578
|
+
return node;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const allowed = new Set(['op', 'surface', 'id', 'type', 'visible', ...Object.keys(entry.props)]);
|
|
582
|
+
if (entry.children) allowed.add('children');
|
|
583
|
+
for (const key of Object.keys(input)) {
|
|
584
|
+
if (allowed.has(key) || input[key] === null) continue;
|
|
585
|
+
unknownKey(key, ctx, `${path}/${escapeKey(key)}`, id);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
release();
|
|
589
|
+
for (const [name, member] of Object.entries(entry.props)) {
|
|
590
|
+
if (!present(input[name])) continue;
|
|
591
|
+
const at = `${path}/${escapeKey(name)}`;
|
|
592
|
+
const value = input[name];
|
|
593
|
+
if (isBinding(value)) {
|
|
594
|
+
if (UNBOUND_PROPS.has(name)) {
|
|
595
|
+
report(ctx, 'not-allowed', `"${name}" defines the surface's inputs and cannot be bound to data; write it into the node`, { id, path: at });
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
const pointer = bindingPointer(value.$data, ctx, `${at}/$data`, id);
|
|
599
|
+
if (pointer !== null) node[name] = { $data: pointer };
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
const checked = checkProp(member, name, value, ctx, at, input, id);
|
|
603
|
+
if (checked !== undefined) node[name] = checked;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
if (entry.type === 'table' && present(node.selectable)) {
|
|
607
|
+
if (inputsBarred) {
|
|
608
|
+
report(ctx, 'not-allowed', `A "${track.intent}" surface takes no inputs; the table is shown without selection`, { id, path: `${path}/selectable` });
|
|
609
|
+
delete node.selectable;
|
|
610
|
+
} else {
|
|
611
|
+
for (const needed of ['name', 'rowId']) {
|
|
612
|
+
if (!present(node[needed])) {
|
|
613
|
+
report(ctx, 'missing', `A selectable table needs "${needed}"; it is shown without selection`, { id, path: `${path}/${needed}` });
|
|
614
|
+
delete node.selectable;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// Input names: unique within the surface, and the order conditions may rely on.
|
|
621
|
+
const seq = track.seq.get(id) ?? track.counter;
|
|
622
|
+
if (entry.input && typeof node.name === 'string' && (entry.type !== 'table' || node.selectable)) {
|
|
623
|
+
const owner = track.names.get(node.name);
|
|
624
|
+
if (owner && owner.owner !== id) {
|
|
625
|
+
report(ctx, 'duplicate-name', `The input name "${node.name}" is already used in this surface`, { id, path: `${path}/name` });
|
|
626
|
+
delete node.name;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
/** @type {string[]} */
|
|
630
|
+
const fieldNames = [];
|
|
631
|
+
if (entry.type === 'fields' && isObject(node.schema) && isObject(node.schema.properties)) {
|
|
632
|
+
const schema = /** @type {{properties: Record<string, any>, required?: string[]}} */ (node.schema);
|
|
633
|
+
let room = LIMITS.fields - countFields(track, id);
|
|
634
|
+
for (const name of Object.keys(schema.properties)) {
|
|
635
|
+
const owner = track.names.get(name);
|
|
636
|
+
if (owner && owner.owner !== id) {
|
|
637
|
+
report(ctx, 'duplicate-name', `The input name "${name}" is already used in this surface`, { id, path: `${path}/schema/properties/${escapeKey(name)}` });
|
|
638
|
+
dropProperty(schema, name);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
if (room <= 0) {
|
|
642
|
+
report(ctx, 'limit', `A surface has at most ${LIMITS.fields} fields`, { id, path: `${path}/schema/properties/${escapeKey(name)}` });
|
|
643
|
+
dropProperty(schema, name);
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
room -= 1;
|
|
647
|
+
fieldNames.push(name);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// Conditions: the grammar now. Which inputs come earlier depends on the tree, which is only
|
|
652
|
+
// known at `end`; there the order is checked depth first from `root`. Within one schema the
|
|
653
|
+
// order is already known, so a property naming itself or a later property is dropped now.
|
|
654
|
+
if (present(input.visible)) {
|
|
655
|
+
const own = new Set(entry.type === 'fields' && isObject(node.schema) && isObject(node.schema.properties) ? Object.keys(node.schema.properties) : []);
|
|
656
|
+
const visible = checkVisible(input.visible, null, ctx, `${path}/visible`, id, 'node', own);
|
|
657
|
+
if (visible) node.visible = visible;
|
|
658
|
+
}
|
|
659
|
+
if (entry.type === 'fields' && isObject(node.schema) && isObject(node.schema.properties)) {
|
|
660
|
+
const schema = /** @type {{properties: Record<string, any>}} */ (node.schema);
|
|
661
|
+
const names = Object.keys(schema.properties);
|
|
662
|
+
names.forEach((name, index) => {
|
|
663
|
+
const hint = schema.properties[name]['x-zx'];
|
|
664
|
+
if (isObject(hint) && present(hint.visible)) {
|
|
665
|
+
const visible = checkVisible(hint.visible, null, ctx, `${path}/schema/properties/${escapeKey(name)}/x-zx/visible`, id, 'node', new Set(names.slice(index)));
|
|
666
|
+
if (visible) hint.visible = visible;
|
|
667
|
+
else delete hint.visible;
|
|
668
|
+
if (!Object.keys(hint).length) delete schema.properties[name]['x-zx'];
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// Recorded before its children, so a lifted child finds its parent and follows it in order.
|
|
674
|
+
record();
|
|
675
|
+
if (entry.children && present(input.children)) {
|
|
676
|
+
node.children = childList(input.children, id, track, catalog, ctx, `${path}/children`, lifted, id);
|
|
677
|
+
}
|
|
678
|
+
if (entry.input && typeof node.name === 'string' && (entry.type !== 'table' || node.selectable)) {
|
|
679
|
+
track.names.set(node.name, { owner: id, seq: track.seq.get(id) ?? seq });
|
|
680
|
+
}
|
|
681
|
+
for (const name of fieldNames) track.names.set(name, { owner: id, seq: track.seq.get(id) ?? seq });
|
|
682
|
+
if (node.children) for (const child of node.children) track.parent.set(child, id);
|
|
683
|
+
return node;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Checks a list of child ids, applies the repairs, and lifts inline children.
|
|
688
|
+
* @param {unknown} value @param {string} parentId `ROOT` or the node's id
|
|
689
|
+
* @param {SurfaceTrack} track @param {SurfaceCatalog} catalog @param {Context} ctx
|
|
690
|
+
* @param {string} path @param {SurfaceOp[]} lifted @param {string} [nodeId]
|
|
691
|
+
* @returns {string[]}
|
|
692
|
+
*/
|
|
693
|
+
function childList(value, parentId, track, catalog, ctx, path, lifted, nodeId) {
|
|
694
|
+
const key = parentId === ROOT ? '"root"' : '"children"';
|
|
695
|
+
if (typeof value === 'string') {
|
|
696
|
+
report(ctx, 'wrapped-list', `${key} must be a list of ids; the single id was wrapped in one`, { id: nodeId, path, repaired: true });
|
|
697
|
+
} else if (!Array.isArray(value)) {
|
|
698
|
+
report(ctx, 'invalid-value', `${key} must be a list of node ids`, { id: nodeId, path });
|
|
699
|
+
return [];
|
|
700
|
+
}
|
|
701
|
+
/** @type {unknown[]} */
|
|
702
|
+
let list = typeof value === 'string' ? [value] : /** @type {unknown[]} */ (value);
|
|
703
|
+
if (list.length > LIMITS.nodes) {
|
|
704
|
+
report(ctx, 'limit', `${key} lists at most ${LIMITS.nodes} ids; the rest were dropped`, { id: nodeId, path });
|
|
705
|
+
list = list.slice(0, LIMITS.nodes);
|
|
706
|
+
}
|
|
707
|
+
const ancestors = new Set(parentId === ROOT ? [] : [parentId, ...ancestorsOf(parentId, track)]);
|
|
708
|
+
const parentDepth = parentId === ROOT ? 0 : depthOf(parentId, track);
|
|
709
|
+
/** @type {string[]} */
|
|
710
|
+
const ids = [];
|
|
711
|
+
/** @type {Array<{node: Record<string, unknown>, path: string}>} */
|
|
712
|
+
const inline = [];
|
|
713
|
+
list.forEach((child, index) => {
|
|
714
|
+
const at = `${path}/${index}`;
|
|
715
|
+
let id = child;
|
|
716
|
+
if (isObject(child)) {
|
|
717
|
+
if (typeof child.id !== 'string' || !ID.test(child.id) || typeof child.type !== 'string') {
|
|
718
|
+
report(ctx, 'invalid-value', 'An inline child needs an "id" and a "type"; send it as its own "node" operation and list its id', { id: nodeId, path: at });
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
report(ctx, 'lifted-child', `The inline node "${child.id}" was lifted out as its own node; list its id instead`, { id: child.id, path: at, repaired: true });
|
|
722
|
+
inline.push({ node: child, path: at });
|
|
723
|
+
id = child.id;
|
|
724
|
+
}
|
|
725
|
+
if (typeof id !== 'string' || !ID.test(id)) {
|
|
726
|
+
report(ctx, 'invalid-value', `${key} must hold node ids`, { id: nodeId, path: at });
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (ids.includes(id)) {
|
|
730
|
+
report(ctx, 'cycle', `"${id}" is listed twice`, { id: nodeId, path: at });
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
if (ancestors.has(id)) {
|
|
734
|
+
report(ctx, 'cycle', `"${id}" cannot be a child of itself or of its own descendant`, { id: nodeId, path: at });
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
const placed = track.parent.get(id);
|
|
738
|
+
if (placed !== undefined && placed !== parentId && stillLists(placed, id, track)) {
|
|
739
|
+
report(ctx, 'cycle', `"${id}" is already placed elsewhere; a node has one place`, { id: nodeId, path: at });
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
if (parentDepth !== null && parentDepth + 1 > LIMITS.depth) {
|
|
743
|
+
report(ctx, 'limit', `The node tree is at most ${LIMITS.depth} deep`, { id: nodeId, path: at });
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
ids.push(id);
|
|
747
|
+
});
|
|
748
|
+
// Children are placed before the inline ones are validated, so those know their depth.
|
|
749
|
+
for (const id of ids) track.parent.set(id, parentId);
|
|
750
|
+
for (const { node, path: at } of inline) {
|
|
751
|
+
if (!ids.includes(/** @type {string} */ (node.id))) continue;
|
|
752
|
+
const sub = validateNode(node, track, catalog, ctx, at, lifted);
|
|
753
|
+
if (sub) lifted.push(/** @type {SurfaceOp} */ ({ op: 'node', surface: ctx.surface, ...sub }));
|
|
754
|
+
}
|
|
755
|
+
// A lifted child's own lifted children were pushed before it; put every parent before its children.
|
|
756
|
+
lifted.sort((a, b) => (track.seq.get(/** @type {{id: string}} */ (a).id) ?? 0) - (track.seq.get(/** @type {{id: string}} */ (b).id) ?? 0));
|
|
757
|
+
return ids;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* @param {Record<string, unknown>} raw @param {SurfaceTrack} track @param {SurfaceCatalog} catalog
|
|
762
|
+
* @param {Context} ctx @returns {OpResult}
|
|
763
|
+
*/
|
|
764
|
+
function validatePatch(raw, track, catalog, ctx) {
|
|
765
|
+
const input = sanitizeOp(raw, ctx);
|
|
766
|
+
checkKeys(input, ['op', 'surface', 'id', 'props'], ctx, '');
|
|
767
|
+
const refused = { op: null, errors: ctx.errors, ops: [] };
|
|
768
|
+
const id = input.id;
|
|
769
|
+
const existing = typeof id === 'string' ? track.nodes.get(id) : undefined;
|
|
770
|
+
if (!existing) {
|
|
771
|
+
report(ctx, 'unknown-node', `There is no node ${JSON.stringify(id ?? null)} to patch`, { path: '/id' });
|
|
772
|
+
return refused;
|
|
773
|
+
}
|
|
774
|
+
if (!isObject(input.props)) {
|
|
775
|
+
report(ctx, 'invalid-value', '"patch" needs "props", an object of properties', { id: existing.id, path: '/props' });
|
|
776
|
+
return refused;
|
|
777
|
+
}
|
|
778
|
+
const props = input.props;
|
|
779
|
+
/** @type {Record<string, unknown>} */
|
|
780
|
+
const merged = { ...existing };
|
|
781
|
+
for (const [key, value] of Object.entries(props)) {
|
|
782
|
+
if (key === 'id' || key === 'type') {
|
|
783
|
+
report(ctx, 'not-allowed', `A patch cannot change "${key}"; send a whole "node" instead`, { id: existing.id, path: `/props/${key}` });
|
|
784
|
+
continue;
|
|
785
|
+
}
|
|
786
|
+
if (value === null) delete merged[key];
|
|
787
|
+
else merged[key] = value;
|
|
788
|
+
}
|
|
789
|
+
/** @type {SurfaceOp[]} */
|
|
790
|
+
const lifted = [];
|
|
791
|
+
// Errors on the merged node can only come from what the patch sets: the rest was clean already.
|
|
792
|
+
let node = validateNode(merged, track, catalog, { ...ctx, at: (path) => ctx.at(path.replace(/^(\/[^/]+)/, '/props$1')) }, '', lifted);
|
|
793
|
+
if (!node) return refused;
|
|
794
|
+
// A value the patch could not set leaves the current one in place, rather than removing it.
|
|
795
|
+
const kept = Object.keys(props).filter((key) => key !== 'id' && key !== 'type' && props[key] !== null
|
|
796
|
+
&& !Object.hasOwn(node, key) && Object.hasOwn(existing, key));
|
|
797
|
+
if (kept.length) {
|
|
798
|
+
for (const key of kept) merged[key] = existing[key];
|
|
799
|
+
node = validateNode(merged, track, catalog, { ...ctx, errors: [] }, '', []) ?? node;
|
|
800
|
+
}
|
|
801
|
+
/** @type {Record<string, unknown>} */
|
|
802
|
+
const applied = {};
|
|
803
|
+
for (const [key, value] of Object.entries(props)) {
|
|
804
|
+
if (key === 'id' || key === 'type') continue;
|
|
805
|
+
if (kept.includes(key)) continue;
|
|
806
|
+
if (Object.hasOwn(node, key)) applied[key] = node[key];
|
|
807
|
+
else if (value === null || Object.hasOwn(existing, key)) applied[key] = null;
|
|
808
|
+
}
|
|
809
|
+
// The fields' own conditions may have been cleaned as the merged node was checked.
|
|
810
|
+
if (Object.hasOwn(props, 'schema') && Object.hasOwn(node, 'schema') && !kept.includes('schema')) applied.schema = node.schema;
|
|
811
|
+
const op = /** @type {SurfaceOp} */ ({ op: 'patch', surface: ctx.surface, id: existing.id, props: clone(applied) });
|
|
812
|
+
return { op, errors: ctx.errors, ops: [op, ...lifted] };
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* @param {Record<string, unknown>} raw @param {SurfaceTrack} track @param {Context} ctx
|
|
817
|
+
* @returns {OpResult}
|
|
818
|
+
*/
|
|
819
|
+
function validateAppend(raw, track, ctx) {
|
|
820
|
+
const input = sanitizeOp(raw, ctx);
|
|
821
|
+
checkKeys(input, ['op', 'surface', 'id', 'text'], ctx, '');
|
|
822
|
+
const refused = { op: null, errors: ctx.errors, ops: [] };
|
|
823
|
+
const node = typeof input.id === 'string' ? track.nodes.get(input.id) : undefined;
|
|
824
|
+
if (!node) {
|
|
825
|
+
report(ctx, 'unknown-node', `There is no node ${JSON.stringify(input.id ?? null)} to append to`, { path: '/id' });
|
|
826
|
+
return refused;
|
|
827
|
+
}
|
|
828
|
+
if (node.type !== 'text' || isBinding(node.text)) {
|
|
829
|
+
report(ctx, 'not-allowed', '"append" adds text to a "text" node whose text is not bound to data', { id: node.id, path: '/id' });
|
|
830
|
+
return refused;
|
|
831
|
+
}
|
|
832
|
+
if (typeof input.text !== 'string') {
|
|
833
|
+
report(ctx, 'invalid-value', '"append" needs "text"', { id: node.id, path: '/text' });
|
|
834
|
+
return refused;
|
|
835
|
+
}
|
|
836
|
+
const current = typeof node.text === 'string' ? node.text : '';
|
|
837
|
+
if (current.length + input.text.length > LIMITS.string) {
|
|
838
|
+
report(ctx, 'limit', `A text node holds at most ${LIMITS.string} characters`, { id: node.id, path: '/text' });
|
|
839
|
+
return refused;
|
|
840
|
+
}
|
|
841
|
+
node.text = current + input.text;
|
|
842
|
+
const op = /** @type {SurfaceOp} */ ({ op: 'append', surface: ctx.surface, id: node.id, text: input.text });
|
|
843
|
+
return { op, errors: ctx.errors, ops: [op] };
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* @param {Record<string, unknown>} raw @param {SurfaceTrack} track @param {Context} ctx
|
|
848
|
+
* @returns {OpResult}
|
|
849
|
+
*/
|
|
850
|
+
function validateRemove(raw, track, ctx) {
|
|
851
|
+
const input = sanitizeOp(raw, ctx);
|
|
852
|
+
checkKeys(input, ['op', 'surface', 'id'], ctx, '');
|
|
853
|
+
const id = input.id;
|
|
854
|
+
if (typeof id !== 'string' || !track.nodes.has(id)) {
|
|
855
|
+
report(ctx, 'unknown-node', `There is no node ${JSON.stringify(id ?? null)} to remove`, { path: '/id' });
|
|
856
|
+
return { op: null, errors: ctx.errors, ops: [] };
|
|
857
|
+
}
|
|
858
|
+
track.nodes.delete(id);
|
|
859
|
+
for (const [name, owner] of track.names) if (owner.owner === id) track.names.delete(name);
|
|
860
|
+
for (const [child, parent] of track.parent) if (parent === id) track.parent.delete(child);
|
|
861
|
+
const parent = track.parent.get(id);
|
|
862
|
+
track.parent.delete(id);
|
|
863
|
+
if (parent === ROOT) track.root = track.root.filter((entry) => entry !== id);
|
|
864
|
+
else if (parent !== undefined) {
|
|
865
|
+
const holder = track.nodes.get(parent);
|
|
866
|
+
if (holder?.children) holder.children = holder.children.filter((entry) => entry !== id);
|
|
867
|
+
}
|
|
868
|
+
const op = /** @type {SurfaceOp} */ ({ op: 'remove', surface: ctx.surface, id });
|
|
869
|
+
return { op, errors: ctx.errors, ops: [op] };
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* @param {Record<string, unknown>} raw @param {SurfaceTrack} track @param {Context} ctx
|
|
874
|
+
* @returns {OpResult}
|
|
875
|
+
*/
|
|
876
|
+
function validateData(raw, track, ctx) {
|
|
877
|
+
const input = sanitizeOp(raw, ctx);
|
|
878
|
+
const removing = input.remove === true;
|
|
879
|
+
checkKeys(input, removing ? ['op', 'surface', 'path', 'remove'] : ['op', 'surface', 'path', 'value', 'remove'], ctx, '');
|
|
880
|
+
const refused = { op: null, errors: ctx.errors, ops: [] };
|
|
881
|
+
const path = input.path;
|
|
882
|
+
if (typeof path !== 'string') {
|
|
883
|
+
report(ctx, 'missing', '"data" needs a "path", a JSON Pointer such as "/rows"', { path: '/path' });
|
|
884
|
+
return refused;
|
|
885
|
+
}
|
|
886
|
+
try {
|
|
887
|
+
parsePointer(path);
|
|
888
|
+
} catch (error) {
|
|
889
|
+
report(ctx, 'pointer-invalid', `${error instanceof Error ? error.message : 'Invalid pointer'}`, { path: '/path' });
|
|
890
|
+
return refused;
|
|
891
|
+
}
|
|
892
|
+
if (present(input.remove) && input.remove !== true) {
|
|
893
|
+
report(ctx, 'invalid-value', '"remove" is true or left out', { path: '/remove' });
|
|
894
|
+
return refused;
|
|
895
|
+
}
|
|
896
|
+
if (!removing && !Object.hasOwn(input, 'value')) {
|
|
897
|
+
report(ctx, 'missing', '"data" needs a "value", or "remove": true', { path: '/value' });
|
|
898
|
+
return refused;
|
|
899
|
+
}
|
|
900
|
+
if (removing && path === '') {
|
|
901
|
+
report(ctx, 'invalid-value', 'The whole data cannot be removed; set "/" paths one by one, or replace it with {}', { path: '/path' });
|
|
902
|
+
return refused;
|
|
903
|
+
}
|
|
904
|
+
if (!removing && path === '' && !isObject(input.value)) {
|
|
905
|
+
report(ctx, 'invalid-value', 'The whole data must be an object', { path: '/value' });
|
|
906
|
+
return refused;
|
|
907
|
+
}
|
|
908
|
+
const applied = applyData(track, parsePointer(path), removing, input.value);
|
|
909
|
+
if (typeof applied === 'object') {
|
|
910
|
+
report(ctx, applied.code, applied.message, { path: applied.code === 'limit' && !removing ? '/value' : '/path' });
|
|
911
|
+
return refused;
|
|
912
|
+
}
|
|
913
|
+
const op = /** @type {SurfaceOp} */ (removing
|
|
914
|
+
? { op: 'data', surface: ctx.surface, path, remove: true }
|
|
915
|
+
: { op: 'data', surface: ctx.surface, path, value: clone(input.value) });
|
|
916
|
+
return { op, errors: ctx.errors, ops: [op] };
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* Stores or removes a data value in place. The whole tree stays within the value depth, and its
|
|
921
|
+
* JSON size is kept up to date from what changes, so an operation costs what it touches rather
|
|
922
|
+
* than what the surface already holds.
|
|
923
|
+
* @param {SurfaceTrack} track @param {string[]} segments @param {boolean} removing @param {unknown} value
|
|
924
|
+
* @returns {true|{code: SurfaceErrorCode, message: string}}
|
|
925
|
+
*/
|
|
926
|
+
function applyData(track, segments, removing, value) {
|
|
927
|
+
const pointer = `/${segments.join('/')}`;
|
|
928
|
+
if (!removing && segments.length + depthOfValue(value) > LIMITS.value) {
|
|
929
|
+
return { code: 'limit', message: `The data nests at most ${LIMITS.value} levels deep, counting the path` };
|
|
930
|
+
}
|
|
931
|
+
const tooBig = { code: /** @type {SurfaceErrorCode} */ ('limit'), message: `A surface holds at most ${LIMITS.data.toLocaleString('en-US')} characters of data` };
|
|
932
|
+
if (segments.length === 0) {
|
|
933
|
+
const size = jsonLength(value);
|
|
934
|
+
if (size > LIMITS.data) return tooBig;
|
|
935
|
+
track.data = /** @type {Record<string, unknown>} */ (clone(value));
|
|
936
|
+
track.dataSize = size;
|
|
937
|
+
return true;
|
|
938
|
+
}
|
|
939
|
+
/** @type {unknown} */
|
|
940
|
+
let parent = track.data;
|
|
941
|
+
for (const segment of segments.slice(0, -1)) {
|
|
942
|
+
if (Array.isArray(parent)) {
|
|
943
|
+
if (!ARRAY_INDEX.test(segment) || Number(segment) >= parent.length) return { code: 'data-path', message: `The path "${pointer}" has no parent to hold the value; set the parent first` };
|
|
944
|
+
parent = parent[Number(segment)];
|
|
945
|
+
} else if (isObject(parent)) {
|
|
946
|
+
if (!Object.hasOwn(parent, segment)) return { code: 'data-path', message: `The path "${pointer}" has no parent to hold the value; set the parent first` };
|
|
947
|
+
parent = parent[segment];
|
|
948
|
+
} else {
|
|
949
|
+
return { code: 'data-path', message: `The path "${pointer}" runs through a value that is not an object or a list` };
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
const key = /** @type {string} */ (segments.at(-1));
|
|
953
|
+
if (Array.isArray(parent)) {
|
|
954
|
+
const index = key === '-' ? parent.length : ARRAY_INDEX.test(key) ? Number(key) : -1;
|
|
955
|
+
const exists = index >= 0 && index < parent.length;
|
|
956
|
+
if (index < 0 || index > parent.length || (removing && !exists)) return { code: 'data-path', message: `"${key}" is not an index of the list at "${pointer}"` };
|
|
957
|
+
if (removing) {
|
|
958
|
+
track.dataSize -= jsonLength(parent[index]) + (parent.length > 1 ? 1 : 0);
|
|
959
|
+
parent.splice(index, 1);
|
|
960
|
+
return true;
|
|
961
|
+
}
|
|
962
|
+
const size = track.dataSize + jsonLength(value) - (exists ? jsonLength(parent[index]) : (parent.length ? -1 : 0));
|
|
963
|
+
if (size > LIMITS.data) return tooBig;
|
|
964
|
+
parent[index] = clone(value);
|
|
965
|
+
track.dataSize = size;
|
|
966
|
+
return true;
|
|
967
|
+
}
|
|
968
|
+
if (!isObject(parent)) return { code: 'data-path', message: `The path "${pointer}" runs through a value that is not an object or a list` };
|
|
969
|
+
const exists = Object.hasOwn(parent, key);
|
|
970
|
+
const member = JSON.stringify(key).length + 1;
|
|
971
|
+
if (removing) {
|
|
972
|
+
if (!exists) return { code: 'data-path', message: `There is nothing at "${pointer}" to remove` };
|
|
973
|
+
track.dataSize -= member + jsonLength(parent[key]) + (hasMembers(parent, 2) ? 1 : 0);
|
|
974
|
+
delete parent[key];
|
|
975
|
+
return true;
|
|
976
|
+
}
|
|
977
|
+
const size = track.dataSize + jsonLength(value) - (exists ? jsonLength(parent[key]) : -(member + (hasMembers(parent, 1) ? 1 : 0)));
|
|
978
|
+
if (size > LIMITS.data) return tooBig;
|
|
979
|
+
parent[key] = clone(value);
|
|
980
|
+
track.dataSize = size;
|
|
981
|
+
return true;
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/**
|
|
985
|
+
* @param {Record<string, unknown>} object @param {number} count
|
|
986
|
+
* @returns {boolean} Whether it has at least that many members, without listing them all.
|
|
987
|
+
*/
|
|
988
|
+
function hasMembers(object, count) {
|
|
989
|
+
let found = 0;
|
|
990
|
+
for (const key in object) {
|
|
991
|
+
if (Object.hasOwn(object, key)) found += 1;
|
|
992
|
+
if (found >= count) return true;
|
|
993
|
+
}
|
|
994
|
+
return false;
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
/** @param {unknown} value @returns {number} Characters of the value written as JSON. */
|
|
998
|
+
function jsonLength(value) {
|
|
999
|
+
return JSON.stringify(value).length;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/** @param {unknown} value @param {number} [level=0] @returns {number} Nesting of objects and lists; 0 for a scalar. */
|
|
1003
|
+
function depthOfValue(value, level = 0) {
|
|
1004
|
+
if (value === null || typeof value !== 'object' || level > LIMITS.value) return 0;
|
|
1005
|
+
let deepest = 0;
|
|
1006
|
+
for (const member of Object.values(value)) deepest = Math.max(deepest, depthOfValue(member, level + 1));
|
|
1007
|
+
return deepest + 1;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/**
|
|
1011
|
+
* @param {Record<string, unknown>} raw @param {SurfaceTrack} track @param {Context} ctx
|
|
1012
|
+
* @returns {OpResult}
|
|
1013
|
+
*/
|
|
1014
|
+
function validateActions(raw, track, ctx) {
|
|
1015
|
+
const input = sanitizeOp(raw, ctx);
|
|
1016
|
+
checkKeys(input, ['op', 'surface', 'items'], ctx, '');
|
|
1017
|
+
if (!Array.isArray(input.items)) {
|
|
1018
|
+
report(ctx, 'invalid-value', '"actions" needs "items", a list of actions', { path: '/items' });
|
|
1019
|
+
return { op: null, errors: ctx.errors, ops: [] };
|
|
1020
|
+
}
|
|
1021
|
+
let items = /** @type {unknown[]} */ (input.items);
|
|
1022
|
+
if (track.intent === 'questionnaire' && items.length) {
|
|
1023
|
+
report(ctx, 'not-allowed', 'A questionnaire answers with its own steps; its actions were dropped', { path: '/items' });
|
|
1024
|
+
items = [];
|
|
1025
|
+
}
|
|
1026
|
+
if (items.length > LIMITS.actions) {
|
|
1027
|
+
report(ctx, 'limit', `A surface has at most ${LIMITS.actions} actions; the rest were dropped`, { path: '/items' });
|
|
1028
|
+
items = items.slice(0, LIMITS.actions);
|
|
1029
|
+
}
|
|
1030
|
+
/** @type {SurfaceAction[]} */
|
|
1031
|
+
const actions = [];
|
|
1032
|
+
items.forEach((item, index) => {
|
|
1033
|
+
const action = checkAction(item, ctx, `/items/${index}`);
|
|
1034
|
+
if (!action) return;
|
|
1035
|
+
if (RESERVED_ACTIONS.includes(action.id)) {
|
|
1036
|
+
report(ctx, 'not-allowed', `The action id "${action.id}" is reserved for closing the surface; the action was dropped`, { id: action.id, path: `/items/${index}/id` });
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
if (actions.some((other) => other.id === action.id)) {
|
|
1040
|
+
report(ctx, 'invalid-value', `The action id "${action.id}" is used twice`, { id: action.id, path: `/items/${index}/id` });
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
actions.push(action);
|
|
1044
|
+
});
|
|
1045
|
+
track.actions = actions;
|
|
1046
|
+
const op = /** @type {SurfaceOp} */ ({ op: 'actions', surface: ctx.surface, items: clone(actions) });
|
|
1047
|
+
return { op, errors: ctx.errors, ops: [op] };
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* @param {unknown} item @param {Context} ctx @param {string} path
|
|
1052
|
+
* @returns {SurfaceAction|null}
|
|
1053
|
+
*/
|
|
1054
|
+
function checkAction(item, ctx, path) {
|
|
1055
|
+
if (!isObject(item)) {
|
|
1056
|
+
report(ctx, 'invalid-value', 'An action must be an object', { path });
|
|
1057
|
+
return null;
|
|
1058
|
+
}
|
|
1059
|
+
for (const key of Object.keys(item)) {
|
|
1060
|
+
if (['id', 'label', 'kind', 'tool', 'description'].includes(key) || item[key] === null) continue;
|
|
1061
|
+
if (CONFIRMATION_KEYS.has(key)) {
|
|
1062
|
+
report(ctx, 'confirmation-ignored', 'An action cannot set its own confirmation; the application decides what each action needs', { id: typeof item.id === 'string' ? item.id : undefined, path: `${path}/${escapeKey(key)}` });
|
|
1063
|
+
} else {
|
|
1064
|
+
unknownKey(key, ctx, `${path}/${escapeKey(key)}`, typeof item.id === 'string' ? item.id : undefined);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
if (typeof item.id !== 'string' || !ID.test(item.id)) {
|
|
1068
|
+
report(ctx, typeof item.id === 'string' ? 'invalid-value' : 'missing', 'An action needs an "id" of letters, digits, "_", ".", ":" or "-"', { path: `${path}/id` });
|
|
1069
|
+
return null;
|
|
1070
|
+
}
|
|
1071
|
+
const id = item.id;
|
|
1072
|
+
const label = text(item, 'label', LIMITS.label, ctx, { required: true, base: path, id });
|
|
1073
|
+
if (!label || !label.trim()) {
|
|
1074
|
+
if (label !== undefined) report(ctx, 'missing', 'An action needs a "label"', { id, path: `${path}/label` });
|
|
1075
|
+
return null;
|
|
1076
|
+
}
|
|
1077
|
+
/** @type {SurfaceAction} */
|
|
1078
|
+
const action = { id, label };
|
|
1079
|
+
if (present(item.kind)) {
|
|
1080
|
+
if (['primary', 'secondary', 'danger'].includes(/** @type {string} */ (item.kind))) action.kind = /** @type {SurfaceAction['kind']} */ (item.kind);
|
|
1081
|
+
else report(ctx, 'invalid-value', '"kind" must be primary, secondary or danger', { id, path: `${path}/kind` });
|
|
1082
|
+
}
|
|
1083
|
+
const tool = text(item, 'tool', 128, ctx, { base: path, id });
|
|
1084
|
+
if (tool !== undefined) {
|
|
1085
|
+
if (/^[A-Za-z0-9_][A-Za-z0-9_.:/-]*$/.test(tool)) action.tool = tool;
|
|
1086
|
+
else report(ctx, 'invalid-value', '"tool" names a tool: letters, digits, "_", ".", ":", "/" or "-"', { id, path: `${path}/tool` });
|
|
1087
|
+
}
|
|
1088
|
+
const description = text(item, 'description', LIMITS.description, ctx, { base: path, id });
|
|
1089
|
+
if (description !== undefined) action.description = description;
|
|
1090
|
+
return action;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
/**
|
|
1094
|
+
* Ends a surface and checks it as a whole: required properties, the intent's needs, the tree and
|
|
1095
|
+
* the order of the inputs its conditions name.
|
|
1096
|
+
* @param {Record<string, unknown>} raw @param {SurfaceTrack} track @param {SurfaceCatalog} catalog
|
|
1097
|
+
* @param {Context} ctx @returns {OpResult}
|
|
1098
|
+
*/
|
|
1099
|
+
function validateEnd(raw, track, catalog, ctx) {
|
|
1100
|
+
const input = sanitizeOp(raw, ctx);
|
|
1101
|
+
checkKeys(input, ['op', 'surface', 'sources'], ctx, '');
|
|
1102
|
+
/** @type {SurfaceOp} */
|
|
1103
|
+
const op = { op: 'end', surface: ctx.surface };
|
|
1104
|
+
if (present(input.sources)) {
|
|
1105
|
+
const sources = checkSources(input.sources, ctx);
|
|
1106
|
+
if (sources) {
|
|
1107
|
+
op.sources = sources;
|
|
1108
|
+
track.sources = sources;
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
/** @type {SurfaceOp[]} */
|
|
1112
|
+
const patches = [];
|
|
1113
|
+
const at = (/** @type {string} */ id) => `/nodes/${escapeKey(id)}`;
|
|
1114
|
+
|
|
1115
|
+
// Depth-first from root: the order inputs are declared in, the depth, and what is missing.
|
|
1116
|
+
/** @type {Set<string>} */
|
|
1117
|
+
const reached = new Set();
|
|
1118
|
+
const seen = new Set();
|
|
1119
|
+
/** @type {Array<{id: string, depth: number}>} */
|
|
1120
|
+
const stack = [...track.root].reverse().map((id) => ({ id, depth: 1 }));
|
|
1121
|
+
while (stack.length) {
|
|
1122
|
+
const { id, depth } = /** @type {{id: string, depth: number}} */ (stack.pop());
|
|
1123
|
+
if (reached.has(id)) continue;
|
|
1124
|
+
const node = track.nodes.get(id);
|
|
1125
|
+
if (!node) {
|
|
1126
|
+
report(ctx, 'missing-node', `The node "${id}" is listed but was never sent`, { id });
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
reached.add(id);
|
|
1130
|
+
const entry = Object.hasOwn(catalog.nodes, node.type) ? catalog.nodes[node.type] : undefined;
|
|
1131
|
+
// Conditions against the inputs that come earlier in the tree.
|
|
1132
|
+
if (node.visible) {
|
|
1133
|
+
const problems = checkCondition(node.visible, { fields: seen, maxDepth: MAX_CONDITION_DEPTH });
|
|
1134
|
+
if (problems.length) {
|
|
1135
|
+
report(ctx, 'condition', `The condition of "${id}" names an input that does not exist or does not come before it in the surface; the condition was dropped and the node stays visible`, { id, path: `${at(id)}/visible` });
|
|
1136
|
+
delete node.visible;
|
|
1137
|
+
patches.push(/** @type {SurfaceOp} */ ({ op: 'patch', surface: ctx.surface, id, props: { visible: null } }));
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
if (node.type === 'fields' && isObject(node.schema) && isObject(node.schema.properties)) {
|
|
1141
|
+
const schema = /** @type {{properties: Record<string, any>}} */ (node.schema);
|
|
1142
|
+
const local = new Set(seen);
|
|
1143
|
+
let changed = false;
|
|
1144
|
+
for (const name of Object.keys(schema.properties)) {
|
|
1145
|
+
const hint = schema.properties[name]['x-zx'];
|
|
1146
|
+
if (isObject(hint) && hint.visible && checkCondition(hint.visible, { fields: local, maxDepth: MAX_CONDITION_DEPTH }).length) {
|
|
1147
|
+
report(ctx, 'condition', `The field "${name}" names an input that does not exist or does not come before it; its condition was dropped and it stays visible`, { id, path: `${at(id)}/schema/properties/${escapeKey(name)}/x-zx/visible` });
|
|
1148
|
+
delete hint.visible;
|
|
1149
|
+
if (!Object.keys(hint).length) delete schema.properties[name]['x-zx'];
|
|
1150
|
+
changed = true;
|
|
1151
|
+
}
|
|
1152
|
+
local.add(name);
|
|
1153
|
+
}
|
|
1154
|
+
if (changed) patches.push(/** @type {SurfaceOp} */ ({ op: 'patch', surface: ctx.surface, id, props: { schema: clone(node.schema) } }));
|
|
1155
|
+
}
|
|
1156
|
+
for (const [name, owner] of track.names) if (owner.owner === id) seen.add(name);
|
|
1157
|
+
if (entry) {
|
|
1158
|
+
for (const [name, member] of Object.entries(entry.props)) {
|
|
1159
|
+
if (member.required && !present(node[name])) {
|
|
1160
|
+
report(ctx, 'missing', `The "${node.type}" node "${id}" needs "${name}"; it is shown as a placeholder`, { id, path: `${at(id)}/${escapeKey(name)}` });
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
if (Array.isArray(node.children)) {
|
|
1165
|
+
const kept = [];
|
|
1166
|
+
for (const child of node.children) {
|
|
1167
|
+
if (depth + 1 > LIMITS.depth) {
|
|
1168
|
+
report(ctx, 'limit', `The node tree is at most ${LIMITS.depth} deep; "${child}" was dropped`, { id, path: `${at(id)}/children` });
|
|
1169
|
+
continue;
|
|
1170
|
+
}
|
|
1171
|
+
kept.push(child);
|
|
1172
|
+
}
|
|
1173
|
+
if (kept.length !== node.children.length) {
|
|
1174
|
+
node.children = kept;
|
|
1175
|
+
patches.push(/** @type {SurfaceOp} */ ({ op: 'patch', surface: ctx.surface, id, props: { children: [...kept] } }));
|
|
1176
|
+
}
|
|
1177
|
+
for (let index = kept.length - 1; index >= 0; index -= 1) stack.push({ id: kept[index], depth: depth + 1 });
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
for (const id of track.nodes.keys()) {
|
|
1181
|
+
if (!reached.has(id)) report(ctx, 'unreachable', `The node "${id}" is not listed in "root" or any "children"; it is not shown`, { id });
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
// The table cells, in the order the tables are drawn.
|
|
1185
|
+
let cells = 0;
|
|
1186
|
+
for (const id of reached) {
|
|
1187
|
+
const node = /** @type {SurfaceNode} */ (track.nodes.get(id));
|
|
1188
|
+
const count = tableCells(node, track.data);
|
|
1189
|
+
if (cells + count <= LIMITS.cells) {
|
|
1190
|
+
cells += count;
|
|
1191
|
+
continue;
|
|
1192
|
+
}
|
|
1193
|
+
report(ctx, 'limit', cellLimitMessage(id), { id, path: `${at(id)}/rows` });
|
|
1194
|
+
delete node.rows;
|
|
1195
|
+
patches.push(/** @type {SurfaceOp} */ ({ op: 'patch', surface: ctx.surface, id, props: { rows: null } }));
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// The intent's needs.
|
|
1199
|
+
if (track.intent) {
|
|
1200
|
+
const entry = Object.hasOwn(catalog.intents, track.intent) ? catalog.intents[track.intent] : undefined;
|
|
1201
|
+
const shown = [...reached].map((id) => /** @type {SurfaceNode} */ (track.nodes.get(id)));
|
|
1202
|
+
const usable = (/** @type {SurfaceNode} */ node) => entry?.requires.includes(node.type) && (node.type !== 'table' || Boolean(node.selectable));
|
|
1203
|
+
if (entry && entry.requires.length) {
|
|
1204
|
+
const found = shown.filter(usable);
|
|
1205
|
+
if (!found.length) {
|
|
1206
|
+
const what = entry.requires.map((type) => (type === 'table' ? 'a selectable "table"' : `a "${type}"`)).join(' or ');
|
|
1207
|
+
report(ctx, 'needs', `A "${track.intent}" surface needs ${what} node`, { path: '/intent' });
|
|
1208
|
+
} else if ((track.intent === 'choose' || track.intent === 'questionnaire') && found.length > 1) {
|
|
1209
|
+
report(ctx, 'needs', `A "${track.intent}" surface has exactly one "${entry.requires[0]}" node`, { path: '/intent' });
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
track.ended = true;
|
|
1214
|
+
return { op, errors: ctx.errors, ops: [...patches, op] };
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/**
|
|
1218
|
+
* @param {unknown} value @param {Context} ctx
|
|
1219
|
+
* @returns {SurfaceSource[]|null}
|
|
1220
|
+
*/
|
|
1221
|
+
function checkSources(value, ctx) {
|
|
1222
|
+
if (!Array.isArray(value)) {
|
|
1223
|
+
report(ctx, 'invalid-value', '"sources" must be a list', { path: '/sources' });
|
|
1224
|
+
return null;
|
|
1225
|
+
}
|
|
1226
|
+
let list = value;
|
|
1227
|
+
if (list.length > LIMITS.sources) {
|
|
1228
|
+
report(ctx, 'limit', `At most ${LIMITS.sources} sources; the rest were dropped`, { path: '/sources' });
|
|
1229
|
+
list = list.slice(0, LIMITS.sources);
|
|
1230
|
+
}
|
|
1231
|
+
/** @type {SurfaceSource[]} */
|
|
1232
|
+
const sources = [];
|
|
1233
|
+
list.forEach((item, index) => {
|
|
1234
|
+
const path = `/sources/${index}`;
|
|
1235
|
+
if (!isObject(item)) {
|
|
1236
|
+
report(ctx, 'invalid-value', 'A source must be an object', { path });
|
|
1237
|
+
return;
|
|
1238
|
+
}
|
|
1239
|
+
checkKeys(item, ['n', 'title', 'call', 'ref'], ctx, path);
|
|
1240
|
+
if (!Number.isInteger(item.n) || /** @type {number} */ (item.n) < 1 || /** @type {number} */ (item.n) > 999) {
|
|
1241
|
+
report(ctx, 'invalid-value', 'A source needs "n", the number of its [n] marker', { path: `${path}/n` });
|
|
1242
|
+
return;
|
|
1243
|
+
}
|
|
1244
|
+
/** @type {SurfaceSource} */
|
|
1245
|
+
const source = { n: /** @type {number} */ (item.n) };
|
|
1246
|
+
const title = text(item, 'title', LIMITS.label, ctx, { base: path });
|
|
1247
|
+
if (title !== undefined) source.title = title;
|
|
1248
|
+
const call = text(item, 'call', 128, ctx, { base: path });
|
|
1249
|
+
if (call !== undefined) source.call = call;
|
|
1250
|
+
if (present(item.ref)) {
|
|
1251
|
+
const ref = checkRef(item.ref, ctx, `${path}/ref`);
|
|
1252
|
+
if (ref) source.ref = ref;
|
|
1253
|
+
}
|
|
1254
|
+
if (sources.some((other) => other.n === source.n)) {
|
|
1255
|
+
report(ctx, 'invalid-value', `Source ${source.n} is listed twice`, { path: `${path}/n` });
|
|
1256
|
+
return;
|
|
1257
|
+
}
|
|
1258
|
+
sources.push(source);
|
|
1259
|
+
});
|
|
1260
|
+
return sources;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/* ------------------------------------------------------------------------------------------------
|
|
1264
|
+
* Values
|
|
1265
|
+
* --------------------------------------------------------------------------------------------- */
|
|
1266
|
+
|
|
1267
|
+
/**
|
|
1268
|
+
* Removes what may not appear anywhere in an operation: forbidden keys, values that are not JSON,
|
|
1269
|
+
* numbers that are not finite, strings over the limit and nesting past the value depth. Returns a
|
|
1270
|
+
* copy; the input is never changed.
|
|
1271
|
+
* @param {Record<string, unknown>} raw @param {Context} ctx
|
|
1272
|
+
* @returns {Record<string, unknown>}
|
|
1273
|
+
*/
|
|
1274
|
+
function sanitizeOp(raw, ctx) {
|
|
1275
|
+
/** @type {Record<string, unknown>} */
|
|
1276
|
+
const out = {};
|
|
1277
|
+
for (const key of Object.keys(raw)) {
|
|
1278
|
+
const value = sanitize(raw[key], `/${escapeKey(key)}`, 2, ctx, key);
|
|
1279
|
+
if (value !== undefined) out[key] = value;
|
|
1280
|
+
}
|
|
1281
|
+
return out;
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
/**
|
|
1285
|
+
* @param {unknown} value @param {string} path @param {number} depth @param {Context} ctx
|
|
1286
|
+
* @param {string} [key] The key holding the value, to report forbidden keys.
|
|
1287
|
+
* @returns {unknown} The cleaned value, or `undefined` when it is dropped.
|
|
1288
|
+
*/
|
|
1289
|
+
function sanitize(value, path, depth, ctx, key) {
|
|
1290
|
+
if (key !== undefined && FORBIDDEN.has(key)) {
|
|
1291
|
+
report(ctx, 'forbidden-key', `The key "${key}" is not allowed`, { path });
|
|
1292
|
+
return undefined;
|
|
1293
|
+
}
|
|
1294
|
+
if (value === null || typeof value === 'boolean') return value;
|
|
1295
|
+
if (typeof value === 'number') {
|
|
1296
|
+
if (Number.isFinite(value)) return value;
|
|
1297
|
+
report(ctx, 'not-finite', 'Numbers must be finite', { path });
|
|
1298
|
+
return undefined;
|
|
1299
|
+
}
|
|
1300
|
+
if (typeof value === 'string') {
|
|
1301
|
+
if (value.length <= LIMITS.string) return value;
|
|
1302
|
+
report(ctx, 'limit', `Strings hold at most ${LIMITS.string} characters`, { path });
|
|
1303
|
+
return undefined;
|
|
1304
|
+
}
|
|
1305
|
+
if (typeof value !== 'object' || value instanceof Date) {
|
|
1306
|
+
report(ctx, 'invalid-value', 'Only JSON values are allowed', { path });
|
|
1307
|
+
return undefined;
|
|
1308
|
+
}
|
|
1309
|
+
if (depth > LIMITS.value) {
|
|
1310
|
+
report(ctx, 'limit', `Values nest at most ${LIMITS.value} levels deep`, { path });
|
|
1311
|
+
return undefined;
|
|
1312
|
+
}
|
|
1313
|
+
if (Array.isArray(value)) {
|
|
1314
|
+
if (value.length > LIMITS.rows) {
|
|
1315
|
+
report(ctx, 'limit', `Lists hold at most ${LIMITS.rows} entries`, { path });
|
|
1316
|
+
return undefined;
|
|
1317
|
+
}
|
|
1318
|
+
/** @type {unknown[]} */
|
|
1319
|
+
const out = [];
|
|
1320
|
+
value.forEach((entry, index) => {
|
|
1321
|
+
const clean = sanitize(entry, `${path}/${index}`, depth + 1, ctx);
|
|
1322
|
+
if (clean !== undefined) out.push(clean);
|
|
1323
|
+
});
|
|
1324
|
+
return out;
|
|
1325
|
+
}
|
|
1326
|
+
const keys = Object.keys(value);
|
|
1327
|
+
if (keys.length > LIMITS.rows) {
|
|
1328
|
+
report(ctx, 'limit', `Objects hold at most ${LIMITS.rows} keys`, { path });
|
|
1329
|
+
return undefined;
|
|
1330
|
+
}
|
|
1331
|
+
/** @type {Record<string, unknown>} */
|
|
1332
|
+
const out = {};
|
|
1333
|
+
for (const member of keys) {
|
|
1334
|
+
const clean = sanitize(/** @type {Record<string, unknown>} */ (value)[member], `${path}/${escapeKey(member)}`, depth + 1, ctx, member);
|
|
1335
|
+
if (clean !== undefined) out[member] = clean;
|
|
1336
|
+
}
|
|
1337
|
+
if (Object.hasOwn(out, '$ref')) return checkRef(out, ctx, path) ?? undefined;
|
|
1338
|
+
if (Object.hasOwn(out, '$asset')) return checkAsset(out, ctx, path) ?? undefined;
|
|
1339
|
+
return out;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
/**
|
|
1343
|
+
* Checks a property's value against its catalog entry.
|
|
1344
|
+
* @param {CatalogProp} member @param {string} name @param {unknown} value @param {Context} ctx
|
|
1345
|
+
* @param {string} path @param {Record<string, unknown>|null} node The node, for context.
|
|
1346
|
+
* @param {string} [id] The node's id.
|
|
1347
|
+
* @returns {unknown} The value, or `undefined` when it is dropped.
|
|
1348
|
+
*/
|
|
1349
|
+
function checkProp(member, name, value, ctx, path, node, id) {
|
|
1350
|
+
const fail = (/** @type {string} */ message, /** @type {SurfaceErrorCode} */ code = 'invalid-value') => {
|
|
1351
|
+
report(ctx, code, message, { id, path });
|
|
1352
|
+
return undefined;
|
|
1353
|
+
};
|
|
1354
|
+
const max = member.max ?? LIMITS.string;
|
|
1355
|
+
if (member.enum) {
|
|
1356
|
+
return member.enum.includes(/** @type {string|number} */ (value)) ? value : fail(`"${name}" must be one of ${member.enum.map((entry) => JSON.stringify(entry)).join(', ')}`);
|
|
1357
|
+
}
|
|
1358
|
+
switch (member.type) {
|
|
1359
|
+
case 'string':
|
|
1360
|
+
if (typeof value !== 'string') return fail(`"${name}" must be text`);
|
|
1361
|
+
if (value.length > max) return fail(`"${name}" holds at most ${max} characters`, 'limit');
|
|
1362
|
+
if ((name === 'name' || name === 'rowId') && !NAME.test(value)) return fail(`"${name}" is a key: a letter or "_", then letters, digits, "_", "." or "-"`);
|
|
1363
|
+
if (name === 'currency' && !/^[A-Z]{3}$/.test(value)) return fail('"currency" is a three-letter ISO 4217 code');
|
|
1364
|
+
return value;
|
|
1365
|
+
case 'integer':
|
|
1366
|
+
return Number.isInteger(value) ? value : fail(`"${name}" must be a whole number`);
|
|
1367
|
+
case 'number':
|
|
1368
|
+
return typeof value === 'number' ? value : fail(`"${name}" must be a number`);
|
|
1369
|
+
case 'boolean':
|
|
1370
|
+
return typeof value === 'boolean' ? value : fail(`"${name}" must be true or false`);
|
|
1371
|
+
case 'number|string':
|
|
1372
|
+
if (typeof value === 'number') return value;
|
|
1373
|
+
if (typeof value !== 'string') return fail(`"${name}" must be a number or text`);
|
|
1374
|
+
return value.length > max ? fail(`"${name}" holds at most ${max} characters`, 'limit') : value;
|
|
1375
|
+
case 'string[]': {
|
|
1376
|
+
if (!Array.isArray(value)) return fail(`"${name}" must be a list of texts`);
|
|
1377
|
+
if (value.length > max) return fail(`"${name}" holds at most ${max} entries`, 'limit');
|
|
1378
|
+
return value.filter((entry, index) => {
|
|
1379
|
+
if (typeof entry === 'string') return true;
|
|
1380
|
+
report(ctx, 'invalid-value', 'Each entry must be text', { id, path: `${path}/${index}` });
|
|
1381
|
+
return false;
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
case 'Href':
|
|
1385
|
+
return checkLink(value, ctx, path, id);
|
|
1386
|
+
case 'Ref':
|
|
1387
|
+
return isObject(value) ? checkRef(value, ctx, path, id) ?? undefined : fail(`"${name}" must be a record {"$ref", "id"}`);
|
|
1388
|
+
case 'Column[]':
|
|
1389
|
+
return listOf(value, max, ctx, path, id, name, (item, at) => checkColumn(item, ctx, at, id), 'id');
|
|
1390
|
+
case 'Row[]':
|
|
1391
|
+
return checkRows(value, max, node, ctx, path, id);
|
|
1392
|
+
case 'Figure[]':
|
|
1393
|
+
return listOf(value, max, ctx, path, id, name, (item, at) => {
|
|
1394
|
+
const row = closed(item, ['label', 'value', 'detail'], ctx, at, id);
|
|
1395
|
+
if (!row) return null;
|
|
1396
|
+
const label = text(row, 'label', LIMITS.label, ctx, { base: at, id, required: true });
|
|
1397
|
+
const figure = row.value;
|
|
1398
|
+
if (label === undefined) return null;
|
|
1399
|
+
if (typeof figure !== 'string' && typeof figure !== 'number') {
|
|
1400
|
+
report(ctx, figure === undefined ? 'missing' : 'invalid-value', 'A figure needs a "value": text or a number', { id, path: `${at}/value` });
|
|
1401
|
+
return null;
|
|
1402
|
+
}
|
|
1403
|
+
/** @type {Record<string, unknown>} */
|
|
1404
|
+
const out = { label, value: figure };
|
|
1405
|
+
const detail = text(row, 'detail', LIMITS.label, ctx, { base: at, id });
|
|
1406
|
+
if (detail !== undefined) out.detail = detail;
|
|
1407
|
+
return out;
|
|
1408
|
+
});
|
|
1409
|
+
case 'ChartData':
|
|
1410
|
+
return checkChartData(value, ctx, path, id);
|
|
1411
|
+
case 'Choice[]':
|
|
1412
|
+
return listOf(value, max, ctx, path, id, name, (item, at) => checkChoice(item, ctx, at, id), 'value');
|
|
1413
|
+
case 'DiffRow[]':
|
|
1414
|
+
return listOf(value, max, ctx, path, id, name, (item, at) => checkDiffRow(item, ctx, at, id), 'id');
|
|
1415
|
+
case 'Schema':
|
|
1416
|
+
return checkSchema(value, ctx, path, id);
|
|
1417
|
+
case 'Step[]':
|
|
1418
|
+
return checkSteps(value, max, ctx, path, id);
|
|
1419
|
+
default:
|
|
1420
|
+
return fail(`"${name}" cannot be checked`);
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
/**
|
|
1425
|
+
* Checks each entry of a list, keeping the ones that pass and, with `unique`, the first of each
|
|
1426
|
+
* value of that member.
|
|
1427
|
+
* @param {unknown} value @param {number} max @param {Context} ctx @param {string} path
|
|
1428
|
+
* @param {string|undefined} id @param {string} name
|
|
1429
|
+
* @param {(item: unknown, path: string) => Record<string, unknown>|null} check
|
|
1430
|
+
* @param {string} [unique]
|
|
1431
|
+
* @returns {Record<string, unknown>[]|undefined}
|
|
1432
|
+
*/
|
|
1433
|
+
function listOf(value, max, ctx, path, id, name, check, unique) {
|
|
1434
|
+
if (!Array.isArray(value)) {
|
|
1435
|
+
report(ctx, 'invalid-value', `"${name}" must be a list`, { id, path });
|
|
1436
|
+
return undefined;
|
|
1437
|
+
}
|
|
1438
|
+
if (value.length > max) {
|
|
1439
|
+
report(ctx, 'limit', `"${name}" holds at most ${max} entries`, { id, path });
|
|
1440
|
+
return undefined;
|
|
1441
|
+
}
|
|
1442
|
+
/** @type {Record<string, unknown>[]} */
|
|
1443
|
+
const out = [];
|
|
1444
|
+
const seen = new Set();
|
|
1445
|
+
value.forEach((item, index) => {
|
|
1446
|
+
const at = `${path}/${index}`;
|
|
1447
|
+
const checked = check(item, at);
|
|
1448
|
+
if (!checked) return;
|
|
1449
|
+
if (unique) {
|
|
1450
|
+
const key = checked[unique];
|
|
1451
|
+
if (seen.has(key)) {
|
|
1452
|
+
report(ctx, 'invalid-value', `"${unique}" ${JSON.stringify(key)} is used twice`, { id, path: `${at}/${unique}` });
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
seen.add(key);
|
|
1456
|
+
}
|
|
1457
|
+
out.push(checked);
|
|
1458
|
+
});
|
|
1459
|
+
return out;
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
/** @param {unknown} item @param {Context} ctx @param {string} path @param {string} [id] */
|
|
1463
|
+
function checkColumn(item, ctx, path, id) {
|
|
1464
|
+
const column = closed(item, ['id', 'label', 'align', 'format', 'currency'], ctx, path, id);
|
|
1465
|
+
if (!column) return null;
|
|
1466
|
+
if (typeof column.id !== 'string' || !NAME.test(column.id)) {
|
|
1467
|
+
report(ctx, column.id === undefined ? 'missing' : 'invalid-value', 'A column needs an "id", the row key it shows', { id, path: `${path}/id` });
|
|
1468
|
+
return null;
|
|
1469
|
+
}
|
|
1470
|
+
const label = text(column, 'label', LIMITS.label, ctx, { base: path, id, required: true });
|
|
1471
|
+
if (label === undefined) return null;
|
|
1472
|
+
/** @type {Record<string, unknown>} */
|
|
1473
|
+
const out = { id: column.id, label };
|
|
1474
|
+
if (present(column.align)) {
|
|
1475
|
+
if (['start', 'center', 'end'].includes(/** @type {string} */ (column.align))) out.align = column.align;
|
|
1476
|
+
else report(ctx, 'invalid-value', '"align" must be start, center or end', { id, path: `${path}/align` });
|
|
1477
|
+
}
|
|
1478
|
+
if (present(column.format)) {
|
|
1479
|
+
if (['text', 'number', 'currency', 'percent', 'date'].includes(/** @type {string} */ (column.format))) out.format = column.format;
|
|
1480
|
+
else report(ctx, 'invalid-value', '"format" must be text, number, currency, percent or date', { id, path: `${path}/format` });
|
|
1481
|
+
}
|
|
1482
|
+
if (present(column.currency)) {
|
|
1483
|
+
if (typeof column.currency === 'string' && /^[A-Z]{3}$/.test(column.currency)) out.currency = column.currency;
|
|
1484
|
+
else report(ctx, 'invalid-value', '"currency" is a three-letter ISO 4217 code', { id, path: `${path}/currency` });
|
|
1485
|
+
}
|
|
1486
|
+
return out;
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/**
|
|
1490
|
+
* Table rows: objects keyed by column id, or lists of cells in column order, which become objects.
|
|
1491
|
+
* @param {unknown} value @param {number} max @param {Record<string, unknown>|null} node
|
|
1492
|
+
* @param {Context} ctx @param {string} path @param {string} [id]
|
|
1493
|
+
* @returns {Record<string, unknown>[]|undefined}
|
|
1494
|
+
*/
|
|
1495
|
+
function checkRows(value, max, node, ctx, path, id) {
|
|
1496
|
+
if (!Array.isArray(value)) {
|
|
1497
|
+
report(ctx, 'invalid-value', '"rows" must be a list of rows', { id, path });
|
|
1498
|
+
return undefined;
|
|
1499
|
+
}
|
|
1500
|
+
if (value.length > max) {
|
|
1501
|
+
report(ctx, 'limit', `A table holds at most ${max} rows`, { id, path });
|
|
1502
|
+
return undefined;
|
|
1503
|
+
}
|
|
1504
|
+
const columns = Array.isArray(node?.columns) && node.columns.every(isObject)
|
|
1505
|
+
? node.columns.map((column) => /** @type {Record<string, unknown>} */ (column).id) : null;
|
|
1506
|
+
/** @type {Record<string, unknown>[]} */
|
|
1507
|
+
const rows = [];
|
|
1508
|
+
value.forEach((row, index) => {
|
|
1509
|
+
const at = `${path}/${index}`;
|
|
1510
|
+
/** @type {Record<string, unknown>} */
|
|
1511
|
+
let object;
|
|
1512
|
+
if (Array.isArray(row)) {
|
|
1513
|
+
if (!columns || columns.some((column) => typeof column !== 'string')) {
|
|
1514
|
+
report(ctx, 'invalid-value', 'A row written as a list needs the table\'s "columns" in the same node', { id, path: at });
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
if (row.length > columns.length) report(ctx, 'invalid-value', 'The row has more cells than the table has columns; the rest were dropped', { id, path: at });
|
|
1518
|
+
// Keyed by column ids the model wrote: a map without a prototype, so no id can reach one.
|
|
1519
|
+
object = Object.create(null);
|
|
1520
|
+
columns.forEach((column, position) => {
|
|
1521
|
+
if (position >= row.length) return;
|
|
1522
|
+
if (!NAME.test(/** @type {string} */ (column))) {
|
|
1523
|
+
report(ctx, FORBIDDEN.has(/** @type {string} */ (column)) ? 'forbidden-key' : 'invalid-value', `"${column}" is not a usable column id; its cell was dropped`, { id, path: `${at}/${position}` });
|
|
1524
|
+
return;
|
|
1525
|
+
}
|
|
1526
|
+
object[/** @type {string} */ (column)] = row[position];
|
|
1527
|
+
});
|
|
1528
|
+
} else if (isObject(row)) {
|
|
1529
|
+
object = row;
|
|
1530
|
+
} else {
|
|
1531
|
+
report(ctx, 'invalid-value', 'A row is an object keyed by column id', { id, path: at });
|
|
1532
|
+
return;
|
|
1533
|
+
}
|
|
1534
|
+
/** @type {Record<string, unknown>} */
|
|
1535
|
+
const out = {};
|
|
1536
|
+
for (const [key, cell] of Object.entries(object)) {
|
|
1537
|
+
const cellPath = Array.isArray(row) ? `${at}/${columns?.indexOf(key)}` : `${at}/${escapeKey(key)}`;
|
|
1538
|
+
if (FORBIDDEN.has(key)) continue;
|
|
1539
|
+
if (!NAME.test(key)) {
|
|
1540
|
+
report(ctx, 'invalid-value', `"${key}" is not a usable column id`, { id, path: cellPath });
|
|
1541
|
+
continue;
|
|
1542
|
+
}
|
|
1543
|
+
if (cell === null || typeof cell === 'string' || typeof cell === 'number' || typeof cell === 'boolean' || (isObject(cell) && Object.hasOwn(cell, '$ref'))) {
|
|
1544
|
+
out[key] = cell;
|
|
1545
|
+
} else {
|
|
1546
|
+
report(ctx, 'invalid-value', 'A cell is text, a number, true or false, null or a record', { id, path: cellPath });
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
rows.push(out);
|
|
1550
|
+
});
|
|
1551
|
+
return rows;
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
/** @param {unknown} value @param {Context} ctx @param {string} path @param {string} [id] */
|
|
1555
|
+
function checkChartData(value, ctx, path, id) {
|
|
1556
|
+
const data = closed(value, ['labels', 'datasets'], ctx, path, id);
|
|
1557
|
+
if (!data) return undefined;
|
|
1558
|
+
const labels = data.labels;
|
|
1559
|
+
if (!Array.isArray(labels) || !labels.every((label) => typeof label === 'string' || typeof label === 'number')) {
|
|
1560
|
+
report(ctx, labels === undefined ? 'missing' : 'invalid-value', 'Chart data needs "labels", a list of texts or numbers', { id, path: `${path}/labels` });
|
|
1561
|
+
return undefined;
|
|
1562
|
+
}
|
|
1563
|
+
const datasets = data.datasets;
|
|
1564
|
+
if (!Array.isArray(datasets) || datasets.length === 0) {
|
|
1565
|
+
report(ctx, datasets === undefined ? 'missing' : 'invalid-value', 'Chart data needs "datasets", a non-empty list', { id, path: `${path}/datasets` });
|
|
1566
|
+
return undefined;
|
|
1567
|
+
}
|
|
1568
|
+
if (datasets.length > LIMITS.datasets) {
|
|
1569
|
+
report(ctx, 'limit', `A chart has at most ${LIMITS.datasets} datasets`, { id, path: `${path}/datasets` });
|
|
1570
|
+
return undefined;
|
|
1571
|
+
}
|
|
1572
|
+
/** @type {Array<{label: string, data: Array<number|null>}>} */
|
|
1573
|
+
const sets = [];
|
|
1574
|
+
datasets.forEach((set, index) => {
|
|
1575
|
+
const at = `${path}/datasets/${index}`;
|
|
1576
|
+
const dataset = closed(set, ['label', 'data'], ctx, at, id);
|
|
1577
|
+
if (!dataset) return;
|
|
1578
|
+
const label = text(dataset, 'label', LIMITS.label, ctx, { base: at, id, required: true });
|
|
1579
|
+
if (label === undefined) return;
|
|
1580
|
+
if (!Array.isArray(dataset.data) || !dataset.data.every((entry) => entry === null || typeof entry === 'number')) {
|
|
1581
|
+
report(ctx, dataset.data === undefined ? 'missing' : 'invalid-value', 'A dataset needs "data", a list of numbers or null', { id, path: `${at}/data` });
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
sets.push({ label, data: /** @type {Array<number|null>} */ (dataset.data) });
|
|
1585
|
+
});
|
|
1586
|
+
return sets.length ? { labels, datasets: sets } : undefined;
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
/** @param {unknown} item @param {Context} ctx @param {string} path @param {string} [id] */
|
|
1590
|
+
function checkChoice(item, ctx, path, id) {
|
|
1591
|
+
const choice = closed(item, ['value', 'label', 'description', 'icon'], ctx, path, id);
|
|
1592
|
+
if (!choice) return null;
|
|
1593
|
+
if (typeof choice.value !== 'string' || choice.value === '' || choice.value.length > LIMITS.label) {
|
|
1594
|
+
report(ctx, choice.value === undefined ? 'missing' : 'invalid-value', 'A choice needs a "value": non-empty text', { id, path: `${path}/value` });
|
|
1595
|
+
return null;
|
|
1596
|
+
}
|
|
1597
|
+
const label = text(choice, 'label', LIMITS.label, ctx, { base: path, id, required: true });
|
|
1598
|
+
if (label === undefined) return null;
|
|
1599
|
+
/** @type {Record<string, unknown>} */
|
|
1600
|
+
const out = { value: choice.value, label };
|
|
1601
|
+
const description = text(choice, 'description', LIMITS.description, ctx, { base: path, id });
|
|
1602
|
+
if (description !== undefined) out.description = description;
|
|
1603
|
+
if (present(choice.icon)) {
|
|
1604
|
+
if (typeof choice.icon === 'string' && ICON.test(choice.icon)) out.icon = choice.icon;
|
|
1605
|
+
else report(ctx, 'invalid-value', '"icon" is an icon name: lowercase letters, digits and "-"', { id, path: `${path}/icon` });
|
|
1606
|
+
}
|
|
1607
|
+
return out;
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
/** @param {unknown} item @param {Context} ctx @param {string} path @param {string} [id] */
|
|
1611
|
+
function checkDiffRow(item, ctx, path, id) {
|
|
1612
|
+
const row = closed(item, ['id', 'field', 'label', 'before', 'after', 'ref'], ctx, path, id);
|
|
1613
|
+
if (!row) return null;
|
|
1614
|
+
if (typeof row.id !== 'string' || !ID.test(row.id)) {
|
|
1615
|
+
report(ctx, row.id === undefined ? 'missing' : 'invalid-value', 'A change needs an "id"', { id, path: `${path}/id` });
|
|
1616
|
+
return null;
|
|
1617
|
+
}
|
|
1618
|
+
if (typeof row.field !== 'string' || !NAME.test(row.field)) {
|
|
1619
|
+
report(ctx, row.field === undefined ? 'missing' : 'invalid-value', 'A change needs a "field", the key of the changed value', { id, path: `${path}/field` });
|
|
1620
|
+
return null;
|
|
1621
|
+
}
|
|
1622
|
+
const label = text(row, 'label', LIMITS.label, ctx, { base: path, id, required: true });
|
|
1623
|
+
if (label === undefined) return null;
|
|
1624
|
+
/** @type {Record<string, unknown>} */
|
|
1625
|
+
const out = { id: row.id, field: row.field, label };
|
|
1626
|
+
for (const key of ['before', 'after']) {
|
|
1627
|
+
const value = Object.hasOwn(row, key) ? row[key] : undefined;
|
|
1628
|
+
if (value === undefined) {
|
|
1629
|
+
report(ctx, 'missing', `A change needs "${key}"; write null for none`, { id, path: `${path}/${key}` });
|
|
1630
|
+
return null;
|
|
1631
|
+
}
|
|
1632
|
+
if (!(value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')) {
|
|
1633
|
+
report(ctx, 'invalid-value', `"${key}" is text, a number, true or false, or null`, { id, path: `${path}/${key}` });
|
|
1634
|
+
return null;
|
|
1635
|
+
}
|
|
1636
|
+
out[key] = value;
|
|
1637
|
+
}
|
|
1638
|
+
if (present(row.ref)) {
|
|
1639
|
+
const ref = isObject(row.ref) ? checkRef(row.ref, ctx, `${path}/ref`, id) : null;
|
|
1640
|
+
if (ref) out.ref = ref;
|
|
1641
|
+
else if (!isObject(row.ref)) report(ctx, 'invalid-value', '"ref" is a record {"$ref", "id"}', { id, path: `${path}/ref` });
|
|
1642
|
+
}
|
|
1643
|
+
return out;
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
/**
|
|
1647
|
+
* An input schema: the list form of `properties` becomes the object form, `null` members are
|
|
1648
|
+
* dropped, and every construct outside the subset is dropped with its property.
|
|
1649
|
+
* @param {unknown} value @param {Context} ctx @param {string} path @param {string} [id]
|
|
1650
|
+
* @returns {Record<string, unknown>|undefined}
|
|
1651
|
+
*/
|
|
1652
|
+
function checkSchema(value, ctx, path, id) {
|
|
1653
|
+
if (!isObject(value)) {
|
|
1654
|
+
report(ctx, 'invalid-value', '"schema" must be a JSON Schema object', { id, path });
|
|
1655
|
+
return undefined;
|
|
1656
|
+
}
|
|
1657
|
+
/** @type {Record<string, unknown>} */
|
|
1658
|
+
const schema = withoutNulls(value);
|
|
1659
|
+
/** @type {Map<string, string>} Property name → its path in the input. */
|
|
1660
|
+
const paths = new Map();
|
|
1661
|
+
if (Array.isArray(schema.properties)) {
|
|
1662
|
+
/** @type {Record<string, unknown>} */
|
|
1663
|
+
const properties = {};
|
|
1664
|
+
schema.properties.forEach((entry, index) => {
|
|
1665
|
+
const at = `${path}/properties/${index}`;
|
|
1666
|
+
if (!isObject(entry) || typeof entry.name !== 'string') {
|
|
1667
|
+
report(ctx, 'invalid-value', 'A property in a list needs a "name"', { id, path: at });
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
// Refused before it becomes a key: `__proto__` would otherwise set the prototype.
|
|
1671
|
+
if (!NAME.test(entry.name)) {
|
|
1672
|
+
report(ctx, FORBIDDEN.has(entry.name) ? 'forbidden-key' : 'invalid-value', `"${entry.name}" is not a usable property name; the property was dropped`, { id, path: `${at}/name` });
|
|
1673
|
+
return;
|
|
1674
|
+
}
|
|
1675
|
+
if (Object.hasOwn(properties, entry.name)) {
|
|
1676
|
+
report(ctx, 'duplicate-name', `The property "${entry.name}" is listed twice`, { id, path: `${at}/name` });
|
|
1677
|
+
return;
|
|
1678
|
+
}
|
|
1679
|
+
const { name, ...property } = entry;
|
|
1680
|
+
properties[name] = property;
|
|
1681
|
+
paths.set(name, at);
|
|
1682
|
+
});
|
|
1683
|
+
schema.properties = properties;
|
|
1684
|
+
} else if (isObject(schema.properties)) {
|
|
1685
|
+
for (const name of Object.keys(schema.properties)) paths.set(name, `${path}/properties/${escapeKey(name)}`);
|
|
1686
|
+
}
|
|
1687
|
+
if (isObject(schema.properties)) {
|
|
1688
|
+
for (const [name, property] of Object.entries(schema.properties)) {
|
|
1689
|
+
if (!isObject(property)) continue;
|
|
1690
|
+
const clean = withoutNulls(property);
|
|
1691
|
+
for (const key of ['items', 'x-zx']) if (isObject(clean[key])) clean[key] = withoutNulls(clean[key]);
|
|
1692
|
+
if (isObject(clean['x-zx']) && isObject(clean['x-zx'].visible)) clean['x-zx'].visible = normalizeCondition(clean['x-zx'].visible);
|
|
1693
|
+
/** @type {Record<string, unknown>} */ (schema.properties)[name] = clean;
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
const problems = unsupported(schema);
|
|
1697
|
+
/** @type {Set<string>} */
|
|
1698
|
+
const dropped = new Set();
|
|
1699
|
+
let whole = false;
|
|
1700
|
+
for (const problem of problems) {
|
|
1701
|
+
const match = /^\/properties\/([^/]+)(.*)$/.exec(problem.path);
|
|
1702
|
+
if (match && isObject(schema.properties)) {
|
|
1703
|
+
const name = match[1].replace(/~1/g, '/').replace(/~0/g, '~');
|
|
1704
|
+
const base = paths.get(name) ?? `${path}/properties/${match[1]}`;
|
|
1705
|
+
report(ctx, 'unsupported-schema', `${problem.message}; the property "${name}" was dropped`, { id, path: `${base}${match[2]}` });
|
|
1706
|
+
dropped.add(name);
|
|
1707
|
+
} else if (problem.path.startsWith('/required')) {
|
|
1708
|
+
report(ctx, 'unsupported-schema', problem.message, { id, path: `${path}${problem.path}` });
|
|
1709
|
+
} else {
|
|
1710
|
+
report(ctx, 'unsupported-schema', problem.message, { id, path: `${path}${problem.path}` });
|
|
1711
|
+
whole = true;
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
if (whole) return undefined;
|
|
1715
|
+
const properties = /** @type {Record<string, Record<string, unknown>>} */ (schema.properties);
|
|
1716
|
+
for (const name of dropped) delete properties[name];
|
|
1717
|
+
if (Array.isArray(schema.required)) {
|
|
1718
|
+
schema.required = schema.required.filter((name) => typeof name === 'string' && Object.hasOwn(properties, name));
|
|
1719
|
+
}
|
|
1720
|
+
for (const [name, property] of Object.entries(properties)) {
|
|
1721
|
+
if (typeof property.title !== 'string' || !property.title.trim()) {
|
|
1722
|
+
report(ctx, 'untitled-property', `The property "${name}" has no "title"; its name is shown instead`, { id, path: `${paths.get(name)}/title` });
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
/** @type {Record<string, unknown>} */
|
|
1726
|
+
const out = { type: 'object', properties };
|
|
1727
|
+
if (Array.isArray(schema.required) && schema.required.length) out.required = schema.required;
|
|
1728
|
+
return out;
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
/**
|
|
1732
|
+
* Questionnaire steps, with their declarative `when`, `next` and `validate`.
|
|
1733
|
+
* @param {unknown} value @param {number} max @param {Context} ctx @param {string} path
|
|
1734
|
+
* @param {string} [id]
|
|
1735
|
+
* @returns {Record<string, unknown>[]|undefined}
|
|
1736
|
+
*/
|
|
1737
|
+
function checkSteps(value, max, ctx, path, id) {
|
|
1738
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
1739
|
+
report(ctx, 'invalid-value', '"steps" must be a non-empty list of steps', { id, path });
|
|
1740
|
+
return undefined;
|
|
1741
|
+
}
|
|
1742
|
+
if (value.length > max) {
|
|
1743
|
+
report(ctx, 'limit', `A questionnaire has at most ${max} steps`, { id, path });
|
|
1744
|
+
return undefined;
|
|
1745
|
+
}
|
|
1746
|
+
/** @type {Record<string, unknown>[]} */
|
|
1747
|
+
const steps = [];
|
|
1748
|
+
/** @type {string[]} */
|
|
1749
|
+
const earlier = [];
|
|
1750
|
+
/** @type {Array<{step: Record<string, unknown>, next: unknown, fields: string[], at: string}>} A `next` can only be checked against the steps that stay. */
|
|
1751
|
+
const branches = [];
|
|
1752
|
+
value.forEach((raw, index) => {
|
|
1753
|
+
const at = `${path}/${index}`;
|
|
1754
|
+
const step = closed(raw, ['name', 'prompt', 'description', 'section', 'required', 'multiple', 'skippable', 'choices', 'input', 'when', 'next', 'validate'], ctx, at, id);
|
|
1755
|
+
if (!step) return;
|
|
1756
|
+
if (typeof step.name !== 'string' || !NAME.test(step.name) || earlier.includes(step.name)) {
|
|
1757
|
+
report(ctx, step.name === undefined ? 'missing' : 'invalid-value', 'A step needs a unique "name"', { id, path: `${at}/name` });
|
|
1758
|
+
return;
|
|
1759
|
+
}
|
|
1760
|
+
const prompt = text(step, 'prompt', LIMITS.label, ctx, { base: at, id, required: true });
|
|
1761
|
+
if (prompt === undefined) return;
|
|
1762
|
+
/** @type {Record<string, unknown>} */
|
|
1763
|
+
const out = { name: step.name, prompt };
|
|
1764
|
+
for (const key of ['description', 'section']) {
|
|
1765
|
+
const member = text(step, key, key === 'description' ? LIMITS.description : LIMITS.label, ctx, { base: at, id });
|
|
1766
|
+
if (member !== undefined) out[key] = member;
|
|
1767
|
+
}
|
|
1768
|
+
for (const key of ['required', 'multiple', 'skippable']) {
|
|
1769
|
+
if (!present(step[key])) continue;
|
|
1770
|
+
if (typeof step[key] === 'boolean') out[key] = step[key];
|
|
1771
|
+
else report(ctx, 'invalid-value', `"${key}" must be true or false`, { id, path: `${at}/${key}` });
|
|
1772
|
+
}
|
|
1773
|
+
if (present(step.choices)) {
|
|
1774
|
+
const choices = listOf(step.choices, LIMITS.choices, ctx, `${at}/choices`, id, 'choices', (item, where) => checkChoice(item, ctx, where, id), 'value');
|
|
1775
|
+
if (choices) out.choices = choices;
|
|
1776
|
+
}
|
|
1777
|
+
if (present(step.input)) {
|
|
1778
|
+
const input = closed(step.input, ['label', 'placeholder', 'multiline', 'maxLength'], ctx, `${at}/input`, id);
|
|
1779
|
+
if (input) {
|
|
1780
|
+
/** @type {Record<string, unknown>} */
|
|
1781
|
+
const field = {};
|
|
1782
|
+
for (const key of ['label', 'placeholder']) {
|
|
1783
|
+
const member = text(input, key, LIMITS.label, ctx, { base: `${at}/input`, id });
|
|
1784
|
+
if (member !== undefined) field[key] = member;
|
|
1785
|
+
}
|
|
1786
|
+
if (present(input.multiline)) {
|
|
1787
|
+
if (typeof input.multiline === 'boolean') field.multiline = input.multiline;
|
|
1788
|
+
else report(ctx, 'invalid-value', '"multiline" must be true or false', { id, path: `${at}/input/multiline` });
|
|
1789
|
+
}
|
|
1790
|
+
if (present(input.maxLength)) {
|
|
1791
|
+
if (Number.isInteger(input.maxLength) && /** @type {number} */ (input.maxLength) >= 0 && /** @type {number} */ (input.maxLength) <= LIMITS.string) field.maxLength = input.maxLength;
|
|
1792
|
+
else report(ctx, 'invalid-value', `"maxLength" is a whole number up to ${LIMITS.string}`, { id, path: `${at}/input/maxLength` });
|
|
1793
|
+
}
|
|
1794
|
+
out.input = field;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
if (present(step.when)) {
|
|
1798
|
+
const when = checkVisible(step.when, new Set(earlier), ctx, `${at}/when`, id, 'step');
|
|
1799
|
+
if (when) out.when = when;
|
|
1800
|
+
}
|
|
1801
|
+
if (present(step.next)) {
|
|
1802
|
+
const next = typeof step.next === 'string' ? step.next : Array.isArray(step.next)
|
|
1803
|
+
? step.next.map((branch) => {
|
|
1804
|
+
if (!isObject(branch)) return branch;
|
|
1805
|
+
const copy = withoutNulls(branch);
|
|
1806
|
+
if (isObject(copy.if)) copy.if = normalizeCondition(copy.if);
|
|
1807
|
+
return copy;
|
|
1808
|
+
})
|
|
1809
|
+
: step.next;
|
|
1810
|
+
branches.push({ step: out, next, fields: [...earlier, step.name], at });
|
|
1811
|
+
}
|
|
1812
|
+
if (present(step.validate)) {
|
|
1813
|
+
const rules = Array.isArray(step.validate) ? step.validate.map((rule) => (isObject(rule) ? withoutNulls(rule) : rule)) : step.validate;
|
|
1814
|
+
const problems = checkRuleList(rules);
|
|
1815
|
+
if (problems.length) {
|
|
1816
|
+
for (const problem of problems) report(ctx, 'invalid-value', `"validate": ${problem.message}; it was dropped`, { id, path: `${at}/validate${problem.path}` });
|
|
1817
|
+
} else {
|
|
1818
|
+
out.validate = rules;
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
earlier.push(step.name);
|
|
1822
|
+
steps.push(out);
|
|
1823
|
+
});
|
|
1824
|
+
for (const { step, next, fields, at } of branches) {
|
|
1825
|
+
const targets = earlier.filter((name) => name !== step.name);
|
|
1826
|
+
const problems = checkNext(next, { targets: [...targets, NEXT_REVIEW, NEXT_SUBMIT], fields });
|
|
1827
|
+
if (problems.length) {
|
|
1828
|
+
for (const problem of problems) report(ctx, 'condition', `"next": ${problem.message}; it was dropped`, { id, path: `${at}/next${problem.path}` });
|
|
1829
|
+
} else {
|
|
1830
|
+
step.next = next;
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
for (const { step, at } of branches) {
|
|
1834
|
+
if (!leadsBack(step, steps)) continue;
|
|
1835
|
+
report(ctx, 'condition', `"next" can lead back to "${step.name}", so the questionnaire might never end; it was dropped`, { id, path: `${at}/next` });
|
|
1836
|
+
delete step.next;
|
|
1837
|
+
}
|
|
1838
|
+
return steps.length ? steps : undefined;
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
/**
|
|
1842
|
+
* Whether a step's `next` can lead back to the step. Only a jump back can close a cycle, as every
|
|
1843
|
+
* other way on goes forward: from there the walk is followed along every `next` and through every
|
|
1844
|
+
* step it falls through to, which a list of branches may do, and past every step with a `when`,
|
|
1845
|
+
* which may be hidden. So a list that could still go elsewhere counts as going back.
|
|
1846
|
+
* @param {Record<string, any>} step @param {Array<Record<string, any>>} steps
|
|
1847
|
+
* @returns {boolean}
|
|
1848
|
+
*/
|
|
1849
|
+
function leadsBack(step, steps) {
|
|
1850
|
+
if (step.next === undefined) return false;
|
|
1851
|
+
const positions = new Map(steps.map((entry, position) => [entry.name, position]));
|
|
1852
|
+
const target = (/** @type {Record<string, any>} */ entry) => (entry.next === undefined ? []
|
|
1853
|
+
: typeof entry.next === 'string' ? [entry.next] : entry.next.map((/** @type {{goto: string}} */ branch) => branch.goto))
|
|
1854
|
+
.filter((/** @type {string} */ name) => positions.has(name));
|
|
1855
|
+
// Where a walk arrives at a step: there, and on past it while it may be hidden.
|
|
1856
|
+
const landing = (/** @type {number} */ position) => {
|
|
1857
|
+
const out = [];
|
|
1858
|
+
for (let at = position; at < steps.length; at += 1) {
|
|
1859
|
+
out.push(at);
|
|
1860
|
+
if (!steps[at].when) break;
|
|
1861
|
+
}
|
|
1862
|
+
return out;
|
|
1863
|
+
};
|
|
1864
|
+
const following = (/** @type {number} */ position) => {
|
|
1865
|
+
const entry = steps[position];
|
|
1866
|
+
const out = target(entry).flatMap((/** @type {string} */ name) => landing(/** @type {number} */ (positions.get(name))));
|
|
1867
|
+
const fallsThrough = entry.next === undefined || (Array.isArray(entry.next) && Object.hasOwn(entry.next.at(-1), 'if'));
|
|
1868
|
+
return fallsThrough ? [...out, ...landing(position + 1)] : out;
|
|
1869
|
+
};
|
|
1870
|
+
const own = /** @type {number} */ (positions.get(step.name));
|
|
1871
|
+
const pending = target(step).filter((name) => /** @type {number} */ (positions.get(name)) <= own)
|
|
1872
|
+
.flatMap((name) => landing(/** @type {number} */ (positions.get(name))));
|
|
1873
|
+
const seen = new Set();
|
|
1874
|
+
while (pending.length) {
|
|
1875
|
+
const position = /** @type {number} */ (pending.pop());
|
|
1876
|
+
if (position === own) return true;
|
|
1877
|
+
if (seen.has(position)) continue;
|
|
1878
|
+
seen.add(position);
|
|
1879
|
+
pending.push(...following(position));
|
|
1880
|
+
}
|
|
1881
|
+
return false;
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
/**
|
|
1885
|
+
* A `visible` or `when` condition: the grammar, at most four levels, and — when `fields` is given
|
|
1886
|
+
* — only those inputs. Names in `later` are refused outright: inputs known to come after it.
|
|
1887
|
+
* @param {unknown} value @param {Set<string>|null} fields @param {Context} ctx @param {string} path
|
|
1888
|
+
* @param {string} [id] @param {'node'|'step'} [kind='node'] @param {Set<string>} [later]
|
|
1889
|
+
* @returns {Condition|undefined}
|
|
1890
|
+
*/
|
|
1891
|
+
function checkVisible(value, fields, ctx, path, id, kind = 'node', later = new Set()) {
|
|
1892
|
+
const condition = normalizeCondition(value);
|
|
1893
|
+
const problems = checkCondition(condition, { fields, maxDepth: MAX_CONDITION_DEPTH });
|
|
1894
|
+
if (!problems.length) {
|
|
1895
|
+
const named = conditionFields(condition).find((field) => later.has(field));
|
|
1896
|
+
if (named === undefined) return /** @type {Condition} */ (condition);
|
|
1897
|
+
problems.push({ path: '', message: `"${named}" is not an input declared before this condition` });
|
|
1898
|
+
}
|
|
1899
|
+
const effect = kind === 'step' ? 'the condition was dropped and the step is always asked' : 'the condition was dropped and the node stays visible';
|
|
1900
|
+
for (const problem of problems) {
|
|
1901
|
+
const message = problem.message.endsWith('is not an input declared before this condition')
|
|
1902
|
+
? problem.message.replace('is not an input declared before this condition', 'is not an input that comes earlier in the surface')
|
|
1903
|
+
: problem.message;
|
|
1904
|
+
report(ctx, 'condition', `${message}; ${effect}`, { id, path: `${path}${problem.path}` });
|
|
1905
|
+
}
|
|
1906
|
+
return undefined;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
/**
|
|
1910
|
+
* The input names a well-formed condition tests.
|
|
1911
|
+
* @param {unknown} condition @param {number} [depth=0]
|
|
1912
|
+
* @returns {string[]}
|
|
1913
|
+
*/
|
|
1914
|
+
function conditionFields(condition, depth = 0) {
|
|
1915
|
+
if (!isObject(condition) || depth > MAX_CONDITION_DEPTH) return [];
|
|
1916
|
+
if (Array.isArray(condition.all)) return condition.all.flatMap((entry) => conditionFields(entry, depth + 1));
|
|
1917
|
+
if (Array.isArray(condition.any)) return condition.any.flatMap((entry) => conditionFields(entry, depth + 1));
|
|
1918
|
+
if (Object.hasOwn(condition, 'not')) return conditionFields(condition.not, depth + 1);
|
|
1919
|
+
return typeof condition.field === 'string' ? [condition.field] : [];
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
/**
|
|
1923
|
+
* Brings a condition written for strict structured output back to the grammar: `null` members are
|
|
1924
|
+
* absent, and an `empty` or `filled` test carries no value.
|
|
1925
|
+
* @param {unknown} value @param {number} [depth=0]
|
|
1926
|
+
* @returns {unknown}
|
|
1927
|
+
*/
|
|
1928
|
+
function normalizeCondition(value, depth = 0) {
|
|
1929
|
+
if (!isObject(value) || depth > MAX_CONDITION_DEPTH + 1) return value;
|
|
1930
|
+
const condition = withoutNulls(value);
|
|
1931
|
+
if (Array.isArray(condition.all)) condition.all = condition.all.map((entry) => normalizeCondition(entry, depth + 1));
|
|
1932
|
+
if (Array.isArray(condition.any)) condition.any = condition.any.map((entry) => normalizeCondition(entry, depth + 1));
|
|
1933
|
+
if (Object.hasOwn(condition, 'not')) condition.not = normalizeCondition(condition.not, depth + 1);
|
|
1934
|
+
if (VALUELESS.has(/** @type {string} */ (condition.op)) && Object.hasOwn(value, 'value') && value.value === null) delete condition.value;
|
|
1935
|
+
if (!VALUELESS.has(/** @type {string} */ (condition.op)) && Object.hasOwn(value, 'value') && value.value === null && Object.hasOwn(value, 'field')) condition.value = null;
|
|
1936
|
+
return condition;
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
/**
|
|
1940
|
+
* A link address, checked and normalised: `https:` only, absolute, in lower case, without
|
|
1941
|
+
* credentials, spaces, backslashes, control or invisible formatting characters, at most
|
|
1942
|
+
* `LIMITS.href` characters, and passing `safeHref()`. The address returned is the parsed one
|
|
1943
|
+
* (`url.href`: Punycode host, default port dropped), so the host shown and the address opened come
|
|
1944
|
+
* from the same string. Pure: it reports nothing, and is shared by every place that opens an
|
|
1945
|
+
* address a surface or a server gave.
|
|
1946
|
+
* @param {unknown} value The address as given.
|
|
1947
|
+
* @returns {{href: string, problem: null}|{href: null, problem: string}} The normalised address,
|
|
1948
|
+
* or why it is refused (English, written for the model).
|
|
1949
|
+
*/
|
|
1950
|
+
export function normaliseLink(value) {
|
|
1951
|
+
const refuse = (/** @type {string} */ problem) => ({ href: null, problem });
|
|
1952
|
+
if (typeof value !== 'string') return refuse('A link address is text');
|
|
1953
|
+
if (value.length > LIMITS.href) return refuse(`A link address holds at most ${LIMITS.href} characters`);
|
|
1954
|
+
if (!HREF.test(value) || /\p{Cf}/u.test(value)) {
|
|
1955
|
+
return refuse('A link must be an absolute "https://" address, in lower case, without credentials, spaces, backslashes, control or invisible formatting characters');
|
|
1956
|
+
}
|
|
1957
|
+
/** @type {URL} */
|
|
1958
|
+
let url;
|
|
1959
|
+
try {
|
|
1960
|
+
url = new URL(value);
|
|
1961
|
+
} catch {
|
|
1962
|
+
return refuse('The link address is malformed');
|
|
1963
|
+
}
|
|
1964
|
+
if (url.protocol !== 'https:' || !url.hostname) return refuse('A link must be an absolute "https://" address');
|
|
1965
|
+
if (url.username || url.password) return refuse('A link address carries no user name or password');
|
|
1966
|
+
const href = url.href;
|
|
1967
|
+
if (href.length > LIMITS.href || !HREF.test(href) || safeHref(href) === null) return refuse('The link address is not safe');
|
|
1968
|
+
return { href, problem: null };
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
/**
|
|
1972
|
+
* A link address through `normaliseLink()`; a refused one is reported and dropped.
|
|
1973
|
+
* @param {unknown} value @param {Context} ctx @param {string} path @param {string} [id]
|
|
1974
|
+
* @returns {string|undefined}
|
|
1975
|
+
*/
|
|
1976
|
+
function checkLink(value, ctx, path, id) {
|
|
1977
|
+
const link = normaliseLink(value);
|
|
1978
|
+
if (link.href !== null) return link.href;
|
|
1979
|
+
report(ctx, 'link-refused', `${link.problem}; the link was dropped`, { id, path });
|
|
1980
|
+
return undefined;
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
/**
|
|
1984
|
+
* A record: exactly `{"$ref", "id"}`, naming an entity the application offers.
|
|
1985
|
+
* @param {Record<string, unknown>} value @param {Context} ctx @param {string} path @param {string} [id]
|
|
1986
|
+
* @returns {{$ref: string, id: string}|null}
|
|
1987
|
+
*/
|
|
1988
|
+
function checkRef(value, ctx, path, id) {
|
|
1989
|
+
if (!isObject(value)) {
|
|
1990
|
+
report(ctx, 'invalid-value', 'A record is {"$ref": "<entity>", "id": "…"}', { id, path });
|
|
1991
|
+
return null;
|
|
1992
|
+
}
|
|
1993
|
+
const keys = Object.keys(value);
|
|
1994
|
+
if (keys.some((key) => key !== '$ref' && key !== 'id') || typeof value.$ref !== 'string' || typeof value.id !== 'string' || value.id === '' || value.id.length > LIMITS.label) {
|
|
1995
|
+
report(ctx, 'invalid-value', 'A record is exactly {"$ref": "<entity>", "id": "…"}, both text', { id, path });
|
|
1996
|
+
return null;
|
|
1997
|
+
}
|
|
1998
|
+
if (!ctx.entities || !ctx.entities.has(value.$ref)) {
|
|
1999
|
+
report(ctx, 'ref-refused', `The entity "${value.$ref}" is not one this application resolves; the record was dropped`, { id, path });
|
|
2000
|
+
return null;
|
|
2001
|
+
}
|
|
2002
|
+
return { $ref: value.$ref, id: value.id };
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
/**
|
|
2006
|
+
* An image the application provides: exactly `{"$asset": "<name>"}`. A name, never an address.
|
|
2007
|
+
* @param {Record<string, unknown>} value @param {Context} ctx @param {string} path
|
|
2008
|
+
* @returns {{$asset: string}|null}
|
|
2009
|
+
*/
|
|
2010
|
+
function checkAsset(value, ctx, path) {
|
|
2011
|
+
if (Object.keys(value).length !== 1 || typeof value.$asset !== 'string' || !ASSET.test(value.$asset)) {
|
|
2012
|
+
report(ctx, 'invalid-value', 'An asset is exactly {"$asset": "<name>"}: a name the application resolves, never an address', { path });
|
|
2013
|
+
return null;
|
|
2014
|
+
}
|
|
2015
|
+
return { $asset: value.$asset };
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2018
|
+
/**
|
|
2019
|
+
* A `$data` pointer, with the leading-slash repair.
|
|
2020
|
+
* @param {unknown} pointer @param {Context} ctx @param {string} path @param {string} [id]
|
|
2021
|
+
* @returns {string|null}
|
|
2022
|
+
*/
|
|
2023
|
+
function bindingPointer(pointer, ctx, path, id) {
|
|
2024
|
+
if (typeof pointer !== 'string') {
|
|
2025
|
+
report(ctx, 'pointer-invalid', '"$data" is a JSON Pointer such as "/rows"', { id, path });
|
|
2026
|
+
return null;
|
|
2027
|
+
}
|
|
2028
|
+
let value = pointer;
|
|
2029
|
+
if (value !== '' && !value.startsWith('/')) {
|
|
2030
|
+
value = `/${value}`;
|
|
2031
|
+
report(ctx, 'pointer-slash', `A pointer starts with "/"; "${pointer}" was read as "${value}"`, { id, path, repaired: true });
|
|
2032
|
+
}
|
|
2033
|
+
try {
|
|
2034
|
+
parsePointer(value);
|
|
2035
|
+
} catch (error) {
|
|
2036
|
+
report(ctx, 'pointer-invalid', error instanceof Error ? error.message : 'Invalid pointer', { id, path });
|
|
2037
|
+
return null;
|
|
2038
|
+
}
|
|
2039
|
+
return value;
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
/**
|
|
2043
|
+
* Reads an optional or required text member.
|
|
2044
|
+
* @param {Record<string, unknown>} object @param {string} key @param {number} max @param {Context} ctx
|
|
2045
|
+
* @param {{required?: boolean, base?: string, id?: string}} [options]
|
|
2046
|
+
* @returns {string|undefined}
|
|
2047
|
+
*/
|
|
2048
|
+
function text(object, key, max, ctx, options = {}) {
|
|
2049
|
+
const value = object[key];
|
|
2050
|
+
const path = `${options.base ?? ''}/${key}`;
|
|
2051
|
+
if (!present(value)) {
|
|
2052
|
+
if (options.required) report(ctx, 'missing', `"${key}" is required`, { id: options.id, path });
|
|
2053
|
+
return undefined;
|
|
2054
|
+
}
|
|
2055
|
+
if (typeof value !== 'string') {
|
|
2056
|
+
report(ctx, 'invalid-value', `"${key}" must be text`, { id: options.id, path });
|
|
2057
|
+
return undefined;
|
|
2058
|
+
}
|
|
2059
|
+
if (value.length > max) {
|
|
2060
|
+
report(ctx, 'limit', `"${key}" holds at most ${max} characters`, { id: options.id, path });
|
|
2061
|
+
return undefined;
|
|
2062
|
+
}
|
|
2063
|
+
return value;
|
|
2064
|
+
}
|
|
2065
|
+
|
|
2066
|
+
/**
|
|
2067
|
+
* An object with a closed set of members: unknown ones are reported and `null` ones dropped.
|
|
2068
|
+
* @param {unknown} value @param {string[]} keys @param {Context} ctx @param {string} path @param {string} [id]
|
|
2069
|
+
* @returns {Record<string, unknown>|null}
|
|
2070
|
+
*/
|
|
2071
|
+
function closed(value, keys, ctx, path, id) {
|
|
2072
|
+
if (!isObject(value)) {
|
|
2073
|
+
report(ctx, 'invalid-value', 'Expected an object', { id, path });
|
|
2074
|
+
return null;
|
|
2075
|
+
}
|
|
2076
|
+
checkKeys(value, keys, ctx, path, id);
|
|
2077
|
+
/** @type {Record<string, unknown>} */
|
|
2078
|
+
const out = {};
|
|
2079
|
+
for (const key of keys) if (present(value[key])) out[key] = value[key];
|
|
2080
|
+
return out;
|
|
2081
|
+
}
|
|
2082
|
+
|
|
2083
|
+
/**
|
|
2084
|
+
* Reports the keys of an object outside a set; `null` ones count as absent.
|
|
2085
|
+
* @param {Record<string, unknown>} value @param {string[]} keys @param {Context} ctx @param {string} path
|
|
2086
|
+
* @param {string} [id]
|
|
2087
|
+
*/
|
|
2088
|
+
function checkKeys(value, keys, ctx, path, id) {
|
|
2089
|
+
for (const key of Object.keys(value)) {
|
|
2090
|
+
if (keys.includes(key) || value[key] === null) continue;
|
|
2091
|
+
unknownKey(key, ctx, `${path}/${escapeKey(key)}`, id);
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
/** @param {string} key @param {Context} ctx @param {string} path @param {string} [id] */
|
|
2096
|
+
function unknownKey(key, ctx, path, id) {
|
|
2097
|
+
if (key === 'token') report(ctx, 'token-refused', 'A surface cannot set its own token; only the application gives one', { id, path });
|
|
2098
|
+
else report(ctx, 'unknown-key', `Unknown key "${key}"; it was dropped`, { id, path });
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
/**
|
|
2102
|
+
* @param {Context} ctx @param {SurfaceErrorCode} code @param {string} message
|
|
2103
|
+
* @param {{id?: string, path?: string, repaired?: boolean}} [where]
|
|
2104
|
+
*/
|
|
2105
|
+
function report(ctx, code, message, where = {}) {
|
|
2106
|
+
/** @type {SurfaceError} */
|
|
2107
|
+
const error = { code, message };
|
|
2108
|
+
if (ctx.surface) error.surface = ctx.surface;
|
|
2109
|
+
if (where.id !== undefined) error.id = where.id;
|
|
2110
|
+
if (where.path !== undefined) error.path = ctx.at(where.path);
|
|
2111
|
+
if (where.repaired) error.repaired = true;
|
|
2112
|
+
ctx.errors.push(error);
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
/* ------------------------------------------------------------------------------------------------
|
|
2116
|
+
* The tree
|
|
2117
|
+
* --------------------------------------------------------------------------------------------- */
|
|
2118
|
+
|
|
2119
|
+
/** @param {string} id @param {SurfaceTrack} track @returns {string[]} The node's ancestors, nearest first. */
|
|
2120
|
+
function ancestorsOf(id, track) {
|
|
2121
|
+
const out = [];
|
|
2122
|
+
let current = track.parent.get(id);
|
|
2123
|
+
while (current !== undefined && current !== ROOT && !out.includes(current)) {
|
|
2124
|
+
out.push(current);
|
|
2125
|
+
current = track.parent.get(current);
|
|
2126
|
+
}
|
|
2127
|
+
return out;
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
/** @param {string} id @param {SurfaceTrack} track @returns {number|null} Depth from root, or null when not yet placed under it. */
|
|
2131
|
+
function depthOf(id, track) {
|
|
2132
|
+
let depth = 1;
|
|
2133
|
+
let current = track.parent.get(id);
|
|
2134
|
+
const seen = new Set([id]);
|
|
2135
|
+
while (current !== ROOT) {
|
|
2136
|
+
if (current === undefined || seen.has(current)) return null;
|
|
2137
|
+
seen.add(current);
|
|
2138
|
+
depth += 1;
|
|
2139
|
+
current = track.parent.get(current);
|
|
2140
|
+
}
|
|
2141
|
+
return depth;
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
/** @param {string} parent @param {string} child @param {SurfaceTrack} track @returns {boolean} */
|
|
2145
|
+
function stillLists(parent, child, track) {
|
|
2146
|
+
if (parent === ROOT) return track.root.includes(child);
|
|
2147
|
+
return Boolean(track.nodes.get(parent)?.children?.includes(child));
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
/** @param {SurfaceTrack} track @param {string} except @returns {number} Fields declared by fields nodes other than `except`. */
|
|
2151
|
+
function countFields(track, except) {
|
|
2152
|
+
let count = 0;
|
|
2153
|
+
for (const owner of track.names.values()) {
|
|
2154
|
+
if (owner.owner === except) continue;
|
|
2155
|
+
if (track.nodes.get(owner.owner)?.type === 'fields') count += 1;
|
|
2156
|
+
}
|
|
2157
|
+
return count;
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
/** @param {{properties: Record<string, unknown>, required?: string[]}} schema @param {string} name */
|
|
2161
|
+
function dropProperty(schema, name) {
|
|
2162
|
+
delete schema.properties[name];
|
|
2163
|
+
if (Array.isArray(schema.required)) schema.required = schema.required.filter((entry) => entry !== name);
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2166
|
+
/* ------------------------------------------------------------------------------------------------ */
|
|
2167
|
+
|
|
2168
|
+
/** @param {unknown} value @returns {value is {$data: unknown}} */
|
|
2169
|
+
function isBinding(value) {
|
|
2170
|
+
return isObject(value) && Object.keys(value).length === 1 && Object.hasOwn(value, '$data');
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
/** @param {unknown} value @returns {boolean} Whether a member counts as given: `null` does not. */
|
|
2174
|
+
function present(value) {
|
|
2175
|
+
return value !== null && value !== undefined;
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
/** @param {Record<string, unknown>} value @returns {Record<string, any>} A shallow copy without `null` members. */
|
|
2179
|
+
function withoutNulls(value) {
|
|
2180
|
+
/** @type {Record<string, unknown>} */
|
|
2181
|
+
const out = {};
|
|
2182
|
+
for (const [key, member] of Object.entries(value)) if (member !== null) out[key] = member;
|
|
2183
|
+
return out;
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
/** @template T @param {T} value @returns {T} */
|
|
2187
|
+
function clone(value) {
|
|
2188
|
+
return value === undefined ? value : JSON.parse(JSON.stringify(value));
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
/**
|
|
2192
|
+
* Names a value that has not been sanitized yet, for a message, without walking into it: it may
|
|
2193
|
+
* nest deeper than the stack can follow, and be as long as a line.
|
|
2194
|
+
* @param {unknown} value
|
|
2195
|
+
* @returns {string}
|
|
2196
|
+
*/
|
|
2197
|
+
export function describeValue(value) {
|
|
2198
|
+
if (typeof value === 'string') return JSON.stringify(value.slice(0, LIMITS.name));
|
|
2199
|
+
if (Array.isArray(value)) return 'a list';
|
|
2200
|
+
return isObject(value) ? 'an object' : String(value ?? null);
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
/** @param {SurfaceError} error @returns {SurfaceError} */
|
|
2204
|
+
function stripSurface(error) {
|
|
2205
|
+
const { surface, ...rest } = error;
|
|
2206
|
+
void surface;
|
|
2207
|
+
return rest;
|
|
2208
|
+
}
|
|
2209
|
+
|
|
2210
|
+
/** @param {unknown} value @returns {value is Record<string, any>} */
|
|
2211
|
+
function isObject(value) {
|
|
2212
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2215
|
+
/** @param {string} key @returns {string} */
|
|
2216
|
+
function escapeKey(key) {
|
|
2217
|
+
return key.replace(/~/g, '~0').replace(/\//g, '~1');
|
|
2218
|
+
}
|