@copilotkit/react-core 2.0.0-rc.31 → 2.0.0-rc.33

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 (34) hide show
  1. package/README.md +1 -1
  2. package/dist/MarkdownRendererContext-CPfNVyde.d.mts +241 -0
  3. package/dist/MarkdownRendererContext-CPfNVyde.d.mts.map +1 -0
  4. package/dist/MarkdownRendererContext-iOl2pj9l.d.cts +241 -0
  5. package/dist/MarkdownRendererContext-iOl2pj9l.d.cts.map +1 -0
  6. package/dist/MarkdownSurfaces-BFoO6wSB.cjs +1650 -0
  7. package/dist/MarkdownSurfaces-BFoO6wSB.cjs.map +1 -0
  8. package/dist/MarkdownSurfaces-BQ1HGCzB.mjs +1442 -0
  9. package/dist/MarkdownSurfaces-BQ1HGCzB.mjs.map +1 -0
  10. package/dist/generative-ui.cjs +687 -2964
  11. package/dist/generative-ui.cjs.map +1 -1
  12. package/dist/generative-ui.d.cts +2478 -2683
  13. package/dist/generative-ui.d.cts.map +1 -1
  14. package/dist/generative-ui.d.mts +2477 -2682
  15. package/dist/generative-ui.d.mts.map +1 -1
  16. package/dist/generative-ui.mjs +299 -2585
  17. package/dist/generative-ui.mjs.map +1 -1
  18. package/dist/index.cjs +26 -1367
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +1 -1
  21. package/dist/index.d.mts +1 -1
  22. package/dist/index.mjs +11 -1352
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/index.umd.js +124 -3358
  25. package/dist/index.umd.js.map +1 -1
  26. package/package.json +9 -9
  27. package/dist/MarkdownRendererContext-BX26QLwl.d.cts +0 -937
  28. package/dist/MarkdownRendererContext-BX26QLwl.d.cts.map +0 -1
  29. package/dist/MarkdownRendererContext-DAOMewji.d.mts +0 -937
  30. package/dist/MarkdownRendererContext-DAOMewji.d.mts.map +0 -1
  31. package/dist/MarkdownSurfaces-BbrHcSHN.cjs +0 -3903
  32. package/dist/MarkdownSurfaces-BbrHcSHN.cjs.map +0 -1
  33. package/dist/MarkdownSurfaces-DQbRS91-.mjs +0 -3587
  34. package/dist/MarkdownSurfaces-DQbRS91-.mjs.map +0 -1
