@frontmcp/uipack 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) hide show
  1. package/CLAUDE.md +246 -0
  2. package/LICENSE +201 -0
  3. package/README.md +150 -0
  4. package/adapters/index.d.ts +13 -0
  5. package/adapters/index.d.ts.map +1 -0
  6. package/adapters/index.js +462 -0
  7. package/adapters/platform-meta.d.ts +166 -0
  8. package/adapters/platform-meta.d.ts.map +1 -0
  9. package/adapters/response-builder.d.ts +108 -0
  10. package/adapters/response-builder.d.ts.map +1 -0
  11. package/adapters/serving-mode.d.ts +107 -0
  12. package/adapters/serving-mode.d.ts.map +1 -0
  13. package/base-template/bridge.d.ts +90 -0
  14. package/base-template/bridge.d.ts.map +1 -0
  15. package/base-template/default-base-template.d.ts +92 -0
  16. package/base-template/default-base-template.d.ts.map +1 -0
  17. package/base-template/index.d.ts +15 -0
  18. package/base-template/index.d.ts.map +1 -0
  19. package/base-template/index.js +1398 -0
  20. package/base-template/polyfills.d.ts +31 -0
  21. package/base-template/polyfills.d.ts.map +1 -0
  22. package/base-template/theme-styles.d.ts +74 -0
  23. package/base-template/theme-styles.d.ts.map +1 -0
  24. package/bridge-runtime/iife-generator.d.ts +62 -0
  25. package/bridge-runtime/iife-generator.d.ts.map +1 -0
  26. package/bridge-runtime/index.d.ts +10 -0
  27. package/bridge-runtime/index.d.ts.map +1 -0
  28. package/bridge-runtime/index.js +883 -0
  29. package/build/cdn-resources.d.ts +243 -0
  30. package/build/cdn-resources.d.ts.map +1 -0
  31. package/build/index.d.ts +295 -0
  32. package/build/index.d.ts.map +1 -0
  33. package/build/index.js +6861 -0
  34. package/build/widget-manifest.d.ts +362 -0
  35. package/build/widget-manifest.d.ts.map +1 -0
  36. package/bundler/cache.d.ts +173 -0
  37. package/bundler/cache.d.ts.map +1 -0
  38. package/bundler/file-cache/component-builder.d.ts +167 -0
  39. package/bundler/file-cache/component-builder.d.ts.map +1 -0
  40. package/bundler/file-cache/hash-calculator.d.ts +155 -0
  41. package/bundler/file-cache/hash-calculator.d.ts.map +1 -0
  42. package/bundler/file-cache/index.d.ts +12 -0
  43. package/bundler/file-cache/index.d.ts.map +1 -0
  44. package/bundler/file-cache/storage/filesystem.d.ts +149 -0
  45. package/bundler/file-cache/storage/filesystem.d.ts.map +1 -0
  46. package/bundler/file-cache/storage/index.d.ts +11 -0
  47. package/bundler/file-cache/storage/index.d.ts.map +1 -0
  48. package/bundler/file-cache/storage/interface.d.ts +152 -0
  49. package/bundler/file-cache/storage/interface.d.ts.map +1 -0
  50. package/bundler/file-cache/storage/redis.d.ts +139 -0
  51. package/bundler/file-cache/storage/redis.d.ts.map +1 -0
  52. package/bundler/index.d.ts +35 -0
  53. package/bundler/index.d.ts.map +1 -0
  54. package/bundler/index.js +2947 -0
  55. package/bundler/sandbox/enclave-adapter.d.ts +121 -0
  56. package/bundler/sandbox/enclave-adapter.d.ts.map +1 -0
  57. package/bundler/sandbox/executor.d.ts +14 -0
  58. package/bundler/sandbox/executor.d.ts.map +1 -0
  59. package/bundler/sandbox/policy.d.ts +62 -0
  60. package/bundler/sandbox/policy.d.ts.map +1 -0
  61. package/bundler/types.d.ts +702 -0
  62. package/bundler/types.d.ts.map +1 -0
  63. package/dependency/cdn-registry.d.ts +98 -0
  64. package/dependency/cdn-registry.d.ts.map +1 -0
  65. package/dependency/import-map.d.ts +186 -0
  66. package/dependency/import-map.d.ts.map +1 -0
  67. package/dependency/import-parser.d.ts +82 -0
  68. package/dependency/import-parser.d.ts.map +1 -0
  69. package/dependency/index.d.ts +17 -0
  70. package/dependency/index.d.ts.map +1 -0
  71. package/dependency/index.js +3215 -0
  72. package/dependency/resolver.d.ts +164 -0
  73. package/dependency/resolver.d.ts.map +1 -0
  74. package/dependency/schemas.d.ts +486 -0
  75. package/dependency/schemas.d.ts.map +1 -0
  76. package/dependency/template-loader.d.ts +204 -0
  77. package/dependency/template-loader.d.ts.map +1 -0
  78. package/dependency/template-processor.d.ts +118 -0
  79. package/dependency/template-processor.d.ts.map +1 -0
  80. package/dependency/types.d.ts +739 -0
  81. package/dependency/types.d.ts.map +1 -0
  82. package/esm/adapters/index.d.ts +13 -0
  83. package/esm/adapters/index.d.ts.map +1 -0
  84. package/esm/adapters/index.js +427 -0
  85. package/esm/adapters/platform-meta.d.ts +166 -0
  86. package/esm/adapters/platform-meta.d.ts.map +1 -0
  87. package/esm/adapters/response-builder.d.ts +108 -0
  88. package/esm/adapters/response-builder.d.ts.map +1 -0
  89. package/esm/adapters/serving-mode.d.ts +107 -0
  90. package/esm/adapters/serving-mode.d.ts.map +1 -0
  91. package/esm/base-template/bridge.d.ts +90 -0
  92. package/esm/base-template/bridge.d.ts.map +1 -0
  93. package/esm/base-template/default-base-template.d.ts +92 -0
  94. package/esm/base-template/default-base-template.d.ts.map +1 -0
  95. package/esm/base-template/index.d.ts +15 -0
  96. package/esm/base-template/index.d.ts.map +1 -0
  97. package/esm/base-template/index.js +1364 -0
  98. package/esm/base-template/polyfills.d.ts +31 -0
  99. package/esm/base-template/polyfills.d.ts.map +1 -0
  100. package/esm/base-template/theme-styles.d.ts +74 -0
  101. package/esm/base-template/theme-styles.d.ts.map +1 -0
  102. package/esm/bridge-runtime/iife-generator.d.ts +62 -0
  103. package/esm/bridge-runtime/iife-generator.d.ts.map +1 -0
  104. package/esm/bridge-runtime/index.d.ts +10 -0
  105. package/esm/bridge-runtime/index.d.ts.map +1 -0
  106. package/esm/bridge-runtime/index.js +853 -0
  107. package/esm/build/cdn-resources.d.ts +243 -0
  108. package/esm/build/cdn-resources.d.ts.map +1 -0
  109. package/esm/build/index.d.ts +295 -0
  110. package/esm/build/index.d.ts.map +1 -0
  111. package/esm/build/index.js +6786 -0
  112. package/esm/build/widget-manifest.d.ts +362 -0
  113. package/esm/build/widget-manifest.d.ts.map +1 -0
  114. package/esm/bundler/cache.d.ts +173 -0
  115. package/esm/bundler/cache.d.ts.map +1 -0
  116. package/esm/bundler/file-cache/component-builder.d.ts +167 -0
  117. package/esm/bundler/file-cache/component-builder.d.ts.map +1 -0
  118. package/esm/bundler/file-cache/hash-calculator.d.ts +155 -0
  119. package/esm/bundler/file-cache/hash-calculator.d.ts.map +1 -0
  120. package/esm/bundler/file-cache/index.d.ts +12 -0
  121. package/esm/bundler/file-cache/index.d.ts.map +1 -0
  122. package/esm/bundler/file-cache/storage/filesystem.d.ts +149 -0
  123. package/esm/bundler/file-cache/storage/filesystem.d.ts.map +1 -0
  124. package/esm/bundler/file-cache/storage/index.d.ts +11 -0
  125. package/esm/bundler/file-cache/storage/index.d.ts.map +1 -0
  126. package/esm/bundler/file-cache/storage/interface.d.ts +152 -0
  127. package/esm/bundler/file-cache/storage/interface.d.ts.map +1 -0
  128. package/esm/bundler/file-cache/storage/redis.d.ts +139 -0
  129. package/esm/bundler/file-cache/storage/redis.d.ts.map +1 -0
  130. package/esm/bundler/index.d.ts +35 -0
  131. package/esm/bundler/index.d.ts.map +1 -0
  132. package/esm/bundler/index.js +2882 -0
  133. package/esm/bundler/sandbox/enclave-adapter.d.ts +121 -0
  134. package/esm/bundler/sandbox/enclave-adapter.d.ts.map +1 -0
  135. package/esm/bundler/sandbox/executor.d.ts +14 -0
  136. package/esm/bundler/sandbox/executor.d.ts.map +1 -0
  137. package/esm/bundler/sandbox/policy.d.ts +62 -0
  138. package/esm/bundler/sandbox/policy.d.ts.map +1 -0
  139. package/esm/bundler/types.d.ts +702 -0
  140. package/esm/bundler/types.d.ts.map +1 -0
  141. package/esm/dependency/cdn-registry.d.ts +98 -0
  142. package/esm/dependency/cdn-registry.d.ts.map +1 -0
  143. package/esm/dependency/import-map.d.ts +186 -0
  144. package/esm/dependency/import-map.d.ts.map +1 -0
  145. package/esm/dependency/import-parser.d.ts +82 -0
  146. package/esm/dependency/import-parser.d.ts.map +1 -0
  147. package/esm/dependency/index.d.ts +17 -0
  148. package/esm/dependency/index.d.ts.map +1 -0
  149. package/esm/dependency/index.js +3096 -0
  150. package/esm/dependency/resolver.d.ts +164 -0
  151. package/esm/dependency/resolver.d.ts.map +1 -0
  152. package/esm/dependency/schemas.d.ts +486 -0
  153. package/esm/dependency/schemas.d.ts.map +1 -0
  154. package/esm/dependency/template-loader.d.ts +204 -0
  155. package/esm/dependency/template-loader.d.ts.map +1 -0
  156. package/esm/dependency/template-processor.d.ts +118 -0
  157. package/esm/dependency/template-processor.d.ts.map +1 -0
  158. package/esm/dependency/types.d.ts +739 -0
  159. package/esm/dependency/types.d.ts.map +1 -0
  160. package/esm/handlebars/expression-extractor.d.ts +147 -0
  161. package/esm/handlebars/expression-extractor.d.ts.map +1 -0
  162. package/esm/handlebars/helpers.d.ts +339 -0
  163. package/esm/handlebars/helpers.d.ts.map +1 -0
  164. package/esm/handlebars/index.d.ts +195 -0
  165. package/esm/handlebars/index.d.ts.map +1 -0
  166. package/esm/handlebars/index.js +587 -0
  167. package/esm/index.d.ts +50 -0
  168. package/esm/index.d.ts.map +1 -0
  169. package/esm/index.js +12434 -0
  170. package/esm/package.json +68 -0
  171. package/esm/registry/index.d.ts +46 -0
  172. package/esm/registry/index.d.ts.map +1 -0
  173. package/esm/registry/index.js +6237 -0
  174. package/esm/registry/render-template.d.ts +91 -0
  175. package/esm/registry/render-template.d.ts.map +1 -0
  176. package/esm/registry/tool-ui.registry.d.ts +294 -0
  177. package/esm/registry/tool-ui.registry.d.ts.map +1 -0
  178. package/esm/registry/uri-utils.d.ts +56 -0
  179. package/esm/registry/uri-utils.d.ts.map +1 -0
  180. package/esm/renderers/cache.d.ts +145 -0
  181. package/esm/renderers/cache.d.ts.map +1 -0
  182. package/esm/renderers/html.renderer.d.ts +123 -0
  183. package/esm/renderers/html.renderer.d.ts.map +1 -0
  184. package/esm/renderers/index.d.ts +36 -0
  185. package/esm/renderers/index.d.ts.map +1 -0
  186. package/esm/renderers/index.js +1654 -0
  187. package/esm/renderers/mdx.renderer.d.ts +120 -0
  188. package/esm/renderers/mdx.renderer.d.ts.map +1 -0
  189. package/esm/renderers/registry.d.ts +133 -0
  190. package/esm/renderers/registry.d.ts.map +1 -0
  191. package/esm/renderers/types.d.ts +342 -0
  192. package/esm/renderers/types.d.ts.map +1 -0
  193. package/esm/renderers/utils/detect.d.ts +107 -0
  194. package/esm/renderers/utils/detect.d.ts.map +1 -0
  195. package/esm/renderers/utils/hash.d.ts +40 -0
  196. package/esm/renderers/utils/hash.d.ts.map +1 -0
  197. package/esm/renderers/utils/index.d.ts +9 -0
  198. package/esm/renderers/utils/index.d.ts.map +1 -0
  199. package/esm/renderers/utils/transpiler.d.ts +89 -0
  200. package/esm/renderers/utils/transpiler.d.ts.map +1 -0
  201. package/esm/runtime/adapters/html.adapter.d.ts +59 -0
  202. package/esm/runtime/adapters/html.adapter.d.ts.map +1 -0
  203. package/esm/runtime/adapters/index.d.ts +26 -0
  204. package/esm/runtime/adapters/index.d.ts.map +1 -0
  205. package/esm/runtime/adapters/mdx.adapter.d.ts +73 -0
  206. package/esm/runtime/adapters/mdx.adapter.d.ts.map +1 -0
  207. package/esm/runtime/adapters/types.d.ts +95 -0
  208. package/esm/runtime/adapters/types.d.ts.map +1 -0
  209. package/esm/runtime/csp.d.ts +48 -0
  210. package/esm/runtime/csp.d.ts.map +1 -0
  211. package/esm/runtime/index.d.ts +17 -0
  212. package/esm/runtime/index.d.ts.map +1 -0
  213. package/esm/runtime/index.js +4976 -0
  214. package/esm/runtime/mcp-bridge.d.ts +101 -0
  215. package/esm/runtime/mcp-bridge.d.ts.map +1 -0
  216. package/esm/runtime/renderer-runtime.d.ts +133 -0
  217. package/esm/runtime/renderer-runtime.d.ts.map +1 -0
  218. package/esm/runtime/sanitizer.d.ts +172 -0
  219. package/esm/runtime/sanitizer.d.ts.map +1 -0
  220. package/esm/runtime/types.d.ts +415 -0
  221. package/esm/runtime/types.d.ts.map +1 -0
  222. package/esm/runtime/wrapper.d.ts +421 -0
  223. package/esm/runtime/wrapper.d.ts.map +1 -0
  224. package/esm/styles/index.d.ts +8 -0
  225. package/esm/styles/index.d.ts.map +1 -0
  226. package/esm/styles/index.js +171 -0
  227. package/esm/styles/variants.d.ts +51 -0
  228. package/esm/styles/variants.d.ts.map +1 -0
  229. package/esm/theme/cdn.d.ts +195 -0
  230. package/esm/theme/cdn.d.ts.map +1 -0
  231. package/esm/theme/index.d.ts +18 -0
  232. package/esm/theme/index.d.ts.map +1 -0
  233. package/esm/theme/index.js +700 -0
  234. package/esm/theme/platforms.d.ts +107 -0
  235. package/esm/theme/platforms.d.ts.map +1 -0
  236. package/esm/theme/presets/github-openai.d.ts +50 -0
  237. package/esm/theme/presets/github-openai.d.ts.map +1 -0
  238. package/esm/theme/presets/index.d.ts +11 -0
  239. package/esm/theme/presets/index.d.ts.map +1 -0
  240. package/esm/theme/theme.d.ts +396 -0
  241. package/esm/theme/theme.d.ts.map +1 -0
  242. package/esm/tool-template/builder.d.ts +213 -0
  243. package/esm/tool-template/builder.d.ts.map +1 -0
  244. package/esm/tool-template/index.d.ts +16 -0
  245. package/esm/tool-template/index.d.ts.map +1 -0
  246. package/esm/tool-template/index.js +3518 -0
  247. package/esm/types/index.d.ts +14 -0
  248. package/esm/types/index.d.ts.map +1 -0
  249. package/esm/types/index.js +75 -0
  250. package/esm/types/ui-config.d.ts +641 -0
  251. package/esm/types/ui-config.d.ts.map +1 -0
  252. package/esm/types/ui-runtime.d.ts +1008 -0
  253. package/esm/types/ui-runtime.d.ts.map +1 -0
  254. package/esm/typings/cache/cache-adapter.d.ts +125 -0
  255. package/esm/typings/cache/cache-adapter.d.ts.map +1 -0
  256. package/esm/typings/cache/index.d.ts +10 -0
  257. package/esm/typings/cache/index.d.ts.map +1 -0
  258. package/esm/typings/cache/memory-cache.d.ts +92 -0
  259. package/esm/typings/cache/memory-cache.d.ts.map +1 -0
  260. package/esm/typings/dts-parser.d.ts +90 -0
  261. package/esm/typings/dts-parser.d.ts.map +1 -0
  262. package/esm/typings/index.d.ts +48 -0
  263. package/esm/typings/index.d.ts.map +1 -0
  264. package/esm/typings/index.js +812 -0
  265. package/esm/typings/schemas.d.ts +232 -0
  266. package/esm/typings/schemas.d.ts.map +1 -0
  267. package/esm/typings/type-fetcher.d.ts +89 -0
  268. package/esm/typings/type-fetcher.d.ts.map +1 -0
  269. package/esm/typings/types.d.ts +320 -0
  270. package/esm/typings/types.d.ts.map +1 -0
  271. package/esm/utils/escape-html.d.ts +58 -0
  272. package/esm/utils/escape-html.d.ts.map +1 -0
  273. package/esm/utils/index.d.ts +10 -0
  274. package/esm/utils/index.d.ts.map +1 -0
  275. package/esm/utils/index.js +40 -0
  276. package/esm/utils/safe-stringify.d.ts +30 -0
  277. package/esm/utils/safe-stringify.d.ts.map +1 -0
  278. package/esm/validation/error-box.d.ts +56 -0
  279. package/esm/validation/error-box.d.ts.map +1 -0
  280. package/esm/validation/index.d.ts +13 -0
  281. package/esm/validation/index.d.ts.map +1 -0
  282. package/esm/validation/index.js +542 -0
  283. package/esm/validation/schema-paths.d.ts +118 -0
  284. package/esm/validation/schema-paths.d.ts.map +1 -0
  285. package/esm/validation/template-validator.d.ts +143 -0
  286. package/esm/validation/template-validator.d.ts.map +1 -0
  287. package/esm/validation/wrapper.d.ts +97 -0
  288. package/esm/validation/wrapper.d.ts.map +1 -0
  289. package/handlebars/expression-extractor.d.ts +147 -0
  290. package/handlebars/expression-extractor.d.ts.map +1 -0
  291. package/handlebars/helpers.d.ts +339 -0
  292. package/handlebars/helpers.d.ts.map +1 -0
  293. package/handlebars/index.d.ts +195 -0
  294. package/handlebars/index.d.ts.map +1 -0
  295. package/handlebars/index.js +666 -0
  296. package/index.d.ts +50 -0
  297. package/index.d.ts.map +1 -0
  298. package/index.js +12683 -0
  299. package/package.json +66 -0
  300. package/registry/index.d.ts +46 -0
  301. package/registry/index.d.ts.map +1 -0
  302. package/registry/index.js +6280 -0
  303. package/registry/render-template.d.ts +91 -0
  304. package/registry/render-template.d.ts.map +1 -0
  305. package/registry/tool-ui.registry.d.ts +294 -0
  306. package/registry/tool-ui.registry.d.ts.map +1 -0
  307. package/registry/uri-utils.d.ts +56 -0
  308. package/registry/uri-utils.d.ts.map +1 -0
  309. package/renderers/cache.d.ts +145 -0
  310. package/renderers/cache.d.ts.map +1 -0
  311. package/renderers/html.renderer.d.ts +123 -0
  312. package/renderers/html.renderer.d.ts.map +1 -0
  313. package/renderers/index.d.ts +36 -0
  314. package/renderers/index.d.ts.map +1 -0
  315. package/renderers/index.js +1706 -0
  316. package/renderers/mdx.renderer.d.ts +120 -0
  317. package/renderers/mdx.renderer.d.ts.map +1 -0
  318. package/renderers/registry.d.ts +133 -0
  319. package/renderers/registry.d.ts.map +1 -0
  320. package/renderers/types.d.ts +342 -0
  321. package/renderers/types.d.ts.map +1 -0
  322. package/renderers/utils/detect.d.ts +107 -0
  323. package/renderers/utils/detect.d.ts.map +1 -0
  324. package/renderers/utils/hash.d.ts +40 -0
  325. package/renderers/utils/hash.d.ts.map +1 -0
  326. package/renderers/utils/index.d.ts +9 -0
  327. package/renderers/utils/index.d.ts.map +1 -0
  328. package/renderers/utils/transpiler.d.ts +89 -0
  329. package/renderers/utils/transpiler.d.ts.map +1 -0
  330. package/runtime/adapters/html.adapter.d.ts +59 -0
  331. package/runtime/adapters/html.adapter.d.ts.map +1 -0
  332. package/runtime/adapters/index.d.ts +26 -0
  333. package/runtime/adapters/index.d.ts.map +1 -0
  334. package/runtime/adapters/mdx.adapter.d.ts +73 -0
  335. package/runtime/adapters/mdx.adapter.d.ts.map +1 -0
  336. package/runtime/adapters/types.d.ts +95 -0
  337. package/runtime/adapters/types.d.ts.map +1 -0
  338. package/runtime/csp.d.ts +48 -0
  339. package/runtime/csp.d.ts.map +1 -0
  340. package/runtime/index.d.ts +17 -0
  341. package/runtime/index.d.ts.map +1 -0
  342. package/runtime/index.js +5052 -0
  343. package/runtime/mcp-bridge.d.ts +101 -0
  344. package/runtime/mcp-bridge.d.ts.map +1 -0
  345. package/runtime/renderer-runtime.d.ts +133 -0
  346. package/runtime/renderer-runtime.d.ts.map +1 -0
  347. package/runtime/sanitizer.d.ts +172 -0
  348. package/runtime/sanitizer.d.ts.map +1 -0
  349. package/runtime/types.d.ts +415 -0
  350. package/runtime/types.d.ts.map +1 -0
  351. package/runtime/wrapper.d.ts +421 -0
  352. package/runtime/wrapper.d.ts.map +1 -0
  353. package/styles/index.d.ts +8 -0
  354. package/styles/index.d.ts.map +1 -0
  355. package/styles/index.js +222 -0
  356. package/styles/variants.d.ts +51 -0
  357. package/styles/variants.d.ts.map +1 -0
  358. package/theme/cdn.d.ts +195 -0
  359. package/theme/cdn.d.ts.map +1 -0
  360. package/theme/index.d.ts +18 -0
  361. package/theme/index.d.ts.map +1 -0
  362. package/theme/index.js +757 -0
  363. package/theme/platforms.d.ts +107 -0
  364. package/theme/platforms.d.ts.map +1 -0
  365. package/theme/presets/github-openai.d.ts +50 -0
  366. package/theme/presets/github-openai.d.ts.map +1 -0
  367. package/theme/presets/index.d.ts +11 -0
  368. package/theme/presets/index.d.ts.map +1 -0
  369. package/theme/theme.d.ts +396 -0
  370. package/theme/theme.d.ts.map +1 -0
  371. package/tool-template/builder.d.ts +213 -0
  372. package/tool-template/builder.d.ts.map +1 -0
  373. package/tool-template/index.d.ts +16 -0
  374. package/tool-template/index.d.ts.map +1 -0
  375. package/tool-template/index.js +3562 -0
  376. package/types/index.d.ts +14 -0
  377. package/types/index.d.ts.map +1 -0
  378. package/types/index.js +108 -0
  379. package/types/ui-config.d.ts +641 -0
  380. package/types/ui-config.d.ts.map +1 -0
  381. package/types/ui-runtime.d.ts +1008 -0
  382. package/types/ui-runtime.d.ts.map +1 -0
  383. package/typings/cache/cache-adapter.d.ts +125 -0
  384. package/typings/cache/cache-adapter.d.ts.map +1 -0
  385. package/typings/cache/index.d.ts +10 -0
  386. package/typings/cache/index.d.ts.map +1 -0
  387. package/typings/cache/memory-cache.d.ts +92 -0
  388. package/typings/cache/memory-cache.d.ts.map +1 -0
  389. package/typings/dts-parser.d.ts +90 -0
  390. package/typings/dts-parser.d.ts.map +1 -0
  391. package/typings/index.d.ts +48 -0
  392. package/typings/index.d.ts.map +1 -0
  393. package/typings/index.js +868 -0
  394. package/typings/schemas.d.ts +232 -0
  395. package/typings/schemas.d.ts.map +1 -0
  396. package/typings/type-fetcher.d.ts +89 -0
  397. package/typings/type-fetcher.d.ts.map +1 -0
  398. package/typings/types.d.ts +320 -0
  399. package/typings/types.d.ts.map +1 -0
  400. package/utils/escape-html.d.ts +58 -0
  401. package/utils/escape-html.d.ts.map +1 -0
  402. package/utils/index.d.ts +10 -0
  403. package/utils/index.d.ts.map +1 -0
  404. package/utils/index.js +70 -0
  405. package/utils/safe-stringify.d.ts +30 -0
  406. package/utils/safe-stringify.d.ts.map +1 -0
  407. package/validation/error-box.d.ts +56 -0
  408. package/validation/error-box.d.ts.map +1 -0
  409. package/validation/index.d.ts +13 -0
  410. package/validation/index.d.ts.map +1 -0
  411. package/validation/index.js +583 -0
  412. package/validation/schema-paths.d.ts +118 -0
  413. package/validation/schema-paths.d.ts.map +1 -0
  414. package/validation/template-validator.d.ts +143 -0
  415. package/validation/template-validator.d.ts.map +1 -0
  416. package/validation/wrapper.d.ts +97 -0
  417. package/validation/wrapper.d.ts.map +1 -0
