@littlepress/renderer-web 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +20 -0
  3. package/README.md +229 -2
  4. package/dist/answer/answerComponents.d.ts +107 -0
  5. package/dist/answer/answerComponents.js +637 -0
  6. package/dist/answer/download.d.ts +63 -0
  7. package/dist/answer/download.js +109 -0
  8. package/dist/answer/downloadExport.d.ts +44 -0
  9. package/dist/answer/downloadExport.js +266 -0
  10. package/dist/answer/hostValues.d.ts +28 -0
  11. package/dist/answer/hostValues.js +379 -0
  12. package/dist/answer/mapComponent.d.ts +6 -0
  13. package/dist/answer/mapComponent.js +213 -0
  14. package/dist/answer/math.d.ts +57 -0
  15. package/dist/answer/math.js +168 -0
  16. package/dist/answer/surfaceStream.d.ts +51 -0
  17. package/dist/answer/surfaceStream.js +260 -0
  18. package/dist/answer/tableLayout.d.ts +42 -0
  19. package/dist/answer/tableLayout.js +89 -0
  20. package/dist/controls/ActionFeedback.d.ts +5 -0
  21. package/dist/controls/ActionFeedback.js +43 -0
  22. package/dist/controls/actionDispatch.d.ts +51 -0
  23. package/dist/controls/actionDispatch.js +211 -0
  24. package/dist/controls/actionOutcome.generated.d.ts +64 -0
  25. package/dist/controls/actionOutcome.generated.js +64 -0
  26. package/dist/controls/calculationPublisher.d.ts +14 -0
  27. package/dist/controls/calculationPublisher.js +6 -0
  28. package/dist/controls/calculations.d.ts +20 -0
  29. package/dist/controls/calculations.generated.d.ts +73 -0
  30. package/dist/controls/calculations.generated.js +85 -0
  31. package/dist/controls/calculations.js +208 -0
  32. package/dist/controls/controlState.d.ts +84 -0
  33. package/dist/controls/controlState.js +256 -0
  34. package/dist/controls/fieldMessages.d.ts +41 -0
  35. package/dist/controls/fieldMessages.js +81 -0
  36. package/dist/controls/fieldValidation.d.ts +19 -0
  37. package/dist/controls/fieldValidation.js +98 -0
  38. package/dist/controls/formComponents.d.ts +23 -0
  39. package/dist/controls/formComponents.js +738 -0
  40. package/dist/controls/formProgress.d.ts +63 -0
  41. package/dist/controls/formProgress.js +122 -0
  42. package/dist/controls/inputDrafts.d.ts +55 -0
  43. package/dist/controls/inputDrafts.js +183 -0
  44. package/dist/controls/inputValidation.d.ts +33 -0
  45. package/dist/controls/inputValidation.js +119 -0
  46. package/dist/controls/localWrites.d.ts +9 -0
  47. package/dist/controls/localWrites.js +29 -0
  48. package/dist/core/A2uiSurface.d.ts +13 -0
  49. package/dist/core/A2uiSurface.js +15 -0
  50. package/dist/core/AtlasIcon.d.ts +18 -0
  51. package/dist/core/AtlasIcon.js +22 -0
  52. package/dist/core/AtlasMedia.d.ts +22 -0
  53. package/dist/core/AtlasMedia.js +45 -0
  54. package/dist/core/Carousel.d.ts +61 -0
  55. package/dist/core/Carousel.js +183 -0
  56. package/dist/core/CoreMedia.d.ts +19 -0
  57. package/dist/core/CoreMedia.js +25 -0
  58. package/dist/core/FoundationA2uiSurface.d.ts +86 -0
  59. package/dist/core/FoundationA2uiSurface.js +440 -0
  60. package/dist/core/ImagePreview.d.ts +42 -0
  61. package/dist/core/ImagePreview.js +73 -0
  62. package/dist/core/LucideIcon.d.ts +19 -0
  63. package/dist/core/LucideIcon.js +42 -0
  64. package/dist/core/SurfaceLink.d.ts +35 -0
  65. package/dist/core/SurfaceLink.js +60 -0
  66. package/dist/core/appearance/aegis.d.ts +49 -0
  67. package/dist/core/appearance/aegis.js +34 -0
  68. package/dist/core/appearance/colour.d.ts +24 -0
  69. package/dist/core/appearance/colour.js +103 -0
  70. package/dist/core/appearance/css.d.ts +17 -0
  71. package/dist/core/appearance/css.js +153 -0
  72. package/dist/core/appearance/presets.generated.d.ts +4 -0
  73. package/dist/core/appearance/presets.generated.js +1184 -0
  74. package/dist/core/appearance/react.d.ts +29 -0
  75. package/dist/core/appearance/react.js +110 -0
  76. package/dist/core/appearance/resolve.d.ts +76 -0
  77. package/dist/core/appearance/resolve.js +127 -0
  78. package/dist/core/appearance/textScale.d.ts +11 -0
  79. package/dist/core/appearance/textScale.js +51 -0
  80. package/dist/core/appearance/theme.d.ts +138 -0
  81. package/dist/core/appearance/theme.js +274 -0
  82. package/dist/core/baseComponents.d.ts +53 -0
  83. package/dist/core/baseComponents.js +480 -0
  84. package/dist/core/binding.d.ts +46 -0
  85. package/dist/core/binding.js +118 -0
  86. package/dist/core/bundle.d.ts +23 -0
  87. package/dist/core/bundle.js +75 -0
  88. package/dist/core/catalog/catalog-index.generated.d.ts +44 -0
  89. package/dist/core/catalog/catalog-index.generated.js +79 -0
  90. package/dist/core/catalog/icons.generated.d.ts +6 -0
  91. package/dist/core/catalog/icons.generated.js +1788 -0
  92. package/dist/core/catalog.d.ts +6 -0
  93. package/dist/core/catalog.generated.d.ts +50 -0
  94. package/dist/core/catalog.generated.js +2174 -0
  95. package/dist/core/catalog.js +8 -0
  96. package/dist/core/chartRows.d.ts +7 -0
  97. package/dist/core/chartRows.js +38 -0
  98. package/dist/core/component-support.d.ts +39 -0
  99. package/dist/core/component-support.js +127 -0
  100. package/dist/core/components/actions.d.ts +4 -0
  101. package/dist/core/components/actions.js +21 -0
  102. package/dist/core/components/cards.d.ts +9 -0
  103. package/dist/core/components/cards.js +227 -0
  104. package/dist/core/components/charts.d.ts +18 -0
  105. package/dist/core/components/charts.js +412 -0
  106. package/dist/core/components/comparisonTable.d.ts +50 -0
  107. package/dist/core/components/comparisonTable.js +89 -0
  108. package/dist/core/components/content.d.ts +13 -0
  109. package/dist/core/components/content.js +108 -0
  110. package/dist/core/components/seriesCharts.d.ts +531 -0
  111. package/dist/core/components/seriesCharts.js +1053 -0
  112. package/dist/core/components/stepFlow.d.ts +7 -0
  113. package/dist/core/components/stepFlow.js +13 -0
  114. package/dist/core/components.full.d.ts +10 -0
  115. package/dist/core/components.full.js +41 -0
  116. package/dist/core/context.d.ts +207 -0
  117. package/dist/core/context.js +172 -0
  118. package/dist/core/coverage.d.ts +30 -0
  119. package/dist/core/coverage.js +93 -0
  120. package/dist/core/foundation.d.ts +21 -0
  121. package/dist/core/foundation.js +22 -0
  122. package/dist/core/fullTheme.d.ts +5 -0
  123. package/dist/core/fullTheme.js +9 -0
  124. package/dist/core/iconNodes.generated.d.ts +7 -0
  125. package/dist/core/iconNodes.generated.js +5 -0
  126. package/dist/core/lucideIcons.d.ts +5 -0
  127. package/dist/core/lucideIcons.js +7 -0
  128. package/dist/core/messages.d.ts +111 -0
  129. package/dist/core/messages.js +134 -0
  130. package/dist/core/pointer.d.ts +17 -0
  131. package/dist/core/pointer.js +104 -0
  132. package/dist/core/registry.d.ts +12 -0
  133. package/dist/core/registry.js +114 -0
  134. package/dist/core/runtime.d.ts +8 -0
  135. package/dist/core/runtime.js +6 -0
  136. package/dist/core/state.d.ts +73 -0
  137. package/dist/core/state.js +274 -0
  138. package/dist/core/surfaceMotion.d.ts +5 -0
  139. package/dist/core/surfaceMotion.js +46 -0
  140. package/dist/core/theme.d.ts +5 -0
  141. package/dist/core/theme.js +7 -0
  142. package/dist/core/useSurfaceImage.d.ts +20 -0
  143. package/dist/core/useSurfaceImage.js +65 -0
  144. package/dist/graph/RelationshipGraph.d.ts +14 -0
  145. package/dist/graph/RelationshipGraph.js +206 -0
  146. package/dist/graph/model.d.ts +20 -0
  147. package/dist/graph/model.js +36 -0
  148. package/dist/graph/program/assets.d.ts +3 -0
  149. package/dist/graph/program/assets.js +3 -0
  150. package/dist/graph/program/bridge.d.ts +6 -0
  151. package/dist/graph/program/bridge.generated.d.ts +136 -0
  152. package/dist/graph/program/bridge.generated.js +1 -0
  153. package/dist/graph/program/bridge.js +24 -0
  154. package/dist/graph/program/bridge.schema.json +717 -0
  155. package/dist/graph/program/bridgeValidator.cjs +2 -0
  156. package/dist/graph/program/bridgeValidator.d.cts +4 -0
  157. package/dist/graph/program/runner.d.ts +1 -0
  158. package/dist/graph/program/runner.html +2193 -0
  159. package/dist/graph/program/runner.js +157 -0
  160. package/dist/graph/program/runtime-manifest.json +1 -0
  161. package/dist/graph/program/view.d.ts +11 -0
  162. package/dist/graph/program/view.js +210 -0
  163. package/dist/graph/program/worker.d.ts +1 -0
  164. package/dist/graph/program/worker.js +2186 -0
  165. package/dist/index.d.ts +20 -0
  166. package/dist/index.js +45 -0
  167. package/dist/internal/dsh.d.ts +4 -0
  168. package/dist/internal/dsh.js +3 -0
  169. package/dist/internal/relationship-graph.d.ts +4 -0
  170. package/dist/internal/relationship-graph.js +7202 -0
  171. package/dist/page/layoutComponents.d.ts +6 -0
  172. package/dist/page/layoutComponents.js +123 -0
  173. package/dist/page/layoutGeometry.d.ts +68 -0
  174. package/dist/page/layoutGeometry.js +174 -0
  175. package/dist/page/pageFormat.d.ts +34 -0
  176. package/dist/page/pageFormat.js +119 -0
  177. package/dist/page/printFit.d.ts +81 -0
  178. package/dist/page/printFit.js +338 -0
  179. package/dist/react/index.d.ts +5 -0
  180. package/dist/react/index.js +2 -0
  181. package/dist/report/locate.d.ts +42 -0
  182. package/dist/report/locate.js +34 -0
  183. package/dist/styles/renderer.css +4580 -0
  184. package/licenses/LUCIDE-LICENSE.txt +43 -0
  185. package/licenses/QUICKJS-EMSCRIPTEN-LICENSE.txt +21 -0
  186. package/licenses/QUICKJS-VARIANT-LICENSE.txt +47 -0
  187. package/package.json +68 -3