@@ -1,3587 +0,0 @@
1
- import { CopilotChatDefaultLabels, extractFenceOperations, flattenInformationalCards, getMarkdownOperationSurfaceId, prepareSurfaceOperations, segmentSurfaceProse, splitA2UIMarkdown, ɵChatConfigurationStore, ɵcn as cn, ɵcopilotIconSvgAttributes, ɵcopilotIcons, ɵshallowEqualRecord } from "@copilotkit/core";
2
- import React, { Component, createContext, createElement, forwardRef, memo, useCallback, useContext, useEffect, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
3
- import { StreamingMarkdownRenderer } from "@copilotkit/markdown/react";
4
- import { CHAT_MARKDOWN_NODE_CLASS_NAMES, warnUnsupportedRichSyntaxOnce } from "@copilotkit/markdown";
5
- import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
6
- import { CopilotKitContext, useCopilotKit, useDefaultAgentId } from "@copilotkit/react-core/context";
7
- import { A2UI_COMPONENT_ENVELOPE_KEYS, A2UI_INDEX_FUNCTION, A2UI_VERSION, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_CHAT_TARGET, GENERATIVE_UI_FUNCTIONS, GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE, GENERATIVE_UI_RENDER_TOOL, GENERATIVE_UI_ROOT_ID, applyChildRefMarks, childIdsAtRefs, collectChildRefs, functionCallers, getOperationKind, hasBoundChildRef, isActionBinding, isCallBinding, isPathBinding, isValidationResult, mapAtChildRef, schemaToJsonSchema, validateOperation, ɵanySchema } from "@copilotkit/shared";
8
- import * as z from "zod";
9
-
10
- //#region src/components/chat/StreamingMarkdownDefaultRenderer.tsx
11
- /**
12
- * react-core's built-in default markdown renderer — a thin adapter over
13
- * `@copilotkit/markdown`'s streaming renderer. Maps the pluggable
14
- * renderer contract (`{ content, isStreaming, className }`) onto the streaming
15
- * renderer for streaming-safe incremental rendering + per-token animation.
16
- * Still overridable via the slot/provider pluggable interface.
17
- */
18
- function StreamingMarkdownDefaultRenderer({ content, isStreaming, className, nodeRenderers, caret, options, onLinkClick, onCitationClick }) {
19
- if (!content) return null;
20
- warnUnsupportedRichSyntaxOnce(content);
21
- return /* @__PURE__ */ jsx(StreamingMarkdownRenderer, {
22
- className,
23
- isComplete: !isStreaming,
24
- caret: caret ?? !!isStreaming,
25
- nodeRenderers,
26
- nodeClassNames: CHAT_MARKDOWN_NODE_CLASS_NAMES,
27
- options,
28
- onLinkClick,
29
- onCitationClick,
30
- children: content
31
- });
32
- }
33
- StreamingMarkdownDefaultRenderer.displayName = "StreamingMarkdownDefaultRenderer";
34
-
35
- //#endregion
36
- //#region src/components/icons/CopilotIcon.tsx
37
- /** Turns SVG attribute names such as `stroke-width` into React's `strokeWidth`. */
38
- function toReactAttributes(attributes) {
39
- return Object.fromEntries(Object.entries(attributes).map(([key, value]) => [key.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase()), value]));
40
- }
41
- const svgDefaults = toReactAttributes(ɵcopilotIconSvgAttributes);
42
- /** True when the props give the icon an accessible name or role. */
43
- function hasAccessibleProp(props) {
44
- return Object.keys(props).some((key) => key.startsWith("aria-") || key === "role" || key === "title");
45
- }
46
- /**
47
- * Internal. Draws a Lucide icon from its node data, the way Lucide's React package
48
- * does: Lucide's default SVG attributes, the `lucide lucide-<name>` classes,
49
- * and `aria-hidden="true"` when no `aria-*`, `role` or `title` prop names it.
50
- */
51
- const IconSvg = forwardRef(function IconSvg({ lucideName, nodes, size = 24, color = "currentColor", strokeWidth = 2, className, children, ...props }, ref) {
52
- const isDecorative = !children && !hasAccessibleProp(props);
53
- return /* @__PURE__ */ jsxs("svg", {
54
- ref,
55
- ...svgDefaults,
56
- width: size,
57
- height: size,
58
- stroke: color,
59
- strokeWidth,
60
- className: cn("lucide", `lucide-${lucideName}`, className),
61
- "aria-hidden": isDecorative || void 0,
62
- ...props,
63
- children: [nodes.map((node, index) => createElement(node.tag, {
64
- key: index,
65
- ...node.attributes
66
- })), children]
67
- });
68
- });
69
- /**
70
- * Draws one of the chat icons as an inline `<svg>`.
71
- *
72
- * The `<svg>` has the classes `lucide lucide-<icon name>`, so CSS that selects
73
- * them (for example `svg.lucide-arrow-up`) keeps working. The icon is hidden
74
- * from screen readers unless you give it an `aria-label`, `role` or `title`.
75
- *
76
- * @param props.name - The chat icon, for example `"ArrowUp"` or `"X"`.
77
- * @param props.size - Width and height. Defaults to `24`.
78
- * @param props.strokeWidth - Line width. Defaults to `2`.
79
- * @param props.color - Line color. Defaults to `currentColor`.
80
- *
81
- * @example
82
- * ```tsx
83
- * <CopilotIcon name="ArrowUp" className="cpk-chat-input-send-icon" />
84
- * <CopilotIcon name="X" aria-label="Close" />
85
- * ```
86
- */
87
- const CopilotIcon = forwardRef(function CopilotIcon({ name, ...props }, ref) {
88
- const icon = ɵcopilotIcons[name];
89
- return /* @__PURE__ */ jsx(IconSvg, {
90
- ref,
91
- lucideName: icon.name,
92
- nodes: icon.nodes,
93
- ...props
94
- });
95
- });
96
-
97
- //#endregion
98
- //#region src/lib/shallow-stable-ref.ts
99
- /**
100
- * Shallow equality comparison for objects: same own keys, each holding the
101
- * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.
102
- */
103
- function shallowEqual(obj1, obj2) {
104
- return ɵshallowEqualRecord(obj1, obj2);
105
- }
106
- /**
107
- * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
108
- * class instances, and other exotic objects that happen to have typeof "object".
109
- */
110
- function isPlainObject(obj) {
111
- return obj !== null && typeof obj === "object" && Object.prototype.toString.call(obj) === "[object Object]";
112
- }
113
- /**
114
- * Returns the same reference as long as the value is shallowly equal to the
115
- * previous render's value.
116
- *
117
- * - Identical references bail out immediately (O(1)).
118
- * - Plain objects ({}) are shallow-compared key-by-key.
119
- * - Arrays, Dates, class instances, functions, and primitives are compared by
120
- * reference only — shallowEqual is never called on non-plain objects, which
121
- * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
122
- *
123
- * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
124
- * equality check isn't defeated by a new object reference on every render.
125
- */
126
- function useShallowStableRef(value) {
127
- const ref = useRef(value);
128
- if (ref.current === value) return ref.current;
129
- if (isPlainObject(ref.current) && isPlainObject(value)) {
130
- if (shallowEqual(ref.current, value)) return ref.current;
131
- }
132
- ref.current = value;
133
- return ref.current;
134
- }
135
-
136
- //#endregion
137
- //#region src/providers/CopilotChatConfigurationProvider.tsx
138
- const CopilotChatConfiguration = createContext(null);
139
- const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
140
- const parentConfig = useContext(CopilotChatConfiguration);
141
- const stableLabels = useShallowStableRef(labels);
142
- const mergedLabels = useMemo(() => ({
143
- ...CopilotChatDefaultLabels,
144
- ...parentConfig?.labels,
145
- ...stableLabels
146
- }), [stableLabels, parentConfig?.labels]);
147
- const providerAgentId = useDefaultAgentId();
148
- const options = {
149
- agentId,
150
- threadId,
151
- hasExplicitThreadId,
152
- isModalDefaultOpen,
153
- providerAgentId
154
- };
155
- const parentStore = parentConfig?.ɵstore ?? null;
156
- const [store] = useState(() => new ɵChatConfigurationStore(options, parentStore));
157
- store.ɵsetOptions(options);
158
- const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
159
- useEffect(() => {
160
- store.update({
161
- agentId,
162
- threadId,
163
- hasExplicitThreadId,
164
- isModalDefaultOpen,
165
- providerAgentId
166
- });
167
- }, [
168
- store,
169
- agentId,
170
- threadId,
171
- hasExplicitThreadId,
172
- isModalDefaultOpen,
173
- providerAgentId
174
- ]);
175
- const copilotkit = useContext(CopilotKitContext)?.copilotkit;
176
- useEffect(() => {
177
- if (copilotkit === void 0) return;
178
- return store.bindOpenThread(copilotkit);
179
- }, [copilotkit, store]);
180
- const ownsModal = isModalDefaultOpen !== void 0;
181
- const isModalOpen = ownsModal || !parentConfig ? snapshot.isModalOpen : parentConfig.isModalOpen;
182
- const setModalOpen = ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;
183
- const { agentId: resolvedAgentId, threadId: resolvedThreadId, hasExplicitThreadId: resolvedHasExplicitThreadId, drawerOpen, drawerRegistered } = snapshot;
184
- const configurationValue = useMemo(() => ({
185
- labels: mergedLabels,
186
- agentId: resolvedAgentId,
187
- threadId: resolvedThreadId,
188
- hasExplicitThreadId: resolvedHasExplicitThreadId,
189
- isModalOpen,
190
- setModalOpen,
191
- drawerOpen,
192
- setDrawerOpen: store.setDrawerOpen,
193
- drawerRegistered,
194
- registerDrawer: store.registerDrawer,
195
- ɵregisterModalCloser: store.registerModalCloser,
196
- setActiveThreadId: store.setActiveThreadId,
197
- startNewThread: store.startNewThread,
198
- ɵstore: store
199
- }), [
200
- mergedLabels,
201
- resolvedAgentId,
202
- resolvedThreadId,
203
- resolvedHasExplicitThreadId,
204
- isModalOpen,
205
- setModalOpen,
206
- drawerOpen,
207
- drawerRegistered,
208
- store
209
- ]);
210
- return /* @__PURE__ */ jsx(CopilotChatConfiguration.Provider, {
211
- value: configurationValue,
212
- children
213
- });
214
- };
215
- const useCopilotChatConfiguration = () => {
216
- return useContext(CopilotChatConfiguration);
217
- };
218
- /**
219
- * Reports modal open/close requests to the host, and — when `open` is
220
- * supplied — makes the modal state of an already-established chat
221
- * configuration **controlled** for the subtree it wraps.
222
- *
223
- * This is deliberately a scope component rather than another mode inside
224
- * {@link CopilotChatConfigurationProvider}. The provider resolves modal state
225
- * across a nested chain (own state, parent sync, drawer mutual-exclusion, the
226
- * modal-closer registry); a controlled branch inside that resolution would add
227
- * a fourth interacting mode. Overriding the context for the subtree instead
228
- * leaves every one of those paths untouched:
229
- *
230
- * - `isModalOpen` is replaced with the host's `open`, so the rendered surface
231
- * follows the prop from the very first frame (no open-then-close flash).
232
- * - `setModalOpen` still calls the underlying setter, so the existing
233
- * parent-sync and drawer mutual-exclusion side effects continue to run, and
234
- * *then* reports the request through `onOpenChange`.
235
- * - The wrapped setter is registered as the modal closer, so the drawer's
236
- * mobile mutual-exclusion reaches the host instead of silently flipping
237
- * state that nothing displays.
238
- *
239
- * A host that supplies `open` and ignores `onOpenChange` gets a modal pinned
240
- * to `open`, which is the standard controlled-component contract. A host that
241
- * supplies only `onOpenChange` is notified while the modal keeps managing
242
- * itself.
243
- *
244
- * Renders `children` unchanged when no chat configuration is in scope.
245
- */
246
- const ControlledModalOpenScope = ({ children, open, onOpenChange }) => {
247
- const parentConfig = useContext(CopilotChatConfiguration);
248
- const parentSetModalOpen = parentConfig?.setModalOpen;
249
- const registerModalCloser = parentConfig?.ɵregisterModalCloser;
250
- const setModalOpen = useCallback((next) => {
251
- parentSetModalOpen?.(next);
252
- onOpenChange?.(next);
253
- }, [parentSetModalOpen, onOpenChange]);
254
- useEffect(() => {
255
- if (!registerModalCloser) return;
256
- return registerModalCloser(setModalOpen);
257
- }, [registerModalCloser, setModalOpen]);
258
- const configurationValue = useMemo(() => parentConfig ? {
259
- ...parentConfig,
260
- isModalOpen: open ?? parentConfig.isModalOpen,
261
- setModalOpen
262
- } : null, [
263
- parentConfig,
264
- open,
265
- setModalOpen
266
- ]);
267
- if (!configurationValue) return /* @__PURE__ */ jsx(Fragment$1, { children });
268
- return /* @__PURE__ */ jsx(CopilotChatConfiguration.Provider, {
269
- value: configurationValue,
270
- children
271
- });
272
- };
273
- ControlledModalOpenScope.displayName = "ControlledModalOpenScope";
274
-
275
- //#endregion
276
- //#region src/lib/slots.tsx
277
- /**
278
- * Check if a value is a React component type (function, class, forwardRef, memo, etc.)
279
- */
280
- function isReactComponentType(value) {
281
- if (typeof value === "function") return true;
282
- if (value && typeof value === "object" && "$$typeof" in value && !React.isValidElement(value)) return true;
283
- return false;
284
- }
285
- /**
286
- * Internal function to render a slot value as a React element (non-memoized).
287
- */
288
- function renderSlotElement(slot, DefaultComponent, props) {
289
- if (typeof slot === "string") {
290
- const existingClassName = props.className;
291
- return React.createElement(DefaultComponent, {
292
- ...props,
293
- className: cn(existingClassName, slot)
294
- });
295
- }
296
- if (isReactComponentType(slot)) return React.createElement(slot, props);
297
- if (slot && typeof slot === "object" && !React.isValidElement(slot)) return React.createElement(DefaultComponent, {
298
- ...props,
299
- ...slot
300
- });
301
- return React.createElement(DefaultComponent, props);
302
- }
303
- /**
304
- * Internal memoized wrapper component for renderSlot.
305
- * Uses forwardRef to support ref forwarding.
306
- */
307
- const MemoizedSlotWrapper = React.memo(React.forwardRef(function MemoizedSlotWrapper(props, ref) {
308
- const { $slot, $component, ...rest } = props;
309
- return renderSlotElement($slot, $component, ref !== null ? {
310
- ...rest,
311
- ref
312
- } : rest);
313
- }), (prev, next) => {
314
- if (prev.$slot !== next.$slot) return false;
315
- if (prev.$component !== next.$component) return false;
316
- const { $slot: _ps, $component: _pc, ...prevRest } = prev;
317
- const { $slot: _ns, $component: _nc, ...nextRest } = next;
318
- return shallowEqual(prevRest, nextRest);
319
- });
320
- /**
321
- * Renders a slot value as a memoized React element.
322
- * Automatically prevents unnecessary re-renders using shallow prop comparison.
323
- * Supports ref forwarding.
324
- *
325
- * @example
326
- * renderSlot(customInput, CopilotChatInput, { onSubmit: handleSubmit })
327
- */
328
- function renderSlot(slot, DefaultComponent, props) {
329
- return React.createElement(MemoizedSlotWrapper, {
330
- ...props,
331
- $slot: slot,
332
- $component: DefaultComponent
333
- });
334
- }
335
-
336
- //#endregion
337
- //#region src/providers/MarkdownRendererContext.tsx
338
- const MarkdownRendererContext = createContext(void 0);
339
- const MarkdownRendererProvider = ({ renderer, children }) => /* @__PURE__ */ jsx(MarkdownRendererContext.Provider, {
340
- value: renderer,
341
- children
342
- });
343
- /**
344
- * The markdown renderer set at the provider level, or `undefined` when none was
345
- * supplied. Message components fall back to the built-in
346
- * `StreamingMarkdownDefaultRenderer` (via `CopilotChatAssistantMessage.MarkdownRenderer`)
347
- * when this is `undefined`.
348
- */
349
- function useMarkdownRenderer() {
350
- return useContext(MarkdownRendererContext);
351
- }
352
-
353
- //#endregion
354
- //#region src/types/defineToolCallRenderer.ts
355
- function defineToolCallRenderer(def) {
356
- const argsSchema = def.name === "*" && !def.args ? ɵanySchema : def.args;
357
- return {
358
- name: def.name,
359
- args: argsSchema,
360
- render: def.render,
361
- ...def.agentId ? { agentId: def.agentId } : {},
362
- ...def.group ? { group: true } : {}
363
- };
364
- }
365
-
366
- //#endregion
367
- //#region src/generative-ui/json-schema.ts
368
- /**
369
- * JSON Schema for a Standard Schema, without `$schema`. A prop marked by `child()` or `childList()`
370
- * becomes an A2UI `$ref` to `ComponentId` or `ChildList`.
371
- */
372
- function toJsonSchema(schema) {
373
- const { $schema: _omit, ...rest } = schemaToJsonSchema(schema);
374
- return applyChildRefMarks(rest);
375
- }
376
-
377
- //#endregion
378
- //#region src/generative-ui/catalog.ts
379
- /** The A2UI component envelope: `id`, `component`, `catalogId`, `accessibility`, `metadata`. */
380
- const RESERVED_KEYS = new Set([
381
- "id",
382
- "component",
383
- ...A2UI_COMPONENT_ENVELOPE_KEYS
384
- ]);
385
- /** The id of the catalog that declared each component, for the inspector. */
386
- const componentCatalogs = /* @__PURE__ */ new WeakMap();
387
- /**
388
- * The id of the catalog that declared each component of `ui`. A component
389
- * from `extends` keeps the id of its base. Not exported from the package.
390
- */
391
- function componentCatalogIds(ui) {
392
- return componentCatalogs.get(ui) ?? /* @__PURE__ */ new Map();
393
- }
394
- /**
395
- * The catalogs that an operation can name: the id of `ui`, then the ids of
396
- * the catalogs in its `extends` that declared a component. Not exported
397
- * from the package.
398
- */
399
- function catalogIdsOf(ui) {
400
- const declared = componentCatalogs.get(ui)?.values() ?? [];
401
- return [...new Set([ui.id, ...declared])];
402
- }
403
- /**
404
- * Experimental. Declares the components the model can render, the app state
405
- * they read, and the functions they call.
406
- *
407
- * - A prop with the name of a top-level state key is bound to that state.
408
- * - `bind: { prop: (state, props) => value }` binds a prop to a selector.
409
- * - An event binds to the function with its name, else to the name without
410
- * `on` (`onAddToCart` calls `addToCart`).
411
- * - `writable: ["value"]` gives the component a `setValue` prop. See
412
- * `GenerativeUIComponentDefinition.writable`.
413
- *
414
- * The model does not see bound props or matched events.
415
- *
416
- * @param config - `id`, then optional `extends`, `state`, `functions` and
417
- * `overrides`, then `components`. Put `state` before `components`, so the selectors
418
- * get typed state.
419
- * @throws Error when a name comes from two places, an override names no
420
- * component of the bases, `props` is not an object
421
- * schema with a JSON Schema, a key is reserved or used
422
- * twice on a component, an event matches two functions, an unmatched event
423
- * has no `parameters`, a `bind` key is not a prop, a `writable` key is not
424
- * a prop or is a bound prop, or a setter name is already a key of the
425
- * component. Also throws when `parameterOrder` contains duplicate or unknown
426
- * keys, or an ordered component declares integer-index keys whose JSON object
427
- * enumeration order cannot be controlled.
428
- *
429
- * @example
430
- * ```ts
431
- * const ui = createGenerativeUI({
432
- * id: "acme/store@1",
433
- * state: { cart: cartSchema },
434
- * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
435
- * components: {
436
- * CartSummary: {
437
- * component: CartSummary,
438
- * props: z.object({ count: z.number() }),
439
- * bind: { count: (state) => state.cart.count },
440
- * },
441
- * },
442
- * });
443
- * ```
444
- */
445
- function createGenerativeUI(config) {
446
- return buildGenerativeUI(config);
447
- }
448
- function buildGenerativeUI(config) {
449
- const where = `generative UI "${config.id}"`;
450
- const state = /* @__PURE__ */ new Map();
451
- const functions = /* @__PURE__ */ new Map();
452
- const definitions = /* @__PURE__ */ new Map();
453
- const catalogs = /* @__PURE__ */ new Map();
454
- function add(map, kind, name, value) {
455
- if (map.has(name)) throw new Error(`[generativeUI] ${kind} "${name}" is defined more than once in ${where}.`);
456
- map.set(name, value);
457
- }
458
- const bases = config.extends ?? [];
459
- for (const base of bases) {
460
- for (const [name, schema] of base.state) add(state, "State key", name, schema);
461
- for (const [name, fn] of base.functions) add(functions, "Function", name, fn);
462
- const baseCatalogs = componentCatalogIds(base);
463
- for (const [name, component] of base.components) {
464
- add(definitions, "Component", name, component);
465
- catalogs.set(name, baseCatalogs.get(name) ?? base.id);
466
- }
467
- }
468
- for (const [name, override] of Object.entries(config.overrides ?? {})) {
469
- const base = definitions.get(name);
470
- if (!base) throw new Error(`[generativeUI] Override "${name}" is not a component of the bases of ${where}.`);
471
- definitions.set(name, {
472
- ...base,
473
- component: override.component
474
- });
475
- }
476
- for (const [name, schema] of Object.entries(config.state ?? {})) add(state, "State key", name, schema);
477
- for (const [name, fn] of Object.entries(config.functions ?? {})) add(functions, "Function", name, fn);
478
- for (const [name, fn] of functions) if (fn.requiresUserActivation === true && fn.allowedCallers !== void 0 && fn.allowedCallers !== "rendererOnly") throw new Error(`[generativeUI] Function "${name}" in ${where} requires user activation, so its allowedCallers must be "rendererOnly", not "${fn.allowedCallers}".`);
479
- for (const [name, component] of Object.entries(config.components)) {
480
- add(definitions, "Component", name, component);
481
- catalogs.set(name, config.id);
482
- }
483
- const components = /* @__PURE__ */ new Map();
484
- const manifestComponents = {};
485
- for (const [name, definition] of definitions) {
486
- const { component, manifest } = resolveComponent(name, definition, {
487
- state,
488
- functions,
489
- where
490
- });
491
- components.set(name, component);
492
- manifestComponents[name] = manifest;
493
- }
494
- return withOmit({
495
- id: config.id,
496
- state,
497
- functions,
498
- components,
499
- manifestComponents
500
- }, catalogs);
501
- }
502
- /** Adds the `omit` method to the data of a generative UI. */
503
- function withOmit(data, catalogs) {
504
- const omit = (names) => {
505
- for (const name of names) if (!data.components.has(name)) throw new Error(`[generativeUI] Cannot omit "${name}": it is not a component of generative UI "${data.id}".`);
506
- const isKept = (name) => !names.includes(name);
507
- return withOmit({
508
- id: data.id,
509
- state: data.state,
510
- functions: data.functions,
511
- components: new Map([...data.components].filter(([name]) => isKept(name))),
512
- manifestComponents: Object.fromEntries(Object.entries(data.manifestComponents).filter(([name]) => isKept(name)))
513
- }, catalogs);
514
- };
515
- const ui = {
516
- ...data,
517
- omit
518
- };
519
- componentCatalogs.set(ui, catalogs);
520
- return ui;
521
- }
522
- /** Builds the selectors, the event map and the manifest of one component. */
523
- function resolveComponent(name, definition, context) {
524
- const propsJson = propsJsonSchema(name, definition, context.where);
525
- const propKeys = Object.keys(propsJson.properties);
526
- assertDisjointKeys(name, definition, propKeys);
527
- assertParameterOrder(name, definition, propKeys);
528
- const selectors = {};
529
- for (const key of propKeys) if (context.state.has(key)) selectors[key] = (state) => state[key];
530
- const bind = definition.bind ?? {};
531
- for (const [key, selector] of Object.entries(bind)) {
532
- if (!propKeys.includes(key)) throw new Error(`[generativeUI] bind key "${key}" is not a prop of component "${name}" in ${context.where}.`);
533
- selectors[key] = selector;
534
- }
535
- const eventFunctions = {};
536
- const modelEvents = {};
537
- const events = definition.events ?? {};
538
- for (const [eventName, event] of Object.entries(events)) {
539
- const functionName = matchFunction(eventName, name, context);
540
- if (functionName !== void 0) {
541
- const matched = context.functions.get(functionName);
542
- if (matched && !functionCallers(matched).renderer) throw new Error(`[generativeUI] Event "${eventName}" of component "${name}" matches function "${functionName}", which the UI cannot call (allowedCallers "agentOnly") in ${context.where}.`);
543
- eventFunctions[eventName] = functionName;
544
- continue;
545
- }
546
- if (!event.parameters) throw new Error(`[generativeUI] Event "${eventName}" of component "${name}" matches no function in ${context.where}, so it needs "parameters".`);
547
- modelEvents[eventName] = {
548
- ...event.description ? { description: event.description } : {},
549
- parameters: toJsonSchema(event.parameters)
550
- };
551
- }
552
- assertWritable(name, definition, propKeys, selectors, context.where);
553
- return {
554
- component: {
555
- component: definition.component,
556
- description: definition.description,
557
- parameterOrder: definition.parameterOrder?.slice(),
558
- props: definition.props,
559
- bind: definition.bind,
560
- events: definition.events,
561
- slots: definition.slots,
562
- writable: definition.writable,
563
- accessibility: definition.accessibility ?? "wrapper",
564
- selectors,
565
- eventFunctions,
566
- propKeys,
567
- childRefs: collectChildRefs(propsJson)
568
- },
569
- manifest: toManifest(definition, modelPropsJsonSchema(propsJson, selectors), modelEvents)
570
- };
571
- }
572
- /** The JSON Schema of `props`. A component without `props` has none. */
573
- function propsJsonSchema(name, definition, where) {
574
- if (!definition.props) return {
575
- type: "object",
576
- properties: {}
577
- };
578
- const json = toJsonSchema(definition.props);
579
- const { properties } = json;
580
- if (!(typeof properties === "object" && properties !== null && !Array.isArray(properties))) throw new Error(`[generativeUI] the props of component "${name}" in ${where} must be an object schema.`);
581
- return json;
582
- }
583
- /**
584
- * What the model sees of the props: the JSON Schema without the bound props,
585
- * and with no other keys allowed.
586
- */
587
- function modelPropsJsonSchema(json, bound) {
588
- const isModelKey = (key) => !Object.hasOwn(bound, key);
589
- const { properties, required, additionalProperties: _additionalProperties, ...rest } = json;
590
- const modelRequired = Array.isArray(required) ? required.filter((key) => isModelKey(String(key))) : [];
591
- return {
592
- ...rest,
593
- type: "object",
594
- properties: Object.fromEntries(Object.entries(properties).filter(([key]) => isModelKey(key))),
595
- ...modelRequired.length > 0 ? { required: modelRequired } : {},
596
- additionalProperties: false
597
- };
598
- }
599
- /** `onAddToCart` to `addToCart`. `undefined` when the name has no `on` prefix. */
600
- function withoutOnPrefix(eventName) {
601
- if (!(eventName.length > 2 && eventName.startsWith("on"))) return void 0;
602
- return eventName.charAt(2).toLowerCase() + eventName.slice(3);
603
- }
604
- /** The declared function an event calls, or `undefined` when none matches. */
605
- function matchFunction(eventName, componentName, context) {
606
- const exact = context.functions.has(eventName) ? eventName : void 0;
607
- const stripped = withoutOnPrefix(eventName);
608
- const fromPrefix = stripped !== void 0 && context.functions.has(stripped) ? stripped : void 0;
609
- if (exact !== void 0 && fromPrefix !== void 0) throw new Error(`[generativeUI] Event "${eventName}" of component "${componentName}" matches two functions, "${exact}" and "${fromPrefix}", in ${context.where}.`);
610
- return exact ?? fromPrefix;
611
- }
612
- /** The setter prop of a writable prop: `value` gives `setValue`. */
613
- function setterNameOf(key) {
614
- return `set${key.charAt(0).toUpperCase()}${key.slice(1)}`;
615
- }
616
- /** Why a `writable` key is not valid, or `undefined` when it is valid. */
617
- function writableProblem(key, definition, propKeys, selectors) {
618
- if (Object.hasOwn(definition.events ?? {}, key)) return "an event";
619
- if (Object.hasOwn(definition.slots ?? {}, key)) return "a slot";
620
- if (!propKeys.includes(key)) return "not a prop";
621
- if (Object.hasOwn(selectors, key)) return "a bound prop";
622
- }
623
- function assertWritable(name, definition, propKeys, selectors, where) {
624
- const writable = definition.writable ?? [];
625
- const keys = new Set([
626
- ...propKeys,
627
- ...Object.keys(definition.events ?? {}),
628
- ...Object.keys(definition.slots ?? {})
629
- ]);
630
- for (const key of writable) {
631
- const problem = writableProblem(key, definition, propKeys, selectors);
632
- if (problem) throw new Error(`[generativeUI] writable key "${key}" of component "${name}" is ${problem} in ${where}.`);
633
- const setter = setterNameOf(key);
634
- if (keys.has(setter)) throw new Error(`[generativeUI] the setter "${setter}" of writable key "${key}" is already a key of component "${name}" in ${where}.`);
635
- }
636
- }
637
- function assertDisjointKeys(name, definition, propKeys) {
638
- const seen = /* @__PURE__ */ new Set();
639
- const keys = [
640
- ...propKeys,
641
- ...Object.keys(definition.events ?? {}),
642
- ...Object.keys(definition.slots ?? {})
643
- ];
644
- for (const key of keys) {
645
- if (RESERVED_KEYS.has(key)) throw new Error(`[generativeUI] "${key}" is reserved by A2UI and cannot be a prop, event or slot of component "${name}".`);
646
- if (seen.has(key)) throw new Error(`[generativeUI] "${key}" is declared as more than one of prop, event, slot on component "${name}".`);
647
- seen.add(key);
648
- }
649
- }
650
- function assertParameterOrder(name, definition, propKeys) {
651
- const order = definition.parameterOrder;
652
- if (order === void 0) return;
653
- const keys = new Set([
654
- ...propKeys,
655
- ...Object.keys(definition.slots ?? {}),
656
- ...Object.keys(definition.events ?? {})
657
- ]);
658
- if ([...keys].some((key) => {
659
- const index = Number(key);
660
- return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === key;
661
- })) throw new Error(`[generativeUI] Component "${name}" with parameterOrder cannot declare integer-index keys: JSON object enumeration sorts them numerically before other keys, ignoring the requested order.`);
662
- if (!Array.isArray(order) || new Set(order).size !== order.length || order.some((key) => !keys.has(key))) throw new Error(`[generativeUI] parameterOrder of component "${name}" must contain unique declared prop, slot or event names.`);
663
- }
664
- function toManifest(definition, modelProps, modelEvents) {
665
- const manifest = { props: modelProps };
666
- if (definition.description) manifest.description = definition.description;
667
- if (Object.keys(modelEvents).length > 0) manifest.events = modelEvents;
668
- if (definition.slots) manifest.slots = { ...definition.slots };
669
- if (definition.parameterOrder !== void 0) {
670
- const visible = new Set([
671
- ...Object.keys(modelProps.properties ?? {}),
672
- ...Object.keys(definition.slots ?? {}),
673
- ...Object.keys(modelEvents)
674
- ]);
675
- manifest.parameterOrder = [...new Set([...definition.parameterOrder.filter((key) => visible.has(key)), ...visible])];
676
- }
677
- return manifest;
678
- }
679
-
680
- //#endregion
681
- //#region src/generative-ui/errors.ts
682
- var GenerativeUIError = class extends Error {
683
- code;
684
- constructor(code, message) {
685
- super(message);
686
- this.name = "GenerativeUIError";
687
- this.code = code;
688
- }
689
- };
690
-
691
- //#endregion
692
- //#region src/generative-ui/functions.ts
693
- /**
694
- * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes
695
- * resolved args (no bindings left in them) and gives a plain value. They
696
- * run synchronously, so a prop bound to one updates in the same render as
697
- * the data it reads. The signatures the model sees are in
698
- * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).
699
- */
700
- /** Thrown for a bad call: an unknown function, bad args, or a bad value. */
701
- var ExpressionError = class extends Error {
702
- constructor(message) {
703
- super(message);
704
- this.name = "ExpressionError";
705
- }
706
- };
707
- /** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
708
- function truthOf(value) {
709
- if (isValidationResult(value)) return value.valid;
710
- return Boolean(value);
711
- }
712
- const valid = () => ({ valid: true });
713
- /** A failed result. `code` names the failure, the same for every locale. */
714
- const invalid = (message, code) => ({
715
- valid: false,
716
- message,
717
- code
718
- });
719
- function text(value) {
720
- if (value === void 0 || value === null) return "";
721
- return typeof value === "string" ? value : String(value);
722
- }
723
- function numberOf$1(value) {
724
- if (typeof value === "number") return value;
725
- if (typeof value === "string" && value.trim() !== "") return Number(value);
726
- return NaN;
727
- }
728
- function optionalNumber(value, name) {
729
- if (value === void 0 || value === null) return void 0;
730
- const parsed = numberOf$1(value);
731
- if (Number.isNaN(parsed)) throw new ExpressionError(`${name} must be a number`);
732
- return parsed;
733
- }
734
- const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
735
- /** The locale of the user. `undefined` lets Intl pick the default. */
736
- function locale() {
737
- return typeof navigator !== "undefined" ? navigator.language : void 0;
738
- }
739
- function numberFormat(args, options) {
740
- const decimals = optionalNumber(args.decimals, "decimals");
741
- return new Intl.NumberFormat(locale(), {
742
- ...options,
743
- useGrouping: args.grouping !== false,
744
- ...decimals === void 0 ? {} : {
745
- minimumFractionDigits: decimals,
746
- maximumFractionDigits: decimals
747
- }
748
- });
749
- }
750
- /** A date from an ISO string, a timestamp, or a Date. */
751
- function dateOf(value) {
752
- const date = value instanceof Date ? value : typeof value === "number" ? new Date(value) : typeof value === "string" ? new Date(/^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00` : value) : void 0;
753
- if (date === void 0 || Number.isNaN(date.getTime())) throw new ExpressionError("value must be a date");
754
- return date;
755
- }
756
- const pad = (value, width) => String(value).padStart(width, "0");
757
- /**
758
- * A TR35 field is a run of one letter ("EEE" is one abbreviated weekday,
759
- * not three), and text in single quotes is literal. Letters that are not
760
- * fields stay as they are.
761
- */
762
- const DATE_FIELD = /([A-Za-z])\1*|'(?:[^']|'')*'/g;
763
- function formatDatePattern(date, pattern) {
764
- const parts = (options) => new Intl.DateTimeFormat(locale(), options).format(date);
765
- const hours12 = date.getHours() % 12 || 12;
766
- const numeric = (value, width) => width >= 2 ? pad(value, 2) : String(value);
767
- return pattern.replace(DATE_FIELD, (token) => {
768
- if (token.startsWith("'")) return token.slice(1, -1).replace(/''/g, "'");
769
- const width = token.length;
770
- switch (token[0]) {
771
- case "y": return width === 2 ? pad(date.getFullYear() % 100, 2) : String(date.getFullYear());
772
- case "M":
773
- if (width >= 4) return parts({ month: "long" });
774
- if (width === 3) return parts({ month: "short" });
775
- return numeric(date.getMonth() + 1, width);
776
- case "d": return numeric(date.getDate(), width);
777
- case "E": return parts({ weekday: width >= 4 ? "long" : "short" });
778
- case "H": return numeric(date.getHours(), width);
779
- case "h": return numeric(hours12, width);
780
- case "m": return pad(date.getMinutes(), 2);
781
- case "s": return pad(date.getSeconds(), 2);
782
- case "a": return date.getHours() < 12 ? "AM" : "PM";
783
- case void 0:
784
- default: return token;
785
- }
786
- });
787
- }
788
- /** Opens an http(s) URL in a new tab. Any other scheme is refused. */
789
- function openUrlSafely(url) {
790
- if (typeof url !== "string" || url === "") throw new ExpressionError("url must be a string");
791
- if (typeof window === "undefined") return;
792
- let parsed;
793
- try {
794
- parsed = new URL(url, window.location.href);
795
- } catch {
796
- throw new ExpressionError(`"${url}" is not a URL`);
797
- }
798
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new ExpressionError(`openUrl takes only http(s) URLs, not ${parsed.protocol}`);
799
- window.open(parsed.href, "_blank", "noopener,noreferrer");
800
- }
801
- /**
802
- * The basic functions, except `formatString`, which needs the resolver.
803
- * `calc` and `series` are added by `resolve.ts`, which imports both.
804
- */
805
- const BASIC_FUNCTIONS = {
806
- required: ({ value }) => {
807
- return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 ? invalid("Required", "required") : valid();
808
- },
809
- regex: ({ value, pattern }) => {
810
- if (typeof pattern !== "string") throw new ExpressionError("pattern must be a string");
811
- let expression;
812
- try {
813
- expression = new RegExp(pattern, "u");
814
- } catch {
815
- throw new ExpressionError(`"${pattern}" is not a regular expression`);
816
- }
817
- return expression.test(text(value)) ? valid() : invalid("Invalid format", "pattern");
818
- },
819
- length: ({ value, min, max }) => {
820
- const size = text(value).length;
821
- const low = optionalNumber(min, "min");
822
- const high = optionalNumber(max, "max");
823
- if (low !== void 0 && size < low) return invalid(`At least ${low} characters`, "tooShort");
824
- if (high !== void 0 && size > high) return invalid(`At most ${high} characters`, "tooLong");
825
- return valid();
826
- },
827
- numeric: ({ value, min, max }) => {
828
- const parsed = numberOf$1(value);
829
- if (Number.isNaN(parsed)) return invalid("Must be a number", "notANumber");
830
- const low = optionalNumber(min, "min");
831
- const high = optionalNumber(max, "max");
832
- if (low !== void 0 && parsed < low) return invalid(`At least ${low}`, "tooSmall");
833
- if (high !== void 0 && parsed > high) return invalid(`At most ${high}`, "tooLarge");
834
- return valid();
835
- },
836
- email: ({ value }) => EMAIL.test(text(value)) ? valid() : invalid("Invalid email address", "email"),
837
- formatNumber: (args) => {
838
- const parsed = numberOf$1(args.value);
839
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
840
- return numberFormat(args, {}).format(parsed);
841
- },
842
- formatCurrency: (args) => {
843
- const parsed = numberOf$1(args.value);
844
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
845
- if (typeof args.currency !== "string" || args.currency === "") throw new ExpressionError("currency must be an ISO 4217 code");
846
- try {
847
- return numberFormat(args, {
848
- style: "currency",
849
- currency: args.currency
850
- }).format(parsed);
851
- } catch {
852
- throw new ExpressionError(`"${args.currency}" is not a currency code`);
853
- }
854
- },
855
- formatDate: ({ value, format }) => {
856
- if (typeof format !== "string") throw new ExpressionError("format must be a string");
857
- return formatDatePattern(dateOf(value), format);
858
- },
859
- pluralize: (args) => {
860
- const parsed = numberOf$1(args.value);
861
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
862
- const category = new Intl.PluralRules(locale()).select(parsed);
863
- return text((parsed === 0 ? args.zero : void 0) ?? args[category] ?? args.other);
864
- },
865
- and: ({ values }) => {
866
- if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
867
- return values.every(truthOf);
868
- },
869
- or: ({ values }) => {
870
- if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
871
- return values.some(truthOf);
872
- },
873
- not: ({ value }) => !truthOf(value),
874
- openUrl: ({ url }) => {
875
- openUrlSafely(url);
876
- }
877
- };
878
- /** True when the basic function `name` must run from a user gesture. */
879
- function requiresUserActivation(name) {
880
- return GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;
881
- }
882
- /** True when a basic function gives a ValidationResult. */
883
- function givesValidationResult(name) {
884
- return GENERATIVE_UI_FUNCTIONS[name]?.returnType === "validationResult";
885
- }
886
-
887
- //#endregion
888
- //#region src/generative-ui/is-record.ts
889
- /** True for a plain object: not null, not an array. Internal, not exported. */
890
- function isRecord(value) {
891
- return typeof value === "object" && value !== null && !Array.isArray(value);
892
- }
893
-
894
- //#endregion
895
- //#region src/generative-ui/markdown/source.ts
896
- /**
897
- * Values by key, from the latest build. A value that a build does not use
898
- * is dropped at the end of that build, so the cache does not grow.
899
- */
900
- var BuildMemo = class {
901
- previous = /* @__PURE__ */ new Map();
902
- current = /* @__PURE__ */ new Map();
903
- /**
904
- * The value of `key`. It is computed when no earlier value is there, or
905
- * when `isFresh` says that the earlier value is out of date.
906
- */
907
- get(key, compute, isFresh = () => true) {
908
- let value = this.current.get(key) ?? this.previous.get(key);
909
- if (value === void 0 || !isFresh(value)) value = compute();
910
- this.current.set(key, value);
911
- return value;
912
- }
913
- endBuild() {
914
- this.previous = this.current;
915
- this.current = /* @__PURE__ */ new Map();
916
- }
917
- };
918
- /** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
919
- var MarkdownBuildCache = class {
920
- segments = new BuildMemo();
921
- fences = new BuildMemo();
922
- drafts = new BuildMemo();
923
- /** The copies of an operation for other surface ids, by operation. */
924
- readdressed = /* @__PURE__ */ new WeakMap();
925
- endBuild() {
926
- this.segments.endBuild();
927
- this.fences.endBuild();
928
- this.drafts.endBuild();
929
- }
930
- };
931
- /** True when both lists hold the same objects in the same order. */
932
- function sameItems(a, b) {
933
- return a.length === b.length && a.every((item, index) => item === b[index]);
934
- }
935
- function isString(value) {
936
- return typeof value === "string";
937
- }
938
- /** The key of one fence of one message. */
939
- function fenceKey(messageId, fenceIndex) {
940
- return `${messageId}:${fenceIndex}`;
941
- }
942
- /**
943
- * The operations of a fence body. While the fence streams, the last object
944
- * can be unfinished. Of an unfinished updateComponents or createSurface, the
945
- * components that are complete render at once (a createSurface also keeps
946
- * its data model when all of it arrived). Any other unfinished object is
947
- * left out, because a part of a data model value can still change. A final
948
- * fence keeps what can be saved from an unfinished object.
949
- */
950
- function fenceOperations(text, isStreaming) {
951
- const parsed = extractFenceOperations(text);
952
- if (!isStreaming || parsed.partialObject === null) return parsed.operations;
953
- const complete = extractFenceOperations(text.slice(0, text.length - parsed.partialObject.length)).operations;
954
- const partial = parsed.operations.length > complete.length ? parsed.operations[parsed.operations.length - 1] : void 0;
955
- return partial !== void 0 && (isRecord(partial.updateComponents) || isRecord(partial.createSurface)) ? [...complete, partial] : complete;
956
- }
957
- /**
958
- * An inline createSurface becomes a createSurface with only its surfaceId
959
- * and catalog, then an updateDataModel for its data model, then an
960
- * updateComponents for its components. The prose lift and the split per
961
- * component read only updateComponents, so they then work for an inline
962
- * surface too. A createSurface with a data model or components of a wrong
963
- * shape does not change, so that validation rejects it with the reason.
964
- */
965
- function expandInlineCreate(operations) {
966
- return operations.flatMap((op) => {
967
- const create = op.createSurface;
968
- if (!isRecord(create)) return [op];
969
- const { dataModel, components, ...rest } = create;
970
- const hasData = isRecord(dataModel);
971
- const hasComponents = Array.isArray(components) && components.length > 0;
972
- if (!((dataModel === void 0 || hasData) && (components === void 0 || hasComponents)) || !hasData && !hasComponents) return [op];
973
- const { surfaceId } = create;
974
- const expanded = [{
975
- ...op,
976
- createSurface: rest
977
- }];
978
- if (hasData) expanded.push({
979
- version: op.version,
980
- updateDataModel: {
981
- surfaceId,
982
- path: "/",
983
- value: dataModel
984
- }
985
- });
986
- if (hasComponents) expanded.push({
987
- version: op.version,
988
- updateComponents: {
989
- surfaceId,
990
- components
991
- }
992
- });
993
- return expanded;
994
- });
995
- }
996
- /**
997
- * Each updateComponents becomes one operation per component, in order. The
998
- * complete components of a streaming line then give the same first
999
- * operations as the finished line, so the operation list only grows and the
1000
- * manager never has to start the surface again.
1001
- */
1002
- function splitComponentUpdates(operations) {
1003
- return operations.flatMap((op) => {
1004
- const update = op.updateComponents;
1005
- if (!isRecord(update) || !Array.isArray(update.components)) return [op];
1006
- if (update.components.length <= 1) return [op];
1007
- return update.components.map((component) => ({
1008
- ...op,
1009
- updateComponents: {
1010
- ...update,
1011
- components: [component]
1012
- }
1013
- }));
1014
- });
1015
- }
1016
- /** createSurface first, the other operations after it in their order. */
1017
- function createSurfaceFirst(operations) {
1018
- const creates = operations.filter((op) => isRecord(op.createSurface));
1019
- const others = operations.filter((op) => !isRecord(op.createSurface));
1020
- return [...creates, ...others];
1021
- }
1022
- /** True when the component of `name` has the prop `prop`. */
1023
- function hasProp(ui, name, prop) {
1024
- const properties = ui.manifestComponents[name]?.props.properties;
1025
- return isRecord(properties) && Object.hasOwn(properties, prop);
1026
- }
1027
- const childRefCache = /* @__PURE__ */ new WeakMap();
1028
- /** The ids in a slot value: an id, a list of ids, or a template. */
1029
- function slotIds(value) {
1030
- if (typeof value === "string") return [value];
1031
- if (Array.isArray(value)) return value.filter(isString);
1032
- return isRecord(value) && isString(value.componentId) ? [value.componentId] : [];
1033
- }
1034
- /**
1035
- * A reader of the ids a component renders beyond `child` and `children`:
1036
- * its declared slots (the `trigger` and `content` of a Modal) and its typed
1037
- * child references (the `child` of each entry of `tabs`), from its catalog
1038
- * entry. The prose lift follows these ids like `children`, so a panel is
1039
- * never cut off from its Tabs. A reference that is bound to the data
1040
- * model is "unknown": its ids exist only at render time.
1041
- */
1042
- function childIdsReader(ui) {
1043
- return (component) => {
1044
- const name = component.component;
1045
- const entry = typeof name === "string" && Object.hasOwn(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
1046
- if (!entry) return [];
1047
- const ids = [];
1048
- for (const slot of Object.keys(entry.slots ?? {})) if (slot !== "child" && slot !== "children") ids.push(...slotIds(component[slot]));
1049
- let refs = childRefCache.get(entry.props);
1050
- if (!refs) {
1051
- refs = collectChildRefs(entry.props);
1052
- childRefCache.set(entry.props, refs);
1053
- }
1054
- if (refs.length === 0) return ids;
1055
- if (hasBoundChildRef(component, refs)) return "unknown";
1056
- return [...ids, ...childIdsAtRefs(component, refs)];
1057
- };
1058
- }
1059
- /** Every component of the operations by id, last definition wins. */
1060
- function collectComponents(operations) {
1061
- const byId = /* @__PURE__ */ new Map();
1062
- for (const op of operations) {
1063
- const update = op.updateComponents;
1064
- const list = isRecord(update) ? update.components : void 0;
1065
- if (!Array.isArray(list)) continue;
1066
- for (const component of list) if (isRecord(component) && isString(component.id)) byId.set(component.id, component);
1067
- }
1068
- return [...byId.values()];
1069
- }
1070
- /**
1071
- * The data model must not be shared between two surfaces. A data model
1072
- * keeps the object it gets, so an input in one surface would change the
1073
- * data of the other one.
1074
- */
1075
- function cloneData(value) {
1076
- return value === void 0 ? void 0 : structuredClone(value);
1077
- }
1078
- /** The operation sent to `surfaceId`, with a copy of its data model value. */
1079
- function readdress(op, surfaceId) {
1080
- const kind = getOperationKind(op);
1081
- const payload = kind ? op[kind] : void 0;
1082
- if (!kind || !isRecord(payload)) return op;
1083
- const next = {
1084
- ...payload,
1085
- surfaceId
1086
- };
1087
- if (kind === "updateDataModel" && "value" in payload) next.value = cloneData(payload.value);
1088
- return {
1089
- ...op,
1090
- [kind]: next
1091
- };
1092
- }
1093
- /**
1094
- * The operations of one sub-surface. Each updateComponents keeps only the
1095
- * components of the sub-surface, with its own root. The other operations
1096
- * are sent to the sub-surface. The order stays the same, so a new operation
1097
- * of the fence only adds operations at the end.
1098
- */
1099
- function subSurfaceOperations(operations, components, surfaceId) {
1100
- const root = components.find((c) => c.id === GENERATIVE_UI_ROOT_ID);
1101
- const ids = new Set(components.map((c) => c.id));
1102
- const out = [];
1103
- for (const op of operations) {
1104
- const update = op.updateComponents;
1105
- if (!isRecord(update) || !Array.isArray(update.components)) {
1106
- out.push(readdress(op, surfaceId));
1107
- continue;
1108
- }
1109
- const kept = update.components.filter((c) => isRecord(c) && ids.has(c.id)).map((c) => isRecord(c) && c.id === GENERATIVE_UI_ROOT_ID ? root : c);
1110
- if (kept.length === 0) continue;
1111
- out.push({
1112
- ...op,
1113
- updateComponents: {
1114
- ...update,
1115
- surfaceId,
1116
- components: kept
1117
- }
1118
- });
1119
- }
1120
- return out;
1121
- }
1122
- /**
1123
- * Prose lift. Text components in the main stack of the surface (titles,
1124
- * paragraphs, text lists and the dividers between them) become chat
1125
- * markdown. The surface splits around them: the first surface keeps
1126
- * `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so
1127
- * on. A surface with no prose comes back as one part with the same
1128
- * operations.
1129
- */
1130
- function liftProse(operations, surfaceId, childIds) {
1131
- const components = collectComponents(operations);
1132
- const segments = segmentSurfaceProse(components, { childIds });
1133
- const [first] = segments;
1134
- if (segments.length === 1 && first?.kind === "surface" && first.components === components) return [{
1135
- kind: "surface",
1136
- surfaceId,
1137
- operations
1138
- }];
1139
- let surfaceIndex = 0;
1140
- return segments.map((segment) => {
1141
- if (segment.kind === "markdown") return segment;
1142
- const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;
1143
- surfaceIndex++;
1144
- return {
1145
- kind: "surface",
1146
- surfaceId: id,
1147
- operations: subSurfaceOperations(operations, segment.components, id)
1148
- };
1149
- });
1150
- }
1151
- /** `validateOperation`, with the operation typed when it is valid. */
1152
- function checkOperation(op, options) {
1153
- const validation = validateOperation(op, options);
1154
- if (!validation.ok) return validation;
1155
- return {
1156
- ok: true,
1157
- operation: op
1158
- };
1159
- }
1160
- /**
1161
- * The content of one surface. Each operation is validated against the
1162
- * manifest. A valid operation goes in `operations`. A rejected one goes in
1163
- * `rejected`, with its position and the reason.
1164
- */
1165
- function surfaceContent(surfaceId, draft, operations, options) {
1166
- const { ui, functions } = options;
1167
- const knownSurfaces = /* @__PURE__ */ new Set();
1168
- const manifest = {
1169
- catalogId: ui.id,
1170
- catalogIds: catalogIdsOf(ui),
1171
- components: ui.manifestComponents
1172
- };
1173
- const valid = [];
1174
- const rejected = [];
1175
- operations.forEach((op, index) => {
1176
- const result = checkOperation(op, {
1177
- manifest,
1178
- knownSurfaces,
1179
- functions
1180
- });
1181
- if (!result.ok) {
1182
- rejected.push({
1183
- index,
1184
- reason: result.reason
1185
- });
1186
- return;
1187
- }
1188
- valid.push(result.operation);
1189
- const kind = getOperationKind(result.operation);
1190
- if (kind === "createSurface") knownSurfaces.add(surfaceId);
1191
- if (kind === "deleteSurface") knownSurfaces.delete(surfaceId);
1192
- });
1193
- const create = valid.find((op) => "createSurface" in op);
1194
- return {
1195
- surfaceId,
1196
- target: draft.target,
1197
- catalogId: create?.createSurface.catalogId ?? ui.id,
1198
- operations: valid,
1199
- status: draft.streaming ? "streaming" : "ready",
1200
- rejected
1201
- };
1202
- }
1203
- /**
1204
- * Builds the surfaces of a thread from the ```a2ui fences of its assistant
1205
- * messages, in message order.
1206
- *
1207
- * - Operations are grouped by surfaceId across all messages. An operation
1208
- * with no surfaceId goes to the first surface of its fence, else to
1209
- * `<messageId>-<fenceIndex>`.
1210
- * - The fence that first writes a surface creates it. The `target=<id>` of
1211
- * that fence sets the target. With no target, the surface goes to the
1212
- * chat.
1213
- * - A later fence of the same reply for the same surfaceId updates it. A
1214
- * later reply that reuses the id of a chat surface gets a surface of its
1215
- * own, `<id>@<messageId>`. A page target is updated from any reply.
1216
- * - The status is "streaming" while the creating fence streams, else
1217
- * "ready".
1218
- * - Each operation is validated with `validateOperation`. Rejected ones are
1219
- * left out and listed in `rejected`.
1220
- * - Chat surfaces get the prose lift: informational cards lose their box,
1221
- * and prose becomes markdown that renders between sub-surfaces
1222
- * (`<surfaceId>#<n>`). An inline createSurface is split into its
1223
- * createSurface, updateDataModel and updateComponents first.
1224
- * - A `callRendererFunction` line is not part of a surface. It goes to
1225
- * `functionCalls`. A streaming line gives nothing, so a function never
1226
- * runs with a part of its args.
1227
- *
1228
- * The function is pure. Call it again on each stream update. The manager
1229
- * applies only the new operations, so unchanged surfaces do not render
1230
- * again.
1231
- *
1232
- * @param messages - The messages of one thread.
1233
- * @param options - The generative UI, its declared functions, and whether
1234
- * the last message can still grow.
1235
- * @returns `surfaces`, one content for each surface and sub-surface;
1236
- * `fences`, the blocks that each fence renders, by `fenceKey` (a fence
1237
- * that is not in `fences` renders nothing); `functionCalls`, the function
1238
- * calls of the fences in order; and `parts`, the surface ids of the parts
1239
- * of each surface, by surface id.
1240
- *
1241
- * @example
1242
- * ```ts
1243
- * const { surfaces } = buildMarkdownSurfaces(agent.messages, {
1244
- * ui,
1245
- * functions: {},
1246
- * running: agent.isRunning,
1247
- * });
1248
- * for (const content of surfaces) manager.ingest(threadId, agentId, content);
1249
- * ```
1250
- */
1251
- function buildMarkdownSurfaces(messages, options) {
1252
- const { ui, cache } = options;
1253
- const drafts = /* @__PURE__ */ new Map();
1254
- const readdressOnce = (op, surfaceId) => {
1255
- if (!cache) return readdress(op, surfaceId);
1256
- let copies = cache.readdressed.get(op);
1257
- if (!copies) {
1258
- copies = /* @__PURE__ */ new Map();
1259
- cache.readdressed.set(op, copies);
1260
- }
1261
- let copy = copies.get(surfaceId);
1262
- if (!copy) {
1263
- copy = readdress(op, surfaceId);
1264
- copies.set(surfaceId, copy);
1265
- }
1266
- return copy;
1267
- };
1268
- /** The surfaces that each fence created, in order. */
1269
- const created = /* @__PURE__ */ new Map();
1270
- const functionCalls = [];
1271
- /** The message that owns each chat surface id, by the id the model wrote. */
1272
- const chatOwners = /* @__PURE__ */ new Map();
1273
- const lastMessage = messages[messages.length - 1];
1274
- /**
1275
- * A chat surface belongs to the reply that wrote it: the chat is a
1276
- * transcript, so a later reply that reuses an id gets a surface of its
1277
- * own (`<id>@<messageId>`) instead of changing the earlier reply. A fence
1278
- * for a page target keeps its id, because a target is a place on the
1279
- * page that a later reply updates on purpose.
1280
- */
1281
- const scopedSurfaceId = (requested, messageId, target) => {
1282
- if (target !== void 0) return requested;
1283
- const owner = chatOwners.get(requested);
1284
- if (owner === void 0) {
1285
- chatOwners.set(requested, messageId);
1286
- return requested;
1287
- }
1288
- return owner === messageId ? requested : `${requested}@${messageId}`;
1289
- };
1290
- for (const message of messages) {
1291
- if (message.role !== "assistant" || !isString(message.content)) continue;
1292
- const isLastMessage = message === lastMessage;
1293
- const content = message.content;
1294
- const segments = cache ? cache.segments.get(content, () => splitA2UIMarkdown(content)) : splitA2UIMarkdown(content);
1295
- for (const segment of segments) {
1296
- if (segment.type !== "a2ui") continue;
1297
- const isStreaming = !segment.closed && isLastMessage && options.running;
1298
- const parseFence = () => {
1299
- const parsed = fenceOperations(segment.text, isStreaming);
1300
- const { functionCalls } = prepareSurfaceOperations({
1301
- operations: parsed,
1302
- fallbackSurfaceId: "",
1303
- catalogId: ui.id
1304
- });
1305
- return {
1306
- operations: parsed,
1307
- functionCalls
1308
- };
1309
- };
1310
- const fence = cache ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence) : parseFence();
1311
- const { operations } = fence;
1312
- const key = fenceKey(message.id, segment.index);
1313
- const fenceSurfaceId = operations.map(getMarkdownOperationSurfaceId).find(isString) ?? `${message.id}-${segment.index}`;
1314
- for (const operation of fence.functionCalls) functionCalls.push({
1315
- messageId: message.id,
1316
- fenceIndex: segment.index,
1317
- operation
1318
- });
1319
- const surfaceOperations = operations.filter((op) => getOperationKind(op) !== "callRendererFunction");
1320
- for (const op of surfaceOperations) {
1321
- const requested = getMarkdownOperationSurfaceId(op) ?? fenceSurfaceId;
1322
- const surfaceId = scopedSurfaceId(requested, message.id, segment.target);
1323
- let draft = drafts.get(surfaceId);
1324
- if (!draft) {
1325
- draft = {
1326
- surfaceId,
1327
- target: segment.target ?? GENERATIVE_UI_CHAT_TARGET,
1328
- operations: [],
1329
- streaming: isStreaming
1330
- };
1331
- drafts.set(surfaceId, draft);
1332
- created.set(key, [...created.get(key) ?? [], surfaceId]);
1333
- }
1334
- draft.operations.push(surfaceId === requested ? op : readdressOnce(op, surfaceId));
1335
- }
1336
- }
1337
- }
1338
- const canFlattenCards = hasProp(ui, "Card", "variant");
1339
- const surfaces = [];
1340
- const partsBySurface = /* @__PURE__ */ new Map();
1341
- const childIds = childIdsReader(ui);
1342
- const buildDraft = (draft) => {
1343
- const operations = splitComponentUpdates(expandInlineCreate(createSurfaceFirst(prepareSurfaceOperations({
1344
- operations: draft.operations,
1345
- fallbackSurfaceId: draft.surfaceId,
1346
- catalogId: ui.id,
1347
- catalogIds: catalogIdsOf(ui)
1348
- }).operations)));
1349
- const parts = draft.target === GENERATIVE_UI_CHAT_TARGET ? liftProse(canFlattenCards ? flattenInformationalCards(operations, { childIds }) : operations, draft.surfaceId, childIds) : [{
1350
- kind: "surface",
1351
- surfaceId: draft.surfaceId,
1352
- operations
1353
- }];
1354
- const contents = parts.flatMap((part) => part.kind === "surface" ? [surfaceContent(part.surfaceId, draft, part.operations, options)] : []);
1355
- return {
1356
- ...draft,
1357
- parts,
1358
- contents
1359
- };
1360
- };
1361
- for (const draft of drafts.values()) {
1362
- const built = cache ? cache.drafts.get(draft.surfaceId, () => buildDraft(draft), (last) => last.target === draft.target && last.streaming === draft.streaming && sameItems(last.operations, draft.operations)) : buildDraft(draft);
1363
- partsBySurface.set(draft.surfaceId, built.parts);
1364
- surfaces.push(...built.contents);
1365
- }
1366
- cache?.endBuild();
1367
- /** The surface ids of the parts of each split surface, by surface id. */
1368
- const parts = /* @__PURE__ */ new Map();
1369
- for (const [surfaceId, surfaceParts] of partsBySurface) {
1370
- const ids = surfaceParts.flatMap((part) => part.kind === "surface" ? [part.surfaceId] : []);
1371
- parts.set(surfaceId, ids);
1372
- }
1373
- const fences = /* @__PURE__ */ new Map();
1374
- for (const [key, surfaceIds] of created) {
1375
- const blocks = [];
1376
- for (const surfaceId of surfaceIds) {
1377
- if (drafts.get(surfaceId)?.target !== GENERATIVE_UI_CHAT_TARGET) continue;
1378
- for (const part of partsBySurface.get(surfaceId) ?? []) blocks.push(part.kind === "markdown" ? part : {
1379
- kind: "surface",
1380
- surfaceId: part.surfaceId
1381
- });
1382
- }
1383
- if (blocks.length > 0) fences.set(key, blocks);
1384
- }
1385
- return {
1386
- surfaces,
1387
- fences,
1388
- functionCalls,
1389
- parts
1390
- };
1391
- }
1392
- /** The declared functions, as `validateOperation` takes them. */
1393
- function declaredFunctions(ui) {
1394
- const functions = {};
1395
- for (const [name, fn] of ui.functions) try {
1396
- functions[name] = {
1397
- ...fn.description ? { description: fn.description } : {},
1398
- parameters: toJsonSchema(fn.parameters)
1399
- };
1400
- } catch {
1401
- functions[name] = { parameters: {} };
1402
- }
1403
- return functions;
1404
- }
1405
- /** True when `list` starts with all the items of `prefix`. */
1406
- function startsWith(list, prefix) {
1407
- return list.length >= prefix.length && prefix.every((item, index) => item === list[index]);
1408
- }
1409
- /** A content that deletes a surface that the fences no longer write. */
1410
- function removalContent(surfaceId, catalogId) {
1411
- return {
1412
- surfaceId,
1413
- target: GENERATIVE_UI_CHAT_TARGET,
1414
- catalogId,
1415
- status: "ready",
1416
- rejected: [],
1417
- operations: [{
1418
- version: A2UI_VERSION,
1419
- createSurface: {
1420
- surfaceId,
1421
- catalogId
1422
- }
1423
- }, {
1424
- version: A2UI_VERSION,
1425
- deleteSurface: { surfaceId }
1426
- }]
1427
- };
1428
- }
1429
- /**
1430
- * The markdown transport source of one surface manager. It turns the
1431
- * messages of a thread into surfaces in the manager, and keeps the blocks
1432
- * that each fence renders.
1433
- */
1434
- var MarkdownSurfaceSource = class {
1435
- functions;
1436
- /** By thread: the blocks of each fence, from the latest sync. */
1437
- fences = /* @__PURE__ */ new Map();
1438
- /** By thread, then surface: the operations last ingested, as JSON. */
1439
- ingested = /* @__PURE__ */ new Map();
1440
- /** By thread, then surface: the content last ingested. */
1441
- contents = /* @__PURE__ */ new Map();
1442
- /** By thread: the results of the earlier builds. */
1443
- caches = /* @__PURE__ */ new Map();
1444
- constructor(manager, ui) {
1445
- this.manager = manager;
1446
- this.ui = ui;
1447
- this.functions = declaredFunctions(ui);
1448
- }
1449
- /**
1450
- * Builds the surfaces of `threadId` from `messages` and gives them to the
1451
- * manager. A surface that an earlier sync of the thread made, and that the
1452
- * messages no longer write, is deleted. Other threads do not change.
1453
- *
1454
- * @param threadId - The thread of the messages.
1455
- * @param agentId - The agent that owns the thread.
1456
- * @param messages - All messages of the thread.
1457
- * @param options - `running`: the last message can still grow.
1458
- * @returns The function calls of the fences, in order. The source does
1459
- * not run them.
1460
- */
1461
- sync(threadId, agentId, messages, options) {
1462
- let cache = this.caches.get(threadId);
1463
- if (!cache) {
1464
- cache = new MarkdownBuildCache();
1465
- this.caches.set(threadId, cache);
1466
- }
1467
- const result = buildMarkdownSurfaces(messages, {
1468
- ui: this.ui,
1469
- functions: this.functions,
1470
- running: options.running,
1471
- cache
1472
- });
1473
- this.fences.set(threadId, result.fences);
1474
- for (const parts of result.parts.values()) this.manager.linkSurfaces(threadId, parts);
1475
- const previous = this.ingested.get(threadId) ?? /* @__PURE__ */ new Map();
1476
- const previousContents = this.contents.get(threadId) ?? /* @__PURE__ */ new Map();
1477
- const next = /* @__PURE__ */ new Map();
1478
- const nextContents = /* @__PURE__ */ new Map();
1479
- for (const content of result.surfaces) {
1480
- nextContents.set(content.surfaceId, content);
1481
- const before = previous.get(content.surfaceId);
1482
- if (before && previousContents.get(content.surfaceId) === content) {
1483
- next.set(content.surfaceId, before);
1484
- continue;
1485
- }
1486
- const fingerprints = content.operations.map((op) => JSON.stringify(op));
1487
- if (before && !startsWith(fingerprints, before)) this.manager.ingest(threadId, agentId, {
1488
- ...content,
1489
- operations: []
1490
- });
1491
- this.manager.ingest(threadId, agentId, content);
1492
- next.set(content.surfaceId, fingerprints);
1493
- }
1494
- for (const surfaceId of previous.keys()) {
1495
- if (next.has(surfaceId)) continue;
1496
- this.manager.ingest(threadId, agentId, removalContent(surfaceId, this.ui.id));
1497
- }
1498
- this.ingested.set(threadId, next);
1499
- this.contents.set(threadId, nextContents);
1500
- return result.functionCalls;
1501
- }
1502
- /**
1503
- * The blocks that a fence renders in the chat, from the latest sync of the
1504
- * thread. `undefined` when the fence renders nothing: it updates a surface
1505
- * of an earlier fence, its surface is for a named target, or it has no
1506
- * complete operation yet.
1507
- */
1508
- getFenceBlocks(threadId, messageId, fenceIndex) {
1509
- return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));
1510
- }
1511
- };
1512
- const sources = /* @__PURE__ */ new WeakMap();
1513
- /**
1514
- * The markdown source of a generative UI runtime. There is one source for
1515
- * each surface manager. The root syncs it, and the chat messages read the
1516
- * fence blocks from it.
1517
- */
1518
- function getMarkdownSurfaceSource(runtime) {
1519
- let source = sources.get(runtime.manager);
1520
- if (!source) {
1521
- source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);
1522
- sources.set(runtime.manager, source);
1523
- }
1524
- return source;
1525
- }
1526
-
1527
- //#endregion
1528
- //#region src/generative-ui/calc.ts
1529
- const MAX_SERIES = 1e3;
1530
- const OPERATORS = [
1531
- "&&",
1532
- "||",
1533
- "==",
1534
- "!=",
1535
- "<=",
1536
- ">=",
1537
- "<",
1538
- ">",
1539
- "+",
1540
- "-",
1541
- "*",
1542
- "/",
1543
- "%",
1544
- "^",
1545
- "(",
1546
- ")",
1547
- ",",
1548
- "?",
1549
- ":",
1550
- "!"
1551
- ];
1552
- function tokenize(source) {
1553
- const tokens = [];
1554
- let i = 0;
1555
- while (i < source.length) {
1556
- const char = source[i];
1557
- if (/\s/.test(char)) {
1558
- i++;
1559
- continue;
1560
- }
1561
- if (/[0-9.]/.test(char)) {
1562
- const match = /^\d*\.?\d+(?:[eE][-+]?\d+)?|^\d+\.?/.exec(source.slice(i));
1563
- if (!match) throw new ExpressionError(`calc: bad number at "${source.slice(i, i + 8)}"`);
1564
- tokens.push({
1565
- kind: "number",
1566
- value: Number(match[0])
1567
- });
1568
- i += match[0].length;
1569
- continue;
1570
- }
1571
- if (char === "'" || char === "\"") {
1572
- let value = "";
1573
- i++;
1574
- while (i < source.length && source[i] !== char) {
1575
- if (source[i] === "\\" && i + 1 < source.length) i++;
1576
- value += source[i++];
1577
- }
1578
- if (i >= source.length) throw new ExpressionError("calc: unclosed string");
1579
- i++;
1580
- tokens.push({
1581
- kind: "string",
1582
- value
1583
- });
1584
- continue;
1585
- }
1586
- if (/[A-Za-z_]/.test(char)) {
1587
- const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));
1588
- tokens.push({
1589
- kind: "name",
1590
- value: match[0]
1591
- });
1592
- i += match[0].length;
1593
- continue;
1594
- }
1595
- const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));
1596
- if (!op) throw new ExpressionError(`calc: unexpected "${char}"`);
1597
- tokens.push({
1598
- kind: "op",
1599
- value: op
1600
- });
1601
- i += op.length;
1602
- }
1603
- tokens.push({ kind: "end" });
1604
- return tokens;
1605
- }
1606
- function numberOf(value, what) {
1607
- if (typeof value === "number") {
1608
- if (!Number.isFinite(value)) throw new ExpressionError(`calc: ${what} is not finite`);
1609
- return value;
1610
- }
1611
- if (typeof value === "boolean") return value ? 1 : 0;
1612
- if (typeof value === "string" && value.trim() !== "") {
1613
- const parsed = Number(value);
1614
- if (Number.isFinite(parsed)) return parsed;
1615
- }
1616
- if (value === null || value === void 0) throw new ExpressionError(`calc: ${what} has no value`);
1617
- throw new ExpressionError(`calc: ${what} is not a number`);
1618
- }
1619
- function describe(value) {
1620
- return typeof value === "string" ? `"${value}"` : String(value);
1621
- }
1622
- const MATH = {
1623
- min: (args) => Math.min(...args),
1624
- max: (args) => Math.max(...args),
1625
- abs: ([x = NaN]) => Math.abs(x),
1626
- floor: ([x = NaN]) => Math.floor(x),
1627
- ceil: ([x = NaN]) => Math.ceil(x),
1628
- round: ([x = NaN, decimals = 0]) => {
1629
- const factor = 10 ** Math.trunc(decimals);
1630
- return Math.round(x * factor) / factor;
1631
- },
1632
- pow: ([x = NaN, y = NaN]) => x ** y,
1633
- sqrt: ([x = NaN]) => Math.sqrt(x),
1634
- exp: ([x = NaN]) => Math.exp(x),
1635
- ln: ([x = NaN]) => Math.log(x),
1636
- log10: ([x = NaN]) => Math.log10(x)
1637
- };
1638
- /** How many args a function takes, at least and at most; min and max take any. */
1639
- const ARITY = {
1640
- abs: [1, 1],
1641
- floor: [1, 1],
1642
- ceil: [1, 1],
1643
- round: [1, 2],
1644
- pow: [2, 2],
1645
- sqrt: [1, 1],
1646
- exp: [1, 1],
1647
- ln: [1, 1],
1648
- log10: [1, 1]
1649
- };
1650
- /** Named constants, when no arg of the same name is passed. */
1651
- const CONSTANTS = {
1652
- pi: Math.PI,
1653
- e: Math.E
1654
- };
1655
- var CalcParser = class {
1656
- pos = 0;
1657
- constructor(tokens, scope, source) {
1658
- this.tokens = tokens;
1659
- this.scope = scope;
1660
- this.source = source;
1661
- }
1662
- parse() {
1663
- const value = this.ternary();
1664
- const token = this.peek();
1665
- if (token.kind !== "end") this.fail(`unexpected "${this.text(token)}"`);
1666
- return value;
1667
- }
1668
- /**
1669
- * The token at `pos`. The parser never moves past the "end" token, which
1670
- * `tokenize` always adds last, so there is always one.
1671
- */
1672
- peek() {
1673
- const token = this.tokens[this.pos];
1674
- if (token === void 0) throw new Error(`calc: no token at ${this.pos} in "${this.source}"`);
1675
- return token;
1676
- }
1677
- fail(what) {
1678
- throw new ExpressionError(`calc: ${what} in "${this.source}"`);
1679
- }
1680
- text(token) {
1681
- return token.kind === "end" ? "end" : String(token.value);
1682
- }
1683
- peekOp(...ops) {
1684
- const token = this.peek();
1685
- return token.kind === "op" && ops.includes(token.value) ? token.value : void 0;
1686
- }
1687
- expectOp(op) {
1688
- if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.peek())}"`);
1689
- this.pos++;
1690
- }
1691
- /**
1692
- * Parses a part of the expression that the result does not need (the
1693
- * other branch of `?:`, the right side of a decided `&&` or `||`). It
1694
- * still has to be parsed to find where it ends, so syntax errors are
1695
- * reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`
1696
- * is a valid guard.
1697
- */
1698
- skipped(parse) {
1699
- this.skipDepth++;
1700
- try {
1701
- parse();
1702
- } finally {
1703
- this.skipDepth--;
1704
- }
1705
- return null;
1706
- }
1707
- /** Above 0 while parsing a part whose value is not needed. */
1708
- skipDepth = 0;
1709
- /** The number of a value, or 0 while skipping. */
1710
- num(value, what) {
1711
- return this.skipDepth > 0 ? 0 : numberOf(value, what);
1712
- }
1713
- ternary() {
1714
- const condition = this.or();
1715
- if (this.peekOp("?") === void 0) return condition;
1716
- this.pos++;
1717
- const takesFirst = truthOf(condition);
1718
- const whenTrue = takesFirst ? this.ternary() : this.skipped(() => this.ternary());
1719
- this.expectOp(":");
1720
- const whenFalse = takesFirst ? this.skipped(() => this.ternary()) : this.ternary();
1721
- return takesFirst ? whenTrue : whenFalse;
1722
- }
1723
- or() {
1724
- let left = this.and();
1725
- while (this.peekOp("||")) {
1726
- this.pos++;
1727
- if (truthOf(left)) {
1728
- this.skipped(() => this.and());
1729
- left = true;
1730
- } else left = truthOf(this.and());
1731
- }
1732
- return left;
1733
- }
1734
- and() {
1735
- let left = this.equality();
1736
- while (this.peekOp("&&")) {
1737
- this.pos++;
1738
- if (!truthOf(left)) {
1739
- this.skipped(() => this.equality());
1740
- left = false;
1741
- } else left = truthOf(this.equality());
1742
- }
1743
- return left;
1744
- }
1745
- equality() {
1746
- let left = this.comparison();
1747
- for (let op = this.peekOp("==", "!="); op; op = this.peekOp("==", "!=")) {
1748
- this.pos++;
1749
- const right = this.comparison();
1750
- const isEqual = typeof left === "number" || typeof right === "number" ? this.num(left, "the left side of ==") === this.num(right, "the right side of ==") : left === right;
1751
- left = op === "==" ? isEqual : !isEqual;
1752
- }
1753
- return left;
1754
- }
1755
- comparison() {
1756
- let left = this.additive();
1757
- for (let op = this.peekOp("<", "<=", ">", ">="); op; op = this.peekOp("<", "<=", ">", ">=")) {
1758
- this.pos++;
1759
- const a = this.num(left, `the left side of ${op}`);
1760
- const b = this.num(this.additive(), `the right side of ${op}`);
1761
- left = op === "<" ? a < b : op === "<=" ? a <= b : op === ">" ? a > b : a >= b;
1762
- }
1763
- return left;
1764
- }
1765
- additive() {
1766
- let left = this.multiplicative();
1767
- for (let op = this.peekOp("+", "-"); op; op = this.peekOp("+", "-")) {
1768
- this.pos++;
1769
- const right = this.multiplicative();
1770
- if (op === "+" && (typeof left === "string" || typeof right === "string")) left = `${left ?? ""}${right ?? ""}`;
1771
- else {
1772
- const a = this.num(left, `the left side of ${op}`);
1773
- const b = this.num(right, `the right side of ${op}`);
1774
- left = op === "+" ? a + b : a - b;
1775
- }
1776
- }
1777
- return left;
1778
- }
1779
- multiplicative() {
1780
- let left = this.unary();
1781
- for (let op = this.peekOp("*", "/", "%"); op; op = this.peekOp("*", "/", "%")) {
1782
- this.pos++;
1783
- const a = this.num(left, `the left side of ${op}`);
1784
- const b = this.num(this.unary(), `the right side of ${op}`);
1785
- if (op !== "*" && b === 0 && this.skipDepth === 0) this.fail("division by zero");
1786
- left = op === "*" ? a * b : op === "/" ? a / b : a % b;
1787
- }
1788
- return left;
1789
- }
1790
- unary() {
1791
- if (this.peekOp("-")) {
1792
- this.pos++;
1793
- return -this.num(this.unary(), "the operand of -");
1794
- }
1795
- if (this.peekOp("!")) {
1796
- this.pos++;
1797
- return !truthOf(this.unary());
1798
- }
1799
- return this.power();
1800
- }
1801
- /** `a ^ b`: binds tighter than `*` and unary minus, right to left. */
1802
- power() {
1803
- const base = this.primary();
1804
- if (!this.peekOp("^")) return base;
1805
- this.pos++;
1806
- const exponent = this.unary();
1807
- if (this.skipDepth > 0) return null;
1808
- return this.finite(this.num(base, "the left side of ^") ** this.num(exponent, "the right side of ^"), "^");
1809
- }
1810
- finite(value, what) {
1811
- if (!Number.isFinite(value)) this.fail(`${what} has no finite result`);
1812
- return value;
1813
- }
1814
- primary() {
1815
- const token = this.peek();
1816
- this.pos++;
1817
- switch (token.kind) {
1818
- case "number": return token.value;
1819
- case "string": return token.value;
1820
- case "name": return this.name(token.value);
1821
- case "op":
1822
- if (token.value === "(") {
1823
- const value = this.ternary();
1824
- this.expectOp(")");
1825
- return value;
1826
- }
1827
- return this.fail(`unexpected "${token.value}"`);
1828
- case "end": return this.fail("missing value");
1829
- }
1830
- }
1831
- name(name) {
1832
- if (name === "true") return true;
1833
- if (name === "false") return false;
1834
- if (name === "null") return null;
1835
- if (this.peekOp("(")) {
1836
- this.pos++;
1837
- const args = [];
1838
- if (this.peekOp(")") === void 0) for (;;) {
1839
- args.push(this.num(this.ternary(), `an argument of ${name}`));
1840
- if (this.peekOp(",") === void 0) break;
1841
- this.pos++;
1842
- }
1843
- this.expectOp(")");
1844
- if (this.skipDepth > 0) return null;
1845
- const fn = Object.prototype.hasOwnProperty.call(MATH, name) ? MATH[name] : void 0;
1846
- if (!fn) this.fail(`unknown function ${name}`);
1847
- if (args.length === 0) this.fail(`${name} needs an argument`);
1848
- const [least, most] = ARITY[name] ?? [1, Infinity];
1849
- if (args.length < least || args.length > most) this.fail(`${name} takes ${least === most ? least : `${least} or ${most}`} argument${most === 1 ? "" : "s"}`);
1850
- return this.finite(fn(args), name);
1851
- }
1852
- if (this.skipDepth > 0) return null;
1853
- if (!Object.prototype.hasOwnProperty.call(this.scope, name)) {
1854
- if (Object.prototype.hasOwnProperty.call(CONSTANTS, name)) return CONSTANTS[name];
1855
- this.fail(`unknown name ${name}; pass it as an arg`);
1856
- }
1857
- const value = this.scope[name];
1858
- if (value !== null && typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean") this.fail(`${name} is not a number, text or boolean (${describe(value)})`);
1859
- return value;
1860
- }
1861
- };
1862
- /**
1863
- * Evaluates `expression` with the names in `scope`. Gives a number, a
1864
- * string, a boolean or null. Throws an {@link ExpressionError} for a bad
1865
- * expression or a missing name.
1866
- */
1867
- function evaluateCalc(expression, scope) {
1868
- if (typeof expression !== "string" || expression.trim() === "") throw new ExpressionError("calc: expression must be a string");
1869
- return new CalcParser(tokenize(expression), scope, expression).parse();
1870
- }
1871
- /** The `calc` function: the expression is `args.expression`, the rest is the scope. */
1872
- function calc(args) {
1873
- const { expression, ...scope } = args;
1874
- return evaluateCalc(expression, scope);
1875
- }
1876
- const WHOLE_EXPRESSION = /^\$\{([^}]*)\}$/;
1877
- /**
1878
- * Fills `item` for one iteration: a string that is one `${...}` gives the
1879
- * typed value of the expression, a string with `${...}` inside it is
1880
- * interpolated as text, and objects and arrays are walked.
1881
- */
1882
- function fillItem(item, scope) {
1883
- if (typeof item === "string") {
1884
- const whole = WHOLE_EXPRESSION.exec(item);
1885
- if (whole) return evaluateCalc(whole[1], scope);
1886
- return item.replace(/\$\{([^}]*)\}/g, (_, expression) => {
1887
- const value = evaluateCalc(expression, scope);
1888
- return value === null ? "" : String(value);
1889
- });
1890
- }
1891
- if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));
1892
- if (typeof item === "object" && item !== null) return Object.fromEntries(Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]));
1893
- return item;
1894
- }
1895
- /**
1896
- * The `series` function: `count` copies of `item`, with the loop variable
1897
- * (`variable`, default "i") counting from `start` (default 1) and the other
1898
- * args in scope of the `${...}` expressions of the item.
1899
- */
1900
- function series(args) {
1901
- const { count, item, variable, start, ...scope } = args;
1902
- const length = numberOf(count, "count");
1903
- if (!Number.isInteger(length) || length < 0) throw new ExpressionError("series: count must be a whole number");
1904
- if (length > MAX_SERIES) throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);
1905
- if (item === void 0) throw new ExpressionError("series: item is required");
1906
- const name = variable === void 0 ? "i" : variable;
1907
- if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ExpressionError("series: variable must be a name");
1908
- const first = start === void 0 ? 1 : numberOf(start, "start");
1909
- return Array.from({ length }, (_, index) => fillItem(item, {
1910
- ...scope,
1911
- [name]: first + index
1912
- }));
1913
- }
1914
-
1915
- //#endregion
1916
- //#region src/generative-ui/resolve.ts
1917
- BASIC_FUNCTIONS.calc = calc;
1918
- BASIC_FUNCTIONS.series = series;
1919
- const NO_DATA = { get: () => void 0 };
1920
- BASIC_FUNCTIONS.formatString = (args) => resolveDynamicValue({
1921
- "@call": "formatString",
1922
- args
1923
- }, {
1924
- data: NO_DATA,
1925
- basePath: void 0
1926
- }).value;
1927
- /** Adds one segment to a JSON pointer: ("/items", "0") gives "/items/0". */
1928
- function joinPath(base, segment) {
1929
- return base === "/" ? `/${segment}` : `${base}/${segment}`;
1930
- }
1931
- /**
1932
- * The absolute data model path of a binding. A path without a leading "/"
1933
- * is relative to the current template item, or to the root outside of one.
1934
- */
1935
- function resolvePath(path, basePath) {
1936
- if (path.startsWith("/")) return path;
1937
- return joinPath(basePath ?? "/", path);
1938
- }
1939
- /**
1940
- * The index of the template item at `basePath`: its last segment.
1941
- * `undefined` outside of a template.
1942
- */
1943
- function templateIndex(basePath) {
1944
- if (basePath === void 0) return void 0;
1945
- const index = Number(basePath.slice(basePath.lastIndexOf("/") + 1));
1946
- return Number.isInteger(index) ? index : void 0;
1947
- }
1948
- /** The value of a ValidationResult where a boolean is expected. */
1949
- function coerce(value, keep) {
1950
- return !keep && isValidationResult(value) ? value.valid : value;
1951
- }
1952
- /**
1953
- * Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by
1954
- * default it becomes its `valid` boolean, which is what every prop except
1955
- * a check condition wants.
1956
- */
1957
- function walk(value, state, keepValidation, scope = "outside") {
1958
- if (Array.isArray(value)) {
1959
- let changed = false;
1960
- const itemScope = scope === "list" ? "check" : "outside";
1961
- const items = value.map((item) => {
1962
- const next = walk(item, state, keepValidation, itemScope);
1963
- if (next !== item) changed = true;
1964
- return next;
1965
- });
1966
- return changed ? items : value;
1967
- }
1968
- if (!isRecord(value)) return value;
1969
- if (isPathBinding(value)) {
1970
- const path = resolvePath(value["@path"], state.context.basePath);
1971
- state.paths.add(path);
1972
- return state.context.data.get(path);
1973
- }
1974
- if (isCallBinding(value)) return call(value, state, keepValidation);
1975
- if (isActionBinding(value)) return value;
1976
- let changed = false;
1977
- const entries = Object.entries(value).map(([key, item]) => {
1978
- const next = walk(item, state, keepValidation || scope === "check" && key === "condition", key === "checks" ? "list" : "outside");
1979
- if (next !== item) changed = true;
1980
- return [key, next];
1981
- });
1982
- return changed ? Object.fromEntries(entries) : value;
1983
- }
1984
- function call(binding, state, keepValidation) {
1985
- const name = binding["@call"];
1986
- const rawArgs = binding.args ?? {};
1987
- if (!isRecord(rawArgs)) throw new ExpressionError(`the args of "${name}" must be an object`);
1988
- if (name === A2UI_INDEX_FUNCTION) {
1989
- const index = templateIndex(state.context.basePath);
1990
- if (index === void 0) return void 0;
1991
- const offset = walk(rawArgs.offset, state, false);
1992
- return index + (typeof offset === "number" ? offset : 0);
1993
- }
1994
- if (name === "formatString") {
1995
- const template = walk(rawArgs.value, state, false);
1996
- if (typeof template !== "string") throw new ExpressionError("formatString takes a string value");
1997
- return formatString(template, state);
1998
- }
1999
- const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name) ? BASIC_FUNCTIONS[name] : void 0;
2000
- if (!fn) throw new ExpressionError(`"${name}" is not a basic function`);
2001
- if (requiresUserActivation(name)) throw new ExpressionError(`"${name}" is not a value; bind it as the functionCall of an event`);
2002
- const result = fn(walk(rawArgs, state, false));
2003
- return givesValidationResult(name) ? coerce(result, keepValidation) : result;
2004
- }
2005
- function resolveDynamicValue(value, context, options = {}) {
2006
- const result = tryResolveDynamicValue(value, context, options);
2007
- if (!result.ok) throw result.error;
2008
- return result;
2009
- }
2010
- /**
2011
- * Like {@link resolveDynamicValue}, but a failure comes back as a result
2012
- * with the paths read so far, so the caller can keep watching them: a
2013
- * function that fails on an empty field works once the user fills it.
2014
- */
2015
- function tryResolveDynamicValue(value, context, options = {}) {
2016
- const state = {
2017
- context,
2018
- paths: /* @__PURE__ */ new Set()
2019
- };
2020
- try {
2021
- return {
2022
- ok: true,
2023
- value: walk(value, state, options.keepValidation ?? false, options.isChecks ? "list" : "outside"),
2024
- paths: state.paths
2025
- };
2026
- } catch (error) {
2027
- return {
2028
- ok: false,
2029
- error: error instanceof Error ? error : new Error(String(error)),
2030
- paths: state.paths
2031
- };
2032
- }
2033
- }
2034
- /** True when `value` holds a `{"@path"}` or `{"@call"}` at any depth. */
2035
- function containsDynamicValue(value) {
2036
- if (Array.isArray(value)) return value.some(containsDynamicValue);
2037
- if (!isRecord(value)) return false;
2038
- if (isPathBinding(value) || isCallBinding(value)) return true;
2039
- if (isActionBinding(value)) return false;
2040
- return Object.values(value).some(containsDynamicValue);
2041
- }
2042
- /**
2043
- * The `${...}` grammar of `formatString`:
2044
- *
2045
- * expression := path | literal | call
2046
- * path := "/" segments | identifier ("/" segments)*
2047
- * literal := 'text' | "text" | number | true | false | null
2048
- * call := identifier "(" [ name ":" expression ("," name ":" expression)* ] ")"
2049
- *
2050
- * A `\${` in the template is a literal `${`.
2051
- */
2052
- function formatString(template, state) {
2053
- let out = "";
2054
- let index = 0;
2055
- while (index < template.length) {
2056
- const start = template.indexOf("${", index);
2057
- if (start === -1) {
2058
- out += template.slice(index);
2059
- break;
2060
- }
2061
- if (start > 0 && template[start - 1] === "\\") {
2062
- out += `${template.slice(index, start - 1)}\${`;
2063
- index = start + 2;
2064
- continue;
2065
- }
2066
- out += template.slice(index, start);
2067
- const end = matchingBrace(template, start + 2);
2068
- if (end === -1) throw new ExpressionError("formatString: unclosed ${");
2069
- const value = new ExpressionParser(template.slice(start + 2, end).trim(), state).parse();
2070
- out += value === void 0 || value === null ? "" : String(value);
2071
- index = end + 1;
2072
- }
2073
- return out;
2074
- }
2075
- /** The index of the `}` that closes the block opened at `from`, or -1. */
2076
- function matchingBrace(template, from) {
2077
- let depth = 1;
2078
- let quote;
2079
- for (let i = from; i < template.length; i++) {
2080
- const char = template[i];
2081
- if (quote) {
2082
- if (char === "\\") i++;
2083
- else if (char === quote) quote = void 0;
2084
- continue;
2085
- }
2086
- if (char === "'" || char === "\"") quote = char;
2087
- else if (char === "{") depth++;
2088
- else if (char === "}" && --depth === 0) return i;
2089
- }
2090
- return -1;
2091
- }
2092
- const IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;
2093
- const NUMBER = /-?\d+(?:\.\d+)?/y;
2094
- const PATH_SEGMENT = /[^\s,():'"]+/y;
2095
- var ExpressionParser = class {
2096
- pos = 0;
2097
- constructor(source, state) {
2098
- this.source = source;
2099
- this.state = state;
2100
- }
2101
- parse() {
2102
- const value = this.expression();
2103
- this.skipSpace();
2104
- if (this.pos < this.source.length) throw new ExpressionError(`formatString: unexpected "${this.source.slice(this.pos)}" in \${${this.source}}`);
2105
- return value;
2106
- }
2107
- fail(what) {
2108
- throw new ExpressionError(`formatString: ${what} in \${${this.source}}`);
2109
- }
2110
- skipSpace() {
2111
- while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) this.pos++;
2112
- }
2113
- match(pattern) {
2114
- pattern.lastIndex = this.pos;
2115
- const found = pattern.exec(this.source);
2116
- if (!found) return void 0;
2117
- this.pos = pattern.lastIndex;
2118
- return found[0];
2119
- }
2120
- expression() {
2121
- this.skipSpace();
2122
- const char = this.source[this.pos];
2123
- if (char === void 0) this.fail("missing expression");
2124
- if (char === "'" || char === "\"") return this.quoted(char);
2125
- if (char === "/") return this.path(this.match(PATH_SEGMENT) ?? "/");
2126
- const number = this.match(NUMBER);
2127
- if (number !== void 0) return Number(number);
2128
- const name = this.match(IDENTIFIER);
2129
- if (name === void 0) this.fail(`unexpected "${char}"`);
2130
- if (name === "true") return true;
2131
- if (name === "false") return false;
2132
- if (name === "null") return null;
2133
- this.skipSpace();
2134
- if (this.source[this.pos] === "(") return this.call(name);
2135
- if (name.startsWith("@")) return call({ "@call": name }, this.state, false);
2136
- const rest = this.source[this.pos] === "/" ? this.match(PATH_SEGMENT) : "";
2137
- return this.path(`${name}${rest ?? ""}`);
2138
- }
2139
- quoted(quote) {
2140
- let value = "";
2141
- this.pos++;
2142
- while (this.pos < this.source.length) {
2143
- const char = this.source[this.pos++];
2144
- if (char === "\\" && this.pos < this.source.length) value += this.source[this.pos++];
2145
- else if (char === quote) return value;
2146
- else value += char;
2147
- }
2148
- return this.fail("unclosed string");
2149
- }
2150
- path(path) {
2151
- const absolute = resolvePath(path, this.state.context.basePath);
2152
- this.state.paths.add(absolute);
2153
- return this.state.context.data.get(absolute);
2154
- }
2155
- call(name) {
2156
- this.pos++;
2157
- const args = {};
2158
- this.skipSpace();
2159
- if (this.source[this.pos] === ")") {
2160
- this.pos++;
2161
- return call({
2162
- "@call": name,
2163
- args
2164
- }, this.state, false);
2165
- }
2166
- for (;;) {
2167
- this.skipSpace();
2168
- const key = this.match(IDENTIFIER);
2169
- if (key === void 0) this.fail("expected an argument name");
2170
- this.skipSpace();
2171
- if (this.source[this.pos] !== ":") this.fail(`expected ":" after ${key}`);
2172
- this.pos++;
2173
- args[key] = this.expression();
2174
- this.skipSpace();
2175
- const next = this.source[this.pos++];
2176
- if (next === ")") break;
2177
- if (next !== ",") this.fail(`expected "," or ")" after ${key}`);
2178
- }
2179
- return call({
2180
- "@call": name,
2181
- args
2182
- }, this.state, false);
2183
- }
2184
- };
2185
-
2186
- //#endregion
2187
- //#region src/generative-ui/schema.ts
2188
- const ASYNC_ISSUE = { message: "the schema validates asynchronously; component props and state need a schema that validates synchronously" };
2189
- function toResult(result) {
2190
- return result.issues ? {
2191
- success: false,
2192
- issues: result.issues
2193
- } : {
2194
- success: true,
2195
- data: result.value
2196
- };
2197
- }
2198
- /**
2199
- * Validates `value` with `schema`. The result comes back at once when the
2200
- * schema validates synchronously, else as a promise.
2201
- */
2202
- function validateSchema(schema, value) {
2203
- const result = schema["~standard"].validate(value);
2204
- return result instanceof Promise ? result.then(toResult) : toResult(result);
2205
- }
2206
- /**
2207
- * Validates `value` synchronously, for code that runs during render. A
2208
- * schema that validates asynchronously fails with an issue that says so.
2209
- */
2210
- function validateSchemaSync(schema, value) {
2211
- const result = validateSchema(schema, value);
2212
- if (!(result instanceof Promise)) return result;
2213
- result.catch(() => {});
2214
- return {
2215
- success: false,
2216
- issues: [ASYNC_ISSUE]
2217
- };
2218
- }
2219
- /** True for the issue that `validateSchemaSync` gives for an async schema. */
2220
- function isAsyncIssue(issue) {
2221
- return issue === ASYNC_ISSUE;
2222
- }
2223
- /** The first key of an issue path: the prop the issue is about. */
2224
- function issueKey(issue) {
2225
- const first = issue.path?.[0];
2226
- const key = typeof first === "object" ? first.key : first;
2227
- return key === void 0 ? void 0 : String(key);
2228
- }
2229
- /**
2230
- * `props` without the top-level props whose `null` the schema rejected, or
2231
- * `undefined` when there are none. A model writes `null` for "not set" (an
2232
- * empty selection, a value it has not filled yet), and A2UI deletes a data
2233
- * model key that is set to `null`, so a rejected `null` is read as an unset
2234
- * prop. A prop whose schema accepts `null` keeps it.
2235
- */
2236
- function withoutRejectedNulls(props, issues) {
2237
- const rejected = /* @__PURE__ */ new Set();
2238
- for (const issue of issues) {
2239
- const key = issueKey(issue);
2240
- if (key !== void 0 && issue.path?.length === 1 && props[key] === null) rejected.add(key);
2241
- }
2242
- if (rejected.size === 0) return void 0;
2243
- return Object.fromEntries(Object.entries(props).filter(([key]) => !rejected.has(key)));
2244
- }
2245
- /** `"a.b: message; c: message"`. A path-less issue gets `fallback`. */
2246
- function formatIssues(issues, fallback = "props") {
2247
- return issues.map((issue) => {
2248
- return `${(issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".") || fallback}: ${issue.message}`;
2249
- }).join("; ");
2250
- }
2251
-
2252
- //#endregion
2253
- //#region src/generative-ui/runtime-context.ts
2254
- const GenerativeUIRuntimeContext = createContext(null);
2255
- function useGenerativeUIRuntime() {
2256
- return useContext(GenerativeUIRuntimeContext);
2257
- }
2258
- function useRequiredGenerativeUIRuntime() {
2259
- const runtime = useContext(GenerativeUIRuntimeContext);
2260
- if (!runtime) throw new Error("Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.");
2261
- return runtime;
2262
- }
2263
- /**
2264
- * Reports an error without ever throwing: `reportError` reaches host code
2265
- * (`onError`), and a throwing host callback must not break rendering or an
2266
- * event handler.
2267
- */
2268
- function reportErrorSafely(runtime, info) {
2269
- try {
2270
- runtime.reportError(info);
2271
- } catch {}
2272
- }
2273
- const GenerativeUINodeContext = createContext(null);
2274
-
2275
- //#endregion
2276
- //#region src/generative-ui/hooks.ts
2277
- const noopSubscribe$1 = () => () => {};
2278
- const zero = () => 0;
2279
- /** Re-renders on any surface-manager change. */
2280
- function useManagerVersion(runtime) {
2281
- return useSyncExternalStore(runtime?.manager.subscribe ?? noopSubscribe$1, runtime?.manager.getVersion ?? zero, zero);
2282
- }
2283
- /**
2284
- * Experimental. Gives one key of the app state declared in
2285
- * `createGenerativeUI({ state })` its value. Bound props of generated
2286
- * components read it. The model does not see it.
2287
- *
2288
- * The key is set on mount and when the value changes (compared as JSON). It
2289
- * is removed on unmount.
2290
- *
2291
- * @param ui - The object from `createGenerativeUI`. It gives the key and the
2292
- * value their types.
2293
- * @param key - A top-level key of `state`.
2294
- * @param value - The value of that key. It must fit the key's schema.
2295
- *
2296
- * @example
2297
- * ```tsx
2298
- * useGenerativeUIState(storeUI, "cart", { count, total, coupon, items });
2299
- * ```
2300
- */
2301
- function useGenerativeUIState(ui, key, value) {
2302
- const runtime = useRequiredGenerativeUIRuntime();
2303
- const serialized = JSON.stringify(value);
2304
- useEffect(() => {
2305
- const raw = JSON.parse(serialized ?? "null");
2306
- let current = true;
2307
- const apply = (parsed) => {
2308
- if (!current) return;
2309
- if (parsed.success) {
2310
- runtime.manager.setState(key, parsed.data);
2311
- return;
2312
- }
2313
- runtime.manager.removeState(key);
2314
- if (process.env.NODE_ENV !== "production") console.error(`[generativeUI] useGenerativeUIState: invalid value for "${key}": ${formatIssues(parsed.issues, "value")}`);
2315
- };
2316
- const schema = runtime.ui.state.get(key);
2317
- const parsed = schema ? validateSchema(schema, raw) : {
2318
- success: true,
2319
- data: raw
2320
- };
2321
- if (parsed instanceof Promise) parsed.then(apply);
2322
- else apply(parsed);
2323
- return () => {
2324
- current = false;
2325
- };
2326
- }, [
2327
- runtime,
2328
- key,
2329
- serialized
2330
- ]);
2331
- useEffect(() => () => runtime.manager.removeState(key), [runtime, key]);
2332
- }
2333
- /**
2334
- * Experimental. Mounts the handler of a function declared in
2335
- * `createGenerativeUI({ functions })`. Generated UI can call the function
2336
- * only while exactly one handler for it is mounted.
2337
- *
2338
- * The handler gets the parsed arguments: schema defaults are set. It can
2339
- * change on each render. The latest handler always runs, and the hook does
2340
- * not register again.
2341
- *
2342
- * @param ui - The object from `createGenerativeUI`. It gives the name and the
2343
- * handler arguments their types.
2344
- * @param name - A key of `functions`.
2345
- * @param handler - Runs when generated UI calls the function. Its return
2346
- * value goes back to the caller as `{ ok: true, result }`.
2347
- *
2348
- * @example
2349
- * ```tsx
2350
- * useGenerativeUIFunction(storeUI, "addToCart", ({ productId, quantity }) =>
2351
- * cart.addItem(productId, quantity),
2352
- * );
2353
- * ```
2354
- */
2355
- function useGenerativeUIFunction(ui, name, handler) {
2356
- const runtime = useRequiredGenerativeUIRuntime();
2357
- const latest = useRef(handler);
2358
- latest.current = handler;
2359
- useEffect(() => runtime.dispatcher.register(name, latest), [runtime, name]);
2360
- }
2361
-
2362
- //#endregion
2363
- //#region src/generative-ui/boundaries.tsx
2364
- function DefaultNodeFallback({ message, componentId, retry }) {
2365
- return /* @__PURE__ */ jsxs("div", {
2366
- role: "alert",
2367
- "data-generative-ui-error": componentId,
2368
- style: {
2369
- border: "1px solid #fca5a5",
2370
- background: "#fef2f2",
2371
- color: "#991b1b",
2372
- borderRadius: 8,
2373
- padding: "8px 12px",
2374
- fontSize: 13
2375
- },
2376
- children: [
2377
- "Couldn’t display this part: ",
2378
- message,
2379
- retry && /* @__PURE__ */ jsx("button", {
2380
- type: "button",
2381
- onClick: retry,
2382
- style: {
2383
- marginLeft: 8,
2384
- textDecoration: "underline"
2385
- },
2386
- children: "Retry"
2387
- })
2388
- ]
2389
- });
2390
- }
2391
- /**
2392
- * A child that has not streamed yet renders nothing. The prose keeps
2393
- * streaming above the surface, and each component appears as soon as it is
2394
- * complete. A grey block in its place would read as a broken layout.
2395
- */
2396
- function NodePlaceholder(_props) {
2397
- return null;
2398
- }
2399
- /** Per-node boundary. Resets on retry or a new agent revision, not on data ticks. */
2400
- var NodeBoundary = class extends Component {
2401
- state = {
2402
- error: null,
2403
- revision: this.props.revision
2404
- };
2405
- static getDerivedStateFromError(error) {
2406
- return { error };
2407
- }
2408
- static getDerivedStateFromProps(props, state) {
2409
- return props.revision !== state.revision ? {
2410
- error: null,
2411
- revision: props.revision
2412
- } : null;
2413
- }
2414
- componentDidCatch(error) {
2415
- const { runtime, surfaceId, componentId } = this.props;
2416
- reportErrorSafely(runtime, {
2417
- kind: "render",
2418
- surfaceId,
2419
- componentId,
2420
- error
2421
- });
2422
- }
2423
- retry = () => this.setState({ error: null });
2424
- render() {
2425
- const { error } = this.state;
2426
- if (!error) return this.props.children;
2427
- const { runtime, surfaceId, componentId } = this.props;
2428
- const fallback = runtime.errorFallback;
2429
- return fallback ? fallback({
2430
- error,
2431
- retry: this.retry,
2432
- surfaceId,
2433
- componentId
2434
- }) : /* @__PURE__ */ jsx(DefaultNodeFallback, {
2435
- message: error.message,
2436
- componentId,
2437
- retry: this.retry
2438
- });
2439
- }
2440
- };
2441
- /** Outer boundary: a failure here must not reach the chat or the host page. */
2442
- var SurfaceBoundary = class extends Component {
2443
- state = { error: null };
2444
- static getDerivedStateFromError(error) {
2445
- return { error };
2446
- }
2447
- componentDidCatch(error) {
2448
- reportErrorSafely(this.props.runtime, {
2449
- kind: "render",
2450
- surfaceId: this.props.surfaceId,
2451
- error
2452
- });
2453
- }
2454
- render() {
2455
- if (!this.state.error) return this.props.children;
2456
- return /* @__PURE__ */ jsx(DefaultNodeFallback, {
2457
- message: "this generated UI failed to render",
2458
- componentId: "surface"
2459
- });
2460
- }
2461
- };
2462
-
2463
- //#endregion
2464
- //#region src/generative-ui/accessibility.ts
2465
- const LIVE = new Set([
2466
- "off",
2467
- "polite",
2468
- "assertive"
2469
- ]);
2470
- /**
2471
- * The accessibility of a component from its resolved `accessibility`
2472
- * value. Fields of the wrong type are left out: a label that is still a
2473
- * binding, or a list, names nothing.
2474
- */
2475
- function readAccessibility(value) {
2476
- if (typeof value !== "object" || value === null || Array.isArray(value)) return;
2477
- const { label, description, live, hidden } = value;
2478
- const result = {};
2479
- if (typeof label === "string" && label !== "") result.label = label;
2480
- if (typeof description === "string" && description !== "") result.description = description;
2481
- if (typeof live === "string" && LIVE.has(live)) result.live = live;
2482
- if (typeof hidden === "boolean") result.hidden = hidden;
2483
- return Object.keys(result).length > 0 ? result : void 0;
2484
- }
2485
- /**
2486
- * The ARIA attributes for an `accessibility`. `live: "off"` is written out:
2487
- * a region inherits the live setting of its ancestors, and a `status` role
2488
- * is live on its own, so only the explicit value silences it.
2489
- *
2490
- * @example
2491
- * ```ts
2492
- * accessibilityAttributes({ label: "Totals", live: "polite" });
2493
- * // { "aria-label": "Totals", "aria-live": "polite" }
2494
- * ```
2495
- */
2496
- function accessibilityAttributes(accessibility) {
2497
- if (!accessibility) return {};
2498
- const { label, description, live, hidden } = accessibility;
2499
- return {
2500
- ...label === void 0 ? {} : { "aria-label": label },
2501
- ...description === void 0 ? {} : { "aria-description": description },
2502
- ...live === void 0 ? {} : { "aria-live": live },
2503
- ...hidden ? { "aria-hidden": true } : {}
2504
- };
2505
- }
2506
- /**
2507
- * Experimental. The ARIA attributes of the `accessibility` that the model
2508
- * gave the component being rendered, to spread on its root element. The
2509
- * standard components do this; a custom component does it itself:
2510
- *
2511
- * @example
2512
- * ```tsx
2513
- * function Panel({ children }: { children?: ReactNode }) {
2514
- * const aria = useGenerativeUIAccessibility();
2515
- * return <section {...aria}>{children}</section>;
2516
- * }
2517
- * ```
2518
- *
2519
- * Outside of generated UI it gives `{}`.
2520
- */
2521
- function useGenerativeUIAccessibility() {
2522
- const accessibility = useContext(GenerativeUINodeContext)?.accessibility;
2523
- return useMemo(() => accessibilityAttributes(accessibility), [accessibility]);
2524
- }
2525
- /**
2526
- * The role of a container that the envelope names. A generic element
2527
- * cannot carry a name, so a label or a description makes it a `group`,
2528
- * unless the component has a role of its own.
2529
- */
2530
- function namedRole(aria, explicit) {
2531
- if (explicit !== void 0) return explicit;
2532
- return aria["aria-label"] !== void 0 || aria["aria-description"] !== void 0 ? "group" : void 0;
2533
- }
2534
- /**
2535
- * The part of the attributes for the focusable control of a labelled pair:
2536
- * its name and its description. ARIA names are not inherited, so the
2537
- * wrapper of a control cannot name it.
2538
- */
2539
- function controlAria(aria) {
2540
- const { "aria-label": label, "aria-description": description } = aria;
2541
- return {
2542
- ...label === void 0 ? {} : { "aria-label": label },
2543
- ...description === void 0 ? {} : { "aria-description": description }
2544
- };
2545
- }
2546
- /**
2547
- * The part of the attributes for the wrapper around a control: hidden and
2548
- * live cover the label and the control together.
2549
- */
2550
- function wrapperAria(aria) {
2551
- const { "aria-hidden": hidden, "aria-live": live } = aria;
2552
- return {
2553
- ...hidden === void 0 ? {} : { "aria-hidden": hidden },
2554
- ...live === void 0 ? {} : { "aria-live": live }
2555
- };
2556
- }
2557
-
2558
- //#endregion
2559
- //#region src/generative-ui/events.ts
2560
- /**
2561
- * The context of a running event binding: it reads the surface data model
2562
- * and resolves relative paths against the template item of the component.
2563
- * A function that needs a user gesture (openUrl) is not a value here
2564
- * either; it runs through the dispatcher as the binding's functionCall.
2565
- */
2566
- function eventContext(surface, basePath) {
2567
- return {
2568
- data: surface.model.dataModel,
2569
- basePath
2570
- };
2571
- }
2572
- /**
2573
- * A value of an event binding with its dynamic values resolved: `{"@path"}`
2574
- * bindings and function values, at any depth.
2575
- */
2576
- function resolveValue(surface, basePath, value) {
2577
- return resolveDynamicValue(value, eventContext(surface, basePath)).value;
2578
- }
2579
- /**
2580
- * The entries of an args or context record, each resolved on its own. The
2581
- * record is not resolved as a whole, because a record with one `event` or
2582
- * `functionCall` key would look like an action binding and stay as it is.
2583
- */
2584
- function resolveValues(surface, basePath, values) {
2585
- return Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [key, resolveValue(surface, basePath, value)]));
2586
- }
2587
- /**
2588
- * The `userMessage` of an event binding, as text. A `{"@path"}` or a
2589
- * function value is resolved. `undefined` when there is no message, or
2590
- * the value is not a string.
2591
- */
2592
- function resolveUserMessage(surface, basePath, userMessage) {
2593
- const value = resolveValue(surface, basePath, userMessage);
2594
- return typeof value === "string" ? value : void 0;
2595
- }
2596
- /**
2597
- * Validates the component's args with the event `parameters`, then runs
2598
- * `send` with them. Never throws: every failure is reported and becomes
2599
- * `{ ok: false, error }`.
2600
- */
2601
- async function runEvent(call, send) {
2602
- const { runtime, surface, componentId, name, parameters, args } = call;
2603
- const origin = {
2604
- surfaceId: surface.surfaceId,
2605
- componentId
2606
- };
2607
- try {
2608
- if (!parameters) return await send(args ?? {}, origin);
2609
- const result = validateSchema(parameters, args ?? {});
2610
- const parsed = result instanceof Promise ? await result : result;
2611
- if (!parsed.success) {
2612
- const error = new GenerativeUIError("invalid_event_args", `${name}: ${formatIssues(parsed.issues, "args")}`);
2613
- reportErrorSafely(runtime, {
2614
- kind: "event",
2615
- ...origin,
2616
- error
2617
- });
2618
- return {
2619
- ok: false,
2620
- error
2621
- };
2622
- }
2623
- return await send(parsed.data ?? {}, origin);
2624
- } catch (cause) {
2625
- const error = new GenerativeUIError("event_forward_failed", `${name}: ${cause instanceof Error ? cause.message : String(cause)}`);
2626
- reportErrorSafely(runtime, {
2627
- kind: "event",
2628
- ...origin,
2629
- error
2630
- });
2631
- return {
2632
- ok: false,
2633
- error
2634
- };
2635
- }
2636
- }
2637
- /**
2638
- * Runs one call of an event that the model bound: validates the component's
2639
- * args, merges them with the args from the binding (binding literals win),
2640
- * then calls a declared function or forwards an agent event. Never throws.
2641
- */
2642
- function invokeBoundEvent(params) {
2643
- const { runtime, surface, binding, basePath } = params;
2644
- return runEvent(params, (args, origin) => {
2645
- const componentArgs = args;
2646
- if ("functionCall" in binding) return runtime.dispatcher.invoke(binding.functionCall["@call"], {
2647
- ...componentArgs,
2648
- ...resolveValues(surface, basePath, binding.functionCall.args)
2649
- }, origin);
2650
- const { event } = binding;
2651
- const forwarded = {
2652
- name: event.name,
2653
- ...origin,
2654
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2655
- userMessage: resolveUserMessage(surface, basePath, event.userMessage),
2656
- context: {
2657
- ...componentArgs,
2658
- ...resolveValues(surface, basePath, event.context)
2659
- }
2660
- };
2661
- return runtime.forwardEvent(forwarded, surface.agentId);
2662
- });
2663
- }
2664
- /**
2665
- * Runs one call of an event that matches a declared function: validates the
2666
- * component's args with the event `parameters` (if any), then calls the
2667
- * function, which validates them with its own schema. Never throws.
2668
- */
2669
- function invokeMatchedEvent(params) {
2670
- const { runtime, functionName } = params;
2671
- return runEvent(params, (componentArgs, origin) => runtime.dispatcher.invoke(functionName, componentArgs, origin));
2672
- }
2673
-
2674
- //#endregion
2675
- //#region src/generative-ui/theme.ts
2676
- /**
2677
- * The built-in dark values. The light values are the fallbacks in the
2678
- * components, so a surface is light when no variable is set.
2679
- */
2680
- const DARK_THEME = {
2681
- "--a2ui-color-text-default": "#ececec",
2682
- "--a2ui-color-text-prose": "#ececec",
2683
- "--a2ui-color-text-primary": "#ececec",
2684
- "--a2ui-color-text-emphasis": "#fff",
2685
- "--a2ui-color-text-secondary": "#b4b4b4",
2686
- "--a2ui-color-text-tertiary": "#8e8e8e",
2687
- "--a2ui-color-text-success": "#4fd1a5",
2688
- "--a2ui-color-text-info": "#6cb6ff",
2689
- "--a2ui-color-text-warning": "#e3b341",
2690
- "--a2ui-color-text-caution": "#e3b341",
2691
- "--a2ui-color-text-danger": "#ff7b72",
2692
- "--a2ui-color-text-discovery": "#bc9cff",
2693
- "--a2ui-color-surface": "#1f1f1f",
2694
- "--a2ui-color-surface-secondary": "#2a2a2a",
2695
- "--a2ui-color-surface-tertiary": "#3a3a3a",
2696
- "--a2ui-color-surface-elevated": "#262626",
2697
- "--a2ui-color-surface-elevated-secondary": "#2f2f2f",
2698
- "--a2ui-color-surface-inverted": "#f2f2f2",
2699
- "--a2ui-color-surface-soft": "#232323",
2700
- "--a2ui-color-info": "rgba(80, 160, 255, 0.14)",
2701
- "--a2ui-color-warning": "rgba(240, 180, 60, 0.14)",
2702
- "--a2ui-color-caution": "rgba(240, 180, 60, 0.14)",
2703
- "--a2ui-color-success": "rgba(60, 200, 150, 0.14)",
2704
- "--a2ui-color-danger": "rgba(255, 110, 100, 0.14)",
2705
- "--a2ui-color-discovery": "rgba(170, 130, 255, 0.14)",
2706
- "--a2ui-color-info-soft": "rgba(80, 160, 255, 0.08)",
2707
- "--a2ui-color-warning-soft": "rgba(240, 180, 60, 0.08)",
2708
- "--a2ui-color-caution-soft": "rgba(240, 180, 60, 0.08)",
2709
- "--a2ui-color-success-soft": "rgba(60, 200, 150, 0.08)",
2710
- "--a2ui-color-danger-soft": "rgba(255, 110, 100, 0.08)",
2711
- "--a2ui-color-discovery-soft": "rgba(170, 130, 255, 0.08)",
2712
- "--a2ui-color-info-solid": "#3b8eea",
2713
- "--a2ui-color-warning-solid": "#c99a2e",
2714
- "--a2ui-color-caution-solid": "#c99a2e",
2715
- "--a2ui-color-success-solid": "#2fae86",
2716
- "--a2ui-color-danger-solid": "#e5534b",
2717
- "--a2ui-color-discovery-solid": "#9a6ff0",
2718
- "--a2ui-color-border-default": "rgba(255, 255, 255, 0.12)",
2719
- "--a2ui-color-border-subtle": "rgba(255, 255, 255, 0.06)",
2720
- "--a2ui-color-border-strong": "#4a4a4a",
2721
- "--a2ui-color-border-info": "#2f5f8f",
2722
- "--a2ui-color-border-warning": "#6b5420",
2723
- "--a2ui-color-border-caution": "#6b5420",
2724
- "--a2ui-color-border-success": "#1f5f4b",
2725
- "--a2ui-color-border-danger": "#7a2f2b",
2726
- "--a2ui-color-border-discovery": "#4f3a80",
2727
- "--a2ui-color-border-control": "rgba(255, 255, 255, 0.2)",
2728
- "--a2ui-color-accent": "#f2f2f2",
2729
- "--a2ui-color-on-accent": "#0d0d0d",
2730
- "--a2ui-color-panel": "#262626",
2731
- "--a2ui-color-control": "#2f2f2f",
2732
- "--a2ui-color-focus": "#3b9bff",
2733
- "--a2ui-color-shimmer": "rgba(255, 255, 255, 0.12)",
2734
- "--a2ui-color-chart-cursor": "rgba(255, 255, 255, 0.06)",
2735
- "--a2ui-color-slider-track": "rgba(255, 255, 255, 0.1)",
2736
- "--a2ui-color-badge-secondary": "rgba(255, 255, 255, 0.08)",
2737
- "--a2ui-color-highlight-green": "#1d4a37",
2738
- "--a2ui-color-highlight-orange": "#4d3418",
2739
- "--a2ui-color-highlight-pink": "#4d2338",
2740
- "--a2ui-shadow-xs": "0 1px 2px rgba(0, 0, 0, 0.5)",
2741
- "--a2ui-shadow-sm": "0 1px 3px rgba(0, 0, 0, 0.5)",
2742
- "--a2ui-shadow-soft": "0 1px 3px rgba(0, 0, 0, 0.3)",
2743
- "--a2ui-shadow-md": "0 4px 12px rgba(0, 0, 0, 0.4)"
2744
- };
2745
- const VARIABLE_NAME = /^--a2ui-[a-z0-9-]+$/;
2746
- const UNSAFE_VALUE = /[{};<>]/;
2747
- /** Matches the `dark` class on an ancestor of a surface, or on the surface. */
2748
- const DARK = ":where(.dark)";
2749
- /** The default dark values, as a rule that any theme rule beats. */
2750
- const DARK_THEME_CSS = `:where(.dark .a2ui-surface,.a2ui-surface.dark){${declarations(DARK_THEME)}}`;
2751
- function declarations(values) {
2752
- return Object.entries(values ?? {}).filter(([name, value]) => VARIABLE_NAME.test(name) && typeof value === "string" && !UNSAFE_VALUE.test(value)).map(([name, value]) => `${name}:${value}`).join(";");
2753
- }
2754
- /** A short, stable id for a stylesheet. */
2755
- function hashOf(text) {
2756
- let hash = 5381;
2757
- for (let index = 0; index < text.length; index++) hash = hash * 33 ^ text.charCodeAt(index);
2758
- return `t${(hash >>> 0).toString(36)}`;
2759
- }
2760
- /**
2761
- * The stylesheet of a theme: its values on the surfaces that carry its id,
2762
- * then its dark values in dark mode. `undefined` when the theme sets no
2763
- * variable. Values that could break out of the rule are left out.
2764
- *
2765
- * @example
2766
- * ```ts
2767
- * themeStyleSheet({ "--a2ui-color-accent": "red" });
2768
- * // { id: "t…", css: '.a2ui-surface[data-a2ui-theme="t…"]{--a2ui-color-accent:red}' }
2769
- * ```
2770
- */
2771
- function themeStyleSheet(theme) {
2772
- const { dark, ...base } = theme ?? {};
2773
- const both = declarations(base);
2774
- const darkOnly = declarations(dark);
2775
- if (!both && !darkOnly) return void 0;
2776
- const id = hashOf(`${both}|${darkOnly}`);
2777
- const self = `.a2ui-surface[data-a2ui-theme="${id}"]`;
2778
- return {
2779
- id,
2780
- css: [both && `${self}{${both}}`, darkOnly && `${DARK} ${self},${self}${DARK}{${darkOnly}}`].filter(Boolean).join("")
2781
- };
2782
- }
2783
-
2784
- //#endregion
2785
- //#region src/generative-ui/SurfaceView.tsx
2786
- const NO_ANCESTORS = [];
2787
- const ROOT_STYLE = { display: "contents" };
2788
- const undefinedSnapshot = () => void 0;
2789
- const noopSubscribe = () => () => {};
2790
- const zeroSnapshot = () => 0;
2791
- /** A "multiple" slot value that repeats a component for each list item. */
2792
- function isTemplateChildren(value) {
2793
- return typeof value === "object" && value !== null && "componentId" in value && typeof value.componentId === "string" && "path" in value && typeof value.path === "string";
2794
- }
2795
- function SurfaceView({ surface }) {
2796
- const runtime = useRequiredGenerativeUIRuntime();
2797
- const { theme } = runtime;
2798
- const sheet = useMemo(() => themeStyleSheet(theme), [theme]);
2799
- return /* @__PURE__ */ jsxs("div", {
2800
- className: "a2ui-surface",
2801
- "data-generative-ui-root": surface.surfaceId,
2802
- "data-a2ui-theme": sheet?.id,
2803
- style: ROOT_STYLE,
2804
- children: [sheet ? /* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: sheet.css } }) : null, /* @__PURE__ */ jsx(SurfaceBoundary, {
2805
- surfaceId: surface.surfaceId,
2806
- runtime,
2807
- children: /* @__PURE__ */ jsx(NodeView, {
2808
- surface,
2809
- componentId: GENERATIVE_UI_ROOT_ID,
2810
- basePath: void 0,
2811
- ancestors: NO_ANCESTORS
2812
- })
2813
- })]
2814
- });
2815
- }
2816
- /**
2817
- * Resolves a component by id. Subscribes to the manager rather than web_core's
2818
- * `onCreated`/`onDeleted`: web_core's EventEmitter awaits each listener in turn,
2819
- * so with several subscribers (one per slotted child, or one per mount of the
2820
- * same surface) all but the first are notified a microtask late. That is only
2821
- * visible inside synchronous flushes such as `act()` / `flushSync`, where the
2822
- * old tree would still be on screen, but it makes updates order-dependent.
2823
- * The manager notifies synchronously once an ingest has been fully applied.
2824
- */
2825
- function useComponentModel(manager, model, id) {
2826
- return useSyncExternalStore(manager.subscribe, () => model.componentsModel.get(id), undefinedSnapshot);
2827
- }
2828
- /** Same reasoning as `useComponentModel`: never rely on web_core's emitters. */
2829
- function useComponentProperties(manager, component) {
2830
- return useSyncExternalStore(manager.subscribe, () => component?.properties, undefinedSnapshot);
2831
- }
2832
- /**
2833
- * The id of a node in the ancestor list. A template renders the same
2834
- * component once per item, so the item path is part of the id. A real cycle
2835
- * repeats both.
2836
- */
2837
- function scopedId(componentId, basePath) {
2838
- return `${basePath ?? ""}#${componentId}`;
2839
- }
2840
- const NodeView = memo(function NodeView({ surface, componentId, basePath, ancestors }) {
2841
- const runtime = useRequiredGenerativeUIRuntime();
2842
- const component = useComponentModel(runtime.manager, surface.model, componentId);
2843
- const properties = useComponentProperties(runtime.manager, component);
2844
- if (ancestors.includes(scopedId(componentId, basePath))) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
2845
- message: `cyclic reference to ${componentId}`,
2846
- componentId
2847
- });
2848
- if (!component || !properties) return /* @__PURE__ */ jsx(NodePlaceholder, { componentId });
2849
- const definition = runtime.ui.components.get(component.type);
2850
- if (!definition) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
2851
- message: `unknown component "${component.type}"`,
2852
- componentId
2853
- });
2854
- return /* @__PURE__ */ jsx(NodeBoundary, {
2855
- surfaceId: surface.surfaceId,
2856
- componentId,
2857
- revision: properties,
2858
- runtime,
2859
- children: /* @__PURE__ */ jsx(ResolvedNode, {
2860
- surface,
2861
- componentId,
2862
- definition,
2863
- properties,
2864
- runtime,
2865
- basePath,
2866
- ancestors
2867
- })
2868
- }, component.type);
2869
- });
2870
- /**
2871
- * Renders the component of a template once for each item of the list at the
2872
- * template path, keyed by index. Renders nothing when there is no list.
2873
- */
2874
- function TemplateChildren({ surface, template, basePath, ancestors }) {
2875
- const dataModel = surface.model.dataModel;
2876
- const listPath = resolvePath(template.path, basePath);
2877
- const subscribe = useCallback((onChange) => {
2878
- const subscription = dataModel.subscribe(listPath, onChange);
2879
- return () => subscription.unsubscribe();
2880
- }, [dataModel, listPath]);
2881
- const getCount = () => {
2882
- const list = dataModel.get(listPath);
2883
- return Array.isArray(list) ? list.length : 0;
2884
- };
2885
- const count = useSyncExternalStore(subscribe, getCount, zeroSnapshot);
2886
- return /* @__PURE__ */ jsx(Fragment$1, { children: Array.from({ length: count }, (_, index) => index).map((index) => /* @__PURE__ */ jsx(NodeView, {
2887
- surface,
2888
- componentId: template.componentId,
2889
- basePath: joinPath(listPath, String(index)),
2890
- ancestors
2891
- }, index)) });
2892
- }
2893
- /**
2894
- * The props the model sets, with their dynamic values resolved from the
2895
- * surface data model: `{"@path"}` bindings, `{"@call"}` function values and
2896
- * `{"@call":"@index"}` in a template, at any depth. A literal writable prop
2897
- * that the component set shows the local value from `overrides`. Bound
2898
- * props, events and slots are left out, and so are the keys of the A2UI
2899
- * component envelope; `accessibility` is resolved the same way and given
2900
- * on its own.
2901
- *
2902
- * A prop is resolved again only when its raw value or a data model value it
2903
- * read has changed, so the result keeps its identity otherwise. A function
2904
- * value that cannot be computed gives a problem instead of values.
2905
- */
2906
- function useModelDataProps(surface, definition, properties, basePath, overrides) {
2907
- const dataModel = surface.model.dataModel;
2908
- const units = useMemo(() => {
2909
- const list = [];
2910
- for (const key of Object.keys(properties)) {
2911
- if (definition.events?.[key] || definition.slots?.[key] || Object.hasOwn(definition.selectors, key) || A2UI_COMPONENT_ENVELOPE_KEYS.has(key)) continue;
2912
- list.push({
2913
- key,
2914
- raw: properties[key]
2915
- });
2916
- }
2917
- const a11y = properties.accessibility;
2918
- if (typeof a11y === "object" && a11y !== null && !Array.isArray(a11y)) for (const [field, raw] of Object.entries(a11y)) list.push({
2919
- key: `accessibility/${field}`,
2920
- raw,
2921
- field
2922
- });
2923
- return list;
2924
- }, [properties, definition]);
2925
- const [, rerender] = useReducer((n) => n + 1, 0);
2926
- const cache = useRef(/* @__PURE__ */ new Map());
2927
- const values = {};
2928
- const a11yValues = {};
2929
- const paths = /* @__PURE__ */ new Set();
2930
- let problem;
2931
- const next = /* @__PURE__ */ new Map();
2932
- for (const { key, raw, field } of units) {
2933
- const cached = cache.current.get(key);
2934
- const isFresh = cached !== void 0 && cached.raw === raw && cached.basePath === basePath && [...cached.reads].every(([path, value]) => Object.is(dataModel.get(path), value));
2935
- const resolve = () => {
2936
- const resolved = tryResolveDynamicValue(raw, {
2937
- data: dataModel,
2938
- basePath
2939
- }, { isChecks: key === "checks" });
2940
- const reads = /* @__PURE__ */ new Map();
2941
- for (const path of resolved.paths) reads.set(path, dataModel.get(path));
2942
- return {
2943
- raw,
2944
- basePath,
2945
- reads,
2946
- outcome: resolved.ok ? {
2947
- ok: true,
2948
- value: resolved.value
2949
- } : {
2950
- ok: false,
2951
- message: resolved.error.message
2952
- }
2953
- };
2954
- };
2955
- const entry = isFresh && cached ? cached : resolve();
2956
- next.set(key, entry);
2957
- if (field !== void 0) {
2958
- if (entry.outcome.ok) a11yValues[field] = entry.outcome.value;
2959
- } else if (entry.outcome.ok) values[key] = entry.outcome.value;
2960
- else problem ??= `${key}: ${entry.outcome.message}`;
2961
- for (const path of entry.reads.keys()) paths.add(path);
2962
- }
2963
- cache.current = next;
2964
- const accessibility = readAccessibility(a11yValues);
2965
- for (const [key, value] of Object.entries(overrides)) if (!isPathBinding(properties[key])) values[key] = value;
2966
- const rendered = useRef(next);
2967
- rendered.current = next;
2968
- const pathKey = [...paths].sort().join("\n");
2969
- useEffect(() => {
2970
- const list = pathKey === "" ? [] : pathKey.split("\n");
2971
- const onChange = () => {
2972
- cache.current = /* @__PURE__ */ new Map();
2973
- rerender();
2974
- };
2975
- const subscriptions = list.map((path) => dataModel.subscribe(path, onChange));
2976
- if ([...rendered.current.values()].some((entry) => [...entry.reads].some(([path, value]) => !Object.is(dataModel.get(path), value)))) rerender();
2977
- return () => subscriptions.forEach((s) => s.unsubscribe());
2978
- }, [dataModel, pathKey]);
2979
- const stable = useRef({
2980
- ok: true,
2981
- values: {},
2982
- accessibility: void 0
2983
- });
2984
- const result = problem === void 0 ? {
2985
- ok: true,
2986
- values,
2987
- accessibility
2988
- } : {
2989
- ok: false,
2990
- problem
2991
- };
2992
- const last = stable.current;
2993
- if (!(result.ok && last.ok ? shallowEqual(last.values, result.values) && shallowEqual(last.accessibility ?? {}, result.accessibility ?? {}) : !result.ok && !last.ok && last.problem === result.problem)) stable.current = result;
2994
- return stable.current;
2995
- }
2996
- const NO_SELECTION = {
2997
- ok: true,
2998
- values: {}
2999
- };
3000
- function isSameSelection(a, b) {
3001
- if (a.ok && b.ok) return shallowEqual(a.values, b.values);
3002
- if (!a.ok && !b.ok) return a.problem === b.problem;
3003
- return false;
3004
- }
3005
- /** Runs every selector of a node. A selector that throws gives a problem. */
3006
- function select(definition, state, modelProps) {
3007
- const values = {};
3008
- const selectors = Object.entries(definition.selectors);
3009
- for (const [key, selector] of selectors) try {
3010
- values[key] = selector(state, modelProps);
3011
- } catch (error) {
3012
- return {
3013
- ok: false,
3014
- problem: `${key}: selector threw: ${error instanceof Error ? error.message : String(error)}`
3015
- };
3016
- }
3017
- return {
3018
- ok: true,
3019
- values
3020
- };
3021
- }
3022
- /**
3023
- * The values of the bound props of a node, read from the app state.
3024
- *
3025
- * The selectors run again only when the state object or the parsed model
3026
- * props change. When the new values are shallow-equal to the last ones, the
3027
- * last snapshot is kept. So the node re-renders only when a selected value
3028
- * changes. A selector that returns a new array on each call cannot cause a
3029
- * render loop: with the same inputs, the cached snapshot comes back.
3030
- *
3031
- * A node without bound props does not subscribe to the state.
3032
- */
3033
- function useSelection(manager, definition, modelProps) {
3034
- const hasSelectors = Object.keys(definition.selectors).length > 0;
3035
- const cache = useRef(void 0);
3036
- const getSnapshot = () => {
3037
- if (!hasSelectors || modelProps === void 0) return NO_SELECTION;
3038
- const state = manager.getState();
3039
- const cached = cache.current;
3040
- if (cached !== void 0 && cached.state === state && cached.modelProps === modelProps) return cached.selection;
3041
- const next = select(definition, state, modelProps);
3042
- const selection = cached !== void 0 && isSameSelection(cached.selection, next) ? cached.selection : next;
3043
- cache.current = {
3044
- state,
3045
- modelProps,
3046
- selection
3047
- };
3048
- return selection;
3049
- };
3050
- return useSyncExternalStore(hasSelectors ? manager.subscribe : noopSubscribe, getSnapshot, getSnapshot);
3051
- }
3052
- /**
3053
- * Checks the model-set props with the props schema before the selectors run.
3054
- * The bound props are not set yet, so their issues do not count. Neither do
3055
- * issues with no path (a check over several props), which the full check
3056
- * after the selectors reports.
3057
- */
3058
- function checkModelProps(definition, modelData) {
3059
- if (!definition.props) return {
3060
- ok: true,
3061
- values: {}
3062
- };
3063
- let values = modelData;
3064
- let result = validateSchemaSync(definition.props, values);
3065
- if (!result.success) {
3066
- const unset = withoutRejectedNulls(values, result.issues);
3067
- if (unset) {
3068
- values = unset;
3069
- result = validateSchemaSync(definition.props, values);
3070
- }
3071
- }
3072
- if (!result.success) {
3073
- const issues = result.issues.filter((issue) => {
3074
- const key = issueKey(issue);
3075
- return key === void 0 ? isAsyncIssue(issue) : !Object.hasOwn(definition.selectors, key);
3076
- });
3077
- if (issues.length > 0) return {
3078
- ok: false,
3079
- problem: formatIssues(issues)
3080
- };
3081
- }
3082
- return {
3083
- ok: true,
3084
- values
3085
- };
3086
- }
3087
- /**
3088
- * The data props of a node, in three steps: check the model-set props with
3089
- * the props schema, run the selectors with them, then parse all props with
3090
- * the props schema. Gives the reason when a step fails.
3091
- */
3092
- function useDataProps(runtime, surface, definition, properties, basePath, overrides) {
3093
- const modelData = useModelDataProps(surface, definition, properties, basePath, overrides);
3094
- const modelCheck = useMemo(() => modelData.ok ? checkModelProps(definition, modelData.values) : modelData, [definition, modelData]);
3095
- const selection = useSelection(runtime.manager, definition, modelCheck.ok ? modelCheck.values : void 0);
3096
- const accessibility = modelData.ok ? modelData.accessibility : void 0;
3097
- return useMemo(() => {
3098
- if (!modelCheck.ok) return modelCheck;
3099
- if (!selection.ok) return selection;
3100
- if (!definition.props) return {
3101
- ok: true,
3102
- props: {},
3103
- accessibility
3104
- };
3105
- const input = {
3106
- ...modelCheck.values,
3107
- ...selection.values
3108
- };
3109
- let parsed = validateSchemaSync(definition.props, input);
3110
- if (!parsed.success) {
3111
- const unset = withoutRejectedNulls(input, parsed.issues);
3112
- if (unset) parsed = validateSchemaSync(definition.props, unset);
3113
- }
3114
- if (!parsed.success) return {
3115
- ok: false,
3116
- problem: formatIssues(parsed.issues)
3117
- };
3118
- return {
3119
- ok: true,
3120
- props: parsed.data,
3121
- accessibility
3122
- };
3123
- }, [
3124
- definition,
3125
- modelCheck,
3126
- selection,
3127
- accessibility
3128
- ]);
3129
- }
3130
- /**
3131
- * The event props of a node. A matched event (one that matches a declared
3132
- * function) is always bound. An unmatched event is bound only when the model
3133
- * bound it.
3134
- */
3135
- function useEventProps(runtime, surface, componentId, definition, properties, basePath) {
3136
- const latest = useRef(properties);
3137
- latest.current = properties;
3138
- const boundNames = Object.keys(definition.events ?? {}).filter((name) => Object.hasOwn(definition.eventFunctions, name) || isActionBinding(properties[name])).join("|");
3139
- return useMemo(() => {
3140
- const handlers = {};
3141
- const names = boundNames ? boundNames.split("|") : [];
3142
- for (const name of names) {
3143
- const call = {
3144
- runtime,
3145
- surface,
3146
- componentId,
3147
- name,
3148
- parameters: definition.events?.[name]?.parameters
3149
- };
3150
- const functionName = Object.hasOwn(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
3151
- handlers[name] = functionName === void 0 ? (args) => invokeBoundEvent({
3152
- ...call,
3153
- binding: latest.current[name],
3154
- basePath,
3155
- args
3156
- }) : (args) => invokeMatchedEvent({
3157
- ...call,
3158
- functionName,
3159
- args
3160
- });
3161
- }
3162
- return handlers;
3163
- }, [
3164
- boundNames,
3165
- runtime,
3166
- surface,
3167
- componentId,
3168
- definition,
3169
- basePath
3170
- ]);
3171
- }
3172
- /**
3173
- * The setter props of a node: `setValue` for the writable prop `value`. For
3174
- * a prop the model bound to `{"@path"}`, the setter writes the data model
3175
- * and makes the path user-owned. For a literal prop, it sets `overrides`, a
3176
- * local value of this mounted node. The setters keep their identity.
3177
- */
3178
- function useSetterProps(runtime, surface, componentId, definition, properties, basePath) {
3179
- const [overrides, setOverrides] = useState({});
3180
- const latest = useRef(properties);
3181
- latest.current = properties;
3182
- return {
3183
- overrides,
3184
- setters: useMemo(() => {
3185
- const result = {};
3186
- const writable = definition.writable ?? [];
3187
- for (const key of writable) result[setterNameOf(key)] = (value) => {
3188
- const binding = latest.current[key];
3189
- if (!isPathBinding(binding)) {
3190
- setOverrides((current) => ({
3191
- ...current,
3192
- [key]: value
3193
- }));
3194
- return;
3195
- }
3196
- try {
3197
- runtime.manager.setOwnedValue(surface.key, resolvePath(binding["@path"], basePath), value);
3198
- } catch (cause) {
3199
- const message = cause instanceof Error ? cause.message : String(cause);
3200
- reportErrorSafely(runtime, {
3201
- kind: "props",
3202
- surfaceId: surface.surfaceId,
3203
- componentId,
3204
- error: /* @__PURE__ */ new Error(`${setterNameOf(key)}: ${message}`)
3205
- });
3206
- }
3207
- };
3208
- return result;
3209
- }, [
3210
- runtime,
3211
- surface,
3212
- componentId,
3213
- definition,
3214
- basePath
3215
- ])
3216
- };
3217
- }
3218
- function useSlotProps(surface, definition, properties, componentId, basePath, ancestors) {
3219
- return useMemo(() => {
3220
- const childAncestors = [...ancestors, scopedId(componentId, basePath)];
3221
- const slots = {};
3222
- for (const [name, kind] of Object.entries(definition.slots ?? {})) {
3223
- const value = properties[name];
3224
- if (kind === "single" && typeof value === "string") slots[name] = /* @__PURE__ */ jsx(NodeView, {
3225
- surface,
3226
- componentId: value,
3227
- basePath,
3228
- ancestors: childAncestors
3229
- });
3230
- else if (kind === "multiple" && isTemplateChildren(value)) slots[name] = /* @__PURE__ */ jsx(TemplateChildren, {
3231
- surface,
3232
- template: value,
3233
- basePath,
3234
- ancestors: childAncestors
3235
- });
3236
- else if (kind === "multiple" && Array.isArray(value)) slots[name] = [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ jsx(NodeView, {
3237
- surface,
3238
- componentId: id,
3239
- basePath,
3240
- ancestors: childAncestors
3241
- }, id));
3242
- }
3243
- return slots;
3244
- }, [
3245
- surface,
3246
- definition,
3247
- properties,
3248
- componentId,
3249
- basePath,
3250
- ancestors
3251
- ]);
3252
- }
3253
- /**
3254
- * The parsed data props with every typed child reference (`child()`,
3255
- * `childList()`, at any depth) replaced by the rendered component. Without
3256
- * references, the parsed props come back as they are.
3257
- */
3258
- function useChildRefProps(surface, refs, props, componentId, basePath, ancestors) {
3259
- return useMemo(() => {
3260
- if (props === void 0 || refs.length === 0) return props;
3261
- const childAncestors = [...ancestors, scopedId(componentId, basePath)];
3262
- const render = (kind, value) => {
3263
- if (kind === "single") return typeof value === "string" ? /* @__PURE__ */ jsx(NodeView, {
3264
- surface,
3265
- componentId: value,
3266
- basePath,
3267
- ancestors: childAncestors
3268
- }) : void 0;
3269
- if (isTemplateChildren(value)) return /* @__PURE__ */ jsx(TemplateChildren, {
3270
- surface,
3271
- template: value,
3272
- basePath,
3273
- ancestors: childAncestors
3274
- });
3275
- if (!Array.isArray(value)) return void 0;
3276
- return [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ jsx(NodeView, {
3277
- surface,
3278
- componentId: id,
3279
- basePath,
3280
- ancestors: childAncestors
3281
- }, id));
3282
- };
3283
- let result = props;
3284
- for (const ref of refs) result = mapAtChildRef(result, ref.path, (found) => render(ref.kind, found));
3285
- return result;
3286
- }, [
3287
- surface,
3288
- refs,
3289
- props,
3290
- componentId,
3291
- basePath,
3292
- ancestors
3293
- ]);
3294
- }
3295
- function ResolvedNode({ surface, componentId, definition, properties, runtime, basePath, ancestors }) {
3296
- const { overrides, setters } = useSetterProps(runtime, surface, componentId, definition, properties, basePath);
3297
- const dataProps = useDataProps(runtime, surface, definition, properties, basePath, overrides);
3298
- const eventProps = useEventProps(runtime, surface, componentId, definition, properties, basePath);
3299
- const slotProps = useSlotProps(surface, definition, properties, componentId, basePath, ancestors);
3300
- const childRefProps = useChildRefProps(surface, definition.childRefs, dataProps.ok ? dataProps.props : void 0, componentId, basePath, ancestors);
3301
- const accessibility = dataProps.ok ? dataProps.accessibility : void 0;
3302
- const nodeContext = useMemo(() => ({
3303
- surfaceKey: surface.key,
3304
- surfaceId: surface.surfaceId,
3305
- componentId,
3306
- accessibility
3307
- }), [
3308
- surface.key,
3309
- surface.surfaceId,
3310
- componentId,
3311
- accessibility
3312
- ]);
3313
- const problem = dataProps.ok ? void 0 : dataProps.problem;
3314
- useEffect(() => {
3315
- if (problem) reportErrorSafely(runtime, {
3316
- kind: "props",
3317
- surfaceId: surface.surfaceId,
3318
- componentId,
3319
- error: /* @__PURE__ */ new Error(`Invalid props: ${problem}`)
3320
- });
3321
- }, [
3322
- problem,
3323
- runtime,
3324
- surface.surfaceId,
3325
- componentId
3326
- ]);
3327
- if (!dataProps.ok) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
3328
- message: `invalid props (${problem})`,
3329
- componentId
3330
- });
3331
- const Component = definition.component;
3332
- const rendered = /* @__PURE__ */ jsx(Component, {
3333
- ...childRefProps,
3334
- ...eventProps,
3335
- ...slotProps,
3336
- ...setters
3337
- });
3338
- const hasEnvelope = properties.accessibility !== void 0 && definition.accessibility !== "self";
3339
- return /* @__PURE__ */ jsx(GenerativeUINodeContext.Provider, {
3340
- value: nodeContext,
3341
- children: hasEnvelope ? /* @__PURE__ */ jsx("span", {
3342
- "data-a2ui-accessibility": "",
3343
- style: ROOT_STYLE,
3344
- ...wrapperAria(accessibilityAttributes(accessibility)),
3345
- children: rendered
3346
- }) : rendered
3347
- });
3348
- }
3349
-
3350
- //#endregion
3351
- //#region src/generative-ui/chat.tsx
3352
- const GenerativeUIChatSlotContext = createContext(void 0);
3353
- function DefaultGenerativeUIChatCard({ surfaceId, error, children }) {
3354
- return /* @__PURE__ */ jsxs("div", {
3355
- "data-generative-ui-chat-surface": surfaceId,
3356
- className: "cpk-generative-ui-chat-card",
3357
- children: [children, error && /* @__PURE__ */ jsx("div", {
3358
- role: "alert",
3359
- className: "cpk-generative-ui-chat-card-error",
3360
- children: "Part of this UI couldn't be shown."
3361
- })]
3362
- });
3363
- }
3364
- const ContentSchema = z.object({
3365
- surfaceId: z.string(),
3366
- target: z.string(),
3367
- catalogId: z.string(),
3368
- operations: z.array(z.any()),
3369
- status: z.enum([
3370
- "streaming",
3371
- "ready",
3372
- "error"
3373
- ]),
3374
- rejected: z.array(z.object({
3375
- index: z.number(),
3376
- reason: z.string()
3377
- })).default([])
3378
- }).loose();
3379
- function GenerativeUIChatActivity({ content, agent }) {
3380
- const runtime = useGenerativeUIRuntime();
3381
- const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;
3382
- const Wrapper = useContext(GenerativeUIChatSlotContext) ?? DefaultGenerativeUIChatCard;
3383
- useManagerVersion(runtime);
3384
- useLayoutEffect(() => {
3385
- if (runtime && threadId) runtime.manager.ingest(threadId, agent?.agentId, content);
3386
- }, [
3387
- runtime,
3388
- threadId,
3389
- agent?.agentId,
3390
- content
3391
- ]);
3392
- if (!runtime || !threadId || content.target !== GENERATIVE_UI_CHAT_TARGET) return null;
3393
- const surface = runtime.manager.getSurface(threadId, content.surfaceId) ?? runtime.manager.getFailedSurface(threadId, content.surfaceId);
3394
- if (!surface) return null;
3395
- const rejected = [...content.rejected ?? [], ...surface.clientRejected];
3396
- const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
3397
- return /* @__PURE__ */ jsx(Wrapper, {
3398
- surfaceId: content.surfaceId,
3399
- isStreaming: content.status === "streaming",
3400
- error,
3401
- rejected,
3402
- children: surface.failed ? null : /* @__PURE__ */ jsx(SurfaceView, { surface })
3403
- });
3404
- }
3405
- function createGenerativeUIActivityRenderer() {
3406
- return {
3407
- activityType: GENERATIVE_UI_ACTIVITY_TYPE,
3408
- content: ContentSchema,
3409
- render: GenerativeUIChatActivity
3410
- };
3411
- }
3412
- /**
3413
- * Shows nothing in the chat for an agent-called function. The root reads the
3414
- * function-call activities from the messages and runs them. This renderer
3415
- * only keeps a wildcard ("*") activity renderer from showing them.
3416
- */
3417
- function createGenerativeUIFunctionCallActivityRenderer() {
3418
- return {
3419
- activityType: GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,
3420
- content: z.unknown(),
3421
- render: () => null
3422
- };
3423
- }
3424
- /** Hides the raw `render_ui` tool call; the surface activity owns the UX. */
3425
- function GenerativeUIToolCallRenderer() {
3426
- const { copilotkit } = useCopilotKit();
3427
- useEffect(() => {
3428
- const renderer = defineToolCallRenderer({
3429
- name: GENERATIVE_UI_RENDER_TOOL,
3430
- args: z.any(),
3431
- render: () => /* @__PURE__ */ jsx(Fragment$1, {})
3432
- });
3433
- return copilotkit.ɵaddBuiltInRenderToolCall(renderer);
3434
- }, [copilotkit]);
3435
- return null;
3436
- }
3437
-
3438
- //#endregion
3439
- //#region src/generative-ui/markdown/ProviderMarkdown.tsx
3440
- /**
3441
- * Markdown prose inside generative UI, rendered like the chat text around
3442
- * it: the renderer set on the provider when there is one, else the built-in
3443
- * streaming renderer. Config passed here wins over provider config.
3444
- */
3445
- function ProviderMarkdown({ content, isStreaming, className, ...config }) {
3446
- const renderer = useMarkdownRenderer();
3447
- if (renderer && isReactComponentType(renderer)) return /* @__PURE__ */ jsx(renderer, {
3448
- content,
3449
- isStreaming,
3450
- className
3451
- });
3452
- return /* @__PURE__ */ jsx(StreamingMarkdownDefaultRenderer, {
3453
- ...renderer,
3454
- ...config,
3455
- content,
3456
- isStreaming,
3457
- className
3458
- });
3459
- }
3460
-
3461
- //#endregion
3462
- //#region src/generative-ui/markdown/MarkdownSurfaces.tsx
3463
- const FADE_STYLE_ID = "a2ui-markdown-fade";
3464
- /**
3465
- * Components fade in as they stream: each element that appears under a
3466
- * markdown surface runs the keyframes once on mount. React keeps the keys
3467
- * stable per component id, so an element that is already there never
3468
- * animates again. SVG internals are left out: a chart library re-creates
3469
- * its nodes on each render, and a fade on each of them would read as the
3470
- * chart flashing whenever a sibling arrives. The fade runs under reduced
3471
- * motion too, because it moves nothing.
3472
- */
3473
- const FADE_CSS = ["@keyframes a2ui-fade-in{from{opacity:0}}", "[data-a2ui-markdown-surface] .a2ui-surface *:not(svg):not(svg *){animation:a2ui-fade-in .35s ease-out backwards}"].join("\n");
3474
- const noEffect = () => {};
3475
- const useInjectEffect = typeof document === "undefined" ? noEffect : useInsertionEffect;
3476
- function useFadeStyles() {
3477
- useInjectEffect(() => {
3478
- if (document.getElementById(FADE_STYLE_ID)) return;
3479
- const style = document.createElement("style");
3480
- style.id = FADE_STYLE_ID;
3481
- style.textContent = FADE_CSS;
3482
- document.head.appendChild(style);
3483
- }, []);
3484
- }
3485
- /**
3486
- * The default wrapper of a chat surface in the markdown transport. It draws
3487
- * no box: a surface sits in the flow of the reply like a paragraph, and a
3488
- * Card draws its own box when it is interactive. Nothing shows while the
3489
- * surface streams. A rejected operation gets one line.
3490
- */
3491
- function DefaultMarkdownChatSurface({ surfaceId, error, children }) {
3492
- useFadeStyles();
3493
- return /* @__PURE__ */ jsxs("div", {
3494
- "data-generative-ui-chat-surface": surfaceId,
3495
- "data-a2ui-markdown-surface": surfaceId,
3496
- className: "cpk-markdown-chat-surface",
3497
- children: [children, error && /* @__PURE__ */ jsx("div", {
3498
- role: "alert",
3499
- className: "cpk-markdown-chat-surface-error",
3500
- children: "Part of this UI couldn't be shown."
3501
- })]
3502
- });
3503
- }
3504
- /**
3505
- * One chat surface in the chat wrapper. Nothing renders until the surface
3506
- * has its root component, so a half-streamed fence shows no empty card.
3507
- */
3508
- function ChatSurface({ runtime, threadId, surfaceId, Wrapper }) {
3509
- const surface = runtime.manager.getSurface(threadId, surfaceId) ?? runtime.manager.getFailedSurface(threadId, surfaceId);
3510
- const root = surface?.model.componentsModel.get(GENERATIVE_UI_ROOT_ID);
3511
- if (!surface || !root && !surface.failed) return null;
3512
- const rejected = [...surface.serverRejected, ...surface.clientRejected];
3513
- const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
3514
- return /* @__PURE__ */ jsx(Wrapper, {
3515
- surfaceId,
3516
- isStreaming: surface.status === "streaming",
3517
- error,
3518
- rejected,
3519
- children: surface.failed ? null : /* @__PURE__ */ jsx(SurfaceView, { surface })
3520
- });
3521
- }
3522
- /** The blocks of one fence: lifted prose and chat surfaces, in order. */
3523
- function FenceBlocks({ blocks, runtime, threadId, isStreaming, markdownProps }) {
3524
- const Wrapper = useContext(GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;
3525
- let surfaceCount = 0;
3526
- return /* @__PURE__ */ jsx(Fragment$1, { children: blocks.map((block, index) => {
3527
- if (block.kind === "markdown") return /* @__PURE__ */ jsx(ProviderMarkdown, {
3528
- ...markdownProps,
3529
- content: block.markdown,
3530
- isStreaming: isStreaming && index === blocks.length - 1
3531
- }, `md-${surfaceCount}`);
3532
- surfaceCount++;
3533
- return /* @__PURE__ */ jsx(ChatSurface, {
3534
- runtime,
3535
- threadId,
3536
- surfaceId: block.surfaceId,
3537
- Wrapper
3538
- }, block.surfaceId);
3539
- }) });
3540
- }
3541
- /**
3542
- * Experimental. Renders an assistant message of the markdown transport.
3543
- * Prose renders as markdown. In place of each ```a2ui fence:
3544
- *
3545
- * - the fence that created a chat surface renders that surface (and the
3546
- * prose lifted out of it) in the chat wrapper;
3547
- * - every other fence renders nothing: a fence that updates the surface of
3548
- * an earlier fence, or a fence for a named target, which
3549
- * `<GenerativeUISurface id>` renders.
3550
- *
3551
- * Use it inside `<CopilotKitProvider generativeUI={{ ui, transport: "markdown" }}>`.
3552
- * `CopilotChatAssistantMessage` uses it there on its own.
3553
- *
3554
- * @example
3555
- * ```tsx
3556
- * <MarkdownSurfaces content={message.content} messageId={message.id} />
3557
- * ```
3558
- */
3559
- function MarkdownSurfaces({ content, messageId, isStreaming = false, ...markdownProps }) {
3560
- const runtime = useRequiredGenerativeUIRuntime();
3561
- const chatThreadId = useCopilotChatConfiguration()?.threadId;
3562
- useManagerVersion(runtime);
3563
- const segments = useMemo(() => splitA2UIMarkdown(content), [content]);
3564
- const threadId = chatThreadId ?? runtime.manager.getActiveThread();
3565
- const source = getMarkdownSurfaceSource(runtime);
3566
- return /* @__PURE__ */ jsx(Fragment$1, { children: segments.map((segment, index) => {
3567
- const isLast = index === segments.length - 1;
3568
- if (segment.type === "markdown") return /* @__PURE__ */ jsx(ProviderMarkdown, {
3569
- ...markdownProps,
3570
- content: segment.text,
3571
- isStreaming: isStreaming && isLast
3572
- }, `md-${index}`);
3573
- const blocks = threadId ? source.getFenceBlocks(threadId, messageId, segment.index) : void 0;
3574
- if (!threadId || !blocks) return null;
3575
- return /* @__PURE__ */ jsx(FenceBlocks, {
3576
- blocks,
3577
- runtime,
3578
- threadId,
3579
- isStreaming: isStreaming && isLast,
3580
- markdownProps
3581
- }, `a2ui-${segment.index}`);
3582
- }) });
3583
- }
3584
-
3585
- //#endregion
3586
- export { ExpressionError as A, renderSlot as B, issueKey as C, getMarkdownSurfaceSource as D, containsDynamicValue as E, toJsonSchema as F, CopilotIcon as G, CopilotChatConfigurationProvider as H, defineToolCallRenderer as I, StreamingMarkdownDefaultRenderer as J, IconSvg as K, MarkdownRendererProvider as L, catalogIdsOf as M, componentCatalogIds as N, isRecord as O, createGenerativeUI as P, useMarkdownRenderer as R, isAsyncIssue as S, withoutRejectedNulls as T, useCopilotChatConfiguration as U, ControlledModalOpenScope as V, useShallowStableRef as W, GenerativeUINodeContext as _, GenerativeUIToolCallRenderer as a, useRequiredGenerativeUIRuntime as b, SurfaceView as c, namedRole as d, useGenerativeUIAccessibility as f, useManagerVersion as g, useGenerativeUIState as h, GenerativeUIChatSlotContext as i, GenerativeUIError as j, BASIC_FUNCTIONS as k, DARK_THEME_CSS as l, useGenerativeUIFunction as m, ProviderMarkdown as n, createGenerativeUIActivityRenderer as o, wrapperAria as p, cn as q, DefaultGenerativeUIChatCard as r, createGenerativeUIFunctionCallActivityRenderer as s, MarkdownSurfaces as t, controlAria as u, GenerativeUIRuntimeContext as v, validateSchemaSync as w, formatIssues as x, useGenerativeUIRuntime as y, isReactComponentType as z };
3587
- //# sourceMappingURL=MarkdownSurfaces-DQbRS91-.mjs.map