@copilotkit/shared 2.0.0-rc.3 → 2.0.0-rc.31

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 (287) hide show
  1. package/README.md +3 -14
  2. package/dist/a2ui-envelope.cjs +2 -2
  3. package/dist/a2ui-envelope.cjs.map +1 -1
  4. package/dist/a2ui-envelope.d.cts +1 -1
  5. package/dist/a2ui-envelope.d.cts.map +1 -1
  6. package/dist/a2ui-envelope.d.mts +1 -1
  7. package/dist/a2ui-envelope.d.mts.map +1 -1
  8. package/dist/a2ui-envelope.mjs +2 -2
  9. package/dist/a2ui-envelope.mjs.map +1 -1
  10. package/dist/a2ui-prompts.cjs +21 -62
  11. package/dist/a2ui-prompts.cjs.map +1 -1
  12. package/dist/a2ui-prompts.d.cts +8 -1
  13. package/dist/a2ui-prompts.d.cts.map +1 -1
  14. package/dist/a2ui-prompts.d.mts +8 -1
  15. package/dist/a2ui-prompts.d.mts.map +1 -1
  16. package/dist/a2ui-prompts.mjs +22 -62
  17. package/dist/a2ui-prompts.mjs.map +1 -1
  18. package/dist/attachments/types.d.cts +1 -3
  19. package/dist/attachments/types.d.cts.map +1 -1
  20. package/dist/attachments/types.d.mts +1 -3
  21. package/dist/attachments/types.d.mts.map +1 -1
  22. package/dist/attachments/utils.cjs +16 -5
  23. package/dist/attachments/utils.cjs.map +1 -1
  24. package/dist/attachments/utils.d.cts +3 -1
  25. package/dist/attachments/utils.d.cts.map +1 -1
  26. package/dist/attachments/utils.d.mts +3 -1
  27. package/dist/attachments/utils.d.mts.map +1 -1
  28. package/dist/attachments/utils.mjs +16 -5
  29. package/dist/attachments/utils.mjs.map +1 -1
  30. package/dist/finalize-events.cjs +16 -0
  31. package/dist/finalize-events.cjs.map +1 -1
  32. package/dist/finalize-events.d.cts.map +1 -1
  33. package/dist/finalize-events.d.mts.map +1 -1
  34. package/dist/finalize-events.mjs +16 -0
  35. package/dist/finalize-events.mjs.map +1 -1
  36. package/dist/generative-ui/basic-functions.cjs +1 -1
  37. package/dist/generative-ui/basic-functions.cjs.map +1 -1
  38. package/dist/generative-ui/basic-functions.mjs +1 -1
  39. package/dist/generative-ui/basic-functions.mjs.map +1 -1
  40. package/dist/generative-ui/child-refs.cjs +3 -3
  41. package/dist/generative-ui/child-refs.cjs.map +1 -1
  42. package/dist/generative-ui/child-refs.d.cts.map +1 -1
  43. package/dist/generative-ui/child-refs.d.mts.map +1 -1
  44. package/dist/generative-ui/child-refs.mjs +3 -3
  45. package/dist/generative-ui/child-refs.mjs.map +1 -1
  46. package/dist/generative-ui/compact-schema.cjs +187 -0
  47. package/dist/generative-ui/compact-schema.cjs.map +1 -0
  48. package/dist/generative-ui/compact-schema.d.cts +55 -0
  49. package/dist/generative-ui/compact-schema.d.cts.map +1 -0
  50. package/dist/generative-ui/compact-schema.d.mts +55 -0
  51. package/dist/generative-ui/compact-schema.d.mts.map +1 -0
  52. package/dist/generative-ui/compact-schema.mjs +185 -0
  53. package/dist/generative-ui/compact-schema.mjs.map +1 -0
  54. package/dist/generative-ui/prompt-spec.cjs +225 -0
  55. package/dist/generative-ui/prompt-spec.cjs.map +1 -0
  56. package/dist/generative-ui/prompt-spec.d.cts +94 -0
  57. package/dist/generative-ui/prompt-spec.d.cts.map +1 -0
  58. package/dist/generative-ui/prompt-spec.d.mts +94 -0
  59. package/dist/generative-ui/prompt-spec.d.mts.map +1 -0
  60. package/dist/generative-ui/prompt-spec.mjs +220 -0
  61. package/dist/generative-ui/prompt-spec.mjs.map +1 -0
  62. package/dist/generative-ui/prompt.cjs +10 -36
  63. package/dist/generative-ui/prompt.cjs.map +1 -1
  64. package/dist/generative-ui/prompt.d.cts +2 -1
  65. package/dist/generative-ui/prompt.d.cts.map +1 -1
  66. package/dist/generative-ui/prompt.d.mts +2 -1
  67. package/dist/generative-ui/prompt.d.mts.map +1 -1
  68. package/dist/generative-ui/prompt.mjs +12 -38
  69. package/dist/generative-ui/prompt.mjs.map +1 -1
  70. package/dist/generative-ui/render-ui-args.cjs +1 -0
  71. package/dist/generative-ui/render-ui-args.cjs.map +1 -1
  72. package/dist/generative-ui/render-ui-args.d.cts.map +1 -1
  73. package/dist/generative-ui/render-ui-args.d.mts.map +1 -1
  74. package/dist/generative-ui/render-ui-args.mjs +1 -0
  75. package/dist/generative-ui/render-ui-args.mjs.map +1 -1
  76. package/dist/generative-ui/schema-render.cjs +242 -0
  77. package/dist/generative-ui/schema-render.cjs.map +1 -0
  78. package/dist/generative-ui/schema-render.d.cts +44 -0
  79. package/dist/generative-ui/schema-render.d.cts.map +1 -0
  80. package/dist/generative-ui/schema-render.d.mts +44 -0
  81. package/dist/generative-ui/schema-render.d.mts.map +1 -0
  82. package/dist/generative-ui/schema-render.mjs +239 -0
  83. package/dist/generative-ui/schema-render.mjs.map +1 -0
  84. package/dist/generative-ui/types.cjs +2 -2
  85. package/dist/generative-ui/types.cjs.map +1 -1
  86. package/dist/generative-ui/types.d.cts +7 -7
  87. package/dist/generative-ui/types.d.cts.map +1 -1
  88. package/dist/generative-ui/types.d.mts +7 -7
  89. package/dist/generative-ui/types.d.mts.map +1 -1
  90. package/dist/generative-ui/types.mjs +2 -2
  91. package/dist/generative-ui/types.mjs.map +1 -1
  92. package/dist/generative-ui/validate-operation.cjs +2 -2
  93. package/dist/generative-ui/validate-operation.cjs.map +1 -1
  94. package/dist/generative-ui/validate-operation.mjs +2 -2
  95. package/dist/generative-ui/validate-operation.mjs.map +1 -1
  96. package/dist/index.cjs +16 -15
  97. package/dist/index.cjs.map +1 -1
  98. package/dist/index.d.cts +10 -10
  99. package/dist/index.d.cts.map +1 -1
  100. package/dist/index.d.mts +10 -10
  101. package/dist/index.d.mts.map +1 -1
  102. package/dist/index.mjs +9 -8
  103. package/dist/index.mjs.map +1 -1
  104. package/dist/index.umd.js +866 -455
  105. package/dist/index.umd.js.map +1 -1
  106. package/dist/package.cjs +1 -1
  107. package/dist/package.mjs +1 -1
  108. package/dist/standard-schema.cjs +20 -7
  109. package/dist/standard-schema.cjs.map +1 -1
  110. package/dist/standard-schema.d.cts +15 -16
  111. package/dist/standard-schema.d.cts.map +1 -1
  112. package/dist/standard-schema.d.mts +15 -16
  113. package/dist/standard-schema.d.mts.map +1 -1
  114. package/dist/standard-schema.mjs +20 -8
  115. package/dist/standard-schema.mjs.map +1 -1
  116. package/dist/telemetry/lambda-client.cjs +1 -1
  117. package/dist/telemetry/lambda-client.cjs.map +1 -1
  118. package/dist/telemetry/lambda-client.d.cts.map +1 -1
  119. package/dist/telemetry/lambda-client.d.mts.map +1 -1
  120. package/dist/telemetry/lambda-client.mjs +1 -1
  121. package/dist/telemetry/lambda-client.mjs.map +1 -1
  122. package/dist/telemetry/telemetry-disabled.cjs +0 -5
  123. package/dist/telemetry/telemetry-disabled.cjs.map +1 -1
  124. package/dist/telemetry/telemetry-disabled.d.cts +0 -5
  125. package/dist/telemetry/telemetry-disabled.d.cts.map +1 -1
  126. package/dist/telemetry/telemetry-disabled.d.mts +0 -5
  127. package/dist/telemetry/telemetry-disabled.d.mts.map +1 -1
  128. package/dist/telemetry/telemetry-disabled.mjs +0 -5
  129. package/dist/telemetry/telemetry-disabled.mjs.map +1 -1
  130. package/dist/types/message.d.cts +1 -18
  131. package/dist/types/message.d.cts.map +1 -1
  132. package/dist/types/message.d.mts +1 -18
  133. package/dist/types/message.d.mts.map +1 -1
  134. package/dist/utils/errors.cjs +5 -42
  135. package/dist/utils/errors.cjs.map +1 -1
  136. package/dist/utils/errors.d.cts +16 -34
  137. package/dist/utils/errors.d.cts.map +1 -1
  138. package/dist/utils/errors.d.mts +16 -34
  139. package/dist/utils/errors.d.mts.map +1 -1
  140. package/dist/utils/errors.mjs +6 -41
  141. package/dist/utils/errors.mjs.map +1 -1
  142. package/dist/utils/index.cjs +0 -2
  143. package/dist/utils/index.cjs.map +1 -1
  144. package/dist/utils/index.d.cts +4 -6
  145. package/dist/utils/index.d.cts.map +1 -1
  146. package/dist/utils/index.d.mts +4 -6
  147. package/dist/utils/index.d.mts.map +1 -1
  148. package/dist/utils/index.mjs +4 -6
  149. package/dist/utils/index.mjs.map +1 -1
  150. package/dist/utils/inspector-visibility.cjs +25 -3
  151. package/dist/utils/inspector-visibility.cjs.map +1 -1
  152. package/dist/utils/inspector-visibility.d.cts +26 -3
  153. package/dist/utils/inspector-visibility.d.cts.map +1 -1
  154. package/dist/utils/inspector-visibility.d.mts +26 -3
  155. package/dist/utils/inspector-visibility.d.mts.map +1 -1
  156. package/dist/utils/inspector-visibility.mjs +25 -4
  157. package/dist/utils/inspector-visibility.mjs.map +1 -1
  158. package/dist/utils/json-schema.cjs +4 -79
  159. package/dist/utils/json-schema.cjs.map +1 -1
  160. package/dist/utils/json-schema.d.cts +1 -4
  161. package/dist/utils/json-schema.d.cts.map +1 -1
  162. package/dist/utils/json-schema.d.mts +1 -4
  163. package/dist/utils/json-schema.d.mts.map +1 -1
  164. package/dist/utils/json-schema.mjs +5 -78
  165. package/dist/utils/json-schema.mjs.map +1 -1
  166. package/dist/utils/random-id.cjs +13 -26
  167. package/dist/utils/random-id.cjs.map +1 -1
  168. package/dist/utils/random-id.d.cts +6 -3
  169. package/dist/utils/random-id.d.cts.map +1 -1
  170. package/dist/utils/random-id.d.mts +6 -3
  171. package/dist/utils/random-id.d.mts.map +1 -1
  172. package/dist/utils/random-id.mjs +14 -25
  173. package/dist/utils/random-id.mjs.map +1 -1
  174. package/package.json +10 -34
  175. package/scripts/verify-cjs-exports.cjs +1 -1
  176. package/src/__tests__/a2ui-envelope.test.ts +18 -13
  177. package/src/__tests__/a2ui-prompts.test.ts +47 -14
  178. package/src/__tests__/fixtures/prompt-goldens.json +354 -0
  179. package/src/__tests__/prompt-spec.test.ts +191 -0
  180. package/src/__tests__/root-entry-browser-safety.test.ts +5 -7
  181. package/src/__tests__/schema-render.test.ts +245 -0
  182. package/src/__tests__/standard-schema.test.ts +61 -101
  183. package/src/a2ui-envelope.ts +7 -6
  184. package/src/a2ui-prompts.ts +47 -96
  185. package/src/attachments/__tests__/utils.test.ts +22 -0
  186. package/src/attachments/types.ts +1 -3
  187. package/src/attachments/utils.ts +23 -5
  188. package/src/finalize-events.ts +16 -0
  189. package/src/generative-ui/__tests__/render-ui-args.test.ts +7 -7
  190. package/src/generative-ui/__tests__/validate-operation.test.ts +19 -13
  191. package/src/generative-ui/basic-functions.ts +1 -1
  192. package/src/generative-ui/child-refs.ts +5 -4
  193. package/src/generative-ui/compact-schema.ts +277 -0
  194. package/src/generative-ui/index.ts +3 -0
  195. package/src/generative-ui/prompt-spec.ts +335 -0
  196. package/src/generative-ui/prompt.ts +25 -75
  197. package/src/generative-ui/render-ui-args.ts +3 -0
  198. package/src/generative-ui/schema-render.ts +377 -0
  199. package/src/generative-ui/types.ts +10 -7
  200. package/src/generative-ui/validate-operation.ts +2 -2
  201. package/src/index.ts +3 -16
  202. package/src/standard-schema.ts +24 -27
  203. package/src/telemetry/lambda-client.ts +8 -3
  204. package/src/telemetry/model-host.test.ts +2 -5
  205. package/src/telemetry/telemetry-disabled.ts +0 -5
  206. package/src/types/message.ts +1 -19
  207. package/src/utils/__tests__/errors.test.ts +44 -0
  208. package/src/utils/__tests__/json-schema.test.ts +3 -479
  209. package/src/utils/__tests__/random-id.test.ts +37 -0
  210. package/src/utils/errors.ts +28 -85
  211. package/src/utils/index.ts +0 -2
  212. package/src/utils/inspector-visibility.test.ts +26 -0
  213. package/src/utils/inspector-visibility.ts +35 -3
  214. package/src/utils/json-schema.ts +5 -152
  215. package/src/utils/random-id.ts +17 -37
  216. package/tsconfig.json +3 -1
  217. package/tsdown.config.ts +2 -19
  218. package/dist/event-transforms/index.cjs +0 -15
  219. package/dist/event-transforms/index.d.cts +0 -4
  220. package/dist/event-transforms/index.d.mts +0 -4
  221. package/dist/event-transforms/index.mjs +0 -5
  222. package/dist/event-transforms/open-generative-ui-middleware.cjs +0 -286
  223. package/dist/event-transforms/open-generative-ui-middleware.cjs.map +0 -1
  224. package/dist/event-transforms/open-generative-ui-middleware.d.cts +0 -60
  225. package/dist/event-transforms/open-generative-ui-middleware.d.cts.map +0 -1
  226. package/dist/event-transforms/open-generative-ui-middleware.d.mts +0 -60
  227. package/dist/event-transforms/open-generative-ui-middleware.d.mts.map +0 -1
  228. package/dist/event-transforms/open-generative-ui-middleware.mjs +0 -283
  229. package/dist/event-transforms/open-generative-ui-middleware.mjs.map +0 -1
  230. package/dist/event-transforms/recorded-events.cjs +0 -59
  231. package/dist/event-transforms/recorded-events.cjs.map +0 -1
  232. package/dist/event-transforms/recorded-events.d.cts +0 -23
  233. package/dist/event-transforms/recorded-events.d.cts.map +0 -1
  234. package/dist/event-transforms/recorded-events.d.mts +0 -23
  235. package/dist/event-transforms/recorded-events.d.mts.map +0 -1
  236. package/dist/event-transforms/recorded-events.mjs +0 -58
  237. package/dist/event-transforms/recorded-events.mjs.map +0 -1
  238. package/dist/telemetry/events.d.cts +0 -72
  239. package/dist/telemetry/events.d.cts.map +0 -1
  240. package/dist/telemetry/events.d.mts +0 -72
  241. package/dist/telemetry/events.d.mts.map +0 -1
  242. package/dist/telemetry/index.cjs +0 -18
  243. package/dist/telemetry/index.d.cts +0 -5
  244. package/dist/telemetry/index.d.mts +0 -5
  245. package/dist/telemetry/index.mjs +0 -6
  246. package/dist/telemetry/telemetry-client.cjs +0 -165
  247. package/dist/telemetry/telemetry-client.cjs.map +0 -1
  248. package/dist/telemetry/telemetry-client.d.cts +0 -87
  249. package/dist/telemetry/telemetry-client.d.cts.map +0 -1
  250. package/dist/telemetry/telemetry-client.d.mts +0 -87
  251. package/dist/telemetry/telemetry-client.d.mts.map +0 -1
  252. package/dist/telemetry/telemetry-client.mjs +0 -164
  253. package/dist/telemetry/telemetry-client.mjs.map +0 -1
  254. package/dist/telemetry/utils.cjs +0 -14
  255. package/dist/telemetry/utils.cjs.map +0 -1
  256. package/dist/telemetry/utils.mjs +0 -13
  257. package/dist/telemetry/utils.mjs.map +0 -1
  258. package/dist/utils/conditions.cjs +0 -32
  259. package/dist/utils/conditions.cjs.map +0 -1
  260. package/dist/utils/conditions.d.cts +0 -31
  261. package/dist/utils/conditions.d.cts.map +0 -1
  262. package/dist/utils/conditions.d.mts +0 -31
  263. package/dist/utils/conditions.d.mts.map +0 -1
  264. package/dist/utils/conditions.mjs +0 -31
  265. package/dist/utils/conditions.mjs.map +0 -1
  266. package/dist/utils/console-styling.cjs +0 -91
  267. package/dist/utils/console-styling.cjs.map +0 -1
  268. package/dist/utils/console-styling.d.cts +0 -65
  269. package/dist/utils/console-styling.d.cts.map +0 -1
  270. package/dist/utils/console-styling.d.mts +0 -65
  271. package/dist/utils/console-styling.d.mts.map +0 -1
  272. package/dist/utils/console-styling.mjs +0 -85
  273. package/dist/utils/console-styling.mjs.map +0 -1
  274. package/src/__tests__/zod-regression.test.ts +0 -319
  275. package/src/event-transforms/index.ts +0 -5
  276. package/src/event-transforms/open-generative-ui-middleware.ts +0 -392
  277. package/src/event-transforms/recorded-events.test.ts +0 -166
  278. package/src/event-transforms/recorded-events.ts +0 -74
  279. package/src/telemetry/events.ts +0 -68
  280. package/src/telemetry/index.ts +0 -9
  281. package/src/telemetry/telemetry-blank-license-identity.test.ts +0 -128
  282. package/src/telemetry/telemetry-client.test.ts +0 -798
  283. package/src/telemetry/telemetry-client.ts +0 -328
  284. package/src/telemetry/utils.ts +0 -15
  285. package/src/utils/__tests__/conditions.test.ts +0 -161
  286. package/src/utils/conditions.ts +0 -116
  287. package/src/utils/console-styling.ts +0 -126