@@ -0,0 +1,274 @@
1
+ /**
2
+ * The A2UI message state machine.
3
+ *
4
+ * Pure functions, zero DOM: a flat component table plus one data model, folded
5
+ * over `createSurface` / `updateComponents` / `updateDataModel` / `deleteSurface`.
6
+ * This is the piece the Compose and SwiftUI decoders have to agree with, so it
7
+ * is kept free of React and testable with `node --test`.
8
+ */
9
+ import { readCreateSurface, readAgentFunctionResponse, readCallRendererFunction, readDeleteSurface, readMessageKind, readUpdateComponents, readUpdateDataModel, } from "./messages.js";
10
+ import { deletePointer, parsePointer, writePointer } from "./pointer.js";
11
+ import { foundationCatalogId, foundationKnownComponents } from "./catalog.js";
12
+ import { layoutContainerComponents } from "../page/layoutGeometry.js";
13
+ const defaultKnownComponents = new Set([
14
+ ...foundationKnownComponents,
15
+ ...layoutContainerComponents,
16
+ ]);
17
+ export function createEmptyA2uiState() {
18
+ return {
19
+ surfaceId: null,
20
+ catalogId: null,
21
+ rendererHints: {},
22
+ releaseManifest: null,
23
+ components: {},
24
+ componentIds: [],
25
+ rootComponentId: null,
26
+ dataModel: {},
27
+ deleted: false,
28
+ appliedMessageCount: 0,
29
+ agentFunctionResponses: [],
30
+ issues: [],
31
+ };
32
+ }
33
+ /** `root` when present, otherwise the first declared component. */
34
+ function pickRootComponentId(components) {
35
+ if (components.length === 0)
36
+ return null;
37
+ const explicitRoot = components.find((component) => component.id === "root");
38
+ return (explicitRoot ?? components[0]).id;
39
+ }
40
+ function indexComponents(components) {
41
+ const table = {};
42
+ const ids = [];
43
+ for (const component of components) {
44
+ if (!(component.id in table))
45
+ ids.push(component.id);
46
+ table[component.id] = component;
47
+ }
48
+ return { table, ids };
49
+ }
50
+ function collectUnsupported(components, known, messageIndex) {
51
+ const seen = new Set();
52
+ const issues = [];
53
+ for (const component of components) {
54
+ if (known.has(component.component) || seen.has(component.component))
55
+ continue;
56
+ seen.add(component.component);
57
+ issues.push({
58
+ kind: "unsupported_component",
59
+ messageIndex,
60
+ detail: `${component.component} (id "${component.id}") has no renderer implementation yet; drawing the placeholder card.`,
61
+ });
62
+ }
63
+ return issues;
64
+ }
65
+ /**
66
+ * Folds a message batch onto a state. Always returns a new object; the input is
67
+ * never mutated, so re-applying the whole history is a legitimate way to
68
+ * recompute (the playground does exactly that on every render).
69
+ */
70
+ export function applyMessages(state, messages, options = {}) {
71
+ const known = options.knownComponents ?? defaultKnownComponents;
72
+ // A direct caller supplies a new revision. The bundle reader restores provenance
73
+ // after applying its explicitly separated live input messages.
74
+ let next = state.sourceRevision === undefined || messages.length === 0
75
+ ? state : { ...state, sourceRevision: undefined };
76
+ const issues = [...state.issues];
77
+ let applied = state.appliedMessageCount;
78
+ function reject(kind, messageIndex, detail) {
79
+ issues.push({ kind, messageIndex, detail });
80
+ }
81
+ messages.forEach((message, messageIndex) => {
82
+ const kind = readMessageKind(message);
83
+ if (kind === null) {
84
+ reject("unknown_message", messageIndex, "Message carries no recognized A2UI v1.0 envelope member.");
85
+ return;
86
+ }
87
+ if (kind === "createSurface") {
88
+ const payload = readCreateSurface(message);
89
+ if (!payload) {
90
+ reject("unknown_message", messageIndex, "createSurface is missing surfaceId.");
91
+ return;
92
+ }
93
+ if (next.surfaceId !== null) {
94
+ reject("duplicate_surface", messageIndex, `Surface id "${payload.surfaceId}" cannot be created twice in one renderer lifetime.`);
95
+ return;
96
+ }
97
+ const components = payload.components ?? [];
98
+ const { table, ids } = indexComponents(components);
99
+ issues.push(...collectUnsupported(components, known, messageIndex));
100
+ const extensions = payload.metadata?.extensions;
101
+ const littlepress = extensions && typeof extensions.littlepress === "object" && extensions.littlepress !== null
102
+ ? extensions.littlepress
103
+ : {};
104
+ next = {
105
+ surfaceId: payload.surfaceId,
106
+ catalogId: payload.catalogId ?? foundationCatalogId,
107
+ rendererHints: littlepress,
108
+ releaseManifest: state.releaseManifest,
109
+ components: table,
110
+ componentIds: ids,
111
+ rootComponentId: pickRootComponentId(components),
112
+ dataModel: payload.dataModel ?? {},
113
+ deleted: false,
114
+ appliedMessageCount: 0,
115
+ agentFunctionResponses: state.agentFunctionResponses,
116
+ issues: [],
117
+ };
118
+ applied += 1;
119
+ return;
120
+ }
121
+ if (kind === "callRendererFunction") {
122
+ const payload = readCallRendererFunction(message);
123
+ if (!payload) {
124
+ reject("unknown_message", messageIndex, "callRendererFunction is malformed.");
125
+ return;
126
+ }
127
+ reject("function_not_allowed", messageIndex, `Function "${payload.callFunction.call}" is renderer-only in the LittlePress catalog and cannot be called by the agent.`);
128
+ return;
129
+ }
130
+ if (kind === "agentFunctionResponse") {
131
+ const payload = readAgentFunctionResponse(message);
132
+ if (!payload) {
133
+ reject("unknown_message", messageIndex, "agentFunctionResponse is malformed.");
134
+ return;
135
+ }
136
+ next = { ...next, agentFunctionResponses: [...next.agentFunctionResponses, payload] };
137
+ applied += 1;
138
+ return;
139
+ }
140
+ // Every other member targets an existing surface.
141
+ const targetSurfaceId = kind === "updateComponents"
142
+ ? readUpdateComponents(message)?.surfaceId
143
+ : kind === "updateDataModel"
144
+ ? readUpdateDataModel(message)?.surfaceId
145
+ : readDeleteSurface(message)?.surfaceId;
146
+ if (!targetSurfaceId) {
147
+ reject("unknown_message", messageIndex, `${kind} is missing a usable surfaceId.`);
148
+ return;
149
+ }
150
+ if (next.surfaceId === null) {
151
+ reject("no_surface", messageIndex, `${kind} arrived before any createSurface.`);
152
+ return;
153
+ }
154
+ if (next.surfaceId !== targetSurfaceId) {
155
+ reject("surface_mismatch", messageIndex, `${kind} targets surface "${targetSurfaceId}" but the runtime holds "${next.surfaceId}".`);
156
+ return;
157
+ }
158
+ if (next.deleted) {
159
+ reject("deleted_surface", messageIndex, `${kind} arrived after the surface was deleted.`);
160
+ return;
161
+ }
162
+ if (kind === "updateComponents") {
163
+ const payload = readUpdateComponents(message);
164
+ if (!payload)
165
+ return;
166
+ const table = { ...next.components };
167
+ const ids = [...next.componentIds];
168
+ for (const component of payload.components) {
169
+ if (!(component.id in table))
170
+ ids.push(component.id);
171
+ table[component.id] = component;
172
+ }
173
+ issues.push(...collectUnsupported(payload.components, known, messageIndex));
174
+ const merged = ids.map((id) => table[id]).filter((component) => Boolean(component));
175
+ next = { ...next, components: table, componentIds: ids, rootComponentId: pickRootComponentId(merged) };
176
+ applied += 1;
177
+ return;
178
+ }
179
+ if (kind === "updateDataModel") {
180
+ const payload = readUpdateDataModel(message);
181
+ if (!payload)
182
+ return;
183
+ const path = payload.path ?? "";
184
+ if (parsePointer(path) === null) {
185
+ reject("invalid_pointer", messageIndex, `updateDataModel path "${path}" is not a JSON Pointer.`);
186
+ return;
187
+ }
188
+ // Current v1: literal null means deletion; `value` itself is required.
189
+ const dataModel = payload.value === null
190
+ ? (deletePointer(next.dataModel, path) ?? {})
191
+ : writePointer(next.dataModel, path, payload.value);
192
+ next = { ...next, dataModel };
193
+ applied += 1;
194
+ return;
195
+ }
196
+ next = {
197
+ ...next,
198
+ components: {},
199
+ componentIds: [],
200
+ rootComponentId: null,
201
+ dataModel: {},
202
+ deleted: true,
203
+ };
204
+ applied += 1;
205
+ });
206
+ return { ...next, appliedMessageCount: applied, issues };
207
+ }
208
+ export function hasRenderableSurface(state) {
209
+ return Boolean(state && !state.deleted && state.rootComponentId);
210
+ }
211
+ /** Distinct component names in the surface that no renderer implementation covers. */
212
+ export function listUnsupportedComponents(state, knownComponents = defaultKnownComponents) {
213
+ const unsupported = new Set();
214
+ for (const id of state.componentIds) {
215
+ const component = state.components[id];
216
+ if (component && !knownComponents.has(component.component))
217
+ unsupported.add(component.component);
218
+ }
219
+ return [...unsupported].sort();
220
+ }
221
+ function readRendererHint(state, key, fallback) {
222
+ const value = state.rendererHints[key];
223
+ return typeof value === "string" && value.length > 0 ? value : fallback;
224
+ }
225
+ function readPublishState(state) {
226
+ const publication = state.releaseManifest?.publication;
227
+ if (typeof publication !== "object" || publication === null || Array.isArray(publication))
228
+ return "unknown";
229
+ const value = publication.state;
230
+ return typeof value === "string" && value.length > 0 ? value : "unknown";
231
+ }
232
+ export function summarizeA2uiState(state, knownComponents = defaultKnownComponents) {
233
+ if (!state || !state.surfaceId)
234
+ return null;
235
+ return {
236
+ surfaceId: state.surfaceId,
237
+ surfaceType: readRendererHint(state, "surfaceType", "unknown"),
238
+ stylePack: readRendererHint(state, "stylePack", "neutral"),
239
+ mode: readRendererHint(state, "mode", "system"),
240
+ pageFormat: readRendererHint(state, "flowModel", "linear_feed"),
241
+ publishState: readPublishState(state),
242
+ catalogId: state.catalogId ?? "unknown",
243
+ componentCount: state.componentIds.length,
244
+ unsupportedCount: listUnsupportedComponents(state, knownComponents).length,
245
+ issueCount: state.issues.length,
246
+ };
247
+ }
248
+ /**
249
+ * Builds the `updateDataModel` message for the catalog's `toggleLocalFlag`
250
+ * client function. A2UI v1.0 has no primitive for client-local state changes
251
+ * (ADR 0004 gap 3), so the renderer synthesizes one and feeds it back through
252
+ * the same state machine instead of keeping a shadow store.
253
+ */
254
+ export function buildLocalToggleMessage(state, path) {
255
+ if (!state.surfaceId || parsePointer(path) === null)
256
+ return null;
257
+ const current = readPointerValue(state.dataModel, path);
258
+ return {
259
+ version: "v1.0",
260
+ updateDataModel: { surfaceId: state.surfaceId, path, value: !current },
261
+ };
262
+ }
263
+ function readPointerValue(dataModel, path) {
264
+ const segments = parsePointer(path);
265
+ if (segments === null)
266
+ return false;
267
+ let cursor = dataModel;
268
+ for (const segment of segments) {
269
+ if (typeof cursor !== "object" || cursor === null)
270
+ return false;
271
+ cursor = cursor[segment];
272
+ }
273
+ return cursor === true;
274
+ }
@@ -0,0 +1,5 @@
1
+ /** Reveals existing top-level content groups without moving or replacing their DOM. */
2
+ export declare function createSurfaceMotion(root: HTMLElement): {
3
+ update(enabled: boolean): void;
4
+ dispose(): void;
5
+ };
@@ -0,0 +1,46 @@
1
+ /** Reveals existing top-level content groups without moving or replacing their DOM. */
2
+ export function createSurfaceMotion(root) {
3
+ const seen = new WeakSet();
4
+ const active = new Set();
5
+ const reduced = root.ownerDocument.defaultView.matchMedia("(prefers-reduced-motion: reduce)");
6
+ let first = true;
7
+ function finish(node) {
8
+ node.classList.remove("lp-content-enter");
9
+ node.style.removeProperty("--lp-enter-delay");
10
+ active.delete(node);
11
+ }
12
+ const settle = () => { for (const node of active)
13
+ finish(node); };
14
+ const ended = (event) => {
15
+ if (event.animationName === "lp-content-enter" && active.has(event.target))
16
+ finish(event.target);
17
+ };
18
+ root.addEventListener("animationend", ended);
19
+ root.addEventListener("focusin", settle);
20
+ reduced.addEventListener("change", settle);
21
+ return {
22
+ update(enabled) {
23
+ const content = root.firstElementChild;
24
+ // Reports already compile each H2 section to a child stack. Keep its heading,
25
+ // paragraphs and charts together; do not animate descendants independently.
26
+ const groups = content?.matches(".lp-stack:not([data-axis='horizontal']), .lp-grid")
27
+ ? [...content.children] : content ? [content] : [];
28
+ const added = groups.filter((node) => node instanceof HTMLElement && !seen.has(node));
29
+ added.forEach((node, index) => {
30
+ seen.add(node);
31
+ if (!enabled || reduced.matches || root.dataset.reducedMotion === "true")
32
+ return;
33
+ node.style.setProperty("--lp-enter-delay", `${(first ? 160 : 0) + Math.min(index, 4) * 80}ms`);
34
+ node.classList.add("lp-content-enter");
35
+ active.add(node);
36
+ });
37
+ first = false;
38
+ },
39
+ dispose() {
40
+ settle();
41
+ root.removeEventListener("animationend", ended);
42
+ root.removeEventListener("focusin", settle);
43
+ reduced.removeEventListener("change", settle);
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,5 @@
1
+ export declare const rendererStylePacks: readonly ["neutral"];
2
+ export type RendererStylePack = (typeof rendererStylePacks)[number];
3
+ export type RendererMode = "light" | "dark" | "system";
4
+ export declare function resolveStylePack(value: unknown, knownPacks?: readonly string[]): string;
5
+ export declare function resolveRendererMode(value: unknown): RendererMode;
@@ -0,0 +1,7 @@
1
+ export const rendererStylePacks = ["neutral"];
2
+ export function resolveStylePack(value, knownPacks = rendererStylePacks) {
3
+ return typeof value === "string" && knownPacks.includes(value) ? value : "neutral";
4
+ }
5
+ export function resolveRendererMode(value) {
6
+ return value === "light" || value === "dark" || value === "system" ? value : "system";
7
+ }
@@ -0,0 +1,20 @@
1
+ import type { RenderContext } from "./context.ts";
2
+ export type SurfaceImageResult = {
3
+ /** Authorized image `src` ready for `<img src>`, or `null` when unavailable/rejected/failed. */
4
+ src: string | null;
5
+ /** Marks the current `src` as failed so the caller falls back to its placeholder. */
6
+ onError: () => void;
7
+ };
8
+ /**
9
+ * Resolves any image URL through the unified Host image entry point (`images` / `imageLoader`):
10
+ * - When `context.imageLoader` is supplied, every image routes through it — even if `images`
11
+ * also holds an entry for the same URL. Returning `null` (or throwing) keeps the placeholder
12
+ * and never falls back to `images` or the raw URL.
13
+ * - When `context.imageLoader` is omitted, `context.images[url]` is preferred when present,
14
+ * otherwise valid `http://`, `https://`, and `data:image/*` URLs render directly (always with
15
+ * `referrerPolicy="no-referrer"` at the `<img>` element).
16
+ * - Executable schemes (`javascript:`, `vbscript:`, `data:text/html`) are always rejected.
17
+ */
18
+ export declare function useSurfaceImage(rawUrl: string | null | undefined, context?: RenderContext, options?: {
19
+ streaming?: boolean;
20
+ }): SurfaceImageResult;
@@ -0,0 +1,65 @@
1
+ import { useEffect, useState } from "react";
2
+ import { isExecutableUrl, validImageUrl, validResolvedImageSrc } from "../answer/hostValues.js";
3
+ /**
4
+ * Resolves any image URL through the unified Host image entry point (`images` / `imageLoader`):
5
+ * - When `context.imageLoader` is supplied, every image routes through it — even if `images`
6
+ * also holds an entry for the same URL. Returning `null` (or throwing) keeps the placeholder
7
+ * and never falls back to `images` or the raw URL.
8
+ * - When `context.imageLoader` is omitted, `context.images[url]` is preferred when present,
9
+ * otherwise valid `http://`, `https://`, and `data:image/*` URLs render directly (always with
10
+ * `referrerPolicy="no-referrer"` at the `<img>` element).
11
+ * - Executable schemes (`javascript:`, `vbscript:`, `data:text/html`) are always rejected.
12
+ */
13
+ export function useSurfaceImage(rawUrl, context, options) {
14
+ const streaming = options?.streaming === true;
15
+ const trimmed = typeof rawUrl === "string" ? rawUrl.trim() : "";
16
+ const preloadedRaw = trimmed &&
17
+ !isExecutableUrl(trimmed) &&
18
+ context?.images &&
19
+ Object.prototype.hasOwnProperty.call(context.images, trimmed)
20
+ ? context.images[trimmed]
21
+ : undefined;
22
+ const preloaded = validResolvedImageSrc(preloadedRaw);
23
+ const safeUrl = validImageUrl(trimmed);
24
+ const hostLoader = context?.imageLoader;
25
+ const activeLoader = !streaming && safeUrl ? hostLoader : undefined;
26
+ const [loaded, setLoaded] = useState(null);
27
+ const [failedSrc, setFailedSrc] = useState(null);
28
+ useEffect(() => {
29
+ if (!safeUrl || !activeLoader)
30
+ return;
31
+ let cancelled = false;
32
+ Promise.resolve()
33
+ .then(() => activeLoader(safeUrl))
34
+ .then((resolved) => {
35
+ if (cancelled)
36
+ return;
37
+ const valid = validResolvedImageSrc(resolved);
38
+ if (valid) {
39
+ setLoaded({ url: safeUrl, loader: activeLoader, src: valid });
40
+ }
41
+ else {
42
+ setLoaded((prev) => (prev?.url === safeUrl && prev.loader === activeLoader ? null : prev));
43
+ }
44
+ })
45
+ .catch(() => {
46
+ if (!cancelled) {
47
+ setLoaded((prev) => (prev?.url === safeUrl && prev.loader === activeLoader ? null : prev));
48
+ }
49
+ });
50
+ return () => {
51
+ cancelled = true;
52
+ };
53
+ }, [safeUrl, activeLoader]);
54
+ const candidateSrc = hostLoader
55
+ ? loaded && loaded.url === safeUrl && loaded.loader === hostLoader
56
+ ? loaded.src
57
+ : null
58
+ : (preloaded ?? safeUrl);
59
+ const src = candidateSrc && failedSrc !== candidateSrc ? candidateSrc : null;
60
+ const onError = () => {
61
+ if (candidateSrc)
62
+ setFailedSrc(candidateSrc);
63
+ };
64
+ return { src, onError };
65
+ }
@@ -0,0 +1,14 @@
1
+ import { prepareAegisArtifact } from "@littlepress/ui-foundation-contracts/aegis";
2
+ import { type RelationshipGraphData } from "./model.ts";
3
+ type PreparationOptions = Parameters<typeof prepareAegisArtifact>[0];
4
+ export type RelationshipGraphProgram = Pick<PreparationOptions, "artifact" | "policy" | "readSource">;
5
+ export type RelationshipGraphProps = {
6
+ data: RelationshipGraphData;
7
+ selectedId: string | null;
8
+ onSelect: (id: string) => void;
9
+ program: RelationshipGraphProgram;
10
+ locale?: "en" | "zh";
11
+ enabled?: boolean;
12
+ };
13
+ export declare function RelationshipGraph({ data, selectedId, onSelect, program, locale, enabled }: RelationshipGraphProps): import("react/jsx-runtime").JSX.Element;
14
+ export {};
@@ -0,0 +1,206 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { prepareAegisArtifact } from "@littlepress/ui-foundation-contracts/aegis";
4
+ import { runtimeDocument, relationshipGraphRuntime } from "./program/assets.js";
5
+ import { isGraphMessage, sameGraphInstance } from "./program/bridge.js";
6
+ import { validateGraph } from "./model.js";
7
+ const buttonStyle = { minHeight: 44, padding: "8px 14px", borderRadius: 8, border: "1px solid #b8c4ba", background: "white", color: "#202523", font: "inherit", cursor: "pointer" };
8
+ function failureText(code, zh) {
9
+ const messages = {
10
+ disabled: ["This application has disabled the graph. Devices and connections remain available below.", "当前应用已禁用关系图。仍可查看下方设备和连接。"],
11
+ runtime_not_allowed: ["This graph requires a runtime version that this application does not support.", "此关系图需要当前应用尚不支持的运行版本。"],
12
+ unsupported_schema: ["This application cannot read this program format version.", "当前应用无法读取此版本的程序格式。"],
13
+ unsupported_bridge: ["This application does not support the program's message version.", "当前应用不支持此程序的消息版本。"],
14
+ missing_action: ["The program requires an action that this application has not allowed.", "此程序需要当前应用尚未允许的操作。"],
15
+ missing_client_effect: ["The program requires a device capability that this application has not allowed.", "此程序需要当前应用尚未允许的设备能力。"],
16
+ budget: ["The program exceeded its calculation or output limit.", "程序超过了计算或输出限制。"],
17
+ invalid_scene: ["The program returned a layout that does not match the devices.", "程序返回的布局与设备不匹配。"],
18
+ first_frame_timeout: ["The program did not draw its first frame within the allowed time.", "程序未能在允许的时间内绘出首帧。"],
19
+ source_hash_mismatch: ["The program bytes do not match the expected version. Reload the source and retry.", "程序内容与预期版本不一致。请重新取得源码后重试。"],
20
+ source_read_failed: ["The program source could not be loaded. Check the connection and retry.", "程序源码未能加载。请检查连接后重试。"],
21
+ source_timeout: ["Loading the program source timed out. You can retry.", "加载程序源码超时,可以重试。"],
22
+ };
23
+ return messages[code]?.[zh ? 1 : 0] ?? (zh ? "程序无法继续运行,当前选择和其他输入不受影响。" : "The program cannot continue. Your selection and other inputs are preserved.");
24
+ }
25
+ function GraphInstance({ data, selectedId, onSelect, locale = "en", prepared, onRetry }) {
26
+ const iframe = useRef(null);
27
+ const channel = useRef(null);
28
+ const current = useRef({ selectedId, onSelect });
29
+ const [status, setStatus] = useState("loading");
30
+ const [reason, setReason] = useState("");
31
+ const instanceId = useMemo(() => crypto.randomUUID(), []);
32
+ const zh = locale === "zh";
33
+ useLayoutEffect(() => {
34
+ current.current = { selectedId, onSelect };
35
+ const connection = channel.current;
36
+ if (connection)
37
+ connection.port.postMessage({ ...connection.identity, kind: "state", state_revision: ++connection.revision, body: { selectedId } });
38
+ }, [selectedId, onSelect]);
39
+ useLayoutEffect(() => {
40
+ const frame = iframe.current;
41
+ if (!frame)
42
+ return;
43
+ let active = true;
44
+ let timeout;
45
+ let connection = null;
46
+ let ready = false;
47
+ let remaining = 10000;
48
+ let runningSince = null;
49
+ const pause = () => {
50
+ clearTimeout(timeout);
51
+ if (runningSince !== null)
52
+ remaining = Math.max(0, remaining - (performance.now() - runningSince));
53
+ runningSince = null;
54
+ };
55
+ const send = (kind, body) => connection?.port.postMessage({ ...connection.identity, kind, state_revision: connection.revision, ...(body ? { body } : {}) });
56
+ const close = () => { send("dispose"); connection?.port.close(); if (channel.current === connection)
57
+ channel.current = null; };
58
+ const fail = (code) => {
59
+ if (!active)
60
+ return;
61
+ active = false;
62
+ pause();
63
+ close();
64
+ setReason(code);
65
+ setStatus("failed");
66
+ };
67
+ const arm = () => {
68
+ pause();
69
+ if (!document.hidden && !ready) {
70
+ runningSince = performance.now();
71
+ timeout = setTimeout(() => fail("first_frame_timeout"), remaining);
72
+ }
73
+ };
74
+ const visibility = () => {
75
+ if (document.hidden) {
76
+ pause();
77
+ send("suspend");
78
+ }
79
+ else {
80
+ arm();
81
+ send("resume", { selectedId: current.current.selectedId });
82
+ }
83
+ };
84
+ const connect = () => {
85
+ if (!active || !frame.contentWindow)
86
+ return;
87
+ close();
88
+ const transport = new MessageChannel();
89
+ const identity = { bridge_version: 1, instance_id: instanceId, session_id: crypto.randomUUID(), execution_id: crypto.randomUUID() };
90
+ const ownConnection = { identity, port: transport.port1, revision: 0, initialized: false };
91
+ connection = ownConnection;
92
+ channel.current = ownConnection;
93
+ ready = false;
94
+ remaining = 10000;
95
+ runningSince = null;
96
+ setStatus("loading");
97
+ arm();
98
+ transport.port1.onmessage = event => {
99
+ const message = event.data;
100
+ if (!active || connection !== ownConnection || !isGraphMessage(message) || !sameGraphInstance(message, identity))
101
+ return;
102
+ if (message.kind === "connected" && !ownConnection.initialized) {
103
+ ownConnection.initialized = true;
104
+ send("initialize", { graph: data, selectedId: current.current.selectedId, locale, sourceText: prepared.sourceText });
105
+ if (document.hidden)
106
+ send("suspend");
107
+ }
108
+ else if (ownConnection.initialized && message.kind === "failed") {
109
+ // Failure ends this execution even when a newer Host selection is already queued.
110
+ fail(message.body.code);
111
+ }
112
+ else if (ownConnection.initialized && message.kind === "ready") {
113
+ // First-frame readiness belongs to this execution, not its selection revision.
114
+ ready = true;
115
+ pause();
116
+ setStatus("ready");
117
+ }
118
+ else if (ownConnection.initialized && message.state_revision === ownConnection.revision) {
119
+ if (message.kind === "select" && data.nodes.some(node => node.id === message.body.id)) {
120
+ // Retire this revision before calling the Host, even if it ignores the selection.
121
+ ownConnection.revision++;
122
+ send("state", { selectedId: current.current.selectedId });
123
+ try {
124
+ current.current.onSelect(message.body.id);
125
+ }
126
+ catch {
127
+ fail("host_callback");
128
+ }
129
+ }
130
+ }
131
+ };
132
+ transport.port1.onmessageerror = () => fail("protocol");
133
+ transport.port1.start();
134
+ frame.contentWindow.postMessage({ ...identity, kind: "connected", state_revision: 0 }, "*", [transport.port2]);
135
+ };
136
+ const frameError = () => fail("frame_load");
137
+ frame.addEventListener("load", connect);
138
+ frame.addEventListener("error", frameError);
139
+ document.addEventListener("visibilitychange", visibility);
140
+ frame.srcdoc = runtimeDocument;
141
+ return () => {
142
+ active = false;
143
+ clearTimeout(timeout);
144
+ frame.removeEventListener("load", connect);
145
+ frame.removeEventListener("error", frameError);
146
+ document.removeEventListener("visibilitychange", visibility);
147
+ close();
148
+ };
149
+ }, [data, locale, prepared, instanceId]);
150
+ return _jsxs("div", { "data-relationship-graph-state": status, "data-program-error": reason || undefined, style: { border: "1px solid #d2dad3", borderRadius: 16, overflow: "hidden", background: "#fafbf9", color: "#202523" }, children: [status === "loading" ? _jsx("p", { role: "status", style: { margin: 0, padding: 16 }, children: zh ? "正在加载关系图…" : "Loading relationship graph…" }) : null, status === "failed" ? _jsxs("div", { role: "alert", style: { padding: 20 }, children: [_jsx("p", { children: zh ? "关系图未能运行。当前选择和其他输入已保留,可以重试。" : "The graph could not run. Your selection and other inputs are preserved. You can retry." }), _jsx("p", { children: failureText(reason, zh) }), _jsx("button", { type: "button", style: buttonStyle, onClick: onRetry, children: zh ? "重试关系图" : "Retry graph" })] }) : _jsx("iframe", { ref: iframe, title: zh ? "可交互设备关系图" : "Interactive device relationship graph", sandbox: "allow-scripts", referrerPolicy: "no-referrer", style: { display: "block", border: 0, width: "100%", height: 510, visibility: status === "ready" ? "visible" : "hidden" } })] });
151
+ }
152
+ /** Admission precedes iframe creation. The installed runtime allowlist is independent of the artifact. */
153
+ function AdmittedGraph(props) {
154
+ const { program, enabled = true, locale = "en" } = props;
155
+ const [attempt, setAttempt] = useState(0);
156
+ const [result, setResult] = useState(null);
157
+ const resultOwner = useRef(null);
158
+ const zh = locale === "zh";
159
+ useEffect(() => {
160
+ const controller = new AbortController();
161
+ setResult(null);
162
+ const installed = relationshipGraphRuntime;
163
+ void prepareAegisArtifact({
164
+ ...program,
165
+ policy: { ...program.policy, enabled: enabled && program.policy.enabled,
166
+ runtimes: program.policy.runtimes.filter(runtime => runtime.id === installed.id && runtime.version === installed.version && runtime.manifest_sha256 === installed.manifest_sha256),
167
+ registeredActions: [], clientEffects: [],
168
+ }, signal: controller.signal,
169
+ }).then(result => {
170
+ if (controller.signal.aborted)
171
+ return;
172
+ resultOwner.current = program;
173
+ if (result.status === "ready") {
174
+ const { inputs, outputs } = result.artifact;
175
+ const graph = inputs.graph;
176
+ const selection = inputs.selectedDeviceId;
177
+ const output = outputs.selectedDeviceId;
178
+ if (Object.keys(inputs).length !== 2 || graph?.type !== "json" || graph.nullable || selection?.type !== "string" || !selection.nullable
179
+ || Object.keys(outputs).length !== 1 || output?.type !== "string" || output.nullable) {
180
+ setResult({ status: "failed", error: { code: "invalid_artifact" }, fallbackText: program.policy.fallbackText });
181
+ return;
182
+ }
183
+ }
184
+ setResult(result);
185
+ });
186
+ return () => controller.abort();
187
+ }, [program, enabled, attempt]);
188
+ const retry = () => { setResult(null); setAttempt(value => value + 1); };
189
+ if (!result || resultOwner.current !== program)
190
+ return _jsx("p", { role: "status", children: zh ? "正在检查关系图程序…" : "Checking relationship graph program…" });
191
+ if (result.status === "ready" && enabled)
192
+ return _jsx(GraphInstance, { ...props, prepared: result, onRetry: retry }, attempt);
193
+ const reason = result.status === "failed" ? result.error.code : result.status === "fallback" ? result.reason : "disabled";
194
+ return _jsxs("div", { "data-relationship-graph-state": result.status === "failed" ? "failed" : "fallback", "data-program-error": reason, role: result.status === "failed" ? "alert" : "status", children: [_jsx("p", { children: result.status === "ready" ? program.policy.fallbackText : result.fallbackText }), _jsx("p", { children: failureText(reason, zh) }), result.status === "failed" ? _jsx("button", { style: buttonStyle, type: "button", onClick: retry, children: zh ? "重试关系图" : "Retry graph" }) : null] });
195
+ }
196
+ export function RelationshipGraph({ data, selectedId, onSelect, program, locale = "en", enabled = true }) {
197
+ const parsed = useMemo(() => validateGraph(data), [data]);
198
+ const zh = locale === "zh";
199
+ if (parsed.error || !parsed.graph)
200
+ return _jsxs("p", { role: "alert", children: [zh ? "关系图数据不符合要求。请检查设备、名称和连接。" : "Invalid graph data. Check the devices, labels and connections.", " (", parsed.error, ")"] });
201
+ const graph = parsed.graph;
202
+ if (selectedId !== null && !graph.nodes.some(node => node.id === selectedId))
203
+ return _jsx("p", { role: "alert", children: zh ? "所选设备不在当前关系图中,请重新选择。" : "The selected device is not in this graph. Choose again." });
204
+ const labels = new Map(graph.nodes.map(node => [node.id, node.label]));
205
+ return _jsxs("section", { "aria-label": zh ? "设备关系图" : "Device relationship graph", children: [_jsx(AdmittedGraph, { data: graph, selectedId: selectedId, onSelect: onSelect, program: program, locale: locale, enabled: enabled }), _jsxs("details", { style: { marginTop: 12 }, open: !enabled, children: [_jsx("summary", { style: { minHeight: 44, cursor: "pointer", padding: "10px 0" }, children: zh ? "查看设备与连接" : "View devices and connections" }), _jsx("ul", { children: graph.nodes.map(node => _jsxs("li", { style: { overflowWrap: "anywhere" }, children: [node.label, node.id === selectedId ? (zh ? "(已选择)" : " (selected)") : ""] }, node.id)) }), graph.edges.length ? _jsx("ul", { children: graph.edges.map(edge => _jsxs("li", { style: { overflowWrap: "anywhere" }, children: [labels.get(edge.from), " \u2192 ", labels.get(edge.to)] }, `${edge.from}/${edge.to}`)) }) : _jsx("p", { children: zh ? "没有连接。" : "No connections." })] })] });
206
+ }