@@ -0,0 +1,3518 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // libs/uipack/src/utils/safe-stringify.ts
12
+ var init_safe_stringify = __esm({
13
+ "libs/uipack/src/utils/safe-stringify.ts"() {
14
+ "use strict";
15
+ }
16
+ });
17
+
18
+ // libs/uipack/src/utils/escape-html.ts
19
+ function escapeHtml(str) {
20
+ if (str === null || str === void 0) {
21
+ return "";
22
+ }
23
+ const s = String(str);
24
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
25
+ }
26
+ var init_escape_html = __esm({
27
+ "libs/uipack/src/utils/escape-html.ts"() {
28
+ "use strict";
29
+ }
30
+ });
31
+
32
+ // libs/uipack/src/utils/index.ts
33
+ var init_utils = __esm({
34
+ "libs/uipack/src/utils/index.ts"() {
35
+ "use strict";
36
+ init_safe_stringify();
37
+ init_escape_html();
38
+ }
39
+ });
40
+
41
+ // libs/uipack/src/handlebars/helpers.ts
42
+ function formatDate(date, format) {
43
+ if (date === null || date === void 0) {
44
+ return "";
45
+ }
46
+ let dateObj;
47
+ if (date instanceof Date) {
48
+ dateObj = date;
49
+ } else if (typeof date === "string" || typeof date === "number") {
50
+ dateObj = new Date(date);
51
+ } else {
52
+ return String(date);
53
+ }
54
+ if (isNaN(dateObj.getTime())) {
55
+ return String(date);
56
+ }
57
+ const options = {};
58
+ switch (format) {
59
+ case "short":
60
+ options.dateStyle = "short";
61
+ break;
62
+ case "medium":
63
+ options.dateStyle = "medium";
64
+ break;
65
+ case "long":
66
+ options.dateStyle = "long";
67
+ break;
68
+ case "full":
69
+ options.dateStyle = "full";
70
+ break;
71
+ case "time":
72
+ options.timeStyle = "short";
73
+ break;
74
+ case "datetime":
75
+ options.dateStyle = "medium";
76
+ options.timeStyle = "short";
77
+ break;
78
+ case "iso":
79
+ return dateObj.toISOString();
80
+ case "relative":
81
+ return formatRelativeDate(dateObj);
82
+ default:
83
+ options.dateStyle = "medium";
84
+ }
85
+ return new Intl.DateTimeFormat("en-US", options).format(dateObj);
86
+ }
87
+ function formatRelativeDate(date) {
88
+ const now = /* @__PURE__ */ new Date();
89
+ const diffMs = now.getTime() - date.getTime();
90
+ const diffSecs = Math.floor(diffMs / 1e3);
91
+ const diffMins = Math.floor(diffSecs / 60);
92
+ const diffHours = Math.floor(diffMins / 60);
93
+ const diffDays = Math.floor(diffHours / 24);
94
+ if (diffSecs < 60) {
95
+ return "just now";
96
+ } else if (diffMins < 60) {
97
+ return `${diffMins} minute${diffMins === 1 ? "" : "s"} ago`;
98
+ } else if (diffHours < 24) {
99
+ return `${diffHours} hour${diffHours === 1 ? "" : "s"} ago`;
100
+ } else if (diffDays < 7) {
101
+ return `${diffDays} day${diffDays === 1 ? "" : "s"} ago`;
102
+ } else {
103
+ return formatDate(date, "medium");
104
+ }
105
+ }
106
+ function formatCurrency(amount, currency) {
107
+ if (amount === null || amount === void 0) {
108
+ return "";
109
+ }
110
+ const num = typeof amount === "number" ? amount : parseFloat(String(amount));
111
+ if (isNaN(num)) {
112
+ return String(amount);
113
+ }
114
+ return new Intl.NumberFormat("en-US", {
115
+ style: "currency",
116
+ currency: typeof currency === "string" ? currency : "USD"
117
+ }).format(num);
118
+ }
119
+ function formatNumber(value, decimals) {
120
+ if (value === null || value === void 0) {
121
+ return "";
122
+ }
123
+ const num = typeof value === "number" ? value : parseFloat(String(value));
124
+ if (isNaN(num)) {
125
+ return String(value);
126
+ }
127
+ const options = {};
128
+ if (typeof decimals === "number") {
129
+ options.minimumFractionDigits = decimals;
130
+ options.maximumFractionDigits = decimals;
131
+ }
132
+ return new Intl.NumberFormat("en-US", options).format(num);
133
+ }
134
+ function jsonEmbed(data) {
135
+ const json2 = JSON.stringify(data ?? null);
136
+ return json2.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
137
+ }
138
+ function json(data, pretty) {
139
+ return JSON.stringify(data ?? null, null, pretty ? 2 : void 0);
140
+ }
141
+ function eq(a, b) {
142
+ return a === b;
143
+ }
144
+ function ne(a, b) {
145
+ return a !== b;
146
+ }
147
+ function gt(a, b) {
148
+ return Number(a) > Number(b);
149
+ }
150
+ function gte(a, b) {
151
+ return Number(a) >= Number(b);
152
+ }
153
+ function lt(a, b) {
154
+ return Number(a) < Number(b);
155
+ }
156
+ function lte(a, b) {
157
+ return Number(a) <= Number(b);
158
+ }
159
+ function and(a, b) {
160
+ return Boolean(a) && Boolean(b);
161
+ }
162
+ function or(a, b) {
163
+ return Boolean(a) || Boolean(b);
164
+ }
165
+ function not(value) {
166
+ return !value;
167
+ }
168
+ function first(arr) {
169
+ if (!Array.isArray(arr)) return void 0;
170
+ return arr[0];
171
+ }
172
+ function last(arr) {
173
+ if (!Array.isArray(arr)) return void 0;
174
+ return arr[arr.length - 1];
175
+ }
176
+ function length(value) {
177
+ if (Array.isArray(value)) return value.length;
178
+ if (typeof value === "string") return value.length;
179
+ return 0;
180
+ }
181
+ function includes(arr, value) {
182
+ if (!Array.isArray(arr)) return false;
183
+ return arr.includes(value);
184
+ }
185
+ function join(arr, separator) {
186
+ if (!Array.isArray(arr)) return "";
187
+ return arr.join(typeof separator === "string" ? separator : ", ");
188
+ }
189
+ function uppercase(str) {
190
+ return String(str ?? "").toUpperCase();
191
+ }
192
+ function lowercase(str) {
193
+ return String(str ?? "").toLowerCase();
194
+ }
195
+ function capitalize(str) {
196
+ const s = String(str ?? "");
197
+ return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
198
+ }
199
+ function truncate(str, maxLength, suffix) {
200
+ const s = String(str ?? "");
201
+ const len = typeof maxLength === "number" ? maxLength : 50;
202
+ const suf = typeof suffix === "string" ? suffix : "...";
203
+ if (s.length <= len) return s;
204
+ return s.slice(0, len - suf.length) + suf;
205
+ }
206
+ function defaultValue(value, defaultValue2) {
207
+ return value || defaultValue2;
208
+ }
209
+ function uniqueId(prefix) {
210
+ const id = ++idCounter;
211
+ return prefix ? `${prefix}-${id}` : `id-${id}`;
212
+ }
213
+ function resetUniqueIdCounter() {
214
+ idCounter = 0;
215
+ }
216
+ function classNames(...classes) {
217
+ return classes.filter(Boolean).map(String).join(" ");
218
+ }
219
+ var idCounter, builtinHelpers;
220
+ var init_helpers = __esm({
221
+ "libs/uipack/src/handlebars/helpers.ts"() {
222
+ "use strict";
223
+ init_utils();
224
+ idCounter = 0;
225
+ builtinHelpers = {
226
+ // Escaping
227
+ escapeHtml,
228
+ // Formatting
229
+ formatDate,
230
+ formatCurrency,
231
+ formatNumber,
232
+ json,
233
+ jsonEmbed,
234
+ // Comparison
235
+ eq,
236
+ ne,
237
+ gt,
238
+ gte,
239
+ lt,
240
+ lte,
241
+ // Logical
242
+ and,
243
+ or,
244
+ not,
245
+ // Array
246
+ first,
247
+ last,
248
+ length,
249
+ includes,
250
+ join,
251
+ // String
252
+ uppercase,
253
+ lowercase,
254
+ capitalize,
255
+ truncate,
256
+ // Utility
257
+ default: defaultValue,
258
+ uniqueId,
259
+ classNames
260
+ };
261
+ }
262
+ });
263
+
264
+ // libs/uipack/src/handlebars/expression-extractor.ts
265
+ function extractExpressions(template) {
266
+ const expressions = [];
267
+ const lines = template.split("\n");
268
+ const positionMap = buildPositionMap(template);
269
+ let match;
270
+ EXPRESSION_REGEX.lastIndex = 0;
271
+ while ((match = EXPRESSION_REGEX.exec(template)) !== null) {
272
+ const fullExpression = match[0];
273
+ const prefix = match[1];
274
+ const content = match[2].trim();
275
+ const position = positionMap.get(match.index) ?? { line: 1, column: 1 };
276
+ let type = "variable";
277
+ let helperName;
278
+ if (prefix === "/") {
279
+ type = "block-close";
280
+ helperName = content;
281
+ } else if (prefix === "#") {
282
+ type = "block";
283
+ const parts = content.split(/\s+/);
284
+ helperName = parts[0];
285
+ } else {
286
+ const parts = content.split(/\s+/);
287
+ if (parts.length > 1 && !content.startsWith("(")) {
288
+ const firstToken = parts[0];
289
+ if (!firstToken.includes(".") && !KEYWORDS.has(firstToken)) {
290
+ type = "helper";
291
+ helperName = firstToken;
292
+ }
293
+ }
294
+ }
295
+ const paths = extractPathsFromContent(content);
296
+ for (const path of paths) {
297
+ expressions.push({
298
+ path,
299
+ fullExpression,
300
+ line: position.line,
301
+ column: position.column,
302
+ type,
303
+ helperName
304
+ });
305
+ }
306
+ if (paths.length === 0 && type === "variable") {
307
+ const cleanContent = content.trim();
308
+ if (!KEYWORDS.has(cleanContent) && !cleanContent.includes(" ") && !cleanContent.startsWith("(")) {
309
+ }
310
+ }
311
+ }
312
+ return expressions;
313
+ }
314
+ function extractPathsFromContent(content) {
315
+ const paths = [];
316
+ let match;
317
+ const regex = new RegExp(PATH_REGEX.source, "g");
318
+ while ((match = regex.exec(content)) !== null) {
319
+ paths.push(match[0]);
320
+ }
321
+ return paths;
322
+ }
323
+ function buildPositionMap(template) {
324
+ const map = /* @__PURE__ */ new Map();
325
+ let line = 1;
326
+ let column = 1;
327
+ for (let i = 0; i < template.length; i++) {
328
+ map.set(i, { line, column });
329
+ if (template[i] === "\n") {
330
+ line++;
331
+ column = 1;
332
+ } else {
333
+ column++;
334
+ }
335
+ }
336
+ return map;
337
+ }
338
+ function extractVariablePaths(template) {
339
+ const expressions = extractExpressions(template);
340
+ const paths = new Set(expressions.map((e) => e.path));
341
+ return Array.from(paths);
342
+ }
343
+ function extractOutputPaths(template) {
344
+ return extractVariablePaths(template).filter((p) => p.startsWith("output."));
345
+ }
346
+ function extractInputPaths(template) {
347
+ return extractVariablePaths(template).filter((p) => p.startsWith("input."));
348
+ }
349
+ function extractStructuredContentPaths(template) {
350
+ return extractVariablePaths(template).filter((p) => p.startsWith("structuredContent."));
351
+ }
352
+ function extractAll(template) {
353
+ const expressions = extractExpressions(template);
354
+ const paths = [...new Set(expressions.map((e) => e.path))];
355
+ return {
356
+ expressions,
357
+ paths,
358
+ outputPaths: paths.filter((p) => p.startsWith("output.")),
359
+ inputPaths: paths.filter((p) => p.startsWith("input.")),
360
+ structuredContentPaths: paths.filter((p) => p.startsWith("structuredContent."))
361
+ };
362
+ }
363
+ function hasVariablePaths(template) {
364
+ return extractVariablePaths(template).length > 0;
365
+ }
366
+ function getExpressionAt(template, line, column) {
367
+ const expressions = extractExpressions(template);
368
+ return expressions.find((expr) => {
369
+ if (expr.line !== line) return false;
370
+ const exprEnd = expr.column + expr.fullExpression.length;
371
+ return column >= expr.column && column <= exprEnd;
372
+ });
373
+ }
374
+ function normalizePath(path) {
375
+ return path.replace(/\.\d+\./g, ".[].").replace(/\.\d+$/g, ".[]").replace(/\[\d+\]/g, ".[]");
376
+ }
377
+ var EXPRESSION_REGEX, PATH_REGEX, KEYWORDS;
378
+ var init_expression_extractor = __esm({
379
+ "libs/uipack/src/handlebars/expression-extractor.ts"() {
380
+ "use strict";
381
+ EXPRESSION_REGEX = /\{\{\{?(?!!)(#|\/)?([^}]+?)\}?\}\}/g;
382
+ PATH_REGEX = /\b(output|input|structuredContent)(\.[a-zA-Z_$][a-zA-Z0-9_$]*|\.\[[^\]]+\])+/g;
383
+ KEYWORDS = /* @__PURE__ */ new Set(["this", "else", "@index", "@key", "@first", "@last", "@root"]);
384
+ }
385
+ });
386
+
387
+ // libs/uipack/src/handlebars/index.ts
388
+ var handlebars_exports = {};
389
+ __export(handlebars_exports, {
390
+ HandlebarsRenderer: () => HandlebarsRenderer,
391
+ and: () => and,
392
+ builtinHelpers: () => builtinHelpers,
393
+ capitalize: () => capitalize,
394
+ classNames: () => classNames,
395
+ containsHandlebars: () => containsHandlebars,
396
+ createHandlebarsRenderer: () => createHandlebarsRenderer,
397
+ defaultValue: () => defaultValue,
398
+ eq: () => eq,
399
+ escapeHtml: () => escapeHtml,
400
+ extractAll: () => extractAll,
401
+ extractExpressions: () => extractExpressions,
402
+ extractInputPaths: () => extractInputPaths,
403
+ extractOutputPaths: () => extractOutputPaths,
404
+ extractStructuredContentPaths: () => extractStructuredContentPaths,
405
+ extractVariablePaths: () => extractVariablePaths,
406
+ first: () => first,
407
+ formatCurrency: () => formatCurrency,
408
+ formatDate: () => formatDate,
409
+ formatNumber: () => formatNumber,
410
+ getExpressionAt: () => getExpressionAt,
411
+ gt: () => gt,
412
+ gte: () => gte,
413
+ hasVariablePaths: () => hasVariablePaths,
414
+ includes: () => includes,
415
+ isHandlebarsAvailable: () => isHandlebarsAvailable,
416
+ join: () => join,
417
+ json: () => json,
418
+ jsonEmbed: () => jsonEmbed,
419
+ last: () => last,
420
+ length: () => length,
421
+ lowercase: () => lowercase,
422
+ lt: () => lt,
423
+ lte: () => lte,
424
+ ne: () => ne,
425
+ normalizePath: () => normalizePath,
426
+ not: () => not,
427
+ or: () => or,
428
+ renderTemplate: () => renderTemplate,
429
+ resetUniqueIdCounter: () => resetUniqueIdCounter,
430
+ truncate: () => truncate,
431
+ uniqueId: () => uniqueId,
432
+ uppercase: () => uppercase
433
+ });
434
+ async function loadHandlebars() {
435
+ if (Handlebars !== null) {
436
+ return Handlebars;
437
+ }
438
+ try {
439
+ Handlebars = await import("handlebars");
440
+ return Handlebars;
441
+ } catch {
442
+ throw new Error("Handlebars is required for template rendering. Install it: npm install handlebars");
443
+ }
444
+ }
445
+ async function isHandlebarsAvailable() {
446
+ try {
447
+ await loadHandlebars();
448
+ return true;
449
+ } catch {
450
+ return false;
451
+ }
452
+ }
453
+ function createHandlebarsRenderer(options) {
454
+ return new HandlebarsRenderer(options);
455
+ }
456
+ async function renderTemplate(template, context) {
457
+ const renderer = createHandlebarsRenderer();
458
+ return renderer.render(template, context);
459
+ }
460
+ function containsHandlebars(template) {
461
+ return HandlebarsRenderer.containsHandlebars(template);
462
+ }
463
+ var Handlebars, HandlebarsRenderer;
464
+ var init_handlebars = __esm({
465
+ "libs/uipack/src/handlebars/index.ts"() {
466
+ "use strict";
467
+ init_helpers();
468
+ init_helpers();
469
+ init_expression_extractor();
470
+ Handlebars = null;
471
+ HandlebarsRenderer = class {
472
+ options;
473
+ compiledTemplates = /* @__PURE__ */ new Map();
474
+ initialized = false;
475
+ hbs = null;
476
+ constructor(options = {}) {
477
+ this.options = {
478
+ strict: false,
479
+ autoEscape: true,
480
+ ...options
481
+ };
482
+ }
483
+ /**
484
+ * Initialize the renderer with Handlebars.
485
+ */
486
+ async init() {
487
+ if (this.initialized) return;
488
+ this.hbs = await loadHandlebars();
489
+ for (const [name, helper] of Object.entries(builtinHelpers)) {
490
+ this.hbs.registerHelper(name, helper);
491
+ }
492
+ if (this.options.helpers) {
493
+ for (const [name, helper] of Object.entries(this.options.helpers)) {
494
+ this.hbs.registerHelper(name, helper);
495
+ }
496
+ }
497
+ if (this.options.partials) {
498
+ for (const [name, template] of Object.entries(this.options.partials)) {
499
+ this.hbs.registerPartial(name, template);
500
+ }
501
+ }
502
+ this.initialized = true;
503
+ }
504
+ /**
505
+ * Render a Handlebars template.
506
+ *
507
+ * @param template - Template string
508
+ * @param context - Render context with input/output
509
+ * @returns Rendered HTML string
510
+ */
511
+ async render(template, context) {
512
+ await this.init();
513
+ if (!this.hbs) {
514
+ throw new Error("Handlebars not initialized");
515
+ }
516
+ let compiled = this.compiledTemplates.get(template);
517
+ if (!compiled) {
518
+ compiled = this.hbs.compile(template, {
519
+ strict: this.options.strict,
520
+ noEscape: !this.options.autoEscape
521
+ });
522
+ this.compiledTemplates.set(template, compiled);
523
+ }
524
+ const data = {
525
+ input: context.input ?? {},
526
+ output: context.output ?? {},
527
+ structuredContent: context.structuredContent,
528
+ // Also expose at root level for convenience
529
+ ...context.input,
530
+ ...typeof context.output === "object" && context.output !== null ? context.output : {}
531
+ };
532
+ try {
533
+ return compiled(data);
534
+ } catch (error) {
535
+ throw new Error(`Template rendering failed: ${error instanceof Error ? error.message : String(error)}`);
536
+ }
537
+ }
538
+ /**
539
+ * Render a template synchronously.
540
+ *
541
+ * Note: Requires Handlebars to be pre-loaded. Use `render()` for async loading.
542
+ *
543
+ * @param template - Template string
544
+ * @param context - Render context
545
+ * @returns Rendered HTML string
546
+ */
547
+ renderSync(template, context) {
548
+ if (!this.initialized || !this.hbs) {
549
+ throw new Error("HandlebarsRenderer not initialized. Call render() first or use initSync().");
550
+ }
551
+ let compiled = this.compiledTemplates.get(template);
552
+ if (!compiled) {
553
+ compiled = this.hbs.compile(template, {
554
+ strict: this.options.strict,
555
+ noEscape: !this.options.autoEscape
556
+ });
557
+ this.compiledTemplates.set(template, compiled);
558
+ }
559
+ const data = {
560
+ input: context.input ?? {},
561
+ output: context.output ?? {},
562
+ structuredContent: context.structuredContent,
563
+ ...context.input,
564
+ ...typeof context.output === "object" && context.output !== null ? context.output : {}
565
+ };
566
+ return compiled(data);
567
+ }
568
+ /**
569
+ * Initialize synchronously (for environments where Handlebars is already loaded).
570
+ */
571
+ initSync(handlebars) {
572
+ this.hbs = handlebars;
573
+ for (const [name, helper] of Object.entries(builtinHelpers)) {
574
+ this.hbs.registerHelper(name, helper);
575
+ }
576
+ if (this.options.helpers) {
577
+ for (const [name, helper] of Object.entries(this.options.helpers)) {
578
+ this.hbs.registerHelper(name, helper);
579
+ }
580
+ }
581
+ if (this.options.partials) {
582
+ for (const [name, template] of Object.entries(this.options.partials)) {
583
+ this.hbs.registerPartial(name, template);
584
+ }
585
+ }
586
+ this.initialized = true;
587
+ }
588
+ /**
589
+ * Register a custom helper.
590
+ *
591
+ * @param name - Helper name
592
+ * @param fn - Helper function
593
+ */
594
+ registerHelper(name, fn) {
595
+ if (this.hbs) {
596
+ this.hbs.registerHelper(name, fn);
597
+ }
598
+ if (!this.options.helpers) {
599
+ this.options.helpers = {};
600
+ }
601
+ this.options.helpers[name] = fn;
602
+ }
603
+ /**
604
+ * Register a partial template.
605
+ *
606
+ * @param name - Partial name
607
+ * @param template - Partial template string
608
+ */
609
+ registerPartial(name, template) {
610
+ if (this.hbs) {
611
+ this.hbs.registerPartial(name, template);
612
+ }
613
+ if (!this.options.partials) {
614
+ this.options.partials = {};
615
+ }
616
+ this.options.partials[name] = template;
617
+ }
618
+ /**
619
+ * Clear compiled template cache.
620
+ */
621
+ clearCache() {
622
+ this.compiledTemplates.clear();
623
+ }
624
+ /**
625
+ * Check if a template string contains Handlebars syntax.
626
+ *
627
+ * @param template - Template string to check
628
+ * @returns true if contains {{...}} syntax
629
+ */
630
+ static containsHandlebars(template) {
631
+ return /\{\{(?!!)[\s\S]*?\}\}/.test(template);
632
+ }
633
+ /**
634
+ * Check if the renderer is initialized.
635
+ */
636
+ get isInitialized() {
637
+ return this.initialized;
638
+ }
639
+ };
640
+ }
641
+ });
642
+
643
+ // libs/uipack/src/bridge-runtime/iife-generator.ts
644
+ function generateBridgeIIFE(options = {}) {
645
+ const { debug = false, trustedOrigins = [], minify = false } = options;
646
+ const adapters = options.adapters || ["openai", "ext-apps", "claude", "gemini", "generic"];
647
+ const parts = [];
648
+ parts.push("(function() {");
649
+ parts.push('"use strict";');
650
+ parts.push("");
651
+ if (debug) {
652
+ parts.push('function log(msg) { console.log("[FrontMcpBridge] " + msg); }');
653
+ } else {
654
+ parts.push("function log() {}");
655
+ }
656
+ parts.push("");
657
+ parts.push("var DEFAULT_SAFE_AREA = { top: 0, bottom: 0, left: 0, right: 0 };");
658
+ parts.push("");
659
+ parts.push(generateContextDetection());
660
+ parts.push("");
661
+ parts.push(generateBaseCapabilities());
662
+ parts.push("");
663
+ if (adapters.includes("openai")) {
664
+ parts.push(generateOpenAIAdapter());
665
+ parts.push("");
666
+ }
667
+ if (adapters.includes("ext-apps")) {
668
+ parts.push(generateExtAppsAdapter(trustedOrigins));
669
+ parts.push("");
670
+ }
671
+ if (adapters.includes("claude")) {
672
+ parts.push(generateClaudeAdapter());
673
+ parts.push("");
674
+ }
675
+ if (adapters.includes("gemini")) {
676
+ parts.push(generateGeminiAdapter());
677
+ parts.push("");
678
+ }
679
+ if (adapters.includes("generic")) {
680
+ parts.push(generateGenericAdapter());
681
+ parts.push("");
682
+ }
683
+ parts.push(generatePlatformDetection(adapters));
684
+ parts.push("");
685
+ parts.push(generateBridgeClass());
686
+ parts.push("");
687
+ parts.push("var bridge = new FrontMcpBridge();");
688
+ parts.push("bridge.initialize().then(function() {");
689
+ parts.push(' log("Bridge initialized with adapter: " + bridge.adapterId);');
690
+ parts.push(' window.dispatchEvent(new CustomEvent("bridge:ready", { detail: { adapter: bridge.adapterId } }));');
691
+ parts.push("}).catch(function(err) {");
692
+ parts.push(' console.error("[FrontMcpBridge] Init failed:", err);');
693
+ parts.push(' window.dispatchEvent(new CustomEvent("bridge:error", { detail: { error: err } }));');
694
+ parts.push("});");
695
+ parts.push("");
696
+ parts.push("window.FrontMcpBridge = bridge;");
697
+ parts.push("})();");
698
+ const code = parts.join("\n");
699
+ if (minify) {
700
+ return minifyJS(code);
701
+ }
702
+ return code;
703
+ }
704
+ function generateContextDetection() {
705
+ return `
706
+ function detectTheme() {
707
+ if (typeof window !== 'undefined' && window.matchMedia) {
708
+ return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
709
+ }
710
+ return 'light';
711
+ }
712
+
713
+ function detectLocale() {
714
+ if (typeof navigator !== 'undefined') {
715
+ return navigator.language || 'en-US';
716
+ }
717
+ return 'en-US';
718
+ }
719
+
720
+ function detectUserAgent() {
721
+ if (typeof navigator === 'undefined') {
722
+ return { type: 'web', hover: true, touch: false };
723
+ }
724
+ var ua = navigator.userAgent || '';
725
+ var isMobile = /iPhone|iPad|iPod|Android/i.test(ua);
726
+ var hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
727
+ var hasHover = window.matchMedia && window.matchMedia('(hover: hover)').matches;
728
+ return { type: isMobile ? 'mobile' : 'web', hover: hasHover !== false, touch: hasTouch };
729
+ }
730
+
731
+ function detectViewport() {
732
+ if (typeof window !== 'undefined') {
733
+ return { width: window.innerWidth, height: window.innerHeight };
734
+ }
735
+ return undefined;
736
+ }
737
+
738
+ function readInjectedData() {
739
+ var data = { toolInput: {}, toolOutput: undefined, structuredContent: undefined };
740
+ if (typeof window !== 'undefined') {
741
+ if (window.__mcpToolInput) data.toolInput = window.__mcpToolInput;
742
+ if (window.__mcpToolOutput) data.toolOutput = window.__mcpToolOutput;
743
+ if (window.__mcpStructuredContent) data.structuredContent = window.__mcpStructuredContent;
744
+ }
745
+ return data;
746
+ }
747
+ `.trim();
748
+ }
749
+ function generateBaseCapabilities() {
750
+ return `
751
+ var DEFAULT_CAPABILITIES = {
752
+ canCallTools: false,
753
+ canSendMessages: false,
754
+ canOpenLinks: false,
755
+ canPersistState: true,
756
+ hasNetworkAccess: true,
757
+ supportsDisplayModes: false,
758
+ supportsTheme: true
759
+ };
760
+ `.trim();
761
+ }
762
+ function generateOpenAIAdapter() {
763
+ return `
764
+ var OpenAIAdapter = {
765
+ id: 'openai',
766
+ name: 'OpenAI ChatGPT',
767
+ priority: 100,
768
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
769
+ canCallTools: true,
770
+ canSendMessages: true,
771
+ canOpenLinks: true,
772
+ supportsDisplayModes: true
773
+ }),
774
+ canHandle: function() {
775
+ if (typeof window === 'undefined') return false;
776
+ // Check for window.openai.callTool (the actual OpenAI SDK API)
777
+ if (window.openai && typeof window.openai.callTool === 'function') return true;
778
+ // Also check if we're being injected with tool metadata (OpenAI injects toolOutput)
779
+ if (window.openai && (window.openai.toolOutput !== undefined || window.openai.toolInput !== undefined)) return true;
780
+ return false;
781
+ },
782
+ initialize: function(context) {
783
+ var sdk = window.openai;
784
+ context.sdk = sdk;
785
+ // OpenAI SDK exposes theme and displayMode directly as properties
786
+ if (sdk.theme) {
787
+ context.hostContext.theme = sdk.theme;
788
+ }
789
+ if (sdk.displayMode) {
790
+ context.hostContext.displayMode = sdk.displayMode;
791
+ }
792
+ // Note: OpenAI SDK does not have an onContextChange equivalent
793
+ return Promise.resolve();
794
+ },
795
+ callTool: function(context, name, args) {
796
+ return context.sdk.callTool(name, args);
797
+ },
798
+ sendMessage: function(context, content) {
799
+ if (typeof context.sdk.sendFollowUpMessage === 'function') {
800
+ return context.sdk.sendFollowUpMessage(content);
801
+ }
802
+ return Promise.reject(new Error('Messages not supported'));
803
+ },
804
+ openLink: function(context, url) {
805
+ window.open(url, '_blank', 'noopener,noreferrer');
806
+ return Promise.resolve();
807
+ },
808
+ requestDisplayMode: function(context, mode) {
809
+ return Promise.resolve();
810
+ },
811
+ requestClose: function(context) {
812
+ return Promise.resolve();
813
+ }
814
+ };
815
+ `.trim();
816
+ }
817
+ function generateExtAppsAdapter(trustedOrigins) {
818
+ const originsArray = trustedOrigins.length > 0 ? JSON.stringify(trustedOrigins) : "[]";
819
+ return `
820
+ var ExtAppsAdapter = {
821
+ id: 'ext-apps',
822
+ name: 'ext-apps (SEP-1865)',
823
+ priority: 80,
824
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, { canPersistState: true, hasNetworkAccess: true }),
825
+ trustedOrigins: ${originsArray},
826
+ trustedOrigin: null,
827
+ pendingRequests: {},
828
+ requestId: 0,
829
+ hostCapabilities: {},
830
+ canHandle: function() {
831
+ if (typeof window === 'undefined') return false;
832
+ if (window.parent === window) return false;
833
+ // Check for OpenAI SDK (window.openai.callTool) - defer to OpenAIAdapter
834
+ if (window.openai && typeof window.openai.callTool === 'function') return false;
835
+ if (window.__mcpPlatform === 'ext-apps') return true;
836
+ return true;
837
+ },
838
+ initialize: function(context) {
839
+ var self = this;
840
+ context.extApps = this;
841
+
842
+ window.addEventListener('message', function(event) {
843
+ self.handleMessage(context, event);
844
+ });
845
+
846
+ return self.performHandshake(context);
847
+ },
848
+ handleMessage: function(context, event) {
849
+ if (!this.isOriginTrusted(event.origin)) return;
850
+ var data = event.data;
851
+ if (!data || typeof data !== 'object' || data.jsonrpc !== '2.0') return;
852
+
853
+ if ('id' in data && (data.result !== undefined || data.error !== undefined)) {
854
+ var pending = this.pendingRequests[data.id];
855
+ if (pending) {
856
+ clearTimeout(pending.timeout);
857
+ delete this.pendingRequests[data.id];
858
+ if (data.error) {
859
+ pending.reject(new Error(data.error.message + ' (code: ' + data.error.code + ')'));
860
+ } else {
861
+ pending.resolve(data.result);
862
+ }
863
+ }
864
+ return;
865
+ }
866
+
867
+ if ('method' in data && !('id' in data)) {
868
+ this.handleNotification(context, data);
869
+ }
870
+ },
871
+ handleNotification: function(context, notification) {
872
+ var params = notification.params || {};
873
+ switch (notification.method) {
874
+ case 'ui/notifications/tool-input':
875
+ context.toolInput = params.arguments || {};
876
+ window.dispatchEvent(new CustomEvent('tool:input', { detail: { arguments: context.toolInput } }));
877
+ break;
878
+ case 'ui/notifications/tool-result':
879
+ context.toolOutput = params.content;
880
+ context.structuredContent = params.structuredContent;
881
+ context.notifyToolResult(params.content);
882
+ window.dispatchEvent(new CustomEvent('tool:result', { detail: params }));
883
+ break;
884
+ case 'ui/notifications/host-context-changed':
885
+ Object.assign(context.hostContext, params);
886
+ context.notifyContextChange(params);
887
+ break;
888
+ }
889
+ },
890
+ isOriginTrusted: function(origin) {
891
+ if (this.trustedOrigins.length > 0) {
892
+ return this.trustedOrigins.indexOf(origin) !== -1;
893
+ }
894
+ // When no trusted origins configured, trust first message origin (trust-on-first-use).
895
+ // SECURITY WARNING: This creates a race condition - whichever iframe sends the first
896
+ // message establishes permanent trust. For production, always configure trustedOrigins.
897
+ if (!this.trustedOrigin) {
898
+ if (window.parent !== window && origin) {
899
+ this.trustedOrigin = origin;
900
+ return true;
901
+ }
902
+ return false;
903
+ }
904
+ return this.trustedOrigin === origin;
905
+ },
906
+ sendRequest: function(method, params) {
907
+ var self = this;
908
+ return new Promise(function(resolve, reject) {
909
+ // Security: Require trusted origin before sending requests to prevent message leaks
910
+ if (!self.trustedOrigin && self.trustedOrigins.length === 0) {
911
+ reject(new Error('Cannot send request: no trusted origin established'));
912
+ return;
913
+ }
914
+
915
+ var id = ++self.requestId;
916
+ var timeout = setTimeout(function() {
917
+ delete self.pendingRequests[id];
918
+ reject(new Error('Request ' + method + ' timed out'));
919
+ }, 10000);
920
+
921
+ self.pendingRequests[id] = { resolve: resolve, reject: reject, timeout: timeout };
922
+
923
+ var targetOrigin = self.trustedOrigin || self.trustedOrigins[0];
924
+ window.parent.postMessage({ jsonrpc: '2.0', id: id, method: method, params: params }, targetOrigin);
925
+ });
926
+ },
927
+ performHandshake: function(context) {
928
+ var self = this;
929
+ var params = {
930
+ appInfo: { name: 'FrontMCP Widget', version: '1.0.0' },
931
+ appCapabilities: { tools: { listChanged: false } },
932
+ protocolVersion: '2024-11-05'
933
+ };
934
+
935
+ return this.sendRequest('ui/initialize', params).then(function(result) {
936
+ self.hostCapabilities = result.hostCapabilities || {};
937
+ self.capabilities = Object.assign({}, self.capabilities, {
938
+ canCallTools: Boolean(self.hostCapabilities.serverToolProxy),
939
+ canSendMessages: true,
940
+ canOpenLinks: Boolean(self.hostCapabilities.openLink),
941
+ supportsDisplayModes: true
942
+ });
943
+ if (result.hostContext) {
944
+ Object.assign(context.hostContext, result.hostContext);
945
+ }
946
+ });
947
+ },
948
+ callTool: function(context, name, args) {
949
+ if (!this.hostCapabilities.serverToolProxy) {
950
+ return Promise.reject(new Error('Server tool proxy not supported'));
951
+ }
952
+ return this.sendRequest('ui/callServerTool', { name: name, arguments: args });
953
+ },
954
+ sendMessage: function(context, content) {
955
+ return this.sendRequest('ui/message', { content: content });
956
+ },
957
+ openLink: function(context, url) {
958
+ if (!this.hostCapabilities.openLink) {
959
+ window.open(url, '_blank', 'noopener,noreferrer');
960
+ return Promise.resolve();
961
+ }
962
+ return this.sendRequest('ui/openLink', { url: url });
963
+ },
964
+ requestDisplayMode: function(context, mode) {
965
+ return this.sendRequest('ui/setDisplayMode', { mode: mode });
966
+ },
967
+ requestClose: function(context) {
968
+ return this.sendRequest('ui/close', {});
969
+ }
970
+ };
971
+ `.trim();
972
+ }
973
+ function generateClaudeAdapter() {
974
+ return `
975
+ var ClaudeAdapter = {
976
+ id: 'claude',
977
+ name: 'Claude (Anthropic)',
978
+ priority: 60,
979
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
980
+ canCallTools: false,
981
+ canSendMessages: false,
982
+ canOpenLinks: true,
983
+ hasNetworkAccess: false,
984
+ supportsDisplayModes: false
985
+ }),
986
+ canHandle: function() {
987
+ if (typeof window === 'undefined') return false;
988
+ if (window.__mcpPlatform === 'claude') return true;
989
+ if (window.claude) return true;
990
+ if (window.__claudeArtifact) return true;
991
+ if (typeof location !== 'undefined') {
992
+ var href = location.href;
993
+ if (href.indexOf('claude.ai') !== -1 || href.indexOf('anthropic.com') !== -1) return true;
994
+ }
995
+ return false;
996
+ },
997
+ initialize: function(context) {
998
+ return Promise.resolve();
999
+ },
1000
+ callTool: function() {
1001
+ return Promise.reject(new Error('Tool calls not supported in Claude'));
1002
+ },
1003
+ sendMessage: function() {
1004
+ return Promise.reject(new Error('Messages not supported in Claude'));
1005
+ },
1006
+ openLink: function(context, url) {
1007
+ window.open(url, '_blank', 'noopener,noreferrer');
1008
+ return Promise.resolve();
1009
+ },
1010
+ requestDisplayMode: function() {
1011
+ return Promise.resolve();
1012
+ },
1013
+ requestClose: function() {
1014
+ return Promise.resolve();
1015
+ }
1016
+ };
1017
+ `.trim();
1018
+ }
1019
+ function generateGeminiAdapter() {
1020
+ return `
1021
+ var GeminiAdapter = {
1022
+ id: 'gemini',
1023
+ name: 'Google Gemini',
1024
+ priority: 40,
1025
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
1026
+ canOpenLinks: true,
1027
+ hasNetworkAccess: true
1028
+ }),
1029
+ canHandle: function() {
1030
+ if (typeof window === 'undefined') return false;
1031
+ if (window.__mcpPlatform === 'gemini') return true;
1032
+ if (window.gemini) return true;
1033
+ if (typeof location !== 'undefined') {
1034
+ var href = location.href;
1035
+ if (href.indexOf('gemini.google.com') !== -1 || href.indexOf('bard.google.com') !== -1) return true;
1036
+ }
1037
+ return false;
1038
+ },
1039
+ initialize: function(context) {
1040
+ if (window.gemini && window.gemini.ui && window.gemini.ui.getTheme) {
1041
+ context.hostContext.theme = window.gemini.ui.getTheme() === 'dark' ? 'dark' : 'light';
1042
+ }
1043
+ return Promise.resolve();
1044
+ },
1045
+ callTool: function() {
1046
+ return Promise.reject(new Error('Tool calls not supported in Gemini'));
1047
+ },
1048
+ sendMessage: function(context, content) {
1049
+ if (window.gemini && window.gemini.ui && window.gemini.ui.sendMessage) {
1050
+ return window.gemini.ui.sendMessage(content);
1051
+ }
1052
+ return Promise.reject(new Error('Messages not supported in Gemini'));
1053
+ },
1054
+ openLink: function(context, url) {
1055
+ if (window.gemini && window.gemini.ui && window.gemini.ui.openLink) {
1056
+ return window.gemini.ui.openLink(url);
1057
+ }
1058
+ window.open(url, '_blank', 'noopener,noreferrer');
1059
+ return Promise.resolve();
1060
+ },
1061
+ requestDisplayMode: function() {
1062
+ return Promise.resolve();
1063
+ },
1064
+ requestClose: function() {
1065
+ return Promise.resolve();
1066
+ }
1067
+ };
1068
+ `.trim();
1069
+ }
1070
+ function generateGenericAdapter() {
1071
+ return `
1072
+ var GenericAdapter = {
1073
+ id: 'generic',
1074
+ name: 'Generic Web',
1075
+ priority: 0,
1076
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
1077
+ canOpenLinks: true,
1078
+ hasNetworkAccess: true
1079
+ }),
1080
+ canHandle: function() {
1081
+ return typeof window !== 'undefined';
1082
+ },
1083
+ initialize: function(context) {
1084
+ return Promise.resolve();
1085
+ },
1086
+ callTool: function() {
1087
+ return Promise.reject(new Error('Tool calls not supported'));
1088
+ },
1089
+ sendMessage: function() {
1090
+ return Promise.reject(new Error('Messages not supported'));
1091
+ },
1092
+ openLink: function(context, url) {
1093
+ window.open(url, '_blank', 'noopener,noreferrer');
1094
+ return Promise.resolve();
1095
+ },
1096
+ requestDisplayMode: function() {
1097
+ return Promise.resolve();
1098
+ },
1099
+ requestClose: function() {
1100
+ return Promise.resolve();
1101
+ }
1102
+ };
1103
+ `.trim();
1104
+ }
1105
+ function generatePlatformDetection(adapters) {
1106
+ const adapterVars = adapters.map((a) => {
1107
+ switch (a) {
1108
+ case "openai":
1109
+ return "OpenAIAdapter";
1110
+ case "ext-apps":
1111
+ return "ExtAppsAdapter";
1112
+ case "claude":
1113
+ return "ClaudeAdapter";
1114
+ case "gemini":
1115
+ return "GeminiAdapter";
1116
+ case "generic":
1117
+ return "GenericAdapter";
1118
+ default:
1119
+ return "";
1120
+ }
1121
+ }).filter(Boolean);
1122
+ return `
1123
+ var ADAPTERS = [${adapterVars.join(", ")}].sort(function(a, b) { return b.priority - a.priority; });
1124
+
1125
+ function detectPlatform() {
1126
+ for (var i = 0; i < ADAPTERS.length; i++) {
1127
+ if (ADAPTERS[i].canHandle()) {
1128
+ log('Detected platform: ' + ADAPTERS[i].id);
1129
+ return ADAPTERS[i];
1130
+ }
1131
+ }
1132
+ log('No platform detected, using generic');
1133
+ return GenericAdapter;
1134
+ }
1135
+ `.trim();
1136
+ }
1137
+ function generateBridgeClass() {
1138
+ return `
1139
+ function FrontMcpBridge() {
1140
+ this._adapter = null;
1141
+ this._initialized = false;
1142
+ this._context = {
1143
+ hostContext: {
1144
+ theme: detectTheme(),
1145
+ displayMode: 'inline',
1146
+ locale: detectLocale(),
1147
+ userAgent: detectUserAgent(),
1148
+ safeArea: DEFAULT_SAFE_AREA,
1149
+ viewport: detectViewport()
1150
+ },
1151
+ toolInput: {},
1152
+ toolOutput: undefined,
1153
+ structuredContent: undefined,
1154
+ widgetState: {},
1155
+ contextListeners: [],
1156
+ toolResultListeners: [],
1157
+ notifyContextChange: function(changes) {
1158
+ Object.assign(this.hostContext, changes);
1159
+ for (var i = 0; i < this.contextListeners.length; i++) {
1160
+ try { this.contextListeners[i](changes); } catch(e) {}
1161
+ }
1162
+ },
1163
+ notifyToolResult: function(result) {
1164
+ this.toolOutput = result;
1165
+ for (var i = 0; i < this.toolResultListeners.length; i++) {
1166
+ try { this.toolResultListeners[i](result); } catch(e) {}
1167
+ }
1168
+ }
1169
+ };
1170
+
1171
+ var injected = readInjectedData();
1172
+ this._context.toolInput = injected.toolInput;
1173
+ this._context.toolOutput = injected.toolOutput;
1174
+ this._context.structuredContent = injected.structuredContent;
1175
+
1176
+ this._loadWidgetState();
1177
+ }
1178
+
1179
+ FrontMcpBridge.prototype._loadWidgetState = function() {
1180
+ try {
1181
+ var key = 'frontmcp:widget:' + (window.__mcpToolName || 'unknown');
1182
+ var stored = localStorage.getItem(key);
1183
+ if (stored) this._context.widgetState = JSON.parse(stored);
1184
+ } catch(e) {}
1185
+ };
1186
+
1187
+ FrontMcpBridge.prototype._saveWidgetState = function() {
1188
+ try {
1189
+ var key = 'frontmcp:widget:' + (window.__mcpToolName || 'unknown');
1190
+ localStorage.setItem(key, JSON.stringify(this._context.widgetState));
1191
+ } catch(e) {}
1192
+ };
1193
+
1194
+ FrontMcpBridge.prototype.initialize = function() {
1195
+ if (this._initialized) return Promise.resolve();
1196
+ var self = this;
1197
+ this._adapter = detectPlatform();
1198
+ return this._adapter.initialize(this._context).then(function() {
1199
+ self._initialized = true;
1200
+ // Set up the data-tool-call click handler after initialization
1201
+ self._setupDataToolCallHandler();
1202
+ });
1203
+ };
1204
+
1205
+ Object.defineProperty(FrontMcpBridge.prototype, 'initialized', { get: function() { return this._initialized; } });
1206
+ Object.defineProperty(FrontMcpBridge.prototype, 'adapterId', { get: function() { return this._adapter ? this._adapter.id : undefined; } });
1207
+ Object.defineProperty(FrontMcpBridge.prototype, 'capabilities', { get: function() { return this._adapter ? this._adapter.capabilities : DEFAULT_CAPABILITIES; } });
1208
+
1209
+ FrontMcpBridge.prototype.getTheme = function() { return this._context.hostContext.theme; };
1210
+ FrontMcpBridge.prototype.getDisplayMode = function() { return this._context.hostContext.displayMode; };
1211
+ FrontMcpBridge.prototype.getToolInput = function() { return this._context.toolInput; };
1212
+ FrontMcpBridge.prototype.getToolOutput = function() { return this._context.toolOutput; };
1213
+ FrontMcpBridge.prototype.getStructuredContent = function() { return this._context.structuredContent; };
1214
+ FrontMcpBridge.prototype.getWidgetState = function() { return this._context.widgetState; };
1215
+ FrontMcpBridge.prototype.getHostContext = function() { return Object.assign({}, this._context.hostContext); };
1216
+ FrontMcpBridge.prototype.hasCapability = function(cap) { return this._adapter && this._adapter.capabilities[cap] === true; };
1217
+
1218
+ // Get tool response metadata (platform-agnostic)
1219
+ // Used by inline mode widgets to detect when ui/html arrives
1220
+ FrontMcpBridge.prototype.getToolResponseMetadata = function() {
1221
+ // OpenAI injects toolResponseMetadata for widget-producing tools
1222
+ if (typeof window !== 'undefined' && window.openai && window.openai.toolResponseMetadata) {
1223
+ return window.openai.toolResponseMetadata;
1224
+ }
1225
+ // Claude (future support)
1226
+ if (typeof window !== 'undefined' && window.claude && window.claude.toolResponseMetadata) {
1227
+ return window.claude.toolResponseMetadata;
1228
+ }
1229
+ // FrontMCP direct injection (for testing/ext-apps)
1230
+ if (typeof window !== 'undefined' && window.__mcpToolResponseMetadata) {
1231
+ return window.__mcpToolResponseMetadata;
1232
+ }
1233
+ return null;
1234
+ };
1235
+
1236
+ // Subscribe to tool response metadata changes (for inline mode injection)
1237
+ FrontMcpBridge.prototype.onToolResponseMetadata = function(callback) {
1238
+ var self = this;
1239
+ var called = false;
1240
+
1241
+ // Check if already available
1242
+ var existing = self.getToolResponseMetadata();
1243
+ if (existing) {
1244
+ called = true;
1245
+ callback(existing);
1246
+ }
1247
+
1248
+ // Set up property interceptors for OpenAI
1249
+ if (typeof window !== 'undefined') {
1250
+ // OpenAI: Intercept toolResponseMetadata assignment
1251
+ if (!window.__frontmcpMetadataIntercepted) {
1252
+ window.__frontmcpMetadataIntercepted = true;
1253
+ window.__frontmcpMetadataCallbacks = [];
1254
+
1255
+ // Create openai object if it doesn't exist
1256
+ if (!window.openai) window.openai = {};
1257
+
1258
+ var originalMetadata = window.openai.toolResponseMetadata;
1259
+ Object.defineProperty(window.openai, 'toolResponseMetadata', {
1260
+ get: function() { return originalMetadata; },
1261
+ set: function(val) {
1262
+ originalMetadata = val;
1263
+ log('toolResponseMetadata set, notifying ' + window.__frontmcpMetadataCallbacks.length + ' listeners');
1264
+ for (var i = 0; i < window.__frontmcpMetadataCallbacks.length; i++) {
1265
+ try { window.__frontmcpMetadataCallbacks[i](val); } catch(e) {}
1266
+ }
1267
+ },
1268
+ configurable: true
1269
+ });
1270
+ }
1271
+
1272
+ // Register callback wrapper (store reference for unsubscribe)
1273
+ var wrapper = function(metadata) {
1274
+ if (!called) {
1275
+ called = true;
1276
+ callback(metadata);
1277
+ }
1278
+ };
1279
+ window.__frontmcpMetadataCallbacks.push(wrapper);
1280
+
1281
+ // Return unsubscribe function that removes the wrapper (not the original callback)
1282
+ return function() {
1283
+ if (window.__frontmcpMetadataCallbacks) {
1284
+ var idx = window.__frontmcpMetadataCallbacks.indexOf(wrapper);
1285
+ if (idx !== -1) window.__frontmcpMetadataCallbacks.splice(idx, 1);
1286
+ }
1287
+ };
1288
+ }
1289
+
1290
+ // Return no-op unsubscribe for non-window environments
1291
+ return function() {};
1292
+ };
1293
+
1294
+ FrontMcpBridge.prototype.callTool = function(name, args) {
1295
+ // Priority 1: Direct OpenAI SDK call (most reliable in OpenAI iframe)
1296
+ // This bypasses adapter abstraction for maximum compatibility
1297
+ if (typeof window !== 'undefined' && window.openai && typeof window.openai.callTool === 'function') {
1298
+ log('callTool: Using OpenAI SDK directly');
1299
+ return window.openai.callTool(name, args);
1300
+ }
1301
+
1302
+ // Priority 2: Use adapter (if initialized and supports tool calls)
1303
+ if (this._adapter && this._adapter.capabilities && this._adapter.capabilities.canCallTools) {
1304
+ log('callTool: Using adapter ' + this._adapter.id);
1305
+ return this._adapter.callTool(this._context, name, args);
1306
+ }
1307
+
1308
+ // Not initialized or no tool support
1309
+ if (!this._adapter) {
1310
+ return Promise.reject(new Error('Bridge not initialized. Wait for bridge:ready event.'));
1311
+ }
1312
+ return Promise.reject(new Error('Tool calls not supported on this platform (' + this._adapter.id + ')'));
1313
+ };
1314
+
1315
+ FrontMcpBridge.prototype.sendMessage = function(content) {
1316
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1317
+ return this._adapter.sendMessage(this._context, content);
1318
+ };
1319
+
1320
+ FrontMcpBridge.prototype.openLink = function(url) {
1321
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1322
+ return this._adapter.openLink(this._context, url);
1323
+ };
1324
+
1325
+ FrontMcpBridge.prototype.requestDisplayMode = function(mode) {
1326
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1327
+ var self = this;
1328
+ return this._adapter.requestDisplayMode(this._context, mode).then(function() {
1329
+ self._context.hostContext.displayMode = mode;
1330
+ });
1331
+ };
1332
+
1333
+ FrontMcpBridge.prototype.requestClose = function() {
1334
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1335
+ return this._adapter.requestClose(this._context);
1336
+ };
1337
+
1338
+ FrontMcpBridge.prototype.setWidgetState = function(state) {
1339
+ Object.assign(this._context.widgetState, state);
1340
+ this._saveWidgetState();
1341
+ };
1342
+
1343
+ FrontMcpBridge.prototype.onContextChange = function(callback) {
1344
+ var listeners = this._context.contextListeners;
1345
+ listeners.push(callback);
1346
+ return function() {
1347
+ var idx = listeners.indexOf(callback);
1348
+ if (idx !== -1) listeners.splice(idx, 1);
1349
+ };
1350
+ };
1351
+
1352
+ FrontMcpBridge.prototype.onToolResult = function(callback) {
1353
+ var listeners = this._context.toolResultListeners;
1354
+ listeners.push(callback);
1355
+ return function() {
1356
+ var idx = listeners.indexOf(callback);
1357
+ if (idx !== -1) listeners.splice(idx, 1);
1358
+ };
1359
+ };
1360
+
1361
+ // ==================== data-tool-call Click Handler ====================
1362
+
1363
+ FrontMcpBridge.prototype._setupDataToolCallHandler = function() {
1364
+ var self = this;
1365
+
1366
+ document.addEventListener('click', function(e) {
1367
+ // Find the closest element with data-tool-call attribute
1368
+ var target = e.target;
1369
+ while (target && target !== document) {
1370
+ if (target.hasAttribute && target.hasAttribute('data-tool-call')) {
1371
+ var toolName = target.getAttribute('data-tool-call');
1372
+ var argsAttr = target.getAttribute('data-tool-args');
1373
+ var args = {};
1374
+
1375
+ try {
1376
+ if (argsAttr) {
1377
+ args = JSON.parse(argsAttr);
1378
+ }
1379
+ } catch (parseErr) {
1380
+ console.error('[frontmcp] Failed to parse data-tool-args:', parseErr);
1381
+ }
1382
+
1383
+ log('data-tool-call clicked: ' + toolName);
1384
+
1385
+ // Show loading state - save original content first
1386
+ var originalContent = target.innerHTML;
1387
+ var originalDisabled = target.disabled;
1388
+ target.disabled = true;
1389
+ target.classList.add('opacity-50', 'cursor-not-allowed');
1390
+
1391
+ // Add spinner for buttons
1392
+ var spinner = '<svg class="animate-spin -ml-1 mr-2 h-4 w-4 inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>';
1393
+ if (target.tagName === 'BUTTON') {
1394
+ target.innerHTML = spinner + 'Loading...';
1395
+ }
1396
+
1397
+ // Helper to reset button state
1398
+ function resetButton() {
1399
+ target.innerHTML = originalContent;
1400
+ target.disabled = originalDisabled;
1401
+ target.classList.remove('opacity-50', 'cursor-not-allowed');
1402
+ }
1403
+
1404
+ // Determine how to call the tool
1405
+ var toolCallPromise;
1406
+
1407
+ // Priority 1: Direct OpenAI SDK call (bypasses adapter abstraction)
1408
+ if (typeof window !== 'undefined' && window.openai && typeof window.openai.callTool === 'function') {
1409
+ log('Using OpenAI SDK directly for tool call');
1410
+ toolCallPromise = window.openai.callTool(toolName, args);
1411
+ }
1412
+ // Priority 2: Use adapter (if it supports tool calls)
1413
+ else if (self.hasCapability('canCallTools')) {
1414
+ log('Using adapter for tool call');
1415
+ toolCallPromise = self.callTool(toolName, args);
1416
+ }
1417
+ // No tool call capability
1418
+ else {
1419
+ console.error('[frontmcp] Tool calls not supported on this platform (' + self.adapterId + ')');
1420
+ resetButton();
1421
+ target.dispatchEvent(new CustomEvent('tool:error', {
1422
+ detail: { name: toolName, args: args, error: 'Tool calls not supported on this platform' },
1423
+ bubbles: true
1424
+ }));
1425
+ e.preventDefault();
1426
+ return;
1427
+ }
1428
+
1429
+ // Handle the tool call result
1430
+ toolCallPromise.then(function(result) {
1431
+ log('Tool call succeeded: ' + toolName);
1432
+ resetButton();
1433
+
1434
+ // Update bridge state to trigger widget re-render
1435
+ // React isn't hydrated in OpenAI iframe, so useState doesn't work
1436
+ // Instead, we use the bridge's reactive state system
1437
+ if (result && window.__frontmcp && window.__frontmcp.bridge && typeof window.__frontmcp.bridge.setWidgetState === 'function') {
1438
+ var newData = result.structuredContent || result;
1439
+ log('Updating bridge state with new data');
1440
+ window.__frontmcp.bridge.setWidgetState(newData);
1441
+ }
1442
+
1443
+ // Dispatch success event
1444
+ target.dispatchEvent(new CustomEvent('tool:success', {
1445
+ detail: { name: toolName, args: args, result: result },
1446
+ bubbles: true
1447
+ }));
1448
+ }).catch(function(err) {
1449
+ console.error('[frontmcp] Tool call failed: ' + toolName, err);
1450
+ resetButton();
1451
+ // Dispatch error event
1452
+ target.dispatchEvent(new CustomEvent('tool:error', {
1453
+ detail: { name: toolName, args: args, error: err.message || err },
1454
+ bubbles: true
1455
+ }));
1456
+ });
1457
+
1458
+ // Prevent default behavior (e.g., form submission)
1459
+ e.preventDefault();
1460
+ return;
1461
+ }
1462
+ target = target.parentElement;
1463
+ }
1464
+ }, true); // Use capture phase to handle before React handlers
1465
+ };
1466
+ `.trim();
1467
+ }
1468
+ function minifyJS(code) {
1469
+ return code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "").replace(/\s+/g, " ").replace(/\s*([{};,:()[\]])\s*/g, "$1").replace(/;\}/g, "}").trim();
1470
+ }
1471
+ function generatePlatformBundle(platform, options = {}) {
1472
+ const platformAdapters = {
1473
+ chatgpt: ["openai", "generic"],
1474
+ claude: ["claude", "generic"],
1475
+ gemini: ["gemini", "generic"],
1476
+ universal: ["openai", "ext-apps", "claude", "gemini", "generic"]
1477
+ };
1478
+ return generateBridgeIIFE({
1479
+ ...options,
1480
+ adapters: platformAdapters[platform]
1481
+ });
1482
+ }
1483
+ var UNIVERSAL_BRIDGE_SCRIPT = generateBridgeIIFE();
1484
+ var BRIDGE_SCRIPT_TAGS = {
1485
+ universal: `<script>${UNIVERSAL_BRIDGE_SCRIPT}</script>`,
1486
+ chatgpt: `<script>${generatePlatformBundle("chatgpt")}</script>`,
1487
+ claude: `<script>${generatePlatformBundle("claude")}</script>`,
1488
+ gemini: `<script>${generatePlatformBundle("gemini")}</script>`
1489
+ };
1490
+
1491
+ // libs/uipack/src/runtime/mcp-bridge.ts
1492
+ var MCP_BRIDGE_RUNTIME = `
1493
+ <script>
1494
+ (function() {
1495
+ 'use strict';
1496
+
1497
+ // ==================== Environment Detection ====================
1498
+
1499
+ var isOpenAI = typeof window.openai !== 'undefined';
1500
+ var isExtApps = window.parent !== window && !isOpenAI;
1501
+ var isClaude = typeof window.claude !== 'undefined' ||
1502
+ (window.__mcpPlatform === 'claude');
1503
+ var isGemini = window.__mcpPlatform === 'gemini';
1504
+
1505
+ // ==================== Internal State ====================
1506
+
1507
+ var messageId = 0;
1508
+ var pendingRequests = new Map();
1509
+ var contextChangeListeners = [];
1510
+ var toolResultListeners = [];
1511
+
1512
+ // Default values for polyfilled properties
1513
+ var defaultSafeArea = { top: 0, bottom: 0, left: 0, right: 0 };
1514
+ var defaultUserAgent = { type: 'web', hover: true, touch: false };
1515
+
1516
+ // Host context (for ext-apps and polyfill mode)
1517
+ var hostContext = window.__mcpHostContext || {
1518
+ theme: 'light',
1519
+ displayMode: 'inline'
1520
+ };
1521
+
1522
+ // Trusted origin for postMessage validation (set during ext-apps initialization)
1523
+ var trustedOrigin = null;
1524
+
1525
+ // Detect device capabilities
1526
+ var detectUserAgent = function() {
1527
+ var ua = navigator.userAgent || '';
1528
+ var isMobile = /iPhone|iPad|iPod|Android/i.test(ua);
1529
+ var hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
1530
+ var hasHover = window.matchMedia && window.matchMedia('(hover: hover)').matches;
1531
+ return {
1532
+ type: isMobile ? 'mobile' : 'web',
1533
+ hover: hasHover !== false,
1534
+ touch: hasTouch
1535
+ };
1536
+ };
1537
+
1538
+ // Detect theme from system preference
1539
+ var detectTheme = function() {
1540
+ if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
1541
+ return 'dark';
1542
+ }
1543
+ return 'light';
1544
+ };
1545
+
1546
+ // ==================== Bridge Implementation ====================
1547
+
1548
+ /**
1549
+ * MCP Bridge provides full OpenAI API compatibility.
1550
+ * On OpenAI, it proxies directly to window.openai.
1551
+ * On other platforms, it provides polyfills.
1552
+ */
1553
+ var bridge = {
1554
+ // ==================== Environment Info ====================
1555
+
1556
+ get provider() {
1557
+ if (isOpenAI) return 'openai';
1558
+ if (isClaude) return 'claude';
1559
+ if (isGemini) return 'gemini';
1560
+ if (isExtApps) return 'ext-apps';
1561
+ return 'unknown';
1562
+ },
1563
+
1564
+ // ==================== OpenAI-Compatible Properties ====================
1565
+
1566
+ get theme() {
1567
+ if (isOpenAI && window.openai) {
1568
+ return window.openai.theme || 'light';
1569
+ }
1570
+ return hostContext.theme || detectTheme();
1571
+ },
1572
+
1573
+ get userAgent() {
1574
+ if (isOpenAI && window.openai && window.openai.userAgent) {
1575
+ return window.openai.userAgent;
1576
+ }
1577
+ return hostContext.userAgent || detectUserAgent();
1578
+ },
1579
+
1580
+ get locale() {
1581
+ if (isOpenAI && window.openai && window.openai.locale) {
1582
+ return window.openai.locale;
1583
+ }
1584
+ return navigator.language || 'en-US';
1585
+ },
1586
+
1587
+ get maxHeight() {
1588
+ if (isOpenAI && window.openai) {
1589
+ return window.openai.maxHeight;
1590
+ }
1591
+ return hostContext.viewport ? hostContext.viewport.maxHeight : undefined;
1592
+ },
1593
+
1594
+ get displayMode() {
1595
+ if (isOpenAI && window.openai) {
1596
+ return window.openai.displayMode || 'inline';
1597
+ }
1598
+ return hostContext.displayMode || 'inline';
1599
+ },
1600
+
1601
+ get safeArea() {
1602
+ if (isOpenAI && window.openai && window.openai.safeArea) {
1603
+ return window.openai.safeArea;
1604
+ }
1605
+ return hostContext.safeArea || defaultSafeArea;
1606
+ },
1607
+
1608
+ get toolInput() {
1609
+ if (isOpenAI && window.openai && window.openai.toolInput) {
1610
+ return window.openai.toolInput;
1611
+ }
1612
+ return window.__mcpToolInput || {};
1613
+ },
1614
+
1615
+ get toolOutput() {
1616
+ if (isOpenAI && window.openai) {
1617
+ return window.openai.toolOutput;
1618
+ }
1619
+ return window.__mcpToolOutput;
1620
+ },
1621
+
1622
+ get structuredContent() {
1623
+ // Alias for toolOutput to maintain compatibility
1624
+ if (isOpenAI && window.openai) {
1625
+ return window.openai.toolOutput;
1626
+ }
1627
+ return window.__mcpStructuredContent;
1628
+ },
1629
+
1630
+ get toolResponseMetadata() {
1631
+ if (isOpenAI && window.openai && window.openai.toolResponseMetadata) {
1632
+ return window.openai.toolResponseMetadata;
1633
+ }
1634
+ return window.__mcpToolResponseMetadata || {};
1635
+ },
1636
+
1637
+ get widgetState() {
1638
+ if (isOpenAI && window.openai) {
1639
+ return window.openai.widgetState || {};
1640
+ }
1641
+ // Polyfill: use localStorage
1642
+ try {
1643
+ var stored = localStorage.getItem('__mcpWidgetState');
1644
+ return stored ? JSON.parse(stored) : {};
1645
+ } catch (e) {
1646
+ return {};
1647
+ }
1648
+ },
1649
+
1650
+ // ==================== OpenAI-Compatible Methods ====================
1651
+
1652
+ callTool: function(name, params) {
1653
+ if (isOpenAI && window.openai && window.openai.callTool) {
1654
+ return window.openai.callTool(name, params);
1655
+ }
1656
+ if (isClaude) {
1657
+ return Promise.reject(new Error(
1658
+ 'Tool calls are not supported in Claude widgets (network-blocked sandbox)'
1659
+ ));
1660
+ }
1661
+ if (isGemini) {
1662
+ return Promise.reject(new Error(
1663
+ 'Tool calls are not supported in Gemini widgets'
1664
+ ));
1665
+ }
1666
+ if (isExtApps) {
1667
+ return this._sendRequest('tools/call', { name: name, arguments: params });
1668
+ }
1669
+ return Promise.reject(new Error('Tool calls not supported in this environment'));
1670
+ },
1671
+
1672
+ requestDisplayMode: function(options) {
1673
+ if (isOpenAI && window.openai && window.openai.requestDisplayMode) {
1674
+ return window.openai.requestDisplayMode(options);
1675
+ }
1676
+ if (isExtApps) {
1677
+ return this._sendRequest('ui/request-display-mode', options);
1678
+ }
1679
+ // Polyfill: just update local state
1680
+ if (options && options.mode) {
1681
+ hostContext.displayMode = options.mode;
1682
+ contextChangeListeners.forEach(function(cb) {
1683
+ try { cb({ displayMode: options.mode }); } catch (e) {}
1684
+ });
1685
+ }
1686
+ return Promise.resolve();
1687
+ },
1688
+
1689
+ requestClose: function() {
1690
+ if (isOpenAI && window.openai && window.openai.requestClose) {
1691
+ return window.openai.requestClose();
1692
+ }
1693
+ if (isExtApps) {
1694
+ return this._sendRequest('ui/request-close', {});
1695
+ }
1696
+ // Polyfill: dispatch event for parent to handle
1697
+ window.dispatchEvent(new CustomEvent('mcp:request-close'));
1698
+ return Promise.resolve();
1699
+ },
1700
+
1701
+ openExternal: function(options) {
1702
+ var href = typeof options === 'string' ? options : (options && options.href);
1703
+ if (!href) {
1704
+ return Promise.reject(new Error('URL required'));
1705
+ }
1706
+ if (isOpenAI && window.openai && window.openai.openExternal) {
1707
+ return window.openai.openExternal({ href: href });
1708
+ }
1709
+ if (isExtApps) {
1710
+ return this._sendRequest('ui/open-link', { url: href });
1711
+ }
1712
+ // Fallback: open in new window
1713
+ window.open(href, '_blank', 'noopener,noreferrer');
1714
+ return Promise.resolve();
1715
+ },
1716
+
1717
+ // Alias for openExternal (backwards compatibility)
1718
+ openLink: function(url) {
1719
+ return this.openExternal({ href: url });
1720
+ },
1721
+
1722
+ sendFollowUpMessage: function(options) {
1723
+ var prompt = typeof options === 'string' ? options : (options && options.prompt);
1724
+ if (!prompt) {
1725
+ return Promise.reject(new Error('Prompt required'));
1726
+ }
1727
+ if (isOpenAI && window.openai && window.openai.sendFollowUpMessage) {
1728
+ return window.openai.sendFollowUpMessage({ prompt: prompt });
1729
+ }
1730
+ if (isClaude) {
1731
+ return Promise.reject(new Error(
1732
+ 'Follow-up messages are not supported in Claude widgets (network-blocked sandbox)'
1733
+ ));
1734
+ }
1735
+ if (isGemini) {
1736
+ return Promise.reject(new Error(
1737
+ 'Follow-up messages are not supported in Gemini widgets'
1738
+ ));
1739
+ }
1740
+ if (isExtApps) {
1741
+ return this._sendRequest('ui/message', {
1742
+ role: 'user',
1743
+ content: { type: 'text', text: prompt }
1744
+ });
1745
+ }
1746
+ return Promise.reject(new Error('Messages not supported in this environment'));
1747
+ },
1748
+
1749
+ // Alias for sendFollowUpMessage (backwards compatibility)
1750
+ sendMessage: function(content) {
1751
+ return this.sendFollowUpMessage({ prompt: content });
1752
+ },
1753
+
1754
+ setWidgetState: function(state) {
1755
+ if (isOpenAI && window.openai && window.openai.setWidgetState) {
1756
+ window.openai.setWidgetState(state);
1757
+ return;
1758
+ }
1759
+ // Polyfill: persist to localStorage
1760
+ try {
1761
+ localStorage.setItem('__mcpWidgetState', JSON.stringify(state));
1762
+ } catch (e) {
1763
+ console.warn('Failed to persist widget state:', e);
1764
+ }
1765
+ },
1766
+
1767
+ // ==================== Context API (MCP-specific) ====================
1768
+
1769
+ get context() {
1770
+ return {
1771
+ theme: this.theme,
1772
+ displayMode: this.displayMode,
1773
+ viewport: this.maxHeight ? { maxHeight: this.maxHeight } : undefined,
1774
+ userAgent: this.userAgent,
1775
+ locale: this.locale,
1776
+ safeArea: this.safeArea
1777
+ };
1778
+ },
1779
+
1780
+ onContextChange: function(callback) {
1781
+ contextChangeListeners.push(callback);
1782
+ return function() {
1783
+ var index = contextChangeListeners.indexOf(callback);
1784
+ if (index > -1) contextChangeListeners.splice(index, 1);
1785
+ };
1786
+ },
1787
+
1788
+ onToolResult: function(callback) {
1789
+ toolResultListeners.push(callback);
1790
+ return function() {
1791
+ var index = toolResultListeners.indexOf(callback);
1792
+ if (index > -1) toolResultListeners.splice(index, 1);
1793
+ };
1794
+ },
1795
+
1796
+ // ==================== Internal Methods ====================
1797
+
1798
+ _sendRequest: function(method, params) {
1799
+ return new Promise(function(resolve, reject) {
1800
+ var id = ++messageId;
1801
+ pendingRequests.set(id, { resolve: resolve, reject: reject });
1802
+
1803
+ window.parent.postMessage({
1804
+ jsonrpc: '2.0',
1805
+ id: id,
1806
+ method: method,
1807
+ params: params
1808
+ }, '*');
1809
+
1810
+ // Timeout after 30s
1811
+ setTimeout(function() {
1812
+ if (pendingRequests.has(id)) {
1813
+ pendingRequests.delete(id);
1814
+ reject(new Error('Request timeout'));
1815
+ }
1816
+ }, 30000);
1817
+ });
1818
+ },
1819
+
1820
+ _initExtApps: function() {
1821
+ var self = this;
1822
+ return this._sendRequest('ui/initialize', {}).then(function(result) {
1823
+ if (result && result.hostContext) {
1824
+ hostContext = Object.assign(hostContext, result.hostContext);
1825
+ }
1826
+ // Note: trustedOrigin is now set from first message event origin (trust-on-first-use)
1827
+ // Send initialized notification
1828
+ window.parent.postMessage({
1829
+ jsonrpc: '2.0',
1830
+ method: 'ui/notifications/initialized',
1831
+ params: {}
1832
+ }, '*');
1833
+ return result;
1834
+ });
1835
+ }
1836
+ };
1837
+
1838
+ // ==================== Event Handling ====================
1839
+
1840
+ window.addEventListener('message', function(event) {
1841
+ var data = event.data;
1842
+ if (!data || data.jsonrpc !== '2.0') return;
1843
+
1844
+ // Trust-on-first-use: Establish trusted origin from the first valid message
1845
+ if (isExtApps && !trustedOrigin && event.origin) {
1846
+ trustedOrigin = event.origin;
1847
+ }
1848
+
1849
+ // Validate origin for ext-apps environment to prevent spoofed messages
1850
+ if (isExtApps && trustedOrigin && event.origin !== trustedOrigin) {
1851
+ console.warn('MCP Bridge: Ignoring message from untrusted origin:', event.origin);
1852
+ return;
1853
+ }
1854
+
1855
+ // Handle responses
1856
+ if (data.id && pendingRequests.has(data.id)) {
1857
+ var pending = pendingRequests.get(data.id);
1858
+ pendingRequests.delete(data.id);
1859
+
1860
+ if (data.error) {
1861
+ var err = new Error(data.error.message || 'Unknown error');
1862
+ err.code = data.error.code;
1863
+ err.data = data.error.data;
1864
+ pending.reject(err);
1865
+ } else {
1866
+ pending.resolve(data.result);
1867
+ }
1868
+ return;
1869
+ }
1870
+
1871
+ // Handle notifications
1872
+ switch (data.method) {
1873
+ case 'ui/notifications/tool-input':
1874
+ window.__mcpToolInput = data.params && data.params.arguments;
1875
+ window.dispatchEvent(new CustomEvent('mcp:tool-input', { detail: data.params }));
1876
+ break;
1877
+
1878
+ case 'ui/notifications/tool-input-partial':
1879
+ if (data.params && data.params.arguments) {
1880
+ window.__mcpToolInput = Object.assign(window.__mcpToolInput || {}, data.params.arguments);
1881
+ }
1882
+ break;
1883
+
1884
+ case 'ui/notifications/tool-result':
1885
+ window.__mcpToolOutput = data.params && data.params.content;
1886
+ window.__mcpStructuredContent = data.params && data.params.structuredContent;
1887
+ toolResultListeners.forEach(function(cb) {
1888
+ try { cb(data.params); } catch (e) { console.error('Tool result listener error:', e); }
1889
+ });
1890
+ window.dispatchEvent(new CustomEvent('mcp:tool-result', { detail: data.params }));
1891
+ break;
1892
+
1893
+ case 'ui/notifications/tool-cancelled':
1894
+ window.dispatchEvent(new CustomEvent('mcp:tool-cancelled', { detail: data.params }));
1895
+ break;
1896
+
1897
+ case 'ui/host-context-change':
1898
+ hostContext = Object.assign(hostContext, data.params);
1899
+ contextChangeListeners.forEach(function(cb) {
1900
+ try { cb(data.params); } catch (e) { console.error('Context change listener error:', e); }
1901
+ });
1902
+ window.dispatchEvent(new CustomEvent('mcp:context-change', { detail: data.params }));
1903
+ break;
1904
+
1905
+ case 'ui/size-change':
1906
+ if (hostContext.viewport) {
1907
+ hostContext.viewport = Object.assign(hostContext.viewport, data.params);
1908
+ } else {
1909
+ hostContext.viewport = data.params;
1910
+ }
1911
+ break;
1912
+ }
1913
+ });
1914
+
1915
+ // ==================== Initialize ====================
1916
+
1917
+ // Export bridge
1918
+ window.mcpBridge = bridge;
1919
+
1920
+ // Also create window.openai polyfill for non-OpenAI platforms
1921
+ // This allows code written for OpenAI to work on other platforms
1922
+ if (!isOpenAI) {
1923
+ window.openai = {
1924
+ get theme() { return bridge.theme; },
1925
+ get userAgent() { return bridge.userAgent; },
1926
+ get locale() { return bridge.locale; },
1927
+ get maxHeight() { return bridge.maxHeight; },
1928
+ get displayMode() { return bridge.displayMode; },
1929
+ get safeArea() { return bridge.safeArea; },
1930
+ get toolInput() { return bridge.toolInput; },
1931
+ get toolOutput() { return bridge.toolOutput; },
1932
+ get toolResponseMetadata() { return bridge.toolResponseMetadata; },
1933
+ get widgetState() { return bridge.widgetState; },
1934
+ callTool: function(n, a) { return bridge.callTool(n, a); },
1935
+ requestDisplayMode: function(o) { return bridge.requestDisplayMode(o); },
1936
+ requestClose: function() { return bridge.requestClose(); },
1937
+ openExternal: function(o) { return bridge.openExternal(o); },
1938
+ sendFollowUpMessage: function(o) { return bridge.sendFollowUpMessage(o); },
1939
+ setWidgetState: function(s) { return bridge.setWidgetState(s); }
1940
+ };
1941
+ }
1942
+
1943
+ // Auto-initialize for ext-apps
1944
+ if (isExtApps) {
1945
+ bridge._initExtApps().catch(function(err) {
1946
+ console.warn('Failed to initialize MCP bridge:', err);
1947
+ });
1948
+ }
1949
+
1950
+ // Dispatch ready event
1951
+ window.dispatchEvent(new CustomEvent('mcp:bridge-ready'));
1952
+ })();
1953
+ </script>
1954
+ `;
1955
+ var FRONTMCP_BRIDGE_RUNTIME = BRIDGE_SCRIPT_TAGS.universal;
1956
+
1957
+ // libs/uipack/src/runtime/csp.ts
1958
+ var DEFAULT_CDN_DOMAINS = [
1959
+ "https://cdn.jsdelivr.net",
1960
+ // Tailwind, Alpine, React, icons
1961
+ "https://cdnjs.cloudflare.com",
1962
+ // HTMX, other libraries
1963
+ "https://fonts.googleapis.com",
1964
+ // Google Fonts stylesheets
1965
+ "https://fonts.gstatic.com"
1966
+ // Google Fonts files
1967
+ ];
1968
+ var DEFAULT_CSP_DIRECTIVES = [
1969
+ "default-src 'none'",
1970
+ `script-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1971
+ `style-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1972
+ `img-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1973
+ `font-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1974
+ "connect-src 'none'"
1975
+ ];
1976
+ function buildCSPDirectives(csp) {
1977
+ if (!csp) {
1978
+ return [...DEFAULT_CSP_DIRECTIVES];
1979
+ }
1980
+ const validResourceDomains = sanitizeCSPDomains(csp.resourceDomains);
1981
+ const validConnectDomains = sanitizeCSPDomains(csp.connectDomains);
1982
+ const allResourceDomains = [.../* @__PURE__ */ new Set([...DEFAULT_CDN_DOMAINS, ...validResourceDomains])];
1983
+ const directives = [
1984
+ "default-src 'none'",
1985
+ `script-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`,
1986
+ `style-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`
1987
+ ];
1988
+ const imgSources = ["'self'", "data:", ...allResourceDomains];
1989
+ directives.push(`img-src ${imgSources.join(" ")}`);
1990
+ const fontSources = ["'self'", "data:", ...allResourceDomains];
1991
+ directives.push(`font-src ${fontSources.join(" ")}`);
1992
+ if (validConnectDomains.length) {
1993
+ directives.push(`connect-src ${validConnectDomains.join(" ")}`);
1994
+ } else {
1995
+ directives.push("connect-src 'none'");
1996
+ }
1997
+ return directives;
1998
+ }
1999
+ function buildCSPMetaTag(csp) {
2000
+ const directives = buildCSPDirectives(csp);
2001
+ const content = directives.join("; ");
2002
+ return `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(content)}">`;
2003
+ }
2004
+ function escapeAttribute(str) {
2005
+ return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2006
+ }
2007
+ function validateCSPDomain(domain) {
2008
+ if (domain.startsWith("https://*.")) {
2009
+ const rest = domain.slice(10);
2010
+ return /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.[a-zA-Z]{2,}$/.test(rest);
2011
+ }
2012
+ try {
2013
+ const url = new URL(domain);
2014
+ return url.protocol === "https:";
2015
+ } catch {
2016
+ return false;
2017
+ }
2018
+ }
2019
+ function sanitizeCSPDomains(domains) {
2020
+ if (!domains) return [];
2021
+ const valid = [];
2022
+ for (const domain of domains) {
2023
+ if (validateCSPDomain(domain)) {
2024
+ valid.push(domain);
2025
+ } else {
2026
+ console.warn(`Invalid CSP domain ignored: ${domain}`);
2027
+ }
2028
+ }
2029
+ return valid;
2030
+ }
2031
+
2032
+ // libs/uipack/src/theme/cdn.ts
2033
+ var CDN = {
2034
+ /**
2035
+ * Tailwind CSS v4 Browser CDN
2036
+ * Generates styles on-the-fly with @theme support
2037
+ * @see https://tailwindcss.com/docs/installation/play-cdn
2038
+ */
2039
+ tailwind: "https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",
2040
+ /**
2041
+ * HTMX 2.x - High power tools for HTML
2042
+ * Enables AJAX, WebSockets, Server Sent Events directly in HTML
2043
+ * @see https://htmx.org
2044
+ */
2045
+ htmx: {
2046
+ url: "https://cdnjs.cloudflare.com/ajax/libs/htmx/2.0.7/htmx.min.js",
2047
+ integrity: "sha512-T6VLg/MJYMbLTmQ8VLvonbWg8VOvmDhXcOvHzCwo6ShdGuUU5SEcp1IAPXL4k9lVoMi8gRXl5K/S/zh43Y9rJA=="
2048
+ },
2049
+ /**
2050
+ * Alpine.js - Lightweight reactive framework
2051
+ * Used for more complex client-side interactions
2052
+ * @see https://alpinejs.dev
2053
+ */
2054
+ alpine: {
2055
+ url: "https://cdn.jsdelivr.net/npm/alpinejs@3.14.3/dist/cdn.min.js",
2056
+ integrity: "sha384-6zY8MFQJ/EqS1r4RJl+7j8rvZPuBWpT0RzWf+IFcKhxqUzQNmJzA1X1VEVZhYaEz"
2057
+ },
2058
+ /**
2059
+ * Google Fonts - Inter for modern UI typography
2060
+ */
2061
+ fonts: {
2062
+ preconnect: ["https://fonts.googleapis.com", "https://fonts.gstatic.com"],
2063
+ inter: "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap",
2064
+ mono: "https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&display=swap"
2065
+ },
2066
+ /**
2067
+ * Lucide Icons - Beautiful & consistent icons
2068
+ * @see https://lucide.dev
2069
+ */
2070
+ icons: {
2071
+ url: "https://cdn.jsdelivr.net/npm/lucide@0.294.0/dist/umd/lucide.min.js",
2072
+ integrity: "sha384-wpLmHb7v7V1LsEuTmPQ9tXqWZvTtRWWVqJuE+Yz6X0I6O2T6bHJVeXH1lVWqF4qE"
2073
+ }
2074
+ };
2075
+ var scriptCache = /* @__PURE__ */ new Map();
2076
+ function getCachedScript(url) {
2077
+ return scriptCache.get(url);
2078
+ }
2079
+ function isScriptCached(url) {
2080
+ return scriptCache.has(url);
2081
+ }
2082
+ function buildFontPreconnect() {
2083
+ return CDN.fonts.preconnect.map((url, i) => `<link rel="preconnect" href="${url}"${i > 0 ? " crossorigin" : ""}>`).join("\n ");
2084
+ }
2085
+ function buildFontStylesheets(options = {}) {
2086
+ const { inter = true, mono = false } = options;
2087
+ const links = [];
2088
+ if (inter) {
2089
+ links.push(`<link href="${CDN.fonts.inter}" rel="stylesheet">`);
2090
+ }
2091
+ if (mono) {
2092
+ links.push(`<link href="${CDN.fonts.mono}" rel="stylesheet">`);
2093
+ }
2094
+ return links.join("\n ");
2095
+ }
2096
+ function buildScriptTag(url, integrity, options = {}) {
2097
+ const attrs = [`src="${url}"`];
2098
+ if (integrity) {
2099
+ attrs.push(`integrity="${integrity}"`);
2100
+ attrs.push('crossorigin="anonymous"');
2101
+ }
2102
+ if (options.defer) attrs.push("defer");
2103
+ if (options.async) attrs.push("async");
2104
+ return `<script ${attrs.join(" ")}></script>`;
2105
+ }
2106
+ function buildInlineScriptTag(content) {
2107
+ return `<script>${content}</script>`;
2108
+ }
2109
+ function buildCdnScripts(options = {}) {
2110
+ const { tailwind = true, htmx = true, alpine = false, icons = false, inline = false } = options;
2111
+ const scripts = [];
2112
+ if (inline) {
2113
+ if (tailwind) {
2114
+ if (isScriptCached(CDN.tailwind)) {
2115
+ scripts.push(buildInlineScriptTag(getCachedScript(CDN.tailwind)));
2116
+ } else {
2117
+ console.warn(
2118
+ "[frontmcp/ui] Inline mode requested but Tailwind script not cached. Call fetchAndCacheScripts() first."
2119
+ );
2120
+ }
2121
+ }
2122
+ if (htmx) {
2123
+ if (isScriptCached(CDN.htmx.url)) {
2124
+ scripts.push(buildInlineScriptTag(getCachedScript(CDN.htmx.url)));
2125
+ } else {
2126
+ console.warn(
2127
+ "[frontmcp/ui] Inline mode requested but HTMX script not cached. Call fetchAndCacheScripts() first."
2128
+ );
2129
+ }
2130
+ }
2131
+ if (alpine) {
2132
+ if (isScriptCached(CDN.alpine.url)) {
2133
+ scripts.push(buildInlineScriptTag(getCachedScript(CDN.alpine.url)));
2134
+ } else {
2135
+ console.warn(
2136
+ "[frontmcp/ui] Inline mode requested but Alpine.js script not cached. Call fetchAndCacheScripts() first."
2137
+ );
2138
+ }
2139
+ }
2140
+ if (icons) {
2141
+ if (isScriptCached(CDN.icons.url)) {
2142
+ scripts.push(buildInlineScriptTag(getCachedScript(CDN.icons.url)));
2143
+ } else {
2144
+ console.warn(
2145
+ "[frontmcp/ui] Inline mode requested but Lucide icons script not cached. Call fetchAndCacheScripts() first."
2146
+ );
2147
+ }
2148
+ }
2149
+ } else {
2150
+ if (tailwind) {
2151
+ scripts.push(buildScriptTag(CDN.tailwind));
2152
+ }
2153
+ if (htmx) {
2154
+ scripts.push(buildScriptTag(CDN.htmx.url, CDN.htmx.integrity));
2155
+ }
2156
+ if (alpine) {
2157
+ scripts.push(buildScriptTag(CDN.alpine.url, CDN.alpine.integrity, { defer: true }));
2158
+ }
2159
+ if (icons) {
2160
+ scripts.push(buildScriptTag(CDN.icons.url, CDN.icons.integrity));
2161
+ }
2162
+ }
2163
+ return scripts.join("\n ");
2164
+ }
2165
+
2166
+ // libs/uipack/src/theme/platforms.ts
2167
+ var OPENAI_PLATFORM = {
2168
+ id: "openai",
2169
+ name: "OpenAI",
2170
+ supportsWidgets: true,
2171
+ supportsTailwind: true,
2172
+ supportsHtmx: true,
2173
+ networkMode: "full",
2174
+ scriptStrategy: "cdn",
2175
+ options: {
2176
+ sdk: "apps-sdk",
2177
+ version: "1.0"
2178
+ }
2179
+ };
2180
+ var CLAUDE_PLATFORM = {
2181
+ id: "claude",
2182
+ name: "Claude (Artifacts)",
2183
+ supportsWidgets: true,
2184
+ supportsTailwind: true,
2185
+ supportsHtmx: false,
2186
+ // Network blocked, HTMX won't work for API calls
2187
+ networkMode: "blocked",
2188
+ scriptStrategy: "inline",
2189
+ maxInlineSize: 100 * 1024,
2190
+ // 100KB limit for artifacts
2191
+ cspRestrictions: ["script-src 'unsafe-inline'", "connect-src 'none'"],
2192
+ options: {
2193
+ mode: "artifacts",
2194
+ framework: "react"
2195
+ // Claude artifacts prefer React
2196
+ }
2197
+ };
2198
+ function canUseCdn(platform) {
2199
+ return platform.networkMode === "full" && platform.scriptStrategy === "cdn";
2200
+ }
2201
+ function needsInlineScripts(platform) {
2202
+ return platform.scriptStrategy === "inline" || platform.networkMode === "blocked";
2203
+ }
2204
+
2205
+ // libs/uipack/src/theme/presets/github-openai.ts
2206
+ var GITHUB_OPENAI_THEME = {
2207
+ name: "github-openai",
2208
+ colors: {
2209
+ semantic: {
2210
+ // Primary: Near-black for main actions and branding
2211
+ primary: "#24292f",
2212
+ // Secondary: Medium gray for secondary elements
2213
+ secondary: "#57606a",
2214
+ // Accent: Blue for links, focus states, and highlights
2215
+ accent: "#0969da",
2216
+ // Status colors
2217
+ success: "#1a7f37",
2218
+ // GitHub green
2219
+ warning: "#9a6700",
2220
+ // Amber warning
2221
+ danger: "#cf222e",
2222
+ // GitHub red
2223
+ info: "#0969da"
2224
+ // Blue info
2225
+ },
2226
+ surface: {
2227
+ // Pure white background
2228
+ background: "#ffffff",
2229
+ // Light gray surface (GitHub code background style)
2230
+ surface: "#f6f8fa",
2231
+ // White elevated surfaces (modals, cards)
2232
+ elevated: "#ffffff",
2233
+ // Dark semi-transparent overlay
2234
+ overlay: "rgba(27, 31, 36, 0.5)"
2235
+ },
2236
+ text: {
2237
+ // Near-black for primary text
2238
+ primary: "#24292f",
2239
+ // Gray for secondary/muted text
2240
+ secondary: "#57606a",
2241
+ // Light gray for disabled text
2242
+ disabled: "#8c959f",
2243
+ // White for text on dark backgrounds
2244
+ inverse: "#ffffff",
2245
+ // Blue for links
2246
+ link: "#0969da"
2247
+ },
2248
+ border: {
2249
+ // Light gray border (GitHub style)
2250
+ default: "#d0d7de",
2251
+ // Medium gray on hover
2252
+ hover: "#8c959f",
2253
+ // Blue focus ring
2254
+ focus: "#0969da",
2255
+ // Subtle divider
2256
+ divider: "#d8dee4"
2257
+ }
2258
+ },
2259
+ typography: {
2260
+ families: {
2261
+ // System UI font stack (GitHub/Apple style)
2262
+ sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji"',
2263
+ // Monospace stack
2264
+ mono: 'ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, "Liberation Mono", monospace'
2265
+ },
2266
+ sizes: {
2267
+ xs: "0.75rem",
2268
+ // 12px
2269
+ sm: "0.875rem",
2270
+ // 14px
2271
+ base: "1rem",
2272
+ // 16px
2273
+ lg: "1.125rem",
2274
+ // 18px
2275
+ xl: "1.25rem",
2276
+ // 20px
2277
+ "2xl": "1.5rem",
2278
+ // 24px
2279
+ "3xl": "1.875rem",
2280
+ // 30px
2281
+ "4xl": "2.25rem"
2282
+ // 36px
2283
+ },
2284
+ weights: {
2285
+ normal: "400",
2286
+ medium: "500",
2287
+ semibold: "600",
2288
+ bold: "700"
2289
+ }
2290
+ },
2291
+ radius: {
2292
+ none: "0",
2293
+ sm: "3px",
2294
+ // GitHub uses smaller radii
2295
+ md: "6px",
2296
+ lg: "8px",
2297
+ xl: "12px",
2298
+ "2xl": "16px",
2299
+ full: "9999px"
2300
+ },
2301
+ shadows: {
2302
+ // Subtle shadows with gray tones
2303
+ sm: "0 1px 0 rgba(27, 31, 36, 0.04)",
2304
+ md: "0 3px 6px rgba(140, 149, 159, 0.15)",
2305
+ lg: "0 8px 24px rgba(140, 149, 159, 0.2)",
2306
+ xl: "0 12px 28px rgba(140, 149, 159, 0.3)"
2307
+ },
2308
+ components: {
2309
+ button: {
2310
+ radius: "6px",
2311
+ paddingX: "16px",
2312
+ paddingY: "5px",
2313
+ fontSize: "14px",
2314
+ fontWeight: "500"
2315
+ },
2316
+ card: {
2317
+ radius: "6px",
2318
+ padding: "16px",
2319
+ shadow: "0 1px 0 rgba(27, 31, 36, 0.04)",
2320
+ borderWidth: "1px"
2321
+ },
2322
+ input: {
2323
+ radius: "6px",
2324
+ paddingX: "12px",
2325
+ paddingY: "5px",
2326
+ borderWidth: "1px",
2327
+ focusRingWidth: "3px"
2328
+ }
2329
+ },
2330
+ cdn: {
2331
+ fonts: {
2332
+ preconnect: ["https://fonts.googleapis.com", "https://fonts.gstatic.com"],
2333
+ stylesheets: [
2334
+ // System UI fonts don't need external stylesheets, but we include
2335
+ // Inter as an optional enhancement for consistent cross-platform rendering
2336
+ "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
2337
+ ]
2338
+ },
2339
+ icons: {
2340
+ script: {
2341
+ url: "https://cdn.jsdelivr.net/npm/lucide@0.294.0/dist/umd/lucide.min.js"
2342
+ }
2343
+ },
2344
+ scripts: {
2345
+ tailwind: "https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",
2346
+ htmx: {
2347
+ url: "https://cdnjs.cloudflare.com/ajax/libs/htmx/2.0.7/htmx.min.js",
2348
+ integrity: "sha512-T6VLg/MJYMbLTmQ8VLvonbWg8VOvmDhXcOvHzCwo6ShdGuUU5SEcp1IAPXL4k9lVoMi8gRXl5K/S/zh43Y9rJA=="
2349
+ },
2350
+ alpine: {
2351
+ url: "https://cdn.jsdelivr.net/npm/alpinejs@3.14.3/dist/cdn.min.js",
2352
+ integrity: "sha384-6zY8MFQJ/EqS1r4RJl+7j8rvZPuBWpT0RzWf+IFcKhxqUzQNmJzA1X1VEVZhYaEz"
2353
+ }
2354
+ }
2355
+ }
2356
+ };
2357
+ var DEFAULT_THEME = GITHUB_OPENAI_THEME;
2358
+
2359
+ // libs/uipack/src/theme/theme.ts
2360
+ function mergeThemesCore(base, override) {
2361
+ const baseColors = base.colors ?? { semantic: { primary: "#24292f" } };
2362
+ const filterStrings = (arr) => arr.filter((s) => s !== void 0);
2363
+ return {
2364
+ ...base,
2365
+ ...override,
2366
+ colors: {
2367
+ ...baseColors,
2368
+ ...override.colors,
2369
+ semantic: { ...baseColors.semantic, ...override.colors?.semantic },
2370
+ surface: { ...baseColors.surface, ...override.colors?.surface },
2371
+ text: { ...baseColors.text, ...override.colors?.text },
2372
+ border: { ...baseColors.border, ...override.colors?.border },
2373
+ custom: { ...baseColors.custom, ...override.colors?.custom }
2374
+ },
2375
+ typography: {
2376
+ ...base.typography,
2377
+ ...override.typography,
2378
+ families: { ...base.typography?.families, ...override.typography?.families },
2379
+ sizes: { ...base.typography?.sizes, ...override.typography?.sizes },
2380
+ weights: { ...base.typography?.weights, ...override.typography?.weights },
2381
+ lineHeight: { ...base.typography?.lineHeight, ...override.typography?.lineHeight }
2382
+ },
2383
+ spacing: { ...base.spacing, ...override.spacing },
2384
+ radius: { ...base.radius, ...override.radius },
2385
+ shadows: { ...base.shadows, ...override.shadows },
2386
+ components: {
2387
+ ...base.components,
2388
+ ...override.components,
2389
+ button: { ...base.components?.button, ...override.components?.button },
2390
+ card: { ...base.components?.card, ...override.components?.card },
2391
+ input: { ...base.components?.input, ...override.components?.input }
2392
+ },
2393
+ cdn: {
2394
+ ...base.cdn,
2395
+ ...override.cdn,
2396
+ fonts: {
2397
+ // Concatenate then dedupe so base entries are preserved without duplicates
2398
+ preconnect: filterStrings(
2399
+ Array.from(/* @__PURE__ */ new Set([...base.cdn?.fonts?.preconnect ?? [], ...override.cdn?.fonts?.preconnect ?? []]))
2400
+ ),
2401
+ stylesheets: filterStrings(
2402
+ Array.from(/* @__PURE__ */ new Set([...base.cdn?.fonts?.stylesheets ?? [], ...override.cdn?.fonts?.stylesheets ?? []]))
2403
+ )
2404
+ },
2405
+ icons: {
2406
+ ...base.cdn?.icons,
2407
+ ...override.cdn?.icons,
2408
+ // Deep merge script to preserve integrity when only url is overridden
2409
+ script: override.cdn?.icons?.script ? { ...base.cdn?.icons?.script, ...override.cdn?.icons?.script } : base.cdn?.icons?.script
2410
+ },
2411
+ scripts: {
2412
+ // tailwind is a simple string, just use override or base
2413
+ tailwind: override.cdn?.scripts?.tailwind ?? base.cdn?.scripts?.tailwind,
2414
+ // Deep merge htmx/alpine to preserve integrity when only url is overridden
2415
+ htmx: override.cdn?.scripts?.htmx ? { ...base.cdn?.scripts?.htmx, ...override.cdn?.scripts?.htmx } : base.cdn?.scripts?.htmx,
2416
+ alpine: override.cdn?.scripts?.alpine ? { ...base.cdn?.scripts?.alpine, ...override.cdn?.scripts?.alpine } : base.cdn?.scripts?.alpine
2417
+ }
2418
+ },
2419
+ customVars: { ...base.customVars, ...override.customVars },
2420
+ customCss: [base.customCss, override.customCss].filter(Boolean).join("\n")
2421
+ };
2422
+ }
2423
+ function mergeThemes(base, override) {
2424
+ const merged = mergeThemesCore(base, override);
2425
+ let darkVariant;
2426
+ if (override.dark !== void 0) {
2427
+ const darkBase = base.dark ?? base;
2428
+ const { dark: _nestedDark, ...overrideDarkWithoutNested } = override.dark;
2429
+ darkVariant = mergeThemesCore(darkBase, overrideDarkWithoutNested);
2430
+ } else if (base.dark !== void 0) {
2431
+ const { dark: _nestedDark, ...baseDarkWithoutNested } = base.dark;
2432
+ darkVariant = baseDarkWithoutNested;
2433
+ }
2434
+ return {
2435
+ ...merged,
2436
+ dark: darkVariant
2437
+ };
2438
+ }
2439
+ function emitColorScale(lines, name, scale) {
2440
+ for (const [shade, value] of Object.entries(scale)) {
2441
+ if (value) lines.push(`--color-${name}-${shade}: ${value};`);
2442
+ }
2443
+ }
2444
+ function buildThemeCss(theme) {
2445
+ const lines = [];
2446
+ const semantic = theme.colors.semantic;
2447
+ if (typeof semantic.primary === "string") {
2448
+ lines.push(`--color-primary: ${semantic.primary};`);
2449
+ } else if (semantic.primary) {
2450
+ emitColorScale(lines, "primary", semantic.primary);
2451
+ }
2452
+ if (semantic.secondary) {
2453
+ if (typeof semantic.secondary === "string") {
2454
+ lines.push(`--color-secondary: ${semantic.secondary};`);
2455
+ } else {
2456
+ emitColorScale(lines, "secondary", semantic.secondary);
2457
+ }
2458
+ }
2459
+ if (semantic.accent) {
2460
+ if (typeof semantic.accent === "string") {
2461
+ lines.push(`--color-accent: ${semantic.accent};`);
2462
+ } else {
2463
+ emitColorScale(lines, "accent", semantic.accent);
2464
+ }
2465
+ }
2466
+ if (semantic.neutral) {
2467
+ if (typeof semantic.neutral === "string") {
2468
+ lines.push(`--color-neutral: ${semantic.neutral};`);
2469
+ } else {
2470
+ emitColorScale(lines, "neutral", semantic.neutral);
2471
+ }
2472
+ }
2473
+ if (semantic.success) lines.push(`--color-success: ${semantic.success};`);
2474
+ if (semantic.warning) lines.push(`--color-warning: ${semantic.warning};`);
2475
+ if (semantic.danger) lines.push(`--color-danger: ${semantic.danger};`);
2476
+ if (semantic.info) lines.push(`--color-info: ${semantic.info};`);
2477
+ const surface = theme.colors.surface;
2478
+ if (surface?.background) lines.push(`--color-background: ${surface.background};`);
2479
+ if (surface?.surface) lines.push(`--color-surface: ${surface.surface};`);
2480
+ if (surface?.elevated) lines.push(`--color-elevated: ${surface.elevated};`);
2481
+ if (surface?.overlay) lines.push(`--color-overlay: ${surface.overlay};`);
2482
+ const text = theme.colors.text;
2483
+ if (text?.primary) lines.push(`--color-text-primary: ${text.primary};`);
2484
+ if (text?.secondary) lines.push(`--color-text-secondary: ${text.secondary};`);
2485
+ if (text?.disabled) lines.push(`--color-text-disabled: ${text.disabled};`);
2486
+ if (text?.inverse) lines.push(`--color-text-inverse: ${text.inverse};`);
2487
+ if (text?.link) lines.push(`--color-text-link: ${text.link};`);
2488
+ const border = theme.colors.border;
2489
+ if (border?.default) lines.push(`--color-border: ${border.default};`);
2490
+ if (border?.hover) lines.push(`--color-border-hover: ${border.hover};`);
2491
+ if (border?.focus) lines.push(`--color-border-focus: ${border.focus};`);
2492
+ if (border?.divider) lines.push(`--color-divider: ${border.divider};`);
2493
+ if (theme.colors.custom) {
2494
+ for (const [key, value] of Object.entries(theme.colors.custom)) {
2495
+ lines.push(`--color-${key}: ${value};`);
2496
+ }
2497
+ }
2498
+ const typography = theme.typography;
2499
+ if (typography?.families?.sans) lines.push(`--font-sans: ${typography.families.sans};`);
2500
+ if (typography?.families?.serif) lines.push(`--font-serif: ${typography.families.serif};`);
2501
+ if (typography?.families?.mono) lines.push(`--font-mono: ${typography.families.mono};`);
2502
+ if (typography?.families?.display) lines.push(`--font-display: ${typography.families.display};`);
2503
+ const radius = theme.radius;
2504
+ if (radius?.none) lines.push(`--radius-none: ${radius.none};`);
2505
+ if (radius?.sm) lines.push(`--radius-sm: ${radius.sm};`);
2506
+ if (radius?.md) lines.push(`--radius-md: ${radius.md};`);
2507
+ if (radius?.lg) lines.push(`--radius-lg: ${radius.lg};`);
2508
+ if (radius?.xl) lines.push(`--radius-xl: ${radius.xl};`);
2509
+ if (radius?.["2xl"]) lines.push(`--radius-2xl: ${radius["2xl"]};`);
2510
+ if (radius?.full) lines.push(`--radius-full: ${radius.full};`);
2511
+ if (theme.customVars) {
2512
+ for (const [key, value] of Object.entries(theme.customVars)) {
2513
+ lines.push(`${key}: ${value};`);
2514
+ }
2515
+ }
2516
+ return lines.join("\n ");
2517
+ }
2518
+
2519
+ // libs/uipack/src/runtime/wrapper.ts
2520
+ init_utils();
2521
+
2522
+ // libs/uipack/src/runtime/sanitizer.ts
2523
+ var REDACTION_TOKENS = {
2524
+ EMAIL: "[EMAIL]",
2525
+ PHONE: "[PHONE]",
2526
+ CARD: "[CARD]",
2527
+ ID: "[ID]",
2528
+ IP: "[IP]",
2529
+ REDACTED: "[REDACTED]"
2530
+ };
2531
+ var PII_PATTERNS = {
2532
+ // Email: user@domain.tld
2533
+ email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
2534
+ // Email embedded in text
2535
+ emailInText: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
2536
+ // Phone: Various formats (US-centric but flexible)
2537
+ phone: /^[+]?[(]?[0-9]{1,4}[)]?[-\s.]?[0-9]{1,4}[-\s.]?[0-9]{1,9}$/,
2538
+ // Phone embedded in text
2539
+ phoneInText: /(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}/g,
2540
+ // Credit card: 13-19 digits (with optional separators)
2541
+ creditCard: /^(?:[0-9]{4}[-\s]?){3,4}[0-9]{1,4}$/,
2542
+ // Credit card embedded in text
2543
+ creditCardInText: /\b(?:[0-9]{4}[-\s]?){3,4}[0-9]{1,4}\b/g,
2544
+ // SSN: XXX-XX-XXXX
2545
+ ssn: /^[0-9]{3}[-]?[0-9]{2}[-]?[0-9]{4}$/,
2546
+ // SSN embedded in text
2547
+ ssnInText: /\b[0-9]{3}[-]?[0-9]{2}[-]?[0-9]{4}\b/g,
2548
+ // IPv4 address
2549
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
2550
+ // IPv4 embedded in text
2551
+ ipv4InText: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g
2552
+ };
2553
+ function isEmail(value) {
2554
+ return PII_PATTERNS.email.test(value);
2555
+ }
2556
+ function isPhone(value) {
2557
+ return PII_PATTERNS.phone.test(value);
2558
+ }
2559
+ function isCreditCard(value) {
2560
+ const digits = value.replace(/[-\s]/g, "");
2561
+ return digits.length >= 13 && digits.length <= 19 && PII_PATTERNS.creditCard.test(value);
2562
+ }
2563
+ function isSSN(value) {
2564
+ return PII_PATTERNS.ssn.test(value);
2565
+ }
2566
+ function isIPv4(value) {
2567
+ return PII_PATTERNS.ipv4.test(value);
2568
+ }
2569
+ function detectPIIType(value) {
2570
+ if (isEmail(value)) return "EMAIL";
2571
+ if (isCreditCard(value)) return "CARD";
2572
+ if (isSSN(value)) return "ID";
2573
+ if (isPhone(value)) return "PHONE";
2574
+ if (isIPv4(value)) return "IP";
2575
+ return null;
2576
+ }
2577
+ function redactPIIFromText(text) {
2578
+ let result = text;
2579
+ result = result.replace(PII_PATTERNS.creditCardInText, REDACTION_TOKENS.CARD);
2580
+ result = result.replace(PII_PATTERNS.ssnInText, REDACTION_TOKENS.ID);
2581
+ result = result.replace(PII_PATTERNS.emailInText, REDACTION_TOKENS.EMAIL);
2582
+ result = result.replace(PII_PATTERNS.phoneInText, REDACTION_TOKENS.PHONE);
2583
+ result = result.replace(PII_PATTERNS.ipv4InText, REDACTION_TOKENS.IP);
2584
+ return result;
2585
+ }
2586
+ function sanitizeValue(key, value, path, options, depth, visited) {
2587
+ const maxDepth = options.maxDepth ?? 10;
2588
+ if (depth > maxDepth) {
2589
+ return value;
2590
+ }
2591
+ if (value === null || value === void 0) {
2592
+ return value;
2593
+ }
2594
+ if (typeof options.mode === "function") {
2595
+ return options.mode(key, value, path);
2596
+ }
2597
+ if (Array.isArray(options.mode)) {
2598
+ const lowerKey = key.toLowerCase();
2599
+ if (options.mode.some((f) => f.toLowerCase() === lowerKey)) {
2600
+ return REDACTION_TOKENS.REDACTED;
2601
+ }
2602
+ }
2603
+ if (typeof value === "string") {
2604
+ if (options.mode === true) {
2605
+ const piiType = detectPIIType(value);
2606
+ if (piiType) {
2607
+ return REDACTION_TOKENS[piiType];
2608
+ }
2609
+ if (options.sanitizeInText !== false) {
2610
+ const redacted = redactPIIFromText(value);
2611
+ if (redacted !== value) {
2612
+ return redacted;
2613
+ }
2614
+ }
2615
+ }
2616
+ return value;
2617
+ }
2618
+ if (Array.isArray(value)) {
2619
+ if (visited.has(value)) {
2620
+ return REDACTION_TOKENS.REDACTED;
2621
+ }
2622
+ visited.add(value);
2623
+ return value.map(
2624
+ (item, index) => sanitizeValue(String(index), item, [...path, String(index)], options, depth + 1, visited)
2625
+ );
2626
+ }
2627
+ if (typeof value === "object") {
2628
+ if (visited.has(value)) {
2629
+ return REDACTION_TOKENS.REDACTED;
2630
+ }
2631
+ visited.add(value);
2632
+ const result = {};
2633
+ for (const [k, v] of Object.entries(value)) {
2634
+ result[k] = sanitizeValue(k, v, [...path, k], options, depth + 1, visited);
2635
+ }
2636
+ return result;
2637
+ }
2638
+ return value;
2639
+ }
2640
+ function sanitizeInput(input, mode = true) {
2641
+ if (!input || typeof input !== "object") {
2642
+ return {};
2643
+ }
2644
+ const options = {
2645
+ mode,
2646
+ maxDepth: 10,
2647
+ sanitizeInText: true
2648
+ };
2649
+ const visited = /* @__PURE__ */ new WeakSet();
2650
+ return sanitizeValue("", input, [], options, 0, visited);
2651
+ }
2652
+
2653
+ // libs/uipack/src/runtime/wrapper.ts
2654
+ function createTemplateHelpers() {
2655
+ let idCounter2 = 0;
2656
+ return {
2657
+ /**
2658
+ * Escape HTML special characters to prevent XSS
2659
+ */
2660
+ escapeHtml,
2661
+ /**
2662
+ * Format a date for display
2663
+ */
2664
+ formatDate: (date, format) => {
2665
+ const d = typeof date === "string" ? new Date(date) : date;
2666
+ if (isNaN(d.getTime())) return String(date);
2667
+ if (format === "iso") {
2668
+ return d.toISOString();
2669
+ }
2670
+ if (format === "time") {
2671
+ return d.toLocaleTimeString();
2672
+ }
2673
+ if (format === "datetime") {
2674
+ return d.toLocaleString();
2675
+ }
2676
+ return d.toLocaleDateString();
2677
+ },
2678
+ /**
2679
+ * Format a number as currency
2680
+ */
2681
+ formatCurrency: (amount, currency = "USD") => {
2682
+ return new Intl.NumberFormat("en-US", {
2683
+ style: "currency",
2684
+ currency
2685
+ }).format(amount);
2686
+ },
2687
+ /**
2688
+ * Generate a unique ID for DOM elements
2689
+ */
2690
+ uniqueId: (prefix = "mcp") => {
2691
+ return `${prefix}-${++idCounter2}-${Date.now().toString(36)}`;
2692
+ },
2693
+ /**
2694
+ * Safely embed JSON data in HTML
2695
+ * Escapes characters that could break out of script tags or HTML
2696
+ */
2697
+ jsonEmbed: (data) => {
2698
+ const json2 = JSON.stringify(data);
2699
+ if (json2 === void 0) {
2700
+ return "undefined";
2701
+ }
2702
+ return json2.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/'/g, "\\u0027");
2703
+ }
2704
+ };
2705
+ }
2706
+ function wrapToolUI(options) {
2707
+ const {
2708
+ content,
2709
+ toolName,
2710
+ input = {},
2711
+ output,
2712
+ structuredContent,
2713
+ csp,
2714
+ widgetAccessible = false,
2715
+ title,
2716
+ theme: themeOverrides,
2717
+ platform = OPENAI_PLATFORM,
2718
+ hostContext,
2719
+ sanitizeInput: sanitizeOption,
2720
+ rendererType,
2721
+ hydrate = false,
2722
+ // Disabled by default to prevent React hydration Error #418 in MCP clients
2723
+ skipCspMeta = false
2724
+ } = options;
2725
+ let sanitizedInput = input;
2726
+ if (sanitizeOption) {
2727
+ const sanitizeMode = sanitizeOption === true ? true : sanitizeOption;
2728
+ sanitizedInput = sanitizeInput(input, sanitizeMode);
2729
+ }
2730
+ const theme = themeOverrides ? mergeThemes(DEFAULT_THEME, themeOverrides) : DEFAULT_THEME;
2731
+ const useCdn = canUseCdn(platform);
2732
+ const useInline = needsInlineScripts(platform);
2733
+ const fontPreconnect = useCdn ? buildFontPreconnect() : "";
2734
+ const fontStylesheets = useCdn ? buildFontStylesheets({ inter: true }) : "";
2735
+ const scripts = buildCdnScripts({
2736
+ tailwind: platform.supportsTailwind,
2737
+ htmx: false,
2738
+ alpine: false,
2739
+ icons: false,
2740
+ inline: useInline
2741
+ });
2742
+ const frameworkScripts = buildFrameworkRuntimeScripts({
2743
+ rendererType,
2744
+ hydrate,
2745
+ platform
2746
+ });
2747
+ const themeCss = buildThemeCss(theme);
2748
+ const customCss = theme.customCss || "";
2749
+ const styleBlock = platform.supportsTailwind ? `<style type="text/tailwindcss">
2750
+ @theme {
2751
+ ${themeCss}
2752
+ }
2753
+ ${customCss}
2754
+ </style>` : "";
2755
+ const cspMetaTag = skipCspMeta ? "" : buildCSPMetaTag(csp);
2756
+ const dataScript = buildDataInjectionScript({
2757
+ toolName,
2758
+ input: sanitizedInput,
2759
+ output,
2760
+ structuredContent,
2761
+ widgetAccessible,
2762
+ hostContext
2763
+ });
2764
+ const pageTitle = title || `${escapeHtml(toolName)} - Tool Result`;
2765
+ return `<!DOCTYPE html>
2766
+ <html lang="en">
2767
+ <head>
2768
+ <meta charset="UTF-8">
2769
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
2770
+ <title>${pageTitle}</title>
2771
+ ${cspMetaTag}
2772
+
2773
+ <!-- Fonts -->
2774
+ ${fontPreconnect}
2775
+ ${fontStylesheets}
2776
+
2777
+ <!-- Tailwind CSS -->
2778
+ ${scripts}
2779
+ ${styleBlock}
2780
+
2781
+ <!-- Framework Runtime -->
2782
+ ${frameworkScripts}
2783
+
2784
+ <!-- Tool Data -->
2785
+ ${dataScript}
2786
+
2787
+ <!-- MCP Bridge Runtime -->
2788
+ ${MCP_BRIDGE_RUNTIME}
2789
+ </head>
2790
+ <body class="bg-background text-text-primary font-sans antialiased">
2791
+ ${content}
2792
+ </body>
2793
+ </html>`;
2794
+ }
2795
+ function buildFrameworkRuntimeScripts(options) {
2796
+ const { rendererType, hydrate, platform } = options;
2797
+ if (!rendererType || rendererType === "html" || rendererType === "html-fallback") {
2798
+ return "";
2799
+ }
2800
+ if (!hydrate) {
2801
+ return "";
2802
+ }
2803
+ if (rendererType === "react" || rendererType === "mdx") {
2804
+ const useCdn = canUseCdn(platform);
2805
+ if (useCdn) {
2806
+ return `
2807
+ <!-- React Runtime (for hydration) -->
2808
+ <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
2809
+ <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
2810
+ <script>
2811
+ // Hydration script for React/MDX components
2812
+ (function() {
2813
+ document.addEventListener('DOMContentLoaded', function() {
2814
+ var hydratables = document.querySelectorAll('[data-hydrate], [data-mdx-hydrate]');
2815
+ if (hydratables.length > 0 && window.__frontmcp_components) {
2816
+ hydratables.forEach(function(el) {
2817
+ var componentName = el.getAttribute('data-hydrate');
2818
+ var propsJson = el.getAttribute('data-props');
2819
+ var props = propsJson ? JSON.parse(propsJson) : {};
2820
+
2821
+ if (window.__frontmcp_components[componentName]) {
2822
+ try {
2823
+ ReactDOM.hydrateRoot(el, React.createElement(
2824
+ window.__frontmcp_components[componentName],
2825
+ props
2826
+ ));
2827
+ } catch (e) {
2828
+ console.error('[FrontMCP] Hydration failed:', e);
2829
+ }
2830
+ }
2831
+ });
2832
+ }
2833
+ });
2834
+ })();
2835
+ </script>`;
2836
+ } else {
2837
+ return `
2838
+ <!-- React hydration not available on blocked-network platforms -->
2839
+ <script>
2840
+ console.warn('[FrontMCP] React hydration disabled - platform does not support external scripts');
2841
+ </script>`;
2842
+ }
2843
+ }
2844
+ return "";
2845
+ }
2846
+ function buildDataInjectionScript(options) {
2847
+ const { toolName, input, output, structuredContent, widgetAccessible, hostContext } = options;
2848
+ const helpers = createTemplateHelpers();
2849
+ const contextData = {
2850
+ theme: hostContext?.theme || "light",
2851
+ displayMode: hostContext?.displayMode || "inline",
2852
+ ...hostContext
2853
+ };
2854
+ return `<script>
2855
+ // Tool metadata
2856
+ window.__mcpToolName = ${helpers.jsonEmbed(toolName)};
2857
+ window.__mcpToolInput = ${helpers.jsonEmbed(input)};
2858
+ window.__mcpToolOutput = ${helpers.jsonEmbed(output)};
2859
+ window.__mcpStructuredContent = ${helpers.jsonEmbed(structuredContent)};
2860
+ window.__mcpWidgetAccessible = ${helpers.jsonEmbed(widgetAccessible)};
2861
+ window.__mcpHostContext = ${helpers.jsonEmbed(contextData)};
2862
+ </script>`;
2863
+ }
2864
+
2865
+ // libs/uipack/src/tool-template/builder.ts
2866
+ init_utils();
2867
+
2868
+ // libs/uipack/src/renderers/utils/detect.ts
2869
+ function isReactComponent(value) {
2870
+ if (typeof value !== "function") {
2871
+ return false;
2872
+ }
2873
+ const fn = value;
2874
+ const typeofSymbol = fn.$$typeof;
2875
+ if (typeofSymbol) {
2876
+ const symbolString = typeofSymbol.toString();
2877
+ return symbolString.includes("react.memo") || symbolString.includes("react.forward_ref") || symbolString.includes("react.lazy");
2878
+ }
2879
+ if (fn.prototype?.isReactComponent) {
2880
+ return true;
2881
+ }
2882
+ if (fn.name && /^[A-Z]/.test(fn.name)) {
2883
+ return true;
2884
+ }
2885
+ return false;
2886
+ }
2887
+ function isTemplateBuilderFunction(fn) {
2888
+ if (isReactComponent(fn)) {
2889
+ return false;
2890
+ }
2891
+ if (fn.name && /^[A-Z]/.test(fn.name)) {
2892
+ return false;
2893
+ }
2894
+ return true;
2895
+ }
2896
+ function containsJsx(source) {
2897
+ if (/<[A-Z][a-zA-Z0-9]*(\s|>|\/)/.test(source)) {
2898
+ return true;
2899
+ }
2900
+ if (/<[A-Z][a-zA-Z0-9]*[^>]*\/>/.test(source)) {
2901
+ return true;
2902
+ }
2903
+ if (/<[a-z]+[^>]*\{[^}]+\}/.test(source)) {
2904
+ return true;
2905
+ }
2906
+ if (/\s(className|onClick|onChange|onSubmit|htmlFor)=/.test(source)) {
2907
+ return true;
2908
+ }
2909
+ if (/<>|<\/>|<React\.Fragment>/.test(source)) {
2910
+ return true;
2911
+ }
2912
+ if (/=>\s*\(?\s*</.test(source)) {
2913
+ return true;
2914
+ }
2915
+ if (/return\s*\(?\s*</.test(source)) {
2916
+ return true;
2917
+ }
2918
+ return false;
2919
+ }
2920
+ function containsMdxSyntax(source) {
2921
+ if (/<[A-Z][a-zA-Z0-9]*/.test(source)) {
2922
+ return true;
2923
+ }
2924
+ if (/^(import|export)\s/m.test(source)) {
2925
+ return true;
2926
+ }
2927
+ if (/\s(className|onClick|onChange|onSubmit|htmlFor|dangerouslySetInnerHTML)=/.test(source)) {
2928
+ return true;
2929
+ }
2930
+ if (/\{[^}"'\n]*\}/.test(source) && !/=\s*["'][^"']*\{/.test(source)) {
2931
+ return true;
2932
+ }
2933
+ if (/^---[\s\S]*?---/m.test(source)) {
2934
+ return true;
2935
+ }
2936
+ if (/<>|<\/>/.test(source)) {
2937
+ return true;
2938
+ }
2939
+ return false;
2940
+ }
2941
+ function detectTemplateType(template) {
2942
+ if (typeof template === "function") {
2943
+ if (isReactComponent(template)) {
2944
+ return {
2945
+ type: "react",
2946
+ confidence: 0.9,
2947
+ reason: "Function detected as React component (PascalCase name or React symbols)"
2948
+ };
2949
+ }
2950
+ return {
2951
+ type: "html-function",
2952
+ confidence: 0.8,
2953
+ reason: "Function assumed to be HTML template builder"
2954
+ };
2955
+ }
2956
+ if (typeof template === "string") {
2957
+ if (containsMdxSyntax(template)) {
2958
+ const hasMarkdown = /^#{1,6}\s|^\*\s|^\d+\.\s|^-\s/m.test(template);
2959
+ if (hasMarkdown) {
2960
+ return {
2961
+ type: "mdx",
2962
+ confidence: 0.9,
2963
+ reason: "String contains Markdown with JSX components"
2964
+ };
2965
+ }
2966
+ return {
2967
+ type: "jsx-string",
2968
+ confidence: 0.8,
2969
+ reason: "String contains JSX syntax"
2970
+ };
2971
+ }
2972
+ if (containsJsx(template)) {
2973
+ return {
2974
+ type: "jsx-string",
2975
+ confidence: 0.85,
2976
+ reason: "String contains JSX component tags or expressions"
2977
+ };
2978
+ }
2979
+ return {
2980
+ type: "html-string",
2981
+ confidence: 1,
2982
+ reason: "Plain HTML string"
2983
+ };
2984
+ }
2985
+ return {
2986
+ type: "html-string",
2987
+ confidence: 0.5,
2988
+ reason: "Unknown template type, defaulting to HTML"
2989
+ };
2990
+ }
2991
+
2992
+ // libs/uipack/src/renderers/utils/hash.ts
2993
+ function hashString(source) {
2994
+ let hash = 2166136261;
2995
+ for (let i = 0; i < source.length; i++) {
2996
+ hash ^= source.charCodeAt(i);
2997
+ hash = hash * 16777619 >>> 0;
2998
+ }
2999
+ return hash.toString(36);
3000
+ }
3001
+
3002
+ // libs/uipack/src/renderers/html.renderer.ts
3003
+ var handlebarsRenderer = null;
3004
+ async function loadHandlebarsRenderer() {
3005
+ if (handlebarsRenderer !== null) {
3006
+ return handlebarsRenderer;
3007
+ }
3008
+ try {
3009
+ const handlebarsModule = await Promise.resolve().then(() => (init_handlebars(), handlebars_exports));
3010
+ const { HandlebarsRenderer: HandlebarsRenderer2 } = handlebarsModule;
3011
+ const renderer = new HandlebarsRenderer2();
3012
+ handlebarsRenderer = {
3013
+ render: (template, context) => renderer.render(template, {
3014
+ input: context.input ?? {},
3015
+ output: context.output,
3016
+ structuredContent: context.structuredContent
3017
+ }),
3018
+ containsHandlebars: (template) => HandlebarsRenderer2.containsHandlebars(template)
3019
+ };
3020
+ return handlebarsRenderer;
3021
+ } catch {
3022
+ return null;
3023
+ }
3024
+ }
3025
+ function containsHandlebars2(template) {
3026
+ return /\{\{(?!!)[\s\S]*?\}\}/.test(template);
3027
+ }
3028
+ var HtmlRenderer = class {
3029
+ type = "html";
3030
+ priority = 0;
3031
+ // Lowest priority - fallback renderer
3032
+ /**
3033
+ * Check if this renderer can handle the given template.
3034
+ *
3035
+ * Accepts:
3036
+ * - Any string (assumed to be HTML, with or without Handlebars)
3037
+ * - Functions that are template builders (not React components)
3038
+ */
3039
+ canHandle(template) {
3040
+ if (typeof template === "string") {
3041
+ return true;
3042
+ }
3043
+ if (typeof template === "function") {
3044
+ return isTemplateBuilderFunction(template);
3045
+ }
3046
+ return false;
3047
+ }
3048
+ /**
3049
+ * Check if a template uses Handlebars syntax.
3050
+ *
3051
+ * @param template - Template string to check
3052
+ * @returns true if template contains {{...}} syntax
3053
+ */
3054
+ usesHandlebars(template) {
3055
+ return containsHandlebars2(template);
3056
+ }
3057
+ /**
3058
+ * Transpile the template.
3059
+ *
3060
+ * For HTML templates, no transpilation is needed.
3061
+ * This method returns a dummy result for consistency.
3062
+ */
3063
+ async transpile(template, _options) {
3064
+ const source = typeof template === "string" ? template : template.toString();
3065
+ const hash = hashString(source);
3066
+ return {
3067
+ code: "",
3068
+ // No transpiled code needed
3069
+ hash,
3070
+ cached: true
3071
+ // Always "cached" since no work is done
3072
+ };
3073
+ }
3074
+ /**
3075
+ * Render the template to HTML string.
3076
+ *
3077
+ * For static strings without Handlebars, returns the string directly.
3078
+ * For strings with Handlebars syntax, processes with HandlebarsRenderer.
3079
+ * For functions, calls the function with the context.
3080
+ */
3081
+ async render(template, context, _options) {
3082
+ if (typeof template === "string") {
3083
+ if (containsHandlebars2(template)) {
3084
+ return this.renderHandlebars(template, context);
3085
+ }
3086
+ return template;
3087
+ }
3088
+ if (typeof template === "function") {
3089
+ const result = template(context);
3090
+ if (typeof result === "string" && containsHandlebars2(result)) {
3091
+ return this.renderHandlebars(result, context);
3092
+ }
3093
+ return result;
3094
+ }
3095
+ return String(template);
3096
+ }
3097
+ /**
3098
+ * Render Handlebars template with context.
3099
+ */
3100
+ async renderHandlebars(template, context) {
3101
+ const renderer = await loadHandlebarsRenderer();
3102
+ if (!renderer) {
3103
+ console.warn(
3104
+ "[@frontmcp/ui] Template contains Handlebars syntax but handlebars is not installed. Install it for template interpolation: npm install handlebars"
3105
+ );
3106
+ return template;
3107
+ }
3108
+ return renderer.render(template, {
3109
+ input: context.input,
3110
+ output: context.output,
3111
+ structuredContent: context.structuredContent
3112
+ });
3113
+ }
3114
+ /**
3115
+ * Get runtime scripts for client-side functionality.
3116
+ *
3117
+ * HTML templates don't need additional runtime scripts.
3118
+ */
3119
+ getRuntimeScripts(_platform) {
3120
+ return {
3121
+ headScripts: "",
3122
+ isInline: false
3123
+ };
3124
+ }
3125
+ };
3126
+ var htmlRenderer = new HtmlRenderer();
3127
+
3128
+ // libs/uipack/src/renderers/registry.ts
3129
+ var RendererRegistry = class {
3130
+ renderers = /* @__PURE__ */ new Map();
3131
+ sortedRenderers = [];
3132
+ defaultRenderer = "html";
3133
+ debug;
3134
+ constructor(options = {}) {
3135
+ this.debug = options.debug ?? false;
3136
+ this.register(htmlRenderer);
3137
+ }
3138
+ /**
3139
+ * Register a renderer.
3140
+ *
3141
+ * Renderers are sorted by priority (highest first) for detection.
3142
+ *
3143
+ * @param renderer - Renderer to register
3144
+ */
3145
+ register(renderer) {
3146
+ this.renderers.set(renderer.type, renderer);
3147
+ this.updateSortedList();
3148
+ if (this.debug) {
3149
+ console.log(`[RendererRegistry] Registered renderer: ${renderer.type} (priority: ${renderer.priority})`);
3150
+ }
3151
+ }
3152
+ /**
3153
+ * Unregister a renderer.
3154
+ *
3155
+ * @param type - Type of renderer to remove
3156
+ * @returns True if renderer was removed
3157
+ */
3158
+ unregister(type) {
3159
+ const removed = this.renderers.delete(type);
3160
+ if (removed) {
3161
+ this.updateSortedList();
3162
+ }
3163
+ return removed;
3164
+ }
3165
+ /**
3166
+ * Get a renderer by type.
3167
+ *
3168
+ * @param type - Renderer type
3169
+ * @returns Renderer or undefined if not found
3170
+ */
3171
+ get(type) {
3172
+ return this.renderers.get(type);
3173
+ }
3174
+ /**
3175
+ * Check if a renderer type is registered.
3176
+ *
3177
+ * @param type - Renderer type
3178
+ * @returns True if registered
3179
+ */
3180
+ has(type) {
3181
+ return this.renderers.has(type);
3182
+ }
3183
+ /**
3184
+ * Get all registered renderer types.
3185
+ *
3186
+ * @returns Array of renderer types
3187
+ */
3188
+ getTypes() {
3189
+ return Array.from(this.renderers.keys());
3190
+ }
3191
+ /**
3192
+ * Auto-detect the renderer for a template.
3193
+ *
3194
+ * Checks renderers in priority order (highest first).
3195
+ * Returns HTML renderer as fallback.
3196
+ *
3197
+ * @param template - Template to detect
3198
+ * @returns Detection result with renderer and confidence
3199
+ */
3200
+ detect(template) {
3201
+ for (const renderer of this.sortedRenderers) {
3202
+ if (renderer.canHandle(template)) {
3203
+ const result = {
3204
+ renderer,
3205
+ confidence: renderer.priority / 100,
3206
+ // Normalize to 0-1
3207
+ reason: `Matched by ${renderer.type} renderer`
3208
+ };
3209
+ if (this.debug) {
3210
+ console.log(`[RendererRegistry] Detected template as ${renderer.type} (confidence: ${result.confidence})`);
3211
+ }
3212
+ return result;
3213
+ }
3214
+ }
3215
+ const fallback = this.renderers.get(this.defaultRenderer);
3216
+ if (!fallback) {
3217
+ throw new Error(`Default renderer '${this.defaultRenderer}' not found`);
3218
+ }
3219
+ return {
3220
+ renderer: fallback,
3221
+ confidence: 0.5,
3222
+ reason: "Fallback to default HTML renderer"
3223
+ };
3224
+ }
3225
+ /**
3226
+ * Render a template with auto-detection.
3227
+ *
3228
+ * @param template - Template to render (React, MDX, or HTML)
3229
+ * @param context - Template context with input/output
3230
+ * @param options - Render options
3231
+ * @returns Rendered result with HTML and metadata
3232
+ */
3233
+ async render(template, context, options = {}) {
3234
+ const platform = options.platform ?? OPENAI_PLATFORM;
3235
+ const detection = this.detect(template);
3236
+ const renderer = detection.renderer;
3237
+ if (this.debug) {
3238
+ console.log(`[RendererRegistry] Rendering with ${renderer.type} renderer`);
3239
+ }
3240
+ const transpileResult = await renderer.transpile(template);
3241
+ const html = await renderer.render(template, context, options);
3242
+ const runtimeScripts = renderer.getRuntimeScripts(platform);
3243
+ return {
3244
+ html,
3245
+ rendererType: renderer.type,
3246
+ transpileCached: transpileResult.cached,
3247
+ runtimeScripts
3248
+ };
3249
+ }
3250
+ /**
3251
+ * Render with a specific renderer type.
3252
+ *
3253
+ * @param type - Renderer type to use
3254
+ * @param template - Template to render
3255
+ * @param context - Template context
3256
+ * @param options - Render options
3257
+ * @returns Rendered result
3258
+ */
3259
+ async renderWith(type, template, context, options = {}) {
3260
+ const renderer = this.renderers.get(type);
3261
+ if (!renderer) {
3262
+ throw new Error(`Renderer '${type}' not registered`);
3263
+ }
3264
+ const platform = options.platform ?? OPENAI_PLATFORM;
3265
+ const transpileResult = await renderer.transpile(template);
3266
+ const html = await renderer.render(template, context, options);
3267
+ const runtimeScripts = renderer.getRuntimeScripts(platform);
3268
+ return {
3269
+ html,
3270
+ rendererType: type,
3271
+ transpileCached: transpileResult.cached,
3272
+ runtimeScripts
3273
+ };
3274
+ }
3275
+ /**
3276
+ * Update the sorted renderer list by priority.
3277
+ */
3278
+ updateSortedList() {
3279
+ this.sortedRenderers = Array.from(this.renderers.values()).sort((a, b) => b.priority - a.priority);
3280
+ }
3281
+ /**
3282
+ * Set the default renderer type.
3283
+ *
3284
+ * @param type - Renderer type to use as default
3285
+ */
3286
+ setDefault(type) {
3287
+ if (!this.renderers.has(type)) {
3288
+ throw new Error(`Cannot set default to unregistered renderer '${type}'`);
3289
+ }
3290
+ this.defaultRenderer = type;
3291
+ }
3292
+ /**
3293
+ * Get registry statistics.
3294
+ */
3295
+ getStats() {
3296
+ return {
3297
+ registeredRenderers: this.getTypes(),
3298
+ defaultRenderer: this.defaultRenderer,
3299
+ priorityOrder: this.sortedRenderers.map((r) => ({
3300
+ type: r.type,
3301
+ priority: r.priority
3302
+ }))
3303
+ };
3304
+ }
3305
+ };
3306
+ var rendererRegistry = new RendererRegistry();
3307
+
3308
+ // libs/uipack/src/tool-template/builder.ts
3309
+ function buildTemplateContext(input, output, structuredContent) {
3310
+ return {
3311
+ input,
3312
+ output,
3313
+ structuredContent,
3314
+ helpers: createTemplateHelpers()
3315
+ };
3316
+ }
3317
+ function executeTemplate(template, ctx) {
3318
+ if (typeof template === "string") {
3319
+ return template;
3320
+ }
3321
+ return template(ctx);
3322
+ }
3323
+ async function renderTemplate2(template, ctx, options) {
3324
+ const detection = detectTemplateType(template);
3325
+ if (detection.type === "html-function" || detection.type === "html-string") {
3326
+ const html = typeof template === "function" ? template(ctx) : template;
3327
+ return { html, rendererType: "html" };
3328
+ }
3329
+ try {
3330
+ const result = await rendererRegistry.render(template, ctx, {
3331
+ hydrate: options?.hydrate,
3332
+ mdxComponents: options?.mdxComponents
3333
+ });
3334
+ return { html: result.html, rendererType: result.rendererType };
3335
+ } catch (error) {
3336
+ console.warn(
3337
+ `[@frontmcp/ui] Renderer failed for ${detection.type}, falling back to HTML:`,
3338
+ error instanceof Error ? error.message : error
3339
+ );
3340
+ if (typeof template === "function") {
3341
+ try {
3342
+ const html = template(ctx);
3343
+ return { html, rendererType: "html-fallback" };
3344
+ } catch {
3345
+ return {
3346
+ html: `<div class="error">Template rendering failed: ${error instanceof Error ? error.message : "Unknown error"}</div>`,
3347
+ rendererType: "error"
3348
+ };
3349
+ }
3350
+ }
3351
+ return { html: String(template), rendererType: "html-fallback" };
3352
+ }
3353
+ }
3354
+ function renderToolTemplate(options) {
3355
+ const { ui, toolName, input, output, structuredContent, theme, platform } = options;
3356
+ const ctx = buildTemplateContext(input, output, structuredContent);
3357
+ const content = executeTemplate(ui.template, ctx);
3358
+ const wrapperOptions = {
3359
+ content,
3360
+ toolName,
3361
+ input,
3362
+ output,
3363
+ structuredContent,
3364
+ csp: ui.csp,
3365
+ widgetAccessible: ui.widgetAccessible,
3366
+ title: `${toolName} Result`,
3367
+ theme,
3368
+ platform
3369
+ };
3370
+ const html = wrapToolUI(wrapperOptions);
3371
+ const openaiMeta = buildOpenAIMetaFromUI(ui);
3372
+ return {
3373
+ html,
3374
+ mimeType: "text/html",
3375
+ openaiMeta: Object.keys(openaiMeta).length > 0 ? openaiMeta : void 0
3376
+ };
3377
+ }
3378
+ async function renderToolTemplateAsync(options) {
3379
+ const { ui, toolName, input, output, structuredContent, theme, platform } = options;
3380
+ const ctx = buildTemplateContext(input, output, structuredContent);
3381
+ const { html: content, rendererType } = await renderTemplate2(ui.template, ctx, {
3382
+ hydrate: ui.hydrate,
3383
+ mdxComponents: ui.mdxComponents
3384
+ });
3385
+ const wrappedContent = ui.wrapper ? ui.wrapper(content, ctx) : content;
3386
+ const wrapperOptions = {
3387
+ content: wrappedContent,
3388
+ toolName,
3389
+ input,
3390
+ output,
3391
+ structuredContent,
3392
+ csp: ui.csp,
3393
+ widgetAccessible: ui.widgetAccessible,
3394
+ title: `${toolName} Result`,
3395
+ theme,
3396
+ platform,
3397
+ // Pass renderer type for framework runtime injection
3398
+ rendererType,
3399
+ hydrate: ui.hydrate
3400
+ };
3401
+ const html = wrapToolUI(wrapperOptions);
3402
+ const openaiMeta = buildOpenAIMetaFromUI(ui);
3403
+ return {
3404
+ html,
3405
+ mimeType: "text/html",
3406
+ rendererType,
3407
+ openaiMeta: Object.keys(openaiMeta).length > 0 ? openaiMeta : void 0
3408
+ };
3409
+ }
3410
+ function buildOpenAIMetaFromUI(ui) {
3411
+ const meta = {};
3412
+ if (ui.widgetAccessible) {
3413
+ meta["openai/widgetAccessible"] = true;
3414
+ }
3415
+ if (ui.widgetDescription) {
3416
+ meta["openai/widgetDescription"] = ui.widgetDescription;
3417
+ }
3418
+ if (ui.csp) {
3419
+ const cspConfig = {};
3420
+ if (ui.csp.connectDomains?.length) {
3421
+ cspConfig["connect_domains"] = ui.csp.connectDomains;
3422
+ }
3423
+ if (ui.csp.resourceDomains?.length) {
3424
+ cspConfig["resource_domains"] = ui.csp.resourceDomains;
3425
+ }
3426
+ if (Object.keys(cspConfig).length > 0) {
3427
+ meta["openai/widgetCSP"] = cspConfig;
3428
+ }
3429
+ }
3430
+ if (ui.displayMode && ui.displayMode !== "inline") {
3431
+ meta["openai/displayMode"] = ui.displayMode;
3432
+ }
3433
+ return meta;
3434
+ }
3435
+ function createTemplate(builder) {
3436
+ return builder;
3437
+ }
3438
+ function createToolUI(config) {
3439
+ return config;
3440
+ }
3441
+ function container(content, className = "") {
3442
+ const baseClasses = "p-4 rounded-lg bg-surface";
3443
+ return `<div class="${baseClasses} ${className}">${content}</div>`;
3444
+ }
3445
+ function heading(text, level = 2) {
3446
+ const tag = `h${level}`;
3447
+ const classes = {
3448
+ 1: "text-2xl font-bold text-text-primary mb-4",
3449
+ 2: "text-xl font-semibold text-text-primary mb-3",
3450
+ 3: "text-lg font-medium text-text-primary mb-2",
3451
+ 4: "text-base font-medium text-text-secondary mb-2"
3452
+ }[level] || "";
3453
+ return `<${tag} class="${classes}">${escapeHtml(text)}</${tag}>`;
3454
+ }
3455
+ function paragraph(text, className = "") {
3456
+ return `<p class="text-text-secondary ${className}">${escapeHtml(text)}</p>`;
3457
+ }
3458
+ function keyValue(key, value, className = "") {
3459
+ const displayValue = typeof value === "boolean" ? value ? "Yes" : "No" : String(value);
3460
+ return `<div class="flex justify-between items-center py-2 border-b border-border ${className}">
3461
+ <span class="text-text-secondary">${escapeHtml(key)}</span>
3462
+ <span class="text-text-primary font-medium">${escapeHtml(displayValue)}</span>
3463
+ </div>`;
3464
+ }
3465
+ function dataList(items) {
3466
+ const listItems = items.map((item) => keyValue(item.key, item.value)).join("");
3467
+ return `<div class="space-y-1">${listItems}</div>`;
3468
+ }
3469
+ function errorDisplay(message, details) {
3470
+ return `<div class="p-4 bg-danger/10 border border-danger rounded-lg">
3471
+ <div class="flex items-center gap-2 text-danger">
3472
+ <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
3473
+ <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
3474
+ </svg>
3475
+ <span class="font-medium">${escapeHtml(message)}</span>
3476
+ </div>
3477
+ ${details ? `<p class="mt-2 text-sm text-text-secondary">${escapeHtml(details)}</p>` : ""}
3478
+ </div>`;
3479
+ }
3480
+ function successDisplay(message, details) {
3481
+ return `<div class="p-4 bg-success/10 border border-success rounded-lg">
3482
+ <div class="flex items-center gap-2 text-success">
3483
+ <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
3484
+ <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
3485
+ </svg>
3486
+ <span class="font-medium">${escapeHtml(message)}</span>
3487
+ </div>
3488
+ ${details ? `<p class="mt-2 text-sm text-text-secondary">${escapeHtml(details)}</p>` : ""}
3489
+ </div>`;
3490
+ }
3491
+ function loadingDisplay(message = "Loading...") {
3492
+ return `<div class="flex items-center justify-center p-8">
3493
+ <div class="flex items-center gap-3 text-text-secondary">
3494
+ <svg class="animate-spin w-5 h-5" fill="none" viewBox="0 0 24 24">
3495
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
3496
+ <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
3497
+ </svg>
3498
+ <span>${escapeHtml(message)}</span>
3499
+ </div>
3500
+ </div>`;
3501
+ }
3502
+ export {
3503
+ buildTemplateContext,
3504
+ container,
3505
+ createTemplate,
3506
+ createToolUI,
3507
+ dataList,
3508
+ errorDisplay,
3509
+ executeTemplate,
3510
+ heading,
3511
+ keyValue,
3512
+ loadingDisplay,
3513
+ paragraph,
3514
+ renderTemplate2 as renderTemplate,
3515
+ renderToolTemplate,
3516
+ renderToolTemplateAsync,
3517
+ successDisplay
3518
+ };