@@ -1 +1 @@
1
- {"version":3,"file":"finalize-events.mjs","names":[],"sources":["../src/finalize-events.ts"],"sourcesContent":["import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\nexport interface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n /**\n * The `protocolVersion` the client declared on its RunAgentInput. When it is\n * set, a stopped run finishes with the AG-UI 1.0 `cancelled` outcome. A\n * client that declares no version predates 1.0 and cannot parse that\n * outcome, so it gets the plain RUN_FINISHED it always got.\n */\n protocolVersion?: string;\n}\n\nexport interface RunEventFinalizer {\n /** Observe one streamed event. Only the ids of open lifecycles are kept. */\n observe(event: BaseEvent): void;\n /** Return the events that close an interrupted or abruptly ended stream. */\n finalize(options?: FinalizeRunOptions): BaseEvent[];\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\ninterface OpenToolCall {\n hasEnd: boolean;\n hasResult: boolean;\n}\n\n/**\n * Incremental finalizer for a streamed AG-UI run. Feed every event to\n * `observe`; when the stream ends without a terminal event, `finalize` returns\n * the closers for reasoning, text messages and tool calls still open plus a\n * terminal event. AG-UI 1.0 fails a run that ends with reasoning still open,\n * so reasoning is closed too. It also fails a RUN_FINISHED while a subagent\n * is still open, so a stop closes open subagents as well; a RUN_ERROR\n * abandons them, which the protocol allows. Closed lifecycles are forgotten at once and payloads are never kept,\n * so a caller does not have to retain the event array for this purpose.\n */\nexport function createRunEventFinalizer(): RunEventFinalizer {\n const openMessageIds = new Set<string>();\n const openReasoningMessageIds = new Set<string>();\n const openReasoningSpanIds = new Set<string>();\n const openToolCalls = new Map<string, OpenToolCall>();\n // Insertion order is start order, so closing in reverse closes children first.\n const openSubagentRunIds = new Set<string>();\n let runIdentity: { threadId?: string; runId?: string } = {};\n let terminalEventObserved = false;\n\n const clearOpen = () => {\n openMessageIds.clear();\n openReasoningMessageIds.clear();\n openReasoningSpanIds.clear();\n openToolCalls.clear();\n openSubagentRunIds.clear();\n };\n\n const observe = (event: BaseEvent) => {\n if (terminalEventObserved) return;\n\n switch (event.type) {\n case EventType.RUN_STARTED: {\n const { threadId, runId } = event as {\n threadId?: string;\n runId?: string;\n };\n runIdentity = { threadId, runId };\n break;\n }\n case EventType.REASONING_START:\n case EventType.REASONING_END:\n case EventType.REASONING_MESSAGE_START:\n case EventType.REASONING_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId !== \"string\") break;\n const open =\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_END\n ? openReasoningSpanIds\n : openReasoningMessageIds;\n if (\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_MESSAGE_START\n ) {\n open.add(messageId);\n } else {\n open.delete(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (messageId) openMessageIds.add(messageId);\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") openMessageIds.delete(messageId);\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (toolCallId && !openToolCalls.has(toolCallId)) {\n openToolCalls.set(toolCallId, { hasEnd: false, hasResult: false });\n }\n break;\n }\n case EventType.TOOL_CALL_END:\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (!toolCallId) break;\n const info = openToolCalls.get(toolCallId);\n if (!info) break;\n\n if (event.type === EventType.TOOL_CALL_END) info.hasEnd = true;\n else info.hasResult = true;\n if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);\n break;\n }\n case EventType.SUBAGENT_STARTED:\n case EventType.SUBAGENT_FINISHED:\n case EventType.SUBAGENT_ERROR: {\n const subagentRunId = (event as { subagentRunId?: string })\n .subagentRunId;\n if (!subagentRunId) break;\n if (event.type === EventType.SUBAGENT_STARTED) {\n openSubagentRunIds.add(subagentRunId);\n } else {\n openSubagentRunIds.delete(subagentRunId);\n }\n break;\n }\n case EventType.RUN_FINISHED:\n case EventType.RUN_ERROR:\n terminalEventObserved = true;\n clearOpen();\n break;\n default:\n break;\n }\n };\n\n const finalize = (options: FinalizeRunOptions = {}): BaseEvent[] => {\n if (terminalEventObserved) return [];\n\n const { stopRequested = false, interruptionMessage } = options;\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n const appended: BaseEvent[] = [];\n\n // A reasoning message closes before the span that holds it.\n for (const messageId of openReasoningMessageIds) {\n appended.push({\n type: EventType.REASONING_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n for (const messageId of openReasoningSpanIds) {\n appended.push({ type: EventType.REASONING_END, messageId } as BaseEvent);\n }\n\n for (const messageId of openMessageIds) {\n appended.push({\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n appended.push({\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent);\n }\n\n if (!info.hasResult) {\n appended.push({\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent);\n }\n }\n\n if (stopRequested) {\n // Newest first, so a nested subagent closes before its parent. An index\n // loop, because `toReversed` is ES2023 and this package targets older.\n const openIds = [...openSubagentRunIds];\n for (let index = openIds.length - 1; index >= 0; index -= 1) {\n appended.push({\n type: EventType.SUBAGENT_ERROR,\n subagentRunId: openIds[index],\n message: resolvedStopMessage,\n code: \"CANCELLED\",\n } as BaseEvent);\n }\n appended.push({\n type: EventType.RUN_FINISHED,\n ...(runIdentity.threadId !== undefined\n ? { threadId: runIdentity.threadId }\n : {}),\n ...(runIdentity.runId !== undefined\n ? { runId: runIdentity.runId }\n : {}),\n ...(options.protocolVersion !== undefined\n ? { outcome: { type: \"cancelled\" } }\n : {}),\n } as BaseEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n appended.push(errorEvent);\n }\n\n terminalEventObserved = true;\n clearOpen();\n return appended;\n };\n\n return { observe, finalize };\n}\n\n/**\n * Array form of {@link createRunEventFinalizer} for callers that already keep\n * the run's events (runners persist them). Appends the closers to `events` in\n * place and returns them.\n */\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const finalizer = createRunEventFinalizer();\n for (const event of events) finalizer.observe(event);\n\n const appended = finalizer.finalize(options);\n events.push(...appended);\n return appended;\n}\n"],"mappings":";;;AAsBA,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;;;;;;;;;;;AAiBhC,SAAgB,0BAA6C;CAC3D,MAAM,iCAAiB,IAAI,KAAa;CACxC,MAAM,0CAA0B,IAAI,KAAa;CACjD,MAAM,uCAAuB,IAAI,KAAa;CAC9C,MAAM,gCAAgB,IAAI,KAA2B;CAErD,MAAM,qCAAqB,IAAI,KAAa;CAC5C,IAAI,cAAqD,EAAE;CAC3D,IAAI,wBAAwB;CAE5B,MAAM,kBAAkB;AACtB,iBAAe,OAAO;AACtB,0BAAwB,OAAO;AAC/B,uBAAqB,OAAO;AAC5B,gBAAc,OAAO;AACrB,qBAAmB,OAAO;;CAG5B,MAAM,WAAW,UAAqB;AACpC,MAAI,sBAAuB;AAE3B,UAAQ,MAAM,MAAd;GACE,KAAK,UAAU,aAAa;IAC1B,MAAM,EAAE,UAAU,UAAU;AAI5B,kBAAc;KAAE;KAAU;KAAO;AACjC;;GAEF,KAAK,UAAU;GACf,KAAK,UAAU;GACf,KAAK,UAAU;GACf,KAAK,UAAU,uBAAuB;IACpC,MAAM,YAAa,MAAiC;AACpD,QAAI,OAAO,cAAc,SAAU;IACnC,MAAM,OACJ,MAAM,SAAS,UAAU,mBACzB,MAAM,SAAS,UAAU,gBACrB,uBACA;AACN,QACE,MAAM,SAAS,UAAU,mBACzB,MAAM,SAAS,UAAU,wBAEzB,MAAK,IAAI,UAAU;QAEnB,MAAK,OAAO,UAAU;AAExB;;GAEF,KAAK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SAAS,OAAQ,WAAU,QAAQ,MAAM;CAEpD,MAAM,WAAW,UAAU,SAAS,QAAQ;AAC5C,QAAO,KAAK,GAAG,SAAS;AACxB,QAAO"}
1
+ {"version":3,"file":"finalize-events.mjs","names":[],"sources":["../src/finalize-events.ts"],"sourcesContent":["import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\nexport interface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n /**\n * The `protocolVersion` the client declared on its RunAgentInput. When it is\n * set, a stopped run finishes with the AG-UI 1.0 `cancelled` outcome. A\n * client that declares no version predates 1.0 and cannot parse that\n * outcome, so it gets the plain RUN_FINISHED it always got.\n */\n protocolVersion?: string;\n}\n\nexport interface RunEventFinalizer {\n /** Observe one streamed event. Only the ids of open lifecycles are kept. */\n observe(event: BaseEvent): void;\n /** Return the events that close an interrupted or abruptly ended stream. */\n finalize(options?: FinalizeRunOptions): BaseEvent[];\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\ninterface OpenToolCall {\n hasEnd: boolean;\n hasResult: boolean;\n}\n\n/**\n * Incremental finalizer for a streamed AG-UI run. Feed every event to\n * `observe`; when the stream ends without a terminal event, `finalize` returns\n * the closers for reasoning, text messages and tool calls still open plus a\n * terminal event. AG-UI 1.0 fails a run that ends with reasoning still open,\n * so reasoning is closed too. It also fails a RUN_FINISHED while a subagent\n * is still open, so a stop closes open subagents as well; a RUN_ERROR\n * abandons them, which the protocol allows. Closed lifecycles are forgotten at once and payloads are never kept,\n * so a caller does not have to retain the event array for this purpose.\n */\nexport function createRunEventFinalizer(): RunEventFinalizer {\n const openMessageIds = new Set<string>();\n const openReasoningMessageIds = new Set<string>();\n const openReasoningSpanIds = new Set<string>();\n const openToolCalls = new Map<string, OpenToolCall>();\n // Insertion order is start order, so closing in reverse closes children first.\n const openSubagentRunIds = new Set<string>();\n let runIdentity: { threadId?: string; runId?: string } = {};\n let terminalEventObserved = false;\n\n const clearOpen = () => {\n openMessageIds.clear();\n openReasoningMessageIds.clear();\n openReasoningSpanIds.clear();\n openToolCalls.clear();\n openSubagentRunIds.clear();\n };\n\n const observe = (event: BaseEvent) => {\n if (terminalEventObserved) return;\n\n switch (event.type) {\n case EventType.RUN_STARTED: {\n const { threadId, runId } = event as {\n threadId?: string;\n runId?: string;\n };\n runIdentity = { threadId, runId };\n break;\n }\n case EventType.REASONING_START:\n case EventType.REASONING_END:\n case EventType.REASONING_MESSAGE_START:\n case EventType.REASONING_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId !== \"string\") break;\n const open =\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_END\n ? openReasoningSpanIds\n : openReasoningMessageIds;\n if (\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_MESSAGE_START\n ) {\n open.add(messageId);\n } else {\n open.delete(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (messageId) openMessageIds.add(messageId);\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") openMessageIds.delete(messageId);\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (toolCallId && !openToolCalls.has(toolCallId)) {\n openToolCalls.set(toolCallId, { hasEnd: false, hasResult: false });\n }\n break;\n }\n case EventType.TOOL_CALL_END:\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (!toolCallId) break;\n const info = openToolCalls.get(toolCallId);\n if (!info) break;\n\n if (event.type === EventType.TOOL_CALL_END) info.hasEnd = true;\n else info.hasResult = true;\n if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);\n break;\n }\n case EventType.SUBAGENT_STARTED:\n case EventType.SUBAGENT_FINISHED:\n case EventType.SUBAGENT_ERROR: {\n const subagentRunId = (event as { subagentRunId?: string })\n .subagentRunId;\n if (!subagentRunId) break;\n if (event.type === EventType.SUBAGENT_STARTED) {\n openSubagentRunIds.add(subagentRunId);\n } else {\n openSubagentRunIds.delete(subagentRunId);\n }\n break;\n }\n case EventType.RUN_FINISHED:\n case EventType.RUN_ERROR:\n terminalEventObserved = true;\n clearOpen();\n break;\n case EventType.TEXT_MESSAGE_CONTENT:\n case EventType.TEXT_MESSAGE_CHUNK:\n case EventType.TOOL_CALL_ARGS:\n case EventType.TOOL_CALL_CHUNK:\n case EventType.STATE_SNAPSHOT:\n case EventType.STATE_DELTA:\n case EventType.MESSAGES_SNAPSHOT:\n case EventType.ACTIVITY_SNAPSHOT:\n case EventType.ACTIVITY_DELTA:\n case EventType.RAW:\n case EventType.CUSTOM:\n case EventType.STEP_STARTED:\n case EventType.STEP_FINISHED:\n case EventType.REASONING_MESSAGE_CONTENT:\n case EventType.REASONING_MESSAGE_CHUNK:\n case EventType.REASONING_ENCRYPTED_VALUE:\n default:\n break;\n }\n };\n\n const finalize = (options: FinalizeRunOptions = {}): BaseEvent[] => {\n if (terminalEventObserved) return [];\n\n const { stopRequested = false, interruptionMessage } = options;\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n const appended: BaseEvent[] = [];\n\n // A reasoning message closes before the span that holds it.\n for (const messageId of openReasoningMessageIds) {\n appended.push({\n type: EventType.REASONING_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n for (const messageId of openReasoningSpanIds) {\n appended.push({ type: EventType.REASONING_END, messageId } as BaseEvent);\n }\n\n for (const messageId of openMessageIds) {\n appended.push({\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n appended.push({\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent);\n }\n\n if (!info.hasResult) {\n appended.push({\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent);\n }\n }\n\n if (stopRequested) {\n // Newest first, so a nested subagent closes before its parent. An index\n // loop, because `toReversed` is ES2023 and this package targets older.\n const openIds = [...openSubagentRunIds];\n for (let index = openIds.length - 1; index >= 0; index -= 1) {\n appended.push({\n type: EventType.SUBAGENT_ERROR,\n subagentRunId: openIds[index],\n message: resolvedStopMessage,\n code: \"CANCELLED\",\n } as BaseEvent);\n }\n appended.push({\n type: EventType.RUN_FINISHED,\n ...(runIdentity.threadId !== undefined\n ? { threadId: runIdentity.threadId }\n : {}),\n ...(runIdentity.runId !== undefined\n ? { runId: runIdentity.runId }\n : {}),\n ...(options.protocolVersion !== undefined\n ? { outcome: { type: \"cancelled\" } }\n : {}),\n } as BaseEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n appended.push(errorEvent);\n }\n\n terminalEventObserved = true;\n clearOpen();\n return appended;\n };\n\n return { observe, finalize };\n}\n\n/**\n * Array form of {@link createRunEventFinalizer} for callers that already keep\n * the run's events (runners persist them). Appends the closers to `events` in\n * place and returns them.\n */\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const finalizer = createRunEventFinalizer();\n for (const event of events) finalizer.observe(event);\n\n const appended = finalizer.finalize(options);\n events.push(...appended);\n return appended;\n}\n"],"mappings":";;;AAsBA,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;;;;;;;;;;;AAiBhC,SAAgB,0B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-123,7 +123,7 @@ const A2UI_BASIC_FUNCTIONS = rendererOnly({
123
123
  */
124
124
  const COPILOTKIT_FUNCTIONS = rendererOnly({
125
125
  calc: {
126
- description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name",
126
+ description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), x ^ y (power), comparisons, && || !, cond ? a : b, min max round floor ceil abs pow sqrt exp ln log10, the constants pi and e, 'text' + name",
127
127
  parameters: "{ expression: string; [name: string]: number | string | boolean }",
128
128
  returnType: "any",
129
129
  extension: true
@@ -1 +1 @@
1
- {"version":3,"file":"basic-functions.cjs","names":[],"sources":["../../src/generative-ui/basic-functions.ts"],"sourcesContent":["/**\n * The functions of the A2UI 1.0 basic catalog, as the model and the\n * validator see them. The renderer implements them (react-core\n * `generative-ui/functions.ts`); this file holds only what both sides share:\n * the names, the short signatures for the schema the model reads, and who\n * may call each one.\n */\n\n/** What a function gives back, as A2UI 1.0 names it. */\nexport type A2UIFunctionReturnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"array\"\n | \"object\"\n | \"validationResult\"\n | \"any\"\n | \"void\";\n\n/**\n * Who may call a function. The renderer calls it from an event binding or\n * as a prop value; the agent calls it with `callRendererFunction`.\n */\nexport type A2UIAllowedCallers =\n | \"rendererOnly\"\n | \"agentOnly\"\n | \"rendererOrAgent\";\n\n/**\n * The callers of an app function that names none: the renderer only, as\n * in A2UI 1.0. The agent calls a function with `callRendererFunction` only\n * when its declaration allows it (`\"rendererOrAgent\"` or `\"agentOnly\"`).\n * The manifests and the exported catalog write the value out.\n */\nexport const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS: A2UIAllowedCallers =\n \"rendererOnly\";\n\n/** The A2UI 1.0 interface fields of a function: who calls it, and how. */\nexport interface A2UIFunctionPermissions {\n allowedCallers?: A2UIAllowedCallers;\n /**\n * True for a function that only runs from a user gesture (a click, a key\n * press). It is `rendererOnly`: the agent cannot call it, and a prop\n * cannot be bound to it.\n */\n requiresUserActivation?: boolean;\n}\n\n/**\n * Who may call a function, from its permissions. A function that needs a\n * user gesture is for the renderer only, whatever `allowedCallers` says.\n *\n * @example\n * ```ts\n * functionCallers({}); // { renderer: true, agent: true }\n * functionCallers({ allowedCallers: \"rendererOnly\" }); // { renderer: true, agent: false }\n * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }\n * ```\n */\nexport function functionCallers(fn: A2UIFunctionPermissions) {\n if (fn.requiresUserActivation) return { renderer: true, agent: false };\n const callers = fn.allowedCallers ?? GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;\n return {\n renderer: callers !== \"agentOnly\",\n agent: callers !== \"rendererOnly\",\n };\n}\n\nexport interface A2UIBasicFunctionInfo extends A2UIFunctionPermissions {\n description: string;\n /** The args, as a short TypeScript-like type for the compact schema. */\n parameters: string;\n returnType: A2UIFunctionReturnType;\n /** Built-in functions are value functions of the renderer. */\n allowedCallers: \"rendererOnly\";\n requiresUserActivation?: true;\n /** True for a CopilotKit function that the A2UI basic catalog lacks. */\n extension?: true;\n}\n\n/** Marks a table of built-in functions as callable by the renderer only. */\nfunction rendererOnly<Name extends string>(\n functions: Record<Name, Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>,\n): Readonly<Record<Name, A2UIBasicFunctionInfo>> {\n return Object.fromEntries(\n Object.entries<Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>(\n functions,\n ).map(([name, info]) => [\n name,\n { ...info, allowedCallers: \"rendererOnly\" },\n ]),\n ) as Record<Name, A2UIBasicFunctionInfo>;\n}\n\n/**\n * The basic functions by name. A `{\"@call\"}` in a prop, in an event\n * binding, or in a `callRendererFunction` may name any of them without a\n * declaration in `createGenerativeUI({ functions })`.\n */\nexport const A2UI_BASIC_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n required: {\n description: \"Valid when the value is not empty\",\n parameters: \"{ value: unknown }\",\n returnType: \"validationResult\",\n },\n regex: {\n description: \"Valid when the value matches the pattern\",\n parameters: \"{ value: string; pattern: string }\",\n returnType: \"validationResult\",\n },\n length: {\n description: \"Valid when the length of the value is within min and max\",\n parameters: \"{ value: string; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n numeric: {\n description: \"Valid when the value is a number within min and max\",\n parameters: \"{ value: number; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n email: {\n description: \"Valid when the value is an email address\",\n parameters: \"{ value: string }\",\n returnType: \"validationResult\",\n },\n formatString: {\n description:\n \"Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\\\${ is a literal\",\n parameters: \"{ value: string }\",\n returnType: \"string\",\n },\n formatNumber: {\n description: \"The number in the locale of the user\",\n parameters: \"{ value: number; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatCurrency: {\n description: \"The amount as money, with an ISO 4217 currency code\",\n parameters:\n \"{ value: number; currency: string; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatDate: {\n description:\n 'A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"',\n parameters: \"{ value: string | number; format: string }\",\n returnType: \"string\",\n },\n pluralize: {\n description: \"The string of the plural category of the value\",\n parameters:\n \"{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }\",\n returnType: \"string\",\n },\n openUrl: {\n description: \"Opens an http(s) URL in a new tab. Only from an event\",\n parameters: \"{ url: string }\",\n returnType: \"void\",\n requiresUserActivation: true,\n },\n and: {\n description: \"True when every value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n or: {\n description: \"True when any value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n not: {\n description: \"The negated value\",\n parameters: \"{ value: boolean }\",\n returnType: \"boolean\",\n },\n});\n\n/**\n * The value functions that CopilotKit adds to the basic catalog, because\n * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named\n * args, and `series` builds a computed list. A catalog may declare its own\n * functions in A2UI, so these are regular catalog functions to the model;\n * a renderer without them rejects the call instead of misrendering.\n */\nexport const COPILOTKIT_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n calc: {\n description:\n \"The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name\",\n parameters:\n \"{ expression: string; [name: string]: number | string | boolean }\",\n returnType: \"any\",\n extension: true,\n },\n // WORKAROUND(a2ui-agent-sdk 0.9.0): examples omit `variable` and use default i\n // because the Express compiler mistakes a literal `variable` key for its AST.\n // Runtime support for custom variable names is unchanged.\n // https://github.com/a2ui-project/a2ui/issues/3410\n series: {\n description:\n 'A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.',\n parameters:\n \"{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }\",\n returnType: \"array\",\n extension: true,\n },\n});\n\n/** Every function a `{\"@call\"}` may name without a declaration: basic and CopilotKit. */\nexport const GENERATIVE_UI_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = { ...A2UI_BASIC_FUNCTIONS, ...COPILOTKIT_FUNCTIONS };\n\n/** The name of the system function that gives the index of a template item. */\nexport const A2UI_INDEX_FUNCTION = \"@index\";\n\n/** True for a built-in function name: basic, CopilotKit, or `@index`. */\nexport function isA2UIBasicFunction(name: string) {\n return (\n name === A2UI_INDEX_FUNCTION ||\n Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name)\n );\n}\n\n/**\n * True for a built-in function that a prop or a check may call: every one\n * except the functions that need a user gesture.\n */\nexport function isA2UIValueFunction(name: string) {\n if (name === A2UI_INDEX_FUNCTION) return true;\n const info = Object.prototype.hasOwnProperty.call(\n GENERATIVE_UI_FUNCTIONS,\n name,\n )\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n return info !== undefined && !info.requiresUserActivation;\n}\n\n/** `{ \"@call\": \"<name>\", \"args\"?: {...} }`: a function call value. */\nexport function isCallBinding(\n value: unknown,\n): value is { \"@call\": string; args?: Record<string, unknown> } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>)[\"@call\"] === \"string\"\n );\n}\n\n/** How bad a failed check is. `error` is the default; only an error blocks. */\nexport type A2UIValidationSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A2UI's `ValidationResult`: what a check gives. A validator function gives\n * one; a check may also bind a boolean, which the renderer coerces to one.\n * `code` names the failure for programs; `severity` says how bad it is,\n * `\"error\"` when left out. Other keys are allowed, for app validators that\n * carry more (a suggested value, a field path).\n */\nexport interface A2UIValidationResult {\n valid: boolean;\n message?: string;\n code?: string;\n severity?: A2UIValidationSeverity;\n [extra: string]: unknown;\n}\n\nexport function isValidationResult(\n value: unknown,\n): value is A2UIValidationResult {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>).valid === \"boolean\"\n );\n}\n"],"mappings":";;;;;;;;AAkCA,MAAa,wCACX;;;;;;;;;;;;AAwBF,SAAgB,gBAAgB,IAA6B;AAC3D,KAAI,GAAG,uBAAwB,QAAO;EAAE,UAAU;EAAM,OAAO;EAAO;CACtE,MAAM,UAAU,GAAG,kBAAkB;AACrC,QAAO;EACL,UAAU,YAAY;EACtB,OAAO,YAAY;EACpB;;;AAgBH,SAAS,aACP,WAC+C;AAC/C,QAAO,OAAO,YACZ,OAAO,QACL,UACD,CAAC,KAAK,CAAC,MAAM,UAAU,CACtB,MAC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e,KAC3C,yBACA,KACD,GACG,wBAAwB,QACxB;AACJ,QAAO,SAAS,UAAa,CAAC,KAAK;;;AAIrC,SAAgB,cACd,OAC8D;AAC9D,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,aAAa;;AAsB3D,SAAgB,mBACd,OAC+B;AAC/B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,UAAU"}
1
+ {"version":3,"file":"basic-functions.cjs","names":[],"sources":["../../src/generative-ui/basic-functions.ts"],"sourcesContent":["/**\n * The functions of the A2UI 1.0 basic catalog, as the model and the\n * validator see them. The renderer implements them (react-core\n * `generative-ui/functions.ts`); this file holds only what both sides share:\n * the names, the short signatures for the schema the model reads, and who\n * may call each one.\n */\n\n/** What a function gives back, as A2UI 1.0 names it. */\nexport type A2UIFunctionReturnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"array\"\n | \"object\"\n | \"validationResult\"\n | \"any\"\n | \"void\";\n\n/**\n * Who may call a function. The renderer calls it from an event binding or\n * as a prop value; the agent calls it with `callRendererFunction`.\n */\nexport type A2UIAllowedCallers =\n | \"rendererOnly\"\n | \"agentOnly\"\n | \"rendererOrAgent\";\n\n/**\n * The callers of an app function that names none: the renderer only, as\n * in A2UI 1.0. The agent calls a function with `callRendererFunction` only\n * when its declaration allows it (`\"rendererOrAgent\"` or `\"agentOnly\"`).\n * The manifests and the exported catalog write the value out.\n */\nexport const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS: A2UIAllowedCallers =\n \"rendererOnly\";\n\n/** The A2UI 1.0 interface fields of a function: who calls it, and how. */\nexport interface A2UIFunctionPermissions {\n allowedCallers?: A2UIAllowedCallers;\n /**\n * True for a function that only runs from a user gesture (a click, a key\n * press). It is `rendererOnly`: the agent cannot call it, and a prop\n * cannot be bound to it.\n */\n requiresUserActivation?: boolean;\n}\n\n/**\n * Who may call a function, from its permissions. A function that needs a\n * user gesture is for the renderer only, whatever `allowedCallers` says.\n *\n * @example\n * ```ts\n * functionCallers({}); // { renderer: true, agent: true }\n * functionCallers({ allowedCallers: \"rendererOnly\" }); // { renderer: true, agent: false }\n * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }\n * ```\n */\nexport function functionCallers(fn: A2UIFunctionPermissions) {\n if (fn.requiresUserActivation) return { renderer: true, agent: false };\n const callers = fn.allowedCallers ?? GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;\n return {\n renderer: callers !== \"agentOnly\",\n agent: callers !== \"rendererOnly\",\n };\n}\n\nexport interface A2UIBasicFunctionInfo extends A2UIFunctionPermissions {\n description: string;\n /** The args, as a short TypeScript-like type for the compact schema. */\n parameters: string;\n returnType: A2UIFunctionReturnType;\n /** Built-in functions are value functions of the renderer. */\n allowedCallers: \"rendererOnly\";\n requiresUserActivation?: true;\n /** True for a CopilotKit function that the A2UI basic catalog lacks. */\n extension?: true;\n}\n\n/** Marks a table of built-in functions as callable by the renderer only. */\nfunction rendererOnly<Name extends string>(\n functions: Record<Name, Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>,\n): Readonly<Record<Name, A2UIBasicFunctionInfo>> {\n return Object.fromEntries(\n Object.entries<Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>(\n functions,\n ).map(([name, info]) => [\n name,\n { ...info, allowedCallers: \"rendererOnly\" },\n ]),\n ) as Record<Name, A2UIBasicFunctionInfo>;\n}\n\n/**\n * The basic functions by name. A `{\"@call\"}` in a prop, in an event\n * binding, or in a `callRendererFunction` may name any of them without a\n * declaration in `createGenerativeUI({ functions })`.\n */\nexport const A2UI_BASIC_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n required: {\n description: \"Valid when the value is not empty\",\n parameters: \"{ value: unknown }\",\n returnType: \"validationResult\",\n },\n regex: {\n description: \"Valid when the value matches the pattern\",\n parameters: \"{ value: string; pattern: string }\",\n returnType: \"validationResult\",\n },\n length: {\n description: \"Valid when the length of the value is within min and max\",\n parameters: \"{ value: string; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n numeric: {\n description: \"Valid when the value is a number within min and max\",\n parameters: \"{ value: number; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n email: {\n description: \"Valid when the value is an email address\",\n parameters: \"{ value: string }\",\n returnType: \"validationResult\",\n },\n formatString: {\n description:\n \"Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\\\${ is a literal\",\n parameters: \"{ value: string }\",\n returnType: \"string\",\n },\n formatNumber: {\n description: \"The number in the locale of the user\",\n parameters: \"{ value: number; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatCurrency: {\n description: \"The amount as money, with an ISO 4217 currency code\",\n parameters:\n \"{ value: number; currency: string; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatDate: {\n description:\n 'A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"',\n parameters: \"{ value: string | number; format: string }\",\n returnType: \"string\",\n },\n pluralize: {\n description: \"The string of the plural category of the value\",\n parameters:\n \"{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }\",\n returnType: \"string\",\n },\n openUrl: {\n description: \"Opens an http(s) URL in a new tab. Only from an event\",\n parameters: \"{ url: string }\",\n returnType: \"void\",\n requiresUserActivation: true,\n },\n and: {\n description: \"True when every value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n or: {\n description: \"True when any value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n not: {\n description: \"The negated value\",\n parameters: \"{ value: boolean }\",\n returnType: \"boolean\",\n },\n});\n\n/**\n * The value functions that CopilotKit adds to the basic catalog, because\n * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named\n * args, and `series` builds a computed list. A catalog may declare its own\n * functions in A2UI, so these are regular catalog functions to the model;\n * a renderer without them rejects the call instead of misrendering.\n */\nexport const COPILOTKIT_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n calc: {\n description:\n \"The value of an arithmetic expression over the other args, by name: + - * / % ( ), x ^ y (power), comparisons, && || !, cond ? a : b, min max round floor ceil abs pow sqrt exp ln log10, the constants pi and e, 'text' + name\",\n parameters:\n \"{ expression: string; [name: string]: number | string | boolean }\",\n returnType: \"any\",\n extension: true,\n },\n // WORKAROUND(a2ui-agent-sdk 0.9.0): examples omit `variable` and use default i\n // because the Express compiler mistakes a literal `variable` key for its AST.\n // Runtime support for custom variable names is unchanged.\n // https://github.com/a2ui-project/a2ui/issues/3410\n series: {\n description:\n 'A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.',\n parameters:\n \"{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }\",\n returnType: \"array\",\n extension: true,\n },\n});\n\n/** Every function a `{\"@call\"}` may name without a declaration: basic and CopilotKit. */\nexport const GENERATIVE_UI_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = { ...A2UI_BASIC_FUNCTIONS, ...COPILOTKIT_FUNCTIONS };\n\n/** The name of the system function that gives the index of a template item. */\nexport const A2UI_INDEX_FUNCTION = \"@index\";\n\n/** True for a built-in function name: basic, CopilotKit, or `@index`. */\nexport function isA2UIBasicFunction(name: string) {\n return (\n name === A2UI_INDEX_FUNCTION ||\n Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name)\n );\n}\n\n/**\n * True for a built-in function that a prop or a check may call: every one\n * except the functions that need a user gesture.\n */\nexport function isA2UIValueFunction(name: string) {\n if (name === A2UI_INDEX_FUNCTION) return true;\n const info = Object.prototype.hasOwnProperty.call(\n GENERATIVE_UI_FUNCTIONS,\n name,\n )\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n return info !== undefined && !info.requiresUserActivation;\n}\n\n/** `{ \"@call\": \"<name>\", \"args\"?: {...} }`: a function call value. */\nexport function isCallBinding(\n value: unknown,\n): value is { \"@call\": string; args?: Record<string, unknown> } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>)[\"@call\"] === \"string\"\n );\n}\n\n/** How bad a failed check is. `error` is the default; only an error blocks. */\nexport type A2UIValidationSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A2UI's `ValidationResult`: what a check gives. A validator function gives\n * one; a check may also bind a boolean, which the renderer coerces to one.\n * `code` names the failure for programs; `severity` says how bad it is,\n * `\"error\"` when left out. Other keys are allowed, for app validators that\n * carry more (a suggested value, a field path).\n */\nexport interface A2UIValidationResult {\n valid: boolean;\n message?: string;\n code?: string;\n severity?: A2UIValidationSeverity;\n [extra: string]: unknown;\n}\n\nexport function isValidationResult(\n value: unknown,\n): value is A2UIValidationResult {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>).valid === \"boolean\"\n );\n}\n"],"mappings":";;;;;;;;AAkCA,MAAa,wCACX;;;;;;;;;;;;AAwBF,SAAgB,gBAAgB,IAA6B;AAC3D,KAAI,GAAG,uBAAwB,QAAO;EAAE,UAAU;EAAM,OAAO;EAAO;CACtE,MAAM,UAAU,GAAG,kBAAkB;AACrC,QAAO;EACL,UAAU,YAAY;EACtB,OAAO,YAAY;EACpB;;;AAgBH,SAAS,aACP,WAC+C;AAC/C,QAAO,OAAO,YACZ,OAAO,QACL,UACD,CAAC,KAAK,CAAC,MAAM,UAAU,CACtB,MACA;EAAE,GAAG;EAAM,gBAAgB;EAAgB,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xB;AACJ,QAAO,SAAS,UAAa,CAAC,KAAK;;;AAIrC,SAAgB,cACd,OAC8D;AAC9D,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,aAAa;;AAsB3D,SAAgB,mBACd,OAC+B;AAC/B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,UAAU"}
@@ -122,7 +122,7 @@ const A2UI_BASIC_FUNCTIONS = rendererOnly({
122
122
  */
123
123
  const COPILOTKIT_FUNCTIONS = rendererOnly({
124
124
  calc: {
125
- description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name",
125
+ description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), x ^ y (power), comparisons, && || !, cond ? a : b, min max round floor ceil abs pow sqrt exp ln log10, the constants pi and e, 'text' + name",
126
126
  parameters: "{ expression: string; [name: string]: number | string | boolean }",
127
127
  returnType: "any",
128
128
  extension: true
@@ -1 +1 @@
1
- {"version":3,"file":"basic-functions.mjs","names":[],"sources":["../../src/generative-ui/basic-functions.ts"],"sourcesContent":["/**\n * The functions of the A2UI 1.0 basic catalog, as the model and the\n * validator see them. The renderer implements them (react-core\n * `generative-ui/functions.ts`); this file holds only what both sides share:\n * the names, the short signatures for the schema the model reads, and who\n * may call each one.\n */\n\n/** What a function gives back, as A2UI 1.0 names it. */\nexport type A2UIFunctionReturnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"array\"\n | \"object\"\n | \"validationResult\"\n | \"any\"\n | \"void\";\n\n/**\n * Who may call a function. The renderer calls it from an event binding or\n * as a prop value; the agent calls it with `callRendererFunction`.\n */\nexport type A2UIAllowedCallers =\n | \"rendererOnly\"\n | \"agentOnly\"\n | \"rendererOrAgent\";\n\n/**\n * The callers of an app function that names none: the renderer only, as\n * in A2UI 1.0. The agent calls a function with `callRendererFunction` only\n * when its declaration allows it (`\"rendererOrAgent\"` or `\"agentOnly\"`).\n * The manifests and the exported catalog write the value out.\n */\nexport const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS: A2UIAllowedCallers =\n \"rendererOnly\";\n\n/** The A2UI 1.0 interface fields of a function: who calls it, and how. */\nexport interface A2UIFunctionPermissions {\n allowedCallers?: A2UIAllowedCallers;\n /**\n * True for a function that only runs from a user gesture (a click, a key\n * press). It is `rendererOnly`: the agent cannot call it, and a prop\n * cannot be bound to it.\n */\n requiresUserActivation?: boolean;\n}\n\n/**\n * Who may call a function, from its permissions. A function that needs a\n * user gesture is for the renderer only, whatever `allowedCallers` says.\n *\n * @example\n * ```ts\n * functionCallers({}); // { renderer: true, agent: true }\n * functionCallers({ allowedCallers: \"rendererOnly\" }); // { renderer: true, agent: false }\n * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }\n * ```\n */\nexport function functionCallers(fn: A2UIFunctionPermissions) {\n if (fn.requiresUserActivation) return { renderer: true, agent: false };\n const callers = fn.allowedCallers ?? GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;\n return {\n renderer: callers !== \"agentOnly\",\n agent: callers !== \"rendererOnly\",\n };\n}\n\nexport interface A2UIBasicFunctionInfo extends A2UIFunctionPermissions {\n description: string;\n /** The args, as a short TypeScript-like type for the compact schema. */\n parameters: string;\n returnType: A2UIFunctionReturnType;\n /** Built-in functions are value functions of the renderer. */\n allowedCallers: \"rendererOnly\";\n requiresUserActivation?: true;\n /** True for a CopilotKit function that the A2UI basic catalog lacks. */\n extension?: true;\n}\n\n/** Marks a table of built-in functions as callable by the renderer only. */\nfunction rendererOnly<Name extends string>(\n functions: Record<Name, Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>,\n): Readonly<Record<Name, A2UIBasicFunctionInfo>> {\n return Object.fromEntries(\n Object.entries<Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>(\n functions,\n ).map(([name, info]) => [\n name,\n { ...info, allowedCallers: \"rendererOnly\" },\n ]),\n ) as Record<Name, A2UIBasicFunctionInfo>;\n}\n\n/**\n * The basic functions by name. A `{\"@call\"}` in a prop, in an event\n * binding, or in a `callRendererFunction` may name any of them without a\n * declaration in `createGenerativeUI({ functions })`.\n */\nexport const A2UI_BASIC_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n required: {\n description: \"Valid when the value is not empty\",\n parameters: \"{ value: unknown }\",\n returnType: \"validationResult\",\n },\n regex: {\n description: \"Valid when the value matches the pattern\",\n parameters: \"{ value: string; pattern: string }\",\n returnType: \"validationResult\",\n },\n length: {\n description: \"Valid when the length of the value is within min and max\",\n parameters: \"{ value: string; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n numeric: {\n description: \"Valid when the value is a number within min and max\",\n parameters: \"{ value: number; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n email: {\n description: \"Valid when the value is an email address\",\n parameters: \"{ value: string }\",\n returnType: \"validationResult\",\n },\n formatString: {\n description:\n \"Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\\\${ is a literal\",\n parameters: \"{ value: string }\",\n returnType: \"string\",\n },\n formatNumber: {\n description: \"The number in the locale of the user\",\n parameters: \"{ value: number; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatCurrency: {\n description: \"The amount as money, with an ISO 4217 currency code\",\n parameters:\n \"{ value: number; currency: string; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatDate: {\n description:\n 'A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"',\n parameters: \"{ value: string | number; format: string }\",\n returnType: \"string\",\n },\n pluralize: {\n description: \"The string of the plural category of the value\",\n parameters:\n \"{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }\",\n returnType: \"string\",\n },\n openUrl: {\n description: \"Opens an http(s) URL in a new tab. Only from an event\",\n parameters: \"{ url: string }\",\n returnType: \"void\",\n requiresUserActivation: true,\n },\n and: {\n description: \"True when every value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n or: {\n description: \"True when any value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n not: {\n description: \"The negated value\",\n parameters: \"{ value: boolean }\",\n returnType: \"boolean\",\n },\n});\n\n/**\n * The value functions that CopilotKit adds to the basic catalog, because\n * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named\n * args, and `series` builds a computed list. A catalog may declare its own\n * functions in A2UI, so these are regular catalog functions to the model;\n * a renderer without them rejects the call instead of misrendering.\n */\nexport const COPILOTKIT_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n calc: {\n description:\n \"The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name\",\n parameters:\n \"{ expression: string; [name: string]: number | string | boolean }\",\n returnType: \"any\",\n extension: true,\n },\n // WORKAROUND(a2ui-agent-sdk 0.9.0): examples omit `variable` and use default i\n // because the Express compiler mistakes a literal `variable` key for its AST.\n // Runtime support for custom variable names is unchanged.\n // https://github.com/a2ui-project/a2ui/issues/3410\n series: {\n description:\n 'A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.',\n parameters:\n \"{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }\",\n returnType: \"array\",\n extension: true,\n },\n});\n\n/** Every function a `{\"@call\"}` may name without a declaration: basic and CopilotKit. */\nexport const GENERATIVE_UI_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = { ...A2UI_BASIC_FUNCTIONS, ...COPILOTKIT_FUNCTIONS };\n\n/** The name of the system function that gives the index of a template item. */\nexport const A2UI_INDEX_FUNCTION = \"@index\";\n\n/** True for a built-in function name: basic, CopilotKit, or `@index`. */\nexport function isA2UIBasicFunction(name: string) {\n return (\n name === A2UI_INDEX_FUNCTION ||\n Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name)\n );\n}\n\n/**\n * True for a built-in function that a prop or a check may call: every one\n * except the functions that need a user gesture.\n */\nexport function isA2UIValueFunction(name: string) {\n if (name === A2UI_INDEX_FUNCTION) return true;\n const info = Object.prototype.hasOwnProperty.call(\n GENERATIVE_UI_FUNCTIONS,\n name,\n )\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n return info !== undefined && !info.requiresUserActivation;\n}\n\n/** `{ \"@call\": \"<name>\", \"args\"?: {...} }`: a function call value. */\nexport function isCallBinding(\n value: unknown,\n): value is { \"@call\": string; args?: Record<string, unknown> } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>)[\"@call\"] === \"string\"\n );\n}\n\n/** How bad a failed check is. `error` is the default; only an error blocks. */\nexport type A2UIValidationSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A2UI's `ValidationResult`: what a check gives. A validator function gives\n * one; a check may also bind a boolean, which the renderer coerces to one.\n * `code` names the failure for programs; `severity` says how bad it is,\n * `\"error\"` when left out. Other keys are allowed, for app validators that\n * carry more (a suggested value, a field path).\n */\nexport interface A2UIValidationResult {\n valid: boolean;\n message?: string;\n code?: string;\n severity?: A2UIValidationSeverity;\n [extra: string]: unknown;\n}\n\nexport function isValidationResult(\n value: unknown,\n): value is A2UIValidationResult {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>).valid === \"boolean\"\n );\n}\n"],"mappings":";;;;;;;AAkCA,MAAa,wCACX;;;;;;;;;;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AAW;EACZ;CACF,CAAC;;AAGF,MAAa,0BAET;CAAE,GAAG;CAAsB,GAAG;CAAsB;;AAGxD,MAAa,sBAAsB;;AAGnC,SAAgB,oBAAoB,MAAc;AAChD,QACE,SAAS,uBACT,OAAO,UAAU,eAAe,KAAK,yBAAyB,KAAK;;;;;;AAQvE,SAAgB,oBAAoB,MAAc;AAChD,KAAI,SAAS,oBAAqB,QAAO;CACzC,MAAM,OAAO,OAAO,UAAU,eAAe,KAC3C,yBACA,KACD,GACG,wBAAwB,QACxB;AACJ,QAAO,SAAS,UAAa,CAAC,KAAK;;;AAIrC,SAAgB,cACd,OAC8D;AAC9D,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,aAAa;;AAsB3D,SAAgB,mBACd,OAC+B;AAC/B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,UAAU"}
1
+ {"version":3,"file":"basic-functions.mjs","names":[],"sources":["../../src/generative-ui/basic-functions.ts"],"sourcesContent":["/**\n * The functions of the A2UI 1.0 basic catalog, as the model and the\n * validator see them. The renderer implements them (react-core\n * `generative-ui/functions.ts`); this file holds only what both sides share:\n * the names, the short signatures for the schema the model reads, and who\n * may call each one.\n */\n\n/** What a function gives back, as A2UI 1.0 names it. */\nexport type A2UIFunctionReturnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"array\"\n | \"object\"\n | \"validationResult\"\n | \"any\"\n | \"void\";\n\n/**\n * Who may call a function. The renderer calls it from an event binding or\n * as a prop value; the agent calls it with `callRendererFunction`.\n */\nexport type A2UIAllowedCallers =\n | \"rendererOnly\"\n | \"agentOnly\"\n | \"rendererOrAgent\";\n\n/**\n * The callers of an app function that names none: the renderer only, as\n * in A2UI 1.0. The agent calls a function with `callRendererFunction` only\n * when its declaration allows it (`\"rendererOrAgent\"` or `\"agentOnly\"`).\n * The manifests and the exported catalog write the value out.\n */\nexport const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS: A2UIAllowedCallers =\n \"rendererOnly\";\n\n/** The A2UI 1.0 interface fields of a function: who calls it, and how. */\nexport interface A2UIFunctionPermissions {\n allowedCallers?: A2UIAllowedCallers;\n /**\n * True for a function that only runs from a user gesture (a click, a key\n * press). It is `rendererOnly`: the agent cannot call it, and a prop\n * cannot be bound to it.\n */\n requiresUserActivation?: boolean;\n}\n\n/**\n * Who may call a function, from its permissions. A function that needs a\n * user gesture is for the renderer only, whatever `allowedCallers` says.\n *\n * @example\n * ```ts\n * functionCallers({}); // { renderer: true, agent: true }\n * functionCallers({ allowedCallers: \"rendererOnly\" }); // { renderer: true, agent: false }\n * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }\n * ```\n */\nexport function functionCallers(fn: A2UIFunctionPermissions) {\n if (fn.requiresUserActivation) return { renderer: true, agent: false };\n const callers = fn.allowedCallers ?? GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;\n return {\n renderer: callers !== \"agentOnly\",\n agent: callers !== \"rendererOnly\",\n };\n}\n\nexport interface A2UIBasicFunctionInfo extends A2UIFunctionPermissions {\n description: string;\n /** The args, as a short TypeScript-like type for the compact schema. */\n parameters: string;\n returnType: A2UIFunctionReturnType;\n /** Built-in functions are value functions of the renderer. */\n allowedCallers: \"rendererOnly\";\n requiresUserActivation?: true;\n /** True for a CopilotKit function that the A2UI basic catalog lacks. */\n extension?: true;\n}\n\n/** Marks a table of built-in functions as callable by the renderer only. */\nfunction rendererOnly<Name extends string>(\n functions: Record<Name, Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>,\n): Readonly<Record<Name, A2UIBasicFunctionInfo>> {\n return Object.fromEntries(\n Object.entries<Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>(\n functions,\n ).map(([name, info]) => [\n name,\n { ...info, allowedCallers: \"rendererOnly\" },\n ]),\n ) as Record<Name, A2UIBasicFunctionInfo>;\n}\n\n/**\n * The basic functions by name. A `{\"@call\"}` in a prop, in an event\n * binding, or in a `callRendererFunction` may name any of them without a\n * declaration in `createGenerativeUI({ functions })`.\n */\nexport const A2UI_BASIC_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n required: {\n description: \"Valid when the value is not empty\",\n parameters: \"{ value: unknown }\",\n returnType: \"validationResult\",\n },\n regex: {\n description: \"Valid when the value matches the pattern\",\n parameters: \"{ value: string; pattern: string }\",\n returnType: \"validationResult\",\n },\n length: {\n description: \"Valid when the length of the value is within min and max\",\n parameters: \"{ value: string; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n numeric: {\n description: \"Valid when the value is a number within min and max\",\n parameters: \"{ value: number; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n email: {\n description: \"Valid when the value is an email address\",\n parameters: \"{ value: string }\",\n returnType: \"validationResult\",\n },\n formatString: {\n description:\n \"Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\\\${ is a literal\",\n parameters: \"{ value: string }\",\n returnType: \"string\",\n },\n formatNumber: {\n description: \"The number in the locale of the user\",\n parameters: \"{ value: number; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatCurrency: {\n description: \"The amount as money, with an ISO 4217 currency code\",\n parameters:\n \"{ value: number; currency: string; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatDate: {\n description:\n 'A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"',\n parameters: \"{ value: string | number; format: string }\",\n returnType: \"string\",\n },\n pluralize: {\n description: \"The string of the plural category of the value\",\n parameters:\n \"{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }\",\n returnType: \"string\",\n },\n openUrl: {\n description: \"Opens an http(s) URL in a new tab. Only from an event\",\n parameters: \"{ url: string }\",\n returnType: \"void\",\n requiresUserActivation: true,\n },\n and: {\n description: \"True when every value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n or: {\n description: \"True when any value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n not: {\n description: \"The negated value\",\n parameters: \"{ value: boolean }\",\n returnType: \"boolean\",\n },\n});\n\n/**\n * The value functions that CopilotKit adds to the basic catalog, because\n * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named\n * args, and `series` builds a computed list. A catalog may declare its own\n * functions in A2UI, so these are regular catalog functions to the model;\n * a renderer without them rejects the call instead of misrendering.\n */\nexport const COPILOTKIT_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n calc: {\n description:\n \"The value of an arithmetic expression over the other args, by name: + - * / % ( ), x ^ y (power), comparisons, && || !, cond ? a : b, min max round floor ceil abs pow sqrt exp ln log10, the constants pi and e, 'text' + name\",\n parameters:\n \"{ expression: string; [name: string]: number | string | boolean }\",\n returnType: \"any\",\n extension: true,\n },\n // WORKAROUND(a2ui-agent-sdk 0.9.0): examples omit `variable` and use default i\n // because the Express compiler mistakes a literal `variable` key for its AST.\n // Runtime support for custom variable names is unchanged.\n // https://github.com/a2ui-project/a2ui/issues/3410\n series: {\n description:\n 'A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.',\n parameters:\n \"{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }\",\n returnType: \"array\",\n extension: true,\n },\n});\n\n/** Every function a `{\"@call\"}` may name without a declaration: basic and CopilotKit. */\nexport const GENERATIVE_UI_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = { ...A2UI_BASIC_FUNCTIONS, ...COPILOTKIT_FUNCTIONS };\n\n/** The name of the system function that gives the index of a template item. */\nexport const A2UI_INDEX_FUNCTION = \"@index\";\n\n/** True for a built-in function name: basic, CopilotKit, or `@index`. */\nexport function isA2UIBasicFunction(name: string) {\n return (\n name === A2UI_INDEX_FUNCTION ||\n Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name)\n );\n}\n\n/**\n * True for a built-in function that a prop or a check may call: every one\n * except the functions that need a user gesture.\n */\nexport function isA2UIValueFunction(name: string) {\n if (name === A2UI_INDEX_FUNCTION) return true;\n const info = Object.prototype.hasOwnProperty.call(\n GENERATIVE_UI_FUNCTIONS,\n name,\n )\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n return info !== undefined && !info.requiresUserActivation;\n}\n\n/** `{ \"@call\": \"<name>\", \"args\"?: {...} }`: a function call value. */\nexport function isCallBinding(\n value: unknown,\n): value is { \"@call\": string; args?: Record<string, unknown> } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>)[\"@call\"] === \"string\"\n );\n}\n\n/** How bad a failed check is. `error` is the default; only an error blocks. */\nexport type A2UIValidationSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A2UI's `ValidationResult`: what a check gives. A validator function gives\n * one; a check may also bind a boolean, which the renderer coerces to one.\n * `code` names the failure for programs; `severity` says how bad it is,\n * `\"error\"` when left out. Other keys are allowed, for app validators that\n * carry more (a suggested value, a field path).\n */\nexport interface A2UIValidationResult {\n valid: boolean;\n message?: string;\n code?: string;\n severity?: A2UIValidationSeverity;\n [extra: string]: unknown;\n}\n\nexport function isValidationResult(\n value: unknown,\n): value is A2UIValidationResult {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>).valid === \"boolean\"\n );\n}\n"],"mappings":";;;;;;;AAkCA,MAAa,wCACX;;;;;;;;;;;;AAwBF,SAAgB,gBAAgB,IAA6B;AAC3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AET;CAAE,GAAG;CAAsB,GAAG;CAAsB;;AAGxD,MAAa,sBAAsB;;AAGnC,SAAgB,oBAAoB,MAAc;AAChD,QACE,SAAS,uBACT,OAAO,UAAU,eAAe,KAAK,yBAAyB,KAAK;;;;;;AAQvE,SAAgB,oBAAoB,MAAc;AAChD,KAAI,SAAS,oBAAqB,QAAO;CACzC,MAAM,OAAO,OAAO,UAAU,eAAe,KAC3C,yBACA,KACD,GACG,wBAAwB,QACxB;AACJ,QAAO,SAAS,UAAa,CAAC,KAAK;;;AAIrC,SAAgB,cACd,OAC8D;AAC9D,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,aAAa;;AAsB3D,SAAgB,mBACd,OAC+B;AAC/B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,UAAU"}
@@ -101,8 +101,8 @@ function childIdsAtRefs(component, refs) {
101
101
  else if (require_is_record.isRecord(value) && typeof value.componentId === "string") ids.push(value.componentId);
102
102
  };
103
103
  const visit = (value, path) => {
104
- if (path.length === 0) return collect(value);
105
104
  const [head, ...rest] = path;
105
+ if (head === void 0) return collect(value);
106
106
  if (head === "*") {
107
107
  if (Array.isArray(value)) value.forEach((item) => visit(item, rest));
108
108
  return;
@@ -121,8 +121,8 @@ function hasBoundChildRef(component, refs) {
121
121
  const isDynamic = (value) => require_is_record.isRecord(value) && ("@path" in value || "@call" in value);
122
122
  const visit = (value, path) => {
123
123
  if (isDynamic(value)) return true;
124
- if (path.length === 0) return false;
125
124
  const [head, ...rest] = path;
125
+ if (head === void 0) return false;
126
126
  if (head === "*") return Array.isArray(value) && value.some((item) => visit(item, rest));
127
127
  return require_is_record.isRecord(value) && Object.prototype.hasOwnProperty.call(value, head) && visit(value[head], rest);
128
128
  };
@@ -134,8 +134,8 @@ function hasBoundChildRef(component, refs) {
134
134
  * else keeps its identity. Missing keys are left alone.
135
135
  */
136
136
  function mapAtChildRef(value, path, replace) {
137
- if (path.length === 0) return replace(value);
138
137
  const [head, ...rest] = path;
138
+ if (head === void 0) return replace(value);
139
139
  if (head === "*") {
140
140
  if (!Array.isArray(value)) return value;
141
141
  return value.map((item) => mapAtChildRef(item, rest, replace));
@@ -1 +1 @@
1
- {"version":3,"file":"child-refs.cjs","names":["isRecord"],"sources":["../../src/generative-ui/child-refs.ts"],"sourcesContent":["import type { GenerativeUIJSONSchema } from \"./types\";\nimport { isRecord } from \"./is-record\";\n\n/**\n * How A2UI 1.0 marks a prop that holds a component reference: the JSON\n * Schema of the prop is a `$ref` to one of these two common types.\n * Validators and renderers find the children of a component by these refs,\n * at any depth of the props schema.\n */\nexport const A2UI_COMPONENT_ID_REF = \"common_types.json#/$defs/ComponentId\";\nexport const A2UI_CHILD_LIST_REF = \"common_types.json#/$defs/ChildList\";\n\n/**\n * The start of the `description` that marks a schema as a component\n * reference before it is turned into JSON Schema. `child()` and\n * `childList()` set it; a schema from another library can set a description\n * that starts with the same mark to get the same effect. What follows the\n * mark (after a space) stays as the description of the reference.\n */\nexport const A2UI_COMPONENT_ID_MARK = \"@a2ui/ComponentId\";\nexport const A2UI_CHILD_LIST_MARK = \"@a2ui/ChildList\";\n\nexport type ChildRefKind = \"single\" | \"multiple\";\n\n/** One component reference in a props schema. */\nexport interface ChildRef {\n /**\n * The keys from the props root to the reference. `\"*\"` stands for the\n * items of an array. `[\"tabs\", \"*\", \"child\"]` is the `child` of each\n * entry of `tabs`.\n */\n path: readonly string[];\n kind: ChildRefKind;\n}\n\n/** The ref kind of a JSON Schema node, or `undefined` for a plain value. */\nexport function childRefKind(\n schema: GenerativeUIJSONSchema,\n): ChildRefKind | undefined {\n const ref = schema.$ref;\n if (ref === A2UI_COMPONENT_ID_REF) return \"single\";\n if (ref === A2UI_CHILD_LIST_REF) return \"multiple\";\n return undefined;\n}\n\n/**\n * Turns the reference marks of a JSON Schema into A2UI `$ref`s, in place of\n * the marked node. The mark is the `description` set by `child()` and\n * `childList()`; after this, the node is `{ \"$ref\": \"common_types.json#/...\" }`.\n */\nexport function applyChildRefMarks(\n schema: GenerativeUIJSONSchema,\n): GenerativeUIJSONSchema {\n const marked = (description: unknown, mark: string, ref: string) => {\n if (typeof description !== \"string\" || !description.startsWith(mark)) {\n return undefined;\n }\n const rest = description.slice(mark.length).trim();\n return rest === \"\" ? { $ref: ref } : { $ref: ref, description: rest };\n };\n const visit = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(visit);\n if (!isRecord(node)) return node;\n const reference =\n marked(node.description, A2UI_COMPONENT_ID_MARK, A2UI_COMPONENT_ID_REF) ??\n marked(node.description, A2UI_CHILD_LIST_MARK, A2UI_CHILD_LIST_REF);\n if (reference) return reference;\n return Object.fromEntries(\n Object.entries(node).map(([key, value]) => [key, visit(value)]),\n );\n };\n return visit(schema) as GenerativeUIJSONSchema;\n}\n\n/**\n * Every component reference in a props schema, with its path. Walks\n * `properties`, array `items`, and the variants of `anyOf` / `oneOf` /\n * `allOf`. A union counts as a reference only when every alternative is\n * one of the same kind: a prop that is text in one branch and a child in\n * another cannot be told apart from its value, so it stays data.\n */\nexport function collectChildRefs(schema: GenerativeUIJSONSchema): ChildRef[] {\n const refs: ChildRef[] = [];\n const seen = new Set<string>();\n const add = (path: string[], kind: ChildRefKind) => {\n const key = path.join(\"\\u0000\");\n if (seen.has(key)) return;\n seen.add(key);\n refs.push({ path, kind });\n };\n const visit = (node: unknown, path: string[]) => {\n if (!isRecord(node)) return;\n const kind = childRefKind(node);\n if (kind) return add(path, kind);\n for (const list of [node.anyOf, node.oneOf]) {\n if (!Array.isArray(list) || list.length === 0) continue;\n const kinds = list.map((variant) =>\n isRecord(variant) ? childRefKind(variant) : undefined,\n );\n const [first] = kinds;\n if (first && kinds.every((k) => k === first)) add(path, first);\n else if (kinds.every((k) => k === undefined)) {\n // Objects in a union: a nested reference counts only when every\n // alternative has it at the same path with the same kind.\n const perVariant = list.map((variant) =>\n collectChildRefs(variant as GenerativeUIJSONSchema),\n );\n const key = (ref: ChildRef) =>\n `${ref.kind}\\u0000${ref.path.join(\"\\u0000\")}`;\n const shared = perVariant[0].filter((ref) =>\n perVariant.every((refs) => refs.some((r) => key(r) === key(ref))),\n );\n shared.forEach((ref) => add([...path, ...ref.path], ref.kind));\n }\n }\n if (Array.isArray(node.allOf)) {\n node.allOf.forEach((variant) => visit(variant, path));\n }\n if (isRecord(node.properties)) {\n for (const [key, value] of Object.entries(node.properties)) {\n visit(value, [...path, key]);\n }\n }\n if (isRecord(node.items)) visit(node.items, [...path, \"*\"]);\n };\n visit(schema, []);\n return refs;\n}\n\n/**\n * The component ids at the references of one component node: a string id,\n * a list of ids, or the `componentId` of a template, at every ref path.\n * Bound or computed values are not ids and are left out.\n */\nexport function childIdsAtRefs(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): string[] {\n const ids: string[] = [];\n const collect = (value: unknown) => {\n if (typeof value === \"string\") ids.push(value);\n else if (Array.isArray(value)) {\n value.forEach((id) => typeof id === \"string\" && ids.push(id));\n } else if (isRecord(value) && typeof value.componentId === \"string\") {\n ids.push(value.componentId);\n }\n };\n const visit = (value: unknown, path: readonly string[]) => {\n if (path.length === 0) return collect(value);\n const [head, ...rest] = path;\n if (head === \"*\") {\n if (Array.isArray(value)) value.forEach((item) => visit(item, rest));\n return;\n }\n if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, head)) {\n visit(value[head], rest);\n }\n };\n for (const ref of refs) visit(component, ref.path);\n return ids;\n}\n\n/**\n * True when a reference of the component is bound or computed (`{\"@path\"}`,\n * `{\"@call\"}`) at the ref itself or above it, so its ids are known only\n * at render time.\n */\nexport function hasBoundChildRef(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): boolean {\n const isDynamic = (value: unknown) =>\n isRecord(value) && (\"@path\" in value || \"@call\" in value);\n const visit = (value: unknown, path: readonly string[]): boolean => {\n if (isDynamic(value)) return true;\n if (path.length === 0) return false;\n const [head, ...rest] = path;\n if (head === \"*\") {\n return Array.isArray(value) && value.some((item) => visit(item, rest));\n }\n return (\n isRecord(value) &&\n Object.prototype.hasOwnProperty.call(value, head) &&\n visit(value[head], rest)\n );\n };\n return refs.some((ref) => visit(component, ref.path));\n}\n\n/**\n * Walks `value` along a ref path and replaces what sits at the end with\n * `replace(found)`. Objects and arrays on the way are copied; everything\n * else keeps its identity. Missing keys are left alone.\n */\nexport function mapAtChildRef(\n value: unknown,\n path: readonly string[],\n replace: (found: unknown) => unknown,\n): unknown {\n if (path.length === 0) return replace(value);\n const [head, ...rest] = path;\n if (head === \"*\") {\n if (!Array.isArray(value)) return value;\n return value.map((item) => mapAtChildRef(item, rest, replace));\n }\n if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, head)) {\n return value;\n }\n return { ...value, [head]: mapAtChildRef(value[head], rest, replace) };\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,wBAAwB;AACrC,MAAa,sBAAsB;;;;;;;;AASnC,MAAa,yBAAyB;AACtC,MAAa,uBAAuB;;AAgBpC,SAAgB,aACd,QAC0B;CAC1B,MAAM,MAAM,OAAO;AACnB,KAAI,QAAQ,sBAAuB,QAAO;AAC1C,KAAI,QAAQ,oBAAqB,QAAO;;;;;;;AAS1C,SAAgB,mBACd,QACwB;CACxB,MAAM,UAAU,aAAsB,MAAc,QAAgB;AAClE,MAAI,OAAO,gBAAgB,YAAY,CAAC,YAAY,WAAW,KAAK,CAClE;EAEF,MAAM,OAAO,YAAY,MAAM,KAAK,OAAO,CAAC,MAAM;AAClD,SAAO,SAAS,KAAK,EAAE,MAAM,KAAK,GAAG;GAAE,MAAM;GAAK,aAAa;GAAM;;CAEvE,MAAM,SAAS,SAA2B;AACxC,MAAI,MAAM,QAAQ,KAAK,CAAE,QAAO,KAAK,IAAI,MAAM;AAC/C,MAAI,CAACA,2BAAS,KAAK,CAAE,QAAO;EAC5B,MAAM,YACJ,OAAO,KAAK,aAAa,wBAAwB,sBAAsB,IACvE,OAAO,KAAK,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CACrD,MAAM,SAAS,OAAgB,SAAqC;AAClE,MAAI,UAAU,MAAM,CAAE,QAAO;AAC7B,MAAI,KAAK,WAAW,EAAG,QAAO;EAC9B,MAAM,CAAC,MAAM,GAAG,QAAQ;AACxB,MAAI,SAAS,IACX,QAAO,MAAM,QAAQ,MAAM,IAAI,MAAM,MAAM,SAAS,MAAM,MAAM,KAAK,CAAC;AAExE,SACEA,2BAAS,MAAM,IACf,OAAO,UAAU,eAAe,KAAK,OAAO,KAAK,IACjD,MAAM,MAAM,OAAO,KAAK;;AAG5B,QAAO,KAAK,MAAM,QAAQ,MAAM,WAAW,IAAI,KAAK,CAAC;;;;;;;AAQvD,SAAgB,cACd,OACA,MACA,SACS;AACT,KAAI,KAAK,WAAW,EAAG,QAAO,QAAQ,MAAM;CAC5C,MAAM,CAAC,MAAM,GAAG,QAAQ;AACxB,KAAI,SAAS,KAAK;AAChB,MAAI,CAAC,MAAM,QAAQ,MAAM,CAAE,QAAO;AAClC,SAAO,MAAM,KAAK,SAAS,cAAc,MAAM,MAAM,QAAQ,CAAC;;AAEhE,KAAI,CAACA,2BAAS,MAAM,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,KAAK,CACxE,QAAO;AAET,QAAO;EAAE,GAAG;GAAQ,OAAO,cAAc,MAAM,OAAO,MAAM,QAAQ;EAAE"}
1
+ {"version":3,"file":"child-refs.cjs","names":["isRecord"],"sources":["../../src/generative-ui/child-refs.ts"],"sourcesContent":["import type { GenerativeUIJSONSchema } from \"./types\";\nimport { isRecord } from \"./is-record\";\n\n/**\n * How A2UI 1.0 marks a prop that holds a component reference: the JSON\n * Schema of the prop is a `$ref` to one of these two common types.\n * Validators and renderers find the children of a component by these refs,\n * at any depth of the props schema.\n */\nexport const A2UI_COMPONENT_ID_REF = \"common_types.json#/$defs/ComponentId\";\nexport const A2UI_CHILD_LIST_REF = \"common_types.json#/$defs/ChildList\";\n\n/**\n * The start of the `description` that marks a schema as a component\n * reference before it is turned into JSON Schema. `child()` and\n * `childList()` set it; a schema from another library can set a description\n * that starts with the same mark to get the same effect. What follows the\n * mark (after a space) stays as the description of the reference.\n */\nexport const A2UI_COMPONENT_ID_MARK = \"@a2ui/ComponentId\";\nexport const A2UI_CHILD_LIST_MARK = \"@a2ui/ChildList\";\n\nexport type ChildRefKind = \"single\" | \"multiple\";\n\n/** One component reference in a props schema. */\nexport interface ChildRef {\n /**\n * The keys from the props root to the reference. `\"*\"` stands for the\n * items of an array. `[\"tabs\", \"*\", \"child\"]` is the `child` of each\n * entry of `tabs`.\n */\n path: readonly string[];\n kind: ChildRefKind;\n}\n\n/** The ref kind of a JSON Schema node, or `undefined` for a plain value. */\nexport function childRefKind(\n schema: GenerativeUIJSONSchema,\n): ChildRefKind | undefined {\n const ref = schema.$ref;\n if (ref === A2UI_COMPONENT_ID_REF) return \"single\";\n if (ref === A2UI_CHILD_LIST_REF) return \"multiple\";\n return undefined;\n}\n\n/**\n * Turns the reference marks of a JSON Schema into A2UI `$ref`s, in place of\n * the marked node. The mark is the `description` set by `child()` and\n * `childList()`; after this, the node is `{ \"$ref\": \"common_types.json#/...\" }`.\n */\nexport function applyChildRefMarks(\n schema: GenerativeUIJSONSchema,\n): GenerativeUIJSONSchema {\n const marked = (description: unknown, mark: string, ref: string) => {\n if (typeof description !== \"string\" || !description.startsWith(mark)) {\n return undefined;\n }\n const rest = description.slice(mark.length).trim();\n return rest === \"\" ? { $ref: ref } : { $ref: ref, description: rest };\n };\n const visit = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(visit);\n if (!isRecord(node)) return node;\n const reference =\n marked(node.description, A2UI_COMPONENT_ID_MARK, A2UI_COMPONENT_ID_REF) ??\n marked(node.description, A2UI_CHILD_LIST_MARK, A2UI_CHILD_LIST_REF);\n if (reference) return reference;\n return Object.fromEntries(\n Object.entries(node).map(([key, value]) => [key, visit(value)]),\n );\n };\n return visit(schema) as GenerativeUIJSONSchema;\n}\n\n/**\n * Every component reference in a props schema, with its path. Walks\n * `properties`, array `items`, and the variants of `anyOf` / `oneOf` /\n * `allOf`. A union counts as a reference only when every alternative is\n * one of the same kind: a prop that is text in one branch and a child in\n * another cannot be told apart from its value, so it stays data.\n */\nexport function collectChildRefs(schema: GenerativeUIJSONSchema): ChildRef[] {\n const refs: ChildRef[] = [];\n const seen = new Set<string>();\n const add = (path: string[], kind: ChildRefKind) => {\n const key = path.join(\"\\u0000\");\n if (seen.has(key)) return;\n seen.add(key);\n refs.push({ path, kind });\n };\n const visit = (node: unknown, path: string[]) => {\n if (!isRecord(node)) return;\n const kind = childRefKind(node);\n if (kind) return add(path, kind);\n for (const list of [node.anyOf, node.oneOf]) {\n if (!Array.isArray(list) || list.length === 0) continue;\n const kinds = list.map((variant) =>\n isRecord(variant) ? childRefKind(variant) : undefined,\n );\n const [first] = kinds;\n if (first && kinds.every((k) => k === first)) add(path, first);\n else if (kinds.every((k) => k === undefined)) {\n // Objects in a union: a nested reference counts only when every\n // alternative has it at the same path with the same kind.\n const perVariant = list.map((variant) =>\n collectChildRefs(variant as GenerativeUIJSONSchema),\n );\n const key = (ref: ChildRef) =>\n `${ref.kind}\\u0000${ref.path.join(\"\\u0000\")}`;\n // `list` is not empty (checked above), so `perVariant` is not empty.\n const shared = perVariant[0]!.filter((ref) =>\n perVariant.every((refs) => refs.some((r) => key(r) === key(ref))),\n );\n shared.forEach((ref) => add([...path, ...ref.path], ref.kind));\n }\n }\n if (Array.isArray(node.allOf)) {\n node.allOf.forEach((variant) => visit(variant, path));\n }\n if (isRecord(node.properties)) {\n for (const [key, value] of Object.entries(node.properties)) {\n visit(value, [...path, key]);\n }\n }\n if (isRecord(node.items)) visit(node.items, [...path, \"*\"]);\n };\n visit(schema, []);\n return refs;\n}\n\n/**\n * The component ids at the references of one component node: a string id,\n * a list of ids, or the `componentId` of a template, at every ref path.\n * Bound or computed values are not ids and are left out.\n */\nexport function childIdsAtRefs(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): string[] {\n const ids: string[] = [];\n const collect = (value: unknown) => {\n if (typeof value === \"string\") ids.push(value);\n else if (Array.isArray(value)) {\n value.forEach((id) => typeof id === \"string\" && ids.push(id));\n } else if (isRecord(value) && typeof value.componentId === \"string\") {\n ids.push(value.componentId);\n }\n };\n const visit = (value: unknown, path: readonly string[]) => {\n const [head, ...rest] = path;\n if (head === undefined) return collect(value);\n if (head === \"*\") {\n if (Array.isArray(value)) value.forEach((item) => visit(item, rest));\n return;\n }\n if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, head)) {\n visit(value[head], rest);\n }\n };\n for (const ref of refs) visit(component, ref.path);\n return ids;\n}\n\n/**\n * True when a reference of the component is bound or computed (`{\"@path\"}`,\n * `{\"@call\"}`) at the ref itself or above it, so its ids are known only\n * at render time.\n */\nexport function hasBoundChildRef(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): boolean {\n const isDynamic = (value: unknown) =>\n isRecord(value) && (\"@path\" in value || \"@call\" in value);\n const visit = (value: unknown, path: readonly string[]): boolean => {\n if (isDynamic(value)) return true;\n const [head, ...rest] = path;\n if (head === undefined) return false;\n if (head === \"*\") {\n return Array.isArray(value) && value.some((item) => visit(item, rest));\n }\n return (\n isRecord(value) &&\n Object.prototype.hasOwnProperty.call(value, head) &&\n visit(value[head], rest)\n );\n };\n return refs.some((ref) => visit(component, ref.path));\n}\n\n/**\n * Walks `value` along a ref path and replaces what sits at the end with\n * `replace(found)`. Objects and arrays on the way are copied; everything\n * else keeps its identity. Missing keys are left alone.\n */\nexport function mapAtChildRef(\n value: unknown,\n path: readonly string[],\n replace: (found: unknown) => unknown,\n): unknown {\n const [head, ...rest] = path;\n if (head === undefined) return replace(value);\n if (head === \"*\") {\n if (!Array.isArray(value)) return value;\n return value.map((item) => mapAtChildRef(item, rest, replace));\n }\n if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, head)) {\n return value;\n }\n return { ...value, [head]: mapAtChildRef(value[head], rest, replace) };\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,wBA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Q,MAAM,CAAE,QAAO;AAClC,SAAO,MAAM,KAAK,SAAS,cAAc,MAAM,MAAM,QAAQ,CAAC;;AAEhE,KAAI,CAACA,2BAAS,MAAM,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,KAAK,CACxE,QAAO;AAET,QAAO;EAAE,GAAG;GAAQ,OAAO,cAAc,MAAM,OAAO,MAAM,QAAQ;EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"child-refs.d.cts","names":[],"sources":["../../src/generative-ui/child-refs.ts"],"mappings":";;;;;AASA;;;;cAAa,qBAAA;AAAA,cACA,mBAAA;;;;;AASb;;;cAAa,sBAAA;AAAA,cACA,oBAAA;AAAA,KAED,YAAA;;UAGK,QAAA;EALgB;;AAEjC;;;EASE,IAAA;EACA,IAAA,EAAM,YAAA;AAAA;;iBAIQ,YAAA,CACd,MAAA,EAAQ,sBAAA,GACP,YAAA;;;;;;iBAYa,kBAAA,CACd,MAAA,EAAQ,sBAAA,GACP,sBAAA;AAhBH;;;;;;;AAAA,iBA6CgB,gBAAA,CAAiB,MAAA,EAAQ,sBAAA,GAAyB,QAAA;;AA/BlE;;;;iBAoFgB,cAAA,CACd,SAAA,EAAW,MAAA,mBACX,IAAA,WAAe,QAAA;;;;;AAvDjB;iBAsFgB,gBAAA,CACd,SAAA,EAAW,MAAA,mBACX,IAAA,WAAe,QAAA;;;;;;iBAyBD,aAAA,CACd,KAAA,WACA,IAAA,qBACA,OAAA,GAAU,KAAA"}
1
+ {"version":3,"file":"child-refs.d.cts","names":[],"sources":["../../src/generative-ui/child-refs.ts"],"mappings":";;;;;AASA;;;;cAAa,qBAAA;AAAA,cACA,mBAAA;;;;;AASb;;;cAAa,sBAAA;AAAA,cACA,oBAAA;AAAA,KAED,YAAA;;UAGK,QAAA;EALgB;;AAEjC;;;EASE,IAAA;EACA,IAAA,EAAM,YAAA;AAAA;;iBAIQ,YAAA,CACd,MAAA,EAAQ,sBAAA,GACP,YAAA;;;;;;iBAYa,kBAAA,CACd,MAAA,EAAQ,sBAAA,GACP,sBAAA;AAhBH;;;;;;;AAAA,iBA6CgB,gBAAA,CAAiB,MAAA,EAAQ,sBAAA,GAAyB,QAAA;;AA/BlE;;;;iBAqFgB,cAAA,CACd,SAAA,EAAW,MAAA,mBACX,IAAA,WAAe,QAAA;;;;;AAxDjB;iBAuFgB,gBAAA,CACd,SAAA,EAAW,MAAA,mBACX,IAAA,WAAe,QAAA;;;;;;iBAyBD,aAAA,CACd,KAAA,WACA,IAAA,qBACA,OAAA,GAAU,KAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"child-refs.d.mts","names":[],"sources":["../../src/generative-ui/child-refs.ts"],"mappings":";;;;;AASA;;;;cAAa,qBAAA;AAAA,cACA,mBAAA;;;;;AASb;;;cAAa,sBAAA;AAAA,cACA,oBAAA;AAAA,KAED,YAAA;;UAGK,QAAA;EALgB;;AAEjC;;;EASE,IAAA;EACA,IAAA,EAAM,YAAA;AAAA;;iBAIQ,YAAA,CACd,MAAA,EAAQ,sBAAA,GACP,YAAA;;;;;;iBAYa,kBAAA,CACd,MAAA,EAAQ,sBAAA,GACP,sBAAA;AAhBH;;;;;;;AAAA,iBA6CgB,gBAAA,CAAiB,MAAA,EAAQ,sBAAA,GAAyB,QAAA;;AA/BlE;;;;iBAoFgB,cAAA,CACd,SAAA,EAAW,MAAA,mBACX,IAAA,WAAe,QAAA;;;;;AAvDjB;iBAsFgB,gBAAA,CACd,SAAA,EAAW,MAAA,mBACX,IAAA,WAAe,QAAA;;;;;;iBAyBD,aAAA,CACd,KAAA,WACA,IAAA,qBACA,OAAA,GAAU,KAAA"}
1
+ {"version":3,"file":"child-refs.d.mts","names":[],"sources":["../../src/generative-ui/child-refs.ts"],"mappings":";;;;;AASA;;;;cAAa,qBAAA;AAAA,cACA,mBAAA;;;;;AASb;;;cAAa,sBAAA;AAAA,cACA,oBAAA;AAAA,KAED,YAAA;;UAGK,QAAA;EALgB;;AAEjC;;;EASE,IAAA;EACA,IAAA,EAAM,YAAA;AAAA;;iBAIQ,YAAA,CACd,MAAA,EAAQ,sBAAA,GACP,YAAA;;;;;;iBAYa,kBAAA,CACd,MAAA,EAAQ,sBAAA,GACP,sBAAA;AAhBH;;;;;;;AAAA,iBA6CgB,gBAAA,CAAiB,MAAA,EAAQ,sBAAA,GAAyB,QAAA;;AA/BlE;;;;iBAqFgB,cAAA,CACd,SAAA,EAAW,MAAA,mBACX,IAAA,WAAe,QAAA;;;;;AAxDjB;iBAuFgB,gBAAA,CACd,SAAA,EAAW,MAAA,mBACX,IAAA,WAAe,QAAA;;;;;;iBAyBD,aAAA,CACd,KAAA,WACA,IAAA,qBACA,OAAA,GAAU,KAAA"}
@@ -101,8 +101,8 @@ function childIdsAtRefs(component, refs) {
101
101
  else if (isRecord(value) && typeof value.componentId === "string") ids.push(value.componentId);
102
102
  };
103
103
  const visit = (value, path) => {
104
- if (path.length === 0) return collect(value);
105
104
  const [head, ...rest] = path;
105
+ if (head === void 0) return collect(value);
106
106
  if (head === "*") {
107
107
  if (Array.isArray(value)) value.forEach((item) => visit(item, rest));
108
108
  return;
@@ -121,8 +121,8 @@ function hasBoundChildRef(component, refs) {
121
121
  const isDynamic = (value) => isRecord(value) && ("@path" in value || "@call" in value);
122
122
  const visit = (value, path) => {
123
123
  if (isDynamic(value)) return true;
124
- if (path.length === 0) return false;
125
124
  const [head, ...rest] = path;
125
+ if (head === void 0) return false;
126
126
  if (head === "*") return Array.isArray(value) && value.some((item) => visit(item, rest));
127
127
  return isRecord(value) && Object.prototype.hasOwnProperty.call(value, head) && visit(value[head], rest);
128
128
  };
@@ -134,8 +134,8 @@ function hasBoundChildRef(component, refs) {
134
134
  * else keeps its identity. Missing keys are left alone.
135
135
  */
136
136
  function mapAtChildRef(value, path, replace) {
137
- if (path.length === 0) return replace(value);
138
137
  const [head, ...rest] = path;
138
+ if (head === void 0) return replace(value);
139
139
  if (head === "*") {
140
140
  if (!Array.isArray(value)) return value;
141
141
  return value.map((item) => mapAtChildRef(item, rest, replace));
@@ -1 +1 @@
1
- {"version":3,"file":"child-refs.mjs","names":[],"sources":["../../src/generative-ui/child-refs.ts"],"sourcesContent":["import type { GenerativeUIJSONSchema } from \"./types\";\nimport { isRecord } from \"./is-record\";\n\n/**\n * How A2UI 1.0 marks a prop that holds a component reference: the JSON\n * Schema of the prop is a `$ref` to one of these two common types.\n * Validators and renderers find the children of a component by these refs,\n * at any depth of the props schema.\n */\nexport const A2UI_COMPONENT_ID_REF = \"common_types.json#/$defs/ComponentId\";\nexport const A2UI_CHILD_LIST_REF = \"common_types.json#/$defs/ChildList\";\n\n/**\n * The start of the `description` that marks a schema as a component\n * reference before it is turned into JSON Schema. `child()` and\n * `childList()` set it; a schema from another library can set a description\n * that starts with the same mark to get the same effect. What follows the\n * mark (after a space) stays as the description of the reference.\n */\nexport const A2UI_COMPONENT_ID_MARK = \"@a2ui/ComponentId\";\nexport const A2UI_CHILD_LIST_MARK = \"@a2ui/ChildList\";\n\nexport type ChildRefKind = \"single\" | \"multiple\";\n\n/** One component reference in a props schema. */\nexport interface ChildRef {\n /**\n * The keys from the props root to the reference. `\"*\"` stands for the\n * items of an array. `[\"tabs\", \"*\", \"child\"]` is the `child` of each\n * entry of `tabs`.\n */\n path: readonly string[];\n kind: ChildRefKind;\n}\n\n/** The ref kind of a JSON Schema node, or `undefined` for a plain value. */\nexport function childRefKind(\n schema: GenerativeUIJSONSchema,\n): ChildRefKind | undefined {\n const ref = schema.$ref;\n if (ref === A2UI_COMPONENT_ID_REF) return \"single\";\n if (ref === A2UI_CHILD_LIST_REF) return \"multiple\";\n return undefined;\n}\n\n/**\n * Turns the reference marks of a JSON Schema into A2UI `$ref`s, in place of\n * the marked node. The mark is the `description` set by `child()` and\n * `childList()`; after this, the node is `{ \"$ref\": \"common_types.json#/...\" }`.\n */\nexport function applyChildRefMarks(\n schema: GenerativeUIJSONSchema,\n): GenerativeUIJSONSchema {\n const marked = (description: unknown, mark: string, ref: string) => {\n if (typeof description !== \"string\" || !description.startsWith(mark)) {\n return undefined;\n }\n const rest = description.slice(mark.length).trim();\n return rest === \"\" ? { $ref: ref } : { $ref: ref, description: rest };\n };\n const visit = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(visit);\n if (!isRecord(node)) return node;\n const reference =\n marked(node.description, A2UI_COMPONENT_ID_MARK, A2UI_COMPONENT_ID_REF) ??\n marked(node.description, A2UI_CHILD_LIST_MARK, A2UI_CHILD_LIST_REF);\n if (reference) return reference;\n return Object.fromEntries(\n Object.entries(node).map(([key, value]) => [key, visit(value)]),\n );\n };\n return visit(schema) as GenerativeUIJSONSchema;\n}\n\n/**\n * Every component reference in a props schema, with its path. Walks\n * `properties`, array `items`, and the variants of `anyOf` / `oneOf` /\n * `allOf`. A union counts as a reference only when every alternative is\n * one of the same kind: a prop that is text in one branch and a child in\n * another cannot be told apart from its value, so it stays data.\n */\nexport function collectChildRefs(schema: GenerativeUIJSONSchema): ChildRef[] {\n const refs: ChildRef[] = [];\n const seen = new Set<string>();\n const add = (path: string[], kind: ChildRefKind) => {\n const key = path.join(\"\\u0000\");\n if (seen.has(key)) return;\n seen.add(key);\n refs.push({ path, kind });\n };\n const visit = (node: unknown, path: string[]) => {\n if (!isRecord(node)) return;\n const kind = childRefKind(node);\n if (kind) return add(path, kind);\n for (const list of [node.anyOf, node.oneOf]) {\n if (!Array.isArray(list) || list.length === 0) continue;\n const kinds = list.map((variant) =>\n isRecord(variant) ? childRefKind(variant) : undefined,\n );\n const [first] = kinds;\n if (first && kinds.every((k) => k === first)) add(path, first);\n else if (kinds.every((k) => k === undefined)) {\n // Objects in a union: a nested reference counts only when every\n // alternative has it at the same path with the same kind.\n const perVariant = list.map((variant) =>\n collectChildRefs(variant as GenerativeUIJSONSchema),\n );\n const key = (ref: ChildRef) =>\n `${ref.kind}\\u0000${ref.path.join(\"\\u0000\")}`;\n const shared = perVariant[0].filter((ref) =>\n perVariant.every((refs) => refs.some((r) => key(r) === key(ref))),\n );\n shared.forEach((ref) => add([...path, ...ref.path], ref.kind));\n }\n }\n if (Array.isArray(node.allOf)) {\n node.allOf.forEach((variant) => visit(variant, path));\n }\n if (isRecord(node.properties)) {\n for (const [key, value] of Object.entries(node.properties)) {\n visit(value, [...path, key]);\n }\n }\n if (isRecord(node.items)) visit(node.items, [...path, \"*\"]);\n };\n visit(schema, []);\n return refs;\n}\n\n/**\n * The component ids at the references of one component node: a string id,\n * a list of ids, or the `componentId` of a template, at every ref path.\n * Bound or computed values are not ids and are left out.\n */\nexport function childIdsAtRefs(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): string[] {\n const ids: string[] = [];\n const collect = (value: unknown) => {\n if (typeof value === \"string\") ids.push(value);\n else if (Array.isArray(value)) {\n value.forEach((id) => typeof id === \"string\" && ids.push(id));\n } else if (isRecord(value) && typeof value.componentId === \"string\") {\n ids.push(value.componentId);\n }\n };\n const visit = (value: unknown, path: readonly string[]) => {\n if (path.length === 0) return collect(value);\n const [head, ...rest] = path;\n if (head === \"*\") {\n if (Array.isArray(value)) value.forEach((item) => visit(item, rest));\n return;\n }\n if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, head)) {\n visit(value[head], rest);\n }\n };\n for (const ref of refs) visit(component, ref.path);\n return ids;\n}\n\n/**\n * True when a reference of the component is bound or computed (`{\"@path\"}`,\n * `{\"@call\"}`) at the ref itself or above it, so its ids are known only\n * at render time.\n */\nexport function hasBoundChildRef(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): boolean {\n const isDynamic = (value: unknown) =>\n isRecord(value) && (\"@path\" in value || \"@call\" in value);\n const visit = (value: unknown, path: readonly string[]): boolean => {\n if (isDynamic(value)) return true;\n if (path.length === 0) return false;\n const [head, ...rest] = path;\n if (head === \"*\") {\n return Array.isArray(value) && value.some((item) => visit(item, rest));\n }\n return (\n isRecord(value) &&\n Object.prototype.hasOwnProperty.call(value, head) &&\n visit(value[head], rest)\n );\n };\n return refs.some((ref) => visit(component, ref.path));\n}\n\n/**\n * Walks `value` along a ref path and replaces what sits at the end with\n * `replace(found)`. Objects and arrays on the way are copied; everything\n * else keeps its identity. Missing keys are left alone.\n */\nexport function mapAtChildRef(\n value: unknown,\n path: readonly string[],\n replace: (found: unknown) => unknown,\n): unknown {\n if (path.length === 0) return replace(value);\n const [head, ...rest] = path;\n if (head === \"*\") {\n if (!Array.isArray(value)) return value;\n return value.map((item) => mapAtChildRef(item, rest, replace));\n }\n if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, head)) {\n return value;\n }\n return { ...value, [head]: mapAtChildRef(value[head], rest, replace) };\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,wBAAwB;AACrC,MAAa,sBAAsB;;;;;;;;AASnC,MAAa,yBAAyB;AACtC,MAAa,uBAAuB;;AAgBpC,SAAgB,aACd,QAC0B;CAC1B,MAAM,MAAM,OAAO;AACnB,KAAI,QAAQ,sBAAuB,QAAO;AAC1C,KAAI,QAAQ,oBAAqB,QAAO;;;;;;;AAS1C,SAAgB,mBACd,QACwB;CACxB,MAAM,UAAU,aAAsB,MAAc,QAAgB;AAClE,MAAI,OAAO,gBAAgB,YAAY,CAAC,YAAY,WAAW,KAAK,CAClE;EAEF,MAAM,OAAO,YAAY,MAAM,KAAK,OAAO,CAAC,MAAM;AAClD,SAAO,SAAS,KAAK,EAAE,MAAM,KAAK,GAAG;GAAE,MAAM;GAAK,aAAa;GAAM;;CAEvE,MAAM,SAAS,SAA2B;AACxC,MAAI,MAAM,QAAQ,KAAK,CAAE,QAAO,KAAK,IAAI,MAAM;AAC/C,MAAI,CAAC,SAAS,KAAK,CAAE,QAAO;EAC5B,MAAM,YACJ,OAAO,KAAK,aAAa,wBAAwB,sBAAsB,IACvE,OAAO,KAAK,aAAa,sBAAsB,oBAAoB;AACrE,MAAI,UAAW,QAAO;AACtB,SAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,MAAM,MAAM,CAAC,CAAC,CAChE;;AAEH,QAAO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M,IAAI,MAAM,MAAM,SAAS,MAAM,MAAM,KAAK,CAAC;AAExE,SACE,SAAS,MAAM,IACf,OAAO,UAAU,eAAe,KAAK,OAAO,KAAK,IACjD,MAAM,MAAM,OAAO,KAAK;;AAG5B,QAAO,KAAK,MAAM,QAAQ,MAAM,WAAW,IAAI,KAAK,CAAC;;;;;;;AAQvD,SAAgB,cACd,OACA,MACA,SACS;AACT,KAAI,KAAK,WAAW,EAAG,QAAO,QAAQ,MAAM;CAC5C,MAAM,CAAC,MAAM,GAAG,QAAQ;AACxB,KAAI,SAAS,KAAK;AAChB,MAAI,CAAC,MAAM,QAAQ,MAAM,CAAE,QAAO;AAClC,SAAO,MAAM,KAAK,SAAS,cAAc,MAAM,MAAM,QAAQ,CAAC;;AAEhE,KAAI,CAAC,SAAS,MAAM,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,KAAK,CACxE,QAAO;AAET,QAAO;EAAE,GAAG;GAAQ,OAAO,cAAc,MAAM,OAAO,MAAM,QAAQ;EAAE"}
1
+ {"version":3,"file":"child-refs.mjs","names":[],"sources":["../../src/generative-ui/child-refs.ts"],"sourcesContent":["import type { GenerativeUIJSONSchema } from \"./types\";\nimport { isRecord } from \"./is-record\";\n\n/**\n * How A2UI 1.0 marks a prop that holds a component reference: the JSON\n * Schema of the prop is a `$ref` to one of these two common types.\n * Validators and renderers find the children of a component by these refs,\n * at any depth of the props schema.\n */\nexport const A2UI_COMPONENT_ID_REF = \"common_types.json#/$defs/ComponentId\";\nexport const A2UI_CHILD_LIST_REF = \"common_types.json#/$defs/ChildList\";\n\n/**\n * The start of the `description` that marks a schema as a component\n * reference before it is turned into JSON Schema. `child()` and\n * `childList()` set it; a schema from another library can set a description\n * that starts with the same mark to get the same effect. What follows the\n * mark (after a space) stays as the description of the reference.\n */\nexport const A2UI_COMPONENT_ID_MARK = \"@a2ui/ComponentId\";\nexport const A2UI_CHILD_LIST_MARK = \"@a2ui/ChildList\";\n\nexport type ChildRefKind = \"single\" | \"multiple\";\n\n/** One component reference in a props schema. */\nexport interface ChildRef {\n /**\n * The keys from the props root to the reference. `\"*\"` stands for the\n * items of an array. `[\"tabs\", \"*\", \"child\"]` is the `child` of each\n * entry of `tabs`.\n */\n path: readonly string[];\n kind: ChildRefKind;\n}\n\n/** The ref kind of a JSON Schema node, or `undefined` for a plain value. */\nexport function childRefKind(\n schema: GenerativeUIJSONSchema,\n): ChildRefKind | undefined {\n const ref = schema.$ref;\n if (ref === A2UI_COMPONENT_ID_REF) return \"single\";\n if (ref === A2UI_CHILD_LIST_REF) return \"multiple\";\n return undefined;\n}\n\n/**\n * Turns the reference marks of a JSON Schema into A2UI `$ref`s, in place of\n * the marked node. The mark is the `description` set by `child()` and\n * `childList()`; after this, the node is `{ \"$ref\": \"common_types.json#/...\" }`.\n */\nexport function applyChildRefMarks(\n schema: GenerativeUIJSONSchema,\n): GenerativeUIJSONSchema {\n const marked = (description: unknown, mark: string, ref: string) => {\n if (typeof description !== \"string\" || !description.startsWith(mark)) {\n return undefined;\n }\n const rest = description.slice(mark.length).trim();\n return rest === \"\" ? { $ref: ref } : { $ref: ref, description: rest };\n };\n const visit = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(visit);\n if (!isRecord(node)) return node;\n const reference =\n marked(node.description, A2UI_COMPONENT_ID_MARK, A2UI_COMPONENT_ID_REF) ??\n marked(node.description, A2UI_CHILD_LIST_MARK, A2UI_CHILD_LIST_REF);\n if (reference) return reference;\n return Object.fromEntries(\n Object.entries(node).map(([key, value]) => [key, visit(value)]),\n );\n };\n return visit(schema) as GenerativeUIJSONSchema;\n}\n\n/**\n * Every component reference in a props schema, with its path. Walks\n * `properties`, array `items`, and the variants of `anyOf` / `oneOf` /\n * `allOf`. A union counts as a reference only when every alternative is\n * one of the same kind: a prop that is text in one branch and a child in\n * another cannot be told apart from its value, so it stays data.\n */\nexport function collectChildRefs(schema: GenerativeUIJSONSchema): ChildRef[] {\n const refs: ChildRef[] = [];\n const seen = new Set<string>();\n const add = (path: string[], kind: ChildRefKind) => {\n const key = path.join(\"\\u0000\");\n if (seen.has(key)) return;\n seen.add(key);\n refs.push({ path, kind });\n };\n const visit = (node: unknown, path: string[]) => {\n if (!isRecord(node)) return;\n const kind = childRefKind(node);\n if (kind) return add(path, kind);\n for (const list of [node.anyOf, node.oneOf]) {\n if (!Array.isArray(list) || list.length === 0) continue;\n const kinds = list.map((variant) =>\n isRecord(variant) ? childRefKind(variant) : undefined,\n );\n const [first] = kinds;\n if (first && kinds.every((k) => k === first)) add(path, first);\n else if (kinds.every((k) => k === undefined)) {\n // Objects in a union: a nested reference counts only when every\n // alternative has it at the same path with the same kind.\n const perVariant = list.map((variant) =>\n collectChildRefs(variant as GenerativeUIJSONSchema),\n );\n const key = (ref: ChildRef) =>\n `${ref.kind}\\u0000${ref.path.join(\"\\u0000\")}`;\n // `list` is not empty (checked above), so `perVariant` is not empty.\n const shared = perVariant[0]!.filter((ref) =>\n perVariant.every((refs) => refs.some((r) => key(r) === key(ref))),\n );\n shared.forEach((ref) => add([...path, ...ref.path], ref.kind));\n }\n }\n if (Array.isArray(node.allOf)) {\n node.allOf.forEach((variant) => visit(variant, path));\n }\n if (isRecord(node.properties)) {\n for (const [key, value] of Object.entries(node.properties)) {\n visit(value, [...path, key]);\n }\n }\n if (isRecord(node.items)) visit(node.items, [...path, \"*\"]);\n };\n visit(schema, []);\n return refs;\n}\n\n/**\n * The component ids at the references of one component node: a string id,\n * a list of ids, or the `componentId` of a template, at every ref path.\n * Bound or computed values are not ids and are left out.\n */\nexport function childIdsAtRefs(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): string[] {\n const ids: string[] = [];\n const collect = (value: unknown) => {\n if (typeof value === \"string\") ids.push(value);\n else if (Array.isArray(value)) {\n value.forEach((id) => typeof id === \"string\" && ids.push(id));\n } else if (isRecord(value) && typeof value.componentId === \"string\") {\n ids.push(value.componentId);\n }\n };\n const visit = (value: unknown, path: readonly string[]) => {\n const [head, ...rest] = path;\n if (head === undefined) return collect(value);\n if (head === \"*\") {\n if (Array.isArray(value)) value.forEach((item) => visit(item, rest));\n return;\n }\n if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, head)) {\n visit(value[head], rest);\n }\n };\n for (const ref of refs) visit(component, ref.path);\n return ids;\n}\n\n/**\n * True when a reference of the component is bound or computed (`{\"@path\"}`,\n * `{\"@call\"}`) at the ref itself or above it, so its ids are known only\n * at render time.\n */\nexport function hasBoundChildRef(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): boolean {\n const isDynamic = (value: unknown) =>\n isRecord(value) && (\"@path\" in value || \"@call\" in value);\n const visit = (value: unknown, path: readonly string[]): boolean => {\n if (isDynamic(value)) return true;\n const [head, ...rest] = path;\n if (head === undefined) return false;\n if (head === \"*\") {\n return Array.isArray(value) && value.some((item) => visit(item, rest));\n }\n return (\n isRecord(value) &&\n Object.prototype.hasOwnProperty.call(value, head) &&\n visit(value[head], rest)\n );\n };\n return refs.some((ref) => visit(component, ref.path));\n}\n\n/**\n * Walks `value` along a ref path and replaces what sits at the end with\n * `replace(found)`. Objects and arrays on the way are copied; everything\n * else keeps its identity. Missing keys are left alone.\n */\nexport function mapAtChildRef(\n value: unknown,\n path: readonly string[],\n replace: (found: unknown) => unknown,\n): unknown {\n const [head, ...rest] = path;\n if (head === undefined) return replace(value);\n if (head === \"*\") {\n if (!Array.isArray(value)) return value;\n return value.map((item) => mapAtChildRef(item, rest, replace));\n }\n if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, head)) {\n return value;\n }\n return { ...value, [head]: mapAtChildRef(value[head], rest, replace) };\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,wBAAwB;AACrC,MAAa,sBAAsB;;;;;;;;AASnC,MAAa,yBAAyB;AACtC,MAAa,uBAAuB;;AAgBpC,SAAgB,aACd,QAC0B;CAC1B,MAAM,MAAM,OAAO;AACnB,KAAI,QAAQ,sBAAuB,QAAO;AAC1C,KAAI,QAAQ,oBAAqB,QAAO;;;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AAM,OAAO,MAAM,QAAQ;EAAE"}
@@ -0,0 +1,187 @@
1
+ const require_basic_functions = require('./basic-functions.cjs');
2
+ const require_child_refs = require('./child-refs.cjs');
3
+ const require_types = require('./types.cjs');
4
+
5
+ //#region src/generative-ui/compact-schema.ts
6
+ /** Objects nested deeper than this show as `object`. */
7
+ const MAX_OBJECT_DEPTH = 2;
8
+ /** A prop must appear verbatim in at least this many components to be hoisted. */
9
+ const COMMON_PROP_MIN_COMPONENTS = 8;
10
+ function isRecord(value) {
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ }
13
+ /** A JSON Schema of a list of schemas (`anyOf`, `oneOf`), else an empty list. */
14
+ function schemaList(value) {
15
+ return Array.isArray(value) ? value.filter(isRecord) : [];
16
+ }
17
+ /**
18
+ * Puts a top-level union in parentheses, so that `[]` applies to all of
19
+ * it. A union inside braces needs none.
20
+ */
21
+ function asArrayItem(type) {
22
+ let outside = type;
23
+ for (let inner = outside.replace(/\{[^{}]*\}/g, ""); inner !== outside;) {
24
+ outside = inner;
25
+ inner = outside.replace(/\{[^{}]*\}/g, "");
26
+ }
27
+ return outside.includes(" | ") ? `(${type})[]` : `${type}[]`;
28
+ }
29
+ /**
30
+ * A JSON Schema as a short TypeScript-like type, for example
31
+ * `{ label: string; size?: "sm" | "md" }`.
32
+ */
33
+ function compactType(schema, depth) {
34
+ const ref = require_child_refs.childRefKind(schema);
35
+ if (ref === "single") return "componentId";
36
+ if (ref === "multiple") return "componentId[] | { componentId: string; path: string }";
37
+ if ("const" in schema) return JSON.stringify(schema.const);
38
+ if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
39
+ const variants = [...schemaList(schema.anyOf), ...schemaList(schema.oneOf)];
40
+ if (variants.length > 0) return variants.map((variant) => compactType(variant, depth)).join(" | ");
41
+ return (Array.isArray(schema.type) ? schema.type : [schema.type]).map((type) => {
42
+ switch (type) {
43
+ case "string":
44
+ case "boolean":
45
+ case "null": return type;
46
+ case "number":
47
+ case "integer": return "number";
48
+ case "array": return isRecord(schema.items) ? asArrayItem(compactType(schema.items, depth)) : "unknown[]";
49
+ case "object": return compactObject(schema, depth);
50
+ default: return "unknown";
51
+ }
52
+ }).join(" | ");
53
+ }
54
+ /** An object schema as `{ key: type; other?: type }`. */
55
+ function compactObject(schema, depth) {
56
+ const properties = isRecord(schema.properties) ? schema.properties : {};
57
+ const entries = Object.entries(properties);
58
+ if (entries.length === 0) return isRecord(schema.additionalProperties) ? `Record<string, ${compactType(schema.additionalProperties, depth + 1)}>` : "object";
59
+ if (depth >= MAX_OBJECT_DEPTH) return "object";
60
+ const required = Array.isArray(schema.required) ? schema.required : [];
61
+ return `{ ${entries.map(([key, value]) => {
62
+ const type = isRecord(value) ? compactType(value, depth + 1) : "unknown";
63
+ return `${key}${required.includes(key) ? "" : "?"}: ${type}`;
64
+ }).join("; ")} }`;
65
+ }
66
+ /** A schema as its type, with its description after `//`. */
67
+ function describedType(schema, depth) {
68
+ const type = compactType(schema, depth);
69
+ return typeof schema.description === "string" ? `${type} // ${schema.description}` : type;
70
+ }
71
+ /**
72
+ * The props of a component: `{ "label": "string", "size?": "..." }`. With
73
+ * `descriptions`, each type carries its description after `//`.
74
+ */
75
+ function compactProps(schema, descriptions = true) {
76
+ const properties = isRecord(schema.properties) ? schema.properties : {};
77
+ const required = Array.isArray(schema.required) ? schema.required : [];
78
+ const props = {};
79
+ for (const [key, value] of Object.entries(properties)) {
80
+ if (!isRecord(value)) continue;
81
+ const name = required.includes(key) ? key : `${key}?`;
82
+ props[name] = descriptions ? describedType(value, 1) : compactType(value, 1);
83
+ }
84
+ return props;
85
+ }
86
+ /**
87
+ * The prop set worth listing once. Candidates are (key, type) pairs that at
88
+ * least {@link COMMON_PROP_MIN_COMPONENTS} components carry verbatim. The
89
+ * candidate subset of each component is a possible common set, scored by
90
+ * the characters it saves (set size times the components that contain all
91
+ * of it). `undefined` when no set is shared by enough components.
92
+ */
93
+ function findCommonProps(propsList) {
94
+ const pairKey = (key, type) => `${key}\u0000${type}`;
95
+ const counts = /* @__PURE__ */ new Map();
96
+ for (const props of propsList) for (const [key, type] of Object.entries(props)) {
97
+ const id = pairKey(key, type);
98
+ counts.set(id, (counts.get(id) ?? 0) + 1);
99
+ }
100
+ let best;
101
+ let bestScore = 0;
102
+ const seen = /* @__PURE__ */ new Set();
103
+ for (const props of propsList) {
104
+ const subset = Object.entries(props).filter(([key, type]) => (counts.get(pairKey(key, type)) ?? 0) >= COMMON_PROP_MIN_COMPONENTS);
105
+ if (subset.length < 2) continue;
106
+ const signature = subset.map(([key, type]) => pairKey(key, type)).join("\n");
107
+ if (seen.has(signature)) continue;
108
+ seen.add(signature);
109
+ const members = propsList.filter((other) => subset.every(([key, type]) => other[key] === type)).length;
110
+ if (members < COMMON_PROP_MIN_COMPONENTS) continue;
111
+ const score = subset.reduce((total, [key, type]) => total + key.length + type.length, 0) * (members - 1);
112
+ if (score > bestScore) {
113
+ bestScore = score;
114
+ best = Object.fromEntries(subset);
115
+ }
116
+ }
117
+ return best;
118
+ }
119
+ /**
120
+ * The component schema of the markdown transport, from the per-run
121
+ * manifest. It is smaller than the manifest: each prop is one short type,
122
+ * and the props that many components share verbatim (the layout props of
123
+ * the containers) are listed once in `commonProps`; a component that takes
124
+ * them is flagged `includesCommonProps`.
125
+ * It has the catalog id, the targets with their descriptions and their
126
+ * component lists, the functions with their parameters, the components
127
+ * with their props, events and slots, and the surfaces of the thread. A surface lists the
128
+ * values that the user set and the operations that the client dropped.
129
+ *
130
+ * @param manifest - The manifest from `buildGenerativeUIManifest`.
131
+ * @param options - `propDescriptions` (default true) writes each prop's
132
+ * description; `commonProps` (default true) lists shared props once.
133
+ * @returns A JSON-ready object.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * const value = JSON.stringify(
138
+ * buildCompactGenerativeUISchema(buildGenerativeUIManifest(runtime, threadId)),
139
+ * );
140
+ * ```
141
+ */
142
+ function buildCompactGenerativeUISchema(manifest, options = {}) {
143
+ const { propDescriptions = true, commonProps = true } = options;
144
+ const components = {};
145
+ for (const [name, component] of Object.entries(manifest.components)) {
146
+ const events = Object.entries(component.events ?? {}).map(([event, definition]) => [event, definition.description ?? compactType(definition.parameters, 0)]);
147
+ components[name] = {
148
+ ...component.description ? { description: component.description } : {},
149
+ props: compactProps(component.props, propDescriptions),
150
+ ...events.length > 0 ? { events: Object.fromEntries(events) } : {},
151
+ ...component.slots ? { slots: component.slots } : {}
152
+ };
153
+ }
154
+ const common = commonProps ? findCommonProps(Object.values(components).map((component) => component.props)) : void 0;
155
+ if (common) {
156
+ const commonKeys = Object.keys(common);
157
+ for (const component of Object.values(components)) {
158
+ if (!commonKeys.every((key) => component.props[key] === common[key])) continue;
159
+ component.includesCommonProps = true;
160
+ component.props = Object.fromEntries(Object.entries(component.props).filter(([key]) => !(key in common)));
161
+ }
162
+ }
163
+ const functions = Object.fromEntries(Object.entries(manifest.functions).map(([name, fn]) => {
164
+ const signature = fn.parameters.description;
165
+ const hasSignature = typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2;
166
+ const callers = require_basic_functions.functionCallers(fn);
167
+ return [name, {
168
+ ...fn.description ? { description: fn.description } : {},
169
+ parameters: hasSignature ? signature : compactType(fn.parameters, 0),
170
+ ...callers.agent && require_types.GENERATIVE_UI_AGENT_FUNCTION_CALLS ? { callers: callers.renderer ? "UI or agent" : "agent only" } : {}
171
+ }];
172
+ }));
173
+ return {
174
+ catalogId: manifest.catalogId,
175
+ targets: manifest.targets,
176
+ functions,
177
+ ...common ? { commonProps: common } : {},
178
+ components,
179
+ surfaces: manifest.surfaces
180
+ };
181
+ }
182
+
183
+ //#endregion
184
+ exports.buildCompactGenerativeUISchema = buildCompactGenerativeUISchema;
185
+ exports.compactProps = compactProps;
186
+ exports.compactType = compactType;
187
+ //# sourceMappingURL=compact-schema.cjs.map