@frontmcp/uipack 0.12.2 → 1.0.0-beta.2

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 (298) hide show
  1. package/CLAUDE.md +56 -154
  2. package/README.md +367 -62
  3. package/adapters/base-template.d.ts +30 -0
  4. package/adapters/base-template.d.ts.map +1 -0
  5. package/adapters/cdn-info.d.ts +34 -0
  6. package/adapters/cdn-info.d.ts.map +1 -0
  7. package/adapters/constants.d.ts +18 -0
  8. package/adapters/constants.d.ts.map +1 -0
  9. package/adapters/content-detector.d.ts +19 -0
  10. package/adapters/content-detector.d.ts.map +1 -0
  11. package/adapters/content-renderers.d.ts +27 -0
  12. package/adapters/content-renderers.d.ts.map +1 -0
  13. package/adapters/index.d.ts +14 -7
  14. package/adapters/index.d.ts.map +1 -1
  15. package/adapters/index.js +2343 -426
  16. package/adapters/render-failure.d.ts +18 -0
  17. package/adapters/render-failure.d.ts.map +1 -0
  18. package/adapters/response-builder.d.ts +34 -104
  19. package/adapters/response-builder.d.ts.map +1 -1
  20. package/adapters/serving-mode.d.ts +28 -91
  21. package/adapters/serving-mode.d.ts.map +1 -1
  22. package/adapters/template-renderer.d.ts +50 -0
  23. package/adapters/template-renderer.d.ts.map +1 -0
  24. package/adapters/type-detector.d.ts +18 -0
  25. package/adapters/type-detector.d.ts.map +1 -0
  26. package/bridge-runtime/index.js +1 -1
  27. package/component/index.d.ts +14 -0
  28. package/component/index.d.ts.map +1 -0
  29. package/component/index.js +2043 -0
  30. package/component/loader.d.ts +36 -0
  31. package/component/loader.d.ts.map +1 -0
  32. package/component/renderer.d.ts +30 -0
  33. package/component/renderer.d.ts.map +1 -0
  34. package/component/transpiler.d.ts +49 -0
  35. package/component/transpiler.d.ts.map +1 -0
  36. package/component/types.d.ts +82 -0
  37. package/component/types.d.ts.map +1 -0
  38. package/esm/adapters/index.mjs +2337 -422
  39. package/esm/bridge-runtime/index.mjs +1 -1
  40. package/esm/component/index.mjs +2013 -0
  41. package/esm/index.mjs +3446 -13935
  42. package/esm/package.json +3 -12
  43. package/esm/resolver/index.mjs +661 -0
  44. package/esm/shell/index.mjs +1406 -0
  45. package/esm/types/index.mjs +11 -11
  46. package/esm/utils/index.mjs +53 -8
  47. package/index.d.ts +12 -40
  48. package/index.d.ts.map +1 -1
  49. package/index.js +3579 -14218
  50. package/package.json +3 -12
  51. package/resolver/cdn-registry.d.ts +39 -0
  52. package/resolver/cdn-registry.d.ts.map +1 -0
  53. package/resolver/esm-sh.resolver.d.ts +54 -0
  54. package/resolver/esm-sh.resolver.d.ts.map +1 -0
  55. package/resolver/import-map.d.ts +47 -0
  56. package/resolver/import-map.d.ts.map +1 -0
  57. package/resolver/import-parser.d.ts +28 -0
  58. package/resolver/import-parser.d.ts.map +1 -0
  59. package/resolver/import-rewriter.d.ts +29 -0
  60. package/resolver/import-rewriter.d.ts.map +1 -0
  61. package/resolver/index.d.ts +15 -0
  62. package/resolver/index.d.ts.map +1 -0
  63. package/resolver/index.js +708 -0
  64. package/resolver/types.d.ts +191 -0
  65. package/resolver/types.d.ts.map +1 -0
  66. package/shell/builder.d.ts +31 -0
  67. package/shell/builder.d.ts.map +1 -0
  68. package/shell/csp.d.ts +37 -0
  69. package/shell/csp.d.ts.map +1 -0
  70. package/shell/custom-shell-applier.d.ts +33 -0
  71. package/shell/custom-shell-applier.d.ts.map +1 -0
  72. package/shell/custom-shell-resolver.d.ts +47 -0
  73. package/shell/custom-shell-resolver.d.ts.map +1 -0
  74. package/shell/custom-shell-types.d.ts +75 -0
  75. package/shell/custom-shell-types.d.ts.map +1 -0
  76. package/shell/custom-shell-validator.d.ts +26 -0
  77. package/shell/custom-shell-validator.d.ts.map +1 -0
  78. package/shell/data-injector.d.ts +40 -0
  79. package/shell/data-injector.d.ts.map +1 -0
  80. package/shell/index.d.ts +19 -0
  81. package/shell/index.d.ts.map +1 -0
  82. package/shell/index.js +1453 -0
  83. package/shell/types.d.ts +54 -0
  84. package/shell/types.d.ts.map +1 -0
  85. package/types/index.d.ts +1 -3
  86. package/types/index.d.ts.map +1 -1
  87. package/types/index.js +11 -11
  88. package/types/ui-config.d.ts +50 -11
  89. package/types/ui-config.d.ts.map +1 -1
  90. package/types/ui-runtime.d.ts +8 -82
  91. package/types/ui-runtime.d.ts.map +1 -1
  92. package/utils/index.d.ts +9 -3
  93. package/utils/index.d.ts.map +1 -1
  94. package/utils/index.js +59 -7
  95. package/adapters/platform-meta.constants.d.ts +0 -26
  96. package/adapters/platform-meta.constants.d.ts.map +0 -1
  97. package/adapters/platform-meta.d.ts +0 -234
  98. package/adapters/platform-meta.d.ts.map +0 -1
  99. package/base-template/bridge.d.ts +0 -90
  100. package/base-template/bridge.d.ts.map +0 -1
  101. package/base-template/default-base-template.d.ts +0 -91
  102. package/base-template/default-base-template.d.ts.map +0 -1
  103. package/base-template/index.d.ts +0 -15
  104. package/base-template/index.d.ts.map +0 -1
  105. package/base-template/index.js +0 -1393
  106. package/base-template/polyfills.d.ts +0 -31
  107. package/base-template/polyfills.d.ts.map +0 -1
  108. package/base-template/theme-styles.d.ts +0 -74
  109. package/base-template/theme-styles.d.ts.map +0 -1
  110. package/build/builders/base-builder.d.ts +0 -124
  111. package/build/builders/base-builder.d.ts.map +0 -1
  112. package/build/builders/esbuild-config.d.ts +0 -94
  113. package/build/builders/esbuild-config.d.ts.map +0 -1
  114. package/build/builders/hybrid-builder.d.ts +0 -93
  115. package/build/builders/hybrid-builder.d.ts.map +0 -1
  116. package/build/builders/index.d.ts +0 -17
  117. package/build/builders/index.d.ts.map +0 -1
  118. package/build/builders/inline-builder.d.ts +0 -83
  119. package/build/builders/inline-builder.d.ts.map +0 -1
  120. package/build/builders/static-builder.d.ts +0 -78
  121. package/build/builders/static-builder.d.ts.map +0 -1
  122. package/build/builders/types.d.ts +0 -341
  123. package/build/builders/types.d.ts.map +0 -1
  124. package/build/cdn-resources.d.ts +0 -244
  125. package/build/cdn-resources.d.ts.map +0 -1
  126. package/build/hybrid-data.d.ts +0 -127
  127. package/build/hybrid-data.d.ts.map +0 -1
  128. package/build/index.d.ts +0 -299
  129. package/build/index.d.ts.map +0 -1
  130. package/build/index.js +0 -8699
  131. package/build/ui-components-browser.d.ts +0 -64
  132. package/build/ui-components-browser.d.ts.map +0 -1
  133. package/build/widget-manifest.d.ts +0 -362
  134. package/build/widget-manifest.d.ts.map +0 -1
  135. package/bundler/cache.d.ts +0 -173
  136. package/bundler/cache.d.ts.map +0 -1
  137. package/bundler/file-cache/component-builder.d.ts +0 -167
  138. package/bundler/file-cache/component-builder.d.ts.map +0 -1
  139. package/bundler/file-cache/hash-calculator.d.ts +0 -155
  140. package/bundler/file-cache/hash-calculator.d.ts.map +0 -1
  141. package/bundler/file-cache/index.d.ts +0 -12
  142. package/bundler/file-cache/index.d.ts.map +0 -1
  143. package/bundler/file-cache/storage/filesystem.d.ts +0 -149
  144. package/bundler/file-cache/storage/filesystem.d.ts.map +0 -1
  145. package/bundler/file-cache/storage/index.d.ts +0 -11
  146. package/bundler/file-cache/storage/index.d.ts.map +0 -1
  147. package/bundler/file-cache/storage/interface.d.ts +0 -152
  148. package/bundler/file-cache/storage/interface.d.ts.map +0 -1
  149. package/bundler/file-cache/storage/redis.d.ts +0 -139
  150. package/bundler/file-cache/storage/redis.d.ts.map +0 -1
  151. package/bundler/index.d.ts +0 -35
  152. package/bundler/index.d.ts.map +0 -1
  153. package/bundler/index.js +0 -2953
  154. package/bundler/sandbox/enclave-adapter.d.ts +0 -121
  155. package/bundler/sandbox/enclave-adapter.d.ts.map +0 -1
  156. package/bundler/sandbox/executor.d.ts +0 -14
  157. package/bundler/sandbox/executor.d.ts.map +0 -1
  158. package/bundler/sandbox/policy.d.ts +0 -62
  159. package/bundler/sandbox/policy.d.ts.map +0 -1
  160. package/bundler/types.d.ts +0 -702
  161. package/bundler/types.d.ts.map +0 -1
  162. package/dependency/cdn-registry.d.ts +0 -98
  163. package/dependency/cdn-registry.d.ts.map +0 -1
  164. package/dependency/import-map.d.ts +0 -186
  165. package/dependency/import-map.d.ts.map +0 -1
  166. package/dependency/import-parser.d.ts +0 -82
  167. package/dependency/import-parser.d.ts.map +0 -1
  168. package/dependency/index.d.ts +0 -17
  169. package/dependency/index.d.ts.map +0 -1
  170. package/dependency/index.js +0 -3180
  171. package/dependency/resolver.d.ts +0 -164
  172. package/dependency/resolver.d.ts.map +0 -1
  173. package/dependency/schemas.d.ts +0 -486
  174. package/dependency/schemas.d.ts.map +0 -1
  175. package/dependency/template-loader.d.ts +0 -204
  176. package/dependency/template-loader.d.ts.map +0 -1
  177. package/dependency/template-processor.d.ts +0 -118
  178. package/dependency/template-processor.d.ts.map +0 -1
  179. package/dependency/types.d.ts +0 -739
  180. package/dependency/types.d.ts.map +0 -1
  181. package/esm/base-template/index.mjs +0 -1359
  182. package/esm/build/index.mjs +0 -8601
  183. package/esm/bundler/index.mjs +0 -2895
  184. package/esm/dependency/index.mjs +0 -3068
  185. package/esm/handlebars/index.mjs +0 -587
  186. package/esm/registry/index.mjs +0 -6305
  187. package/esm/renderers/index.mjs +0 -1557
  188. package/esm/runtime/index.mjs +0 -5361
  189. package/esm/styles/index.mjs +0 -171
  190. package/esm/theme/index.mjs +0 -756
  191. package/esm/tool-template/index.mjs +0 -3652
  192. package/esm/validation/index.mjs +0 -542
  193. package/handlebars/expression-extractor.d.ts +0 -147
  194. package/handlebars/expression-extractor.d.ts.map +0 -1
  195. package/handlebars/helpers.d.ts +0 -339
  196. package/handlebars/helpers.d.ts.map +0 -1
  197. package/handlebars/index.d.ts +0 -195
  198. package/handlebars/index.d.ts.map +0 -1
  199. package/handlebars/index.js +0 -659
  200. package/preview/claude-preview.d.ts +0 -67
  201. package/preview/claude-preview.d.ts.map +0 -1
  202. package/preview/generic-preview.d.ts +0 -66
  203. package/preview/generic-preview.d.ts.map +0 -1
  204. package/preview/index.d.ts +0 -36
  205. package/preview/index.d.ts.map +0 -1
  206. package/preview/openai-preview.d.ts +0 -70
  207. package/preview/openai-preview.d.ts.map +0 -1
  208. package/preview/types.d.ts +0 -199
  209. package/preview/types.d.ts.map +0 -1
  210. package/registry/index.d.ts +0 -46
  211. package/registry/index.d.ts.map +0 -1
  212. package/registry/index.js +0 -6342
  213. package/registry/render-template.d.ts +0 -91
  214. package/registry/render-template.d.ts.map +0 -1
  215. package/registry/tool-ui.registry.d.ts +0 -294
  216. package/registry/tool-ui.registry.d.ts.map +0 -1
  217. package/registry/uri-utils.d.ts +0 -56
  218. package/registry/uri-utils.d.ts.map +0 -1
  219. package/renderers/cache.d.ts +0 -145
  220. package/renderers/cache.d.ts.map +0 -1
  221. package/renderers/html.renderer.d.ts +0 -123
  222. package/renderers/html.renderer.d.ts.map +0 -1
  223. package/renderers/index.d.ts +0 -36
  224. package/renderers/index.d.ts.map +0 -1
  225. package/renderers/index.js +0 -1603
  226. package/renderers/mdx-client.renderer.d.ts +0 -124
  227. package/renderers/mdx-client.renderer.d.ts.map +0 -1
  228. package/renderers/registry.d.ts +0 -133
  229. package/renderers/registry.d.ts.map +0 -1
  230. package/renderers/types.d.ts +0 -343
  231. package/renderers/types.d.ts.map +0 -1
  232. package/renderers/utils/detect.d.ts +0 -107
  233. package/renderers/utils/detect.d.ts.map +0 -1
  234. package/renderers/utils/hash.d.ts +0 -40
  235. package/renderers/utils/hash.d.ts.map +0 -1
  236. package/renderers/utils/index.d.ts +0 -9
  237. package/renderers/utils/index.d.ts.map +0 -1
  238. package/renderers/utils/transpiler.d.ts +0 -70
  239. package/renderers/utils/transpiler.d.ts.map +0 -1
  240. package/runtime/adapters/html.adapter.d.ts +0 -59
  241. package/runtime/adapters/html.adapter.d.ts.map +0 -1
  242. package/runtime/adapters/index.d.ts +0 -26
  243. package/runtime/adapters/index.d.ts.map +0 -1
  244. package/runtime/adapters/mdx.adapter.d.ts +0 -73
  245. package/runtime/adapters/mdx.adapter.d.ts.map +0 -1
  246. package/runtime/adapters/types.d.ts +0 -95
  247. package/runtime/adapters/types.d.ts.map +0 -1
  248. package/runtime/csp.d.ts +0 -48
  249. package/runtime/csp.d.ts.map +0 -1
  250. package/runtime/index.d.ts +0 -17
  251. package/runtime/index.d.ts.map +0 -1
  252. package/runtime/index.js +0 -5432
  253. package/runtime/mcp-bridge.d.ts +0 -101
  254. package/runtime/mcp-bridge.d.ts.map +0 -1
  255. package/runtime/renderer-runtime.d.ts +0 -133
  256. package/runtime/renderer-runtime.d.ts.map +0 -1
  257. package/runtime/sanitizer.d.ts +0 -180
  258. package/runtime/sanitizer.d.ts.map +0 -1
  259. package/runtime/types.d.ts +0 -415
  260. package/runtime/types.d.ts.map +0 -1
  261. package/runtime/wrapper.d.ts +0 -421
  262. package/runtime/wrapper.d.ts.map +0 -1
  263. package/styles/index.d.ts +0 -8
  264. package/styles/index.d.ts.map +0 -1
  265. package/styles/index.js +0 -222
  266. package/styles/variants.d.ts +0 -51
  267. package/styles/variants.d.ts.map +0 -1
  268. package/theme/cdn.d.ts +0 -195
  269. package/theme/cdn.d.ts.map +0 -1
  270. package/theme/css-to-theme.d.ts +0 -64
  271. package/theme/css-to-theme.d.ts.map +0 -1
  272. package/theme/index.d.ts +0 -19
  273. package/theme/index.d.ts.map +0 -1
  274. package/theme/index.js +0 -814
  275. package/theme/platforms.d.ts +0 -102
  276. package/theme/platforms.d.ts.map +0 -1
  277. package/theme/presets/github-openai.d.ts +0 -50
  278. package/theme/presets/github-openai.d.ts.map +0 -1
  279. package/theme/presets/index.d.ts +0 -11
  280. package/theme/presets/index.d.ts.map +0 -1
  281. package/theme/theme.d.ts +0 -396
  282. package/theme/theme.d.ts.map +0 -1
  283. package/tool-template/builder.d.ts +0 -213
  284. package/tool-template/builder.d.ts.map +0 -1
  285. package/tool-template/index.d.ts +0 -16
  286. package/tool-template/index.d.ts.map +0 -1
  287. package/tool-template/index.js +0 -3690
  288. package/validation/error-box.d.ts +0 -56
  289. package/validation/error-box.d.ts.map +0 -1
  290. package/validation/index.d.ts +0 -13
  291. package/validation/index.d.ts.map +0 -1
  292. package/validation/index.js +0 -576
  293. package/validation/schema-paths.d.ts +0 -118
  294. package/validation/schema-paths.d.ts.map +0 -1
  295. package/validation/template-validator.d.ts +0 -143
  296. package/validation/template-validator.d.ts.map +0 -1
  297. package/validation/wrapper.d.ts +0 -97
  298. package/validation/wrapper.d.ts.map +0 -1
@@ -0,0 +1,2043 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // libs/uipack/src/component/index.ts
21
+ var component_exports = {};
22
+ __export(component_exports, {
23
+ FRONTMCP_META_KEY: () => FRONTMCP_META_KEY,
24
+ bundleFileSource: () => bundleFileSource,
25
+ extractDefaultExportName: () => extractDefaultExportName,
26
+ generateMountScript: () => generateMountScript,
27
+ isFileSource: () => isFileSource,
28
+ isFunctionSource: () => isFunctionSource,
29
+ isImportSource: () => isImportSource,
30
+ isNpmSource: () => isNpmSource,
31
+ renderComponent: () => renderComponent,
32
+ resolveUISource: () => resolveUISource,
33
+ transpileReactSource: () => transpileReactSource
34
+ });
35
+ module.exports = __toCommonJS(component_exports);
36
+
37
+ // libs/uipack/src/component/types.ts
38
+ function isNpmSource(source) {
39
+ return typeof source === "object" && source !== null && "npm" in source;
40
+ }
41
+ function isFileSource(source) {
42
+ return typeof source === "object" && source !== null && "file" in source;
43
+ }
44
+ function isImportSource(source) {
45
+ return typeof source === "object" && source !== null && "import" in source;
46
+ }
47
+ function isFunctionSource(source) {
48
+ return typeof source === "function";
49
+ }
50
+ var FRONTMCP_META_KEY = "__frontmcp_meta";
51
+
52
+ // libs/uipack/src/resolver/cdn-registry.ts
53
+ var DEFAULT_CDN_REGISTRY = {
54
+ react: {
55
+ packageName: "react",
56
+ defaultVersion: "19.2.4",
57
+ providers: {
58
+ cloudflare: {
59
+ url: "https://cdnjs.cloudflare.com/ajax/libs/react/19.2.4/umd/react.production.min.js",
60
+ global: "React",
61
+ crossorigin: "anonymous"
62
+ },
63
+ jsdelivr: {
64
+ url: "https://cdn.jsdelivr.net/npm/react@19.2.4/umd/react.production.min.js",
65
+ global: "React",
66
+ crossorigin: "anonymous"
67
+ },
68
+ unpkg: {
69
+ url: "https://unpkg.com/react@19.2.4/umd/react.production.min.js",
70
+ global: "React",
71
+ crossorigin: "anonymous"
72
+ },
73
+ "esm.sh": {
74
+ url: "https://esm.sh/react@19.2.4",
75
+ esm: true,
76
+ crossorigin: "anonymous"
77
+ }
78
+ },
79
+ preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
80
+ metadata: {
81
+ description: "A JavaScript library for building user interfaces",
82
+ homepage: "https://react.dev",
83
+ license: "MIT"
84
+ }
85
+ },
86
+ "react-dom": {
87
+ packageName: "react-dom",
88
+ defaultVersion: "19.2.4",
89
+ providers: {
90
+ cloudflare: {
91
+ url: "https://cdnjs.cloudflare.com/ajax/libs/react-dom/19.2.4/umd/react-dom.production.min.js",
92
+ global: "ReactDOM",
93
+ crossorigin: "anonymous",
94
+ peerDependencies: ["react"]
95
+ },
96
+ jsdelivr: {
97
+ url: "https://cdn.jsdelivr.net/npm/react-dom@19.2.4/umd/react-dom.production.min.js",
98
+ global: "ReactDOM",
99
+ crossorigin: "anonymous",
100
+ peerDependencies: ["react"]
101
+ },
102
+ unpkg: {
103
+ url: "https://unpkg.com/react-dom@19.2.4/umd/react-dom.production.min.js",
104
+ global: "ReactDOM",
105
+ crossorigin: "anonymous",
106
+ peerDependencies: ["react"]
107
+ },
108
+ "esm.sh": {
109
+ url: "https://esm.sh/react-dom@19.2.4",
110
+ esm: true,
111
+ crossorigin: "anonymous",
112
+ peerDependencies: ["react"]
113
+ }
114
+ },
115
+ preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
116
+ metadata: {
117
+ description: "React package for working with the DOM",
118
+ homepage: "https://react.dev",
119
+ license: "MIT"
120
+ }
121
+ },
122
+ "chart.js": {
123
+ packageName: "chart.js",
124
+ defaultVersion: "4.5.1",
125
+ providers: {
126
+ cloudflare: {
127
+ url: "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.1/chart.umd.min.js",
128
+ global: "Chart",
129
+ crossorigin: "anonymous"
130
+ },
131
+ jsdelivr: {
132
+ url: "https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js",
133
+ global: "Chart",
134
+ crossorigin: "anonymous"
135
+ },
136
+ unpkg: {
137
+ url: "https://unpkg.com/chart.js@4.5.1/dist/chart.umd.min.js",
138
+ global: "Chart",
139
+ crossorigin: "anonymous"
140
+ }
141
+ },
142
+ preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
143
+ metadata: {
144
+ description: "Simple yet flexible JavaScript charting library",
145
+ homepage: "https://www.chartjs.org",
146
+ license: "MIT"
147
+ }
148
+ },
149
+ d3: {
150
+ packageName: "d3",
151
+ defaultVersion: "7.9.0",
152
+ providers: {
153
+ cloudflare: {
154
+ url: "https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js",
155
+ integrity: "sha512-vc58qvvBdrDR4etbxMdlTt4GBQk1qjvyORR2nrsPsFPyrs+/u5c3+1Ct6upOgdZoIl7eq6k3a1UPDSNAQi/32A==",
156
+ global: "d3",
157
+ crossorigin: "anonymous"
158
+ },
159
+ jsdelivr: {
160
+ url: "https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js",
161
+ global: "d3",
162
+ crossorigin: "anonymous"
163
+ },
164
+ unpkg: {
165
+ url: "https://unpkg.com/d3@7.9.0/dist/d3.min.js",
166
+ global: "d3",
167
+ crossorigin: "anonymous"
168
+ }
169
+ },
170
+ preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
171
+ metadata: {
172
+ description: "Data-Driven Documents",
173
+ homepage: "https://d3js.org",
174
+ license: "ISC"
175
+ }
176
+ },
177
+ lodash: {
178
+ packageName: "lodash",
179
+ defaultVersion: "4.17.21",
180
+ providers: {
181
+ cloudflare: {
182
+ url: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js",
183
+ integrity: "sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==",
184
+ global: "_",
185
+ crossorigin: "anonymous"
186
+ },
187
+ jsdelivr: {
188
+ url: "https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js",
189
+ global: "_",
190
+ crossorigin: "anonymous"
191
+ },
192
+ unpkg: {
193
+ url: "https://unpkg.com/lodash@4.17.21/lodash.min.js",
194
+ global: "_",
195
+ crossorigin: "anonymous"
196
+ }
197
+ },
198
+ preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
199
+ metadata: {
200
+ description: "A modern JavaScript utility library",
201
+ homepage: "https://lodash.com",
202
+ license: "MIT"
203
+ }
204
+ }
205
+ };
206
+ function lookupPackage(packageName, registry = DEFAULT_CDN_REGISTRY) {
207
+ return registry[packageName];
208
+ }
209
+
210
+ // libs/uipack/src/resolver/import-parser.ts
211
+ var IMPORT_PATTERNS = {
212
+ named: /import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,
213
+ default: /import\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
214
+ namespace: /import\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
215
+ sideEffect: /import\s*['"]([^'"]+)['"]/g,
216
+ dynamic: /(?:await\s+)?import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
217
+ defaultAndNamed: /import\s+(\w+)\s*,\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,
218
+ defaultAndNamespace: /import\s+(\w+)\s*,\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
219
+ reExport: /export\s*\{[^}]+\}\s*from\s*['"]([^'"]+)['"]/g,
220
+ reExportAll: /export\s*\*\s*from\s*['"]([^'"]+)['"]/g
221
+ };
222
+ function parseNamedImports(namedString) {
223
+ return namedString.split(",").map((s) => s.trim()).filter((s) => s.length > 0).map((s) => {
224
+ const asMatch = s.match(/^(\w+)\s+as\s+\w+$/);
225
+ return asMatch ? asMatch[1] : s;
226
+ });
227
+ }
228
+ function isRelativeImport(specifier) {
229
+ return specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/");
230
+ }
231
+ function isExternalImport(specifier) {
232
+ return !isRelativeImport(specifier) && !specifier.startsWith("#");
233
+ }
234
+ function getPackageName(specifier) {
235
+ if (specifier.startsWith("@")) {
236
+ const parts = specifier.split("/");
237
+ if (parts.length >= 2) {
238
+ return `${parts[0]}/${parts[1]}`;
239
+ }
240
+ return specifier;
241
+ }
242
+ const firstSlash = specifier.indexOf("/");
243
+ return firstSlash === -1 ? specifier : specifier.slice(0, firstSlash);
244
+ }
245
+ function getLineNumber(source, index) {
246
+ let line = 1;
247
+ for (let i = 0; i < index && i < source.length; i++) {
248
+ if (source[i] === "\n") {
249
+ line++;
250
+ }
251
+ }
252
+ return line;
253
+ }
254
+ function getColumnNumber(source, index) {
255
+ let column = 0;
256
+ for (let i = index - 1; i >= 0 && source[i] !== "\n"; i--) {
257
+ column++;
258
+ }
259
+ return column;
260
+ }
261
+ function parseImports(source) {
262
+ const imports = [];
263
+ const seenStatements = /* @__PURE__ */ new Set();
264
+ const addImport = (imp) => {
265
+ const key = `${imp.type}:${imp.specifier}:${imp.statement}`;
266
+ if (!seenStatements.has(key)) {
267
+ seenStatements.add(key);
268
+ imports.push(imp);
269
+ }
270
+ };
271
+ let match;
272
+ const defaultAndNamedRegex = new RegExp(IMPORT_PATTERNS.defaultAndNamed.source, "g");
273
+ while ((match = defaultAndNamedRegex.exec(source)) !== null) {
274
+ const [statement, defaultName, namedString, specifier] = match;
275
+ addImport({
276
+ statement,
277
+ specifier,
278
+ type: "default",
279
+ defaultImport: defaultName,
280
+ namedImports: parseNamedImports(namedString),
281
+ line: getLineNumber(source, match.index),
282
+ column: getColumnNumber(source, match.index)
283
+ });
284
+ }
285
+ const defaultAndNamespaceRegex = new RegExp(IMPORT_PATTERNS.defaultAndNamespace.source, "g");
286
+ while ((match = defaultAndNamespaceRegex.exec(source)) !== null) {
287
+ const [statement, defaultName, namespaceName, specifier] = match;
288
+ addImport({
289
+ statement,
290
+ specifier,
291
+ type: "default",
292
+ defaultImport: defaultName,
293
+ namespaceImport: namespaceName,
294
+ line: getLineNumber(source, match.index),
295
+ column: getColumnNumber(source, match.index)
296
+ });
297
+ }
298
+ const namedRegex = new RegExp(IMPORT_PATTERNS.named.source, "g");
299
+ while ((match = namedRegex.exec(source)) !== null) {
300
+ const [statement, namedString, specifier] = match;
301
+ addImport({
302
+ statement,
303
+ specifier,
304
+ type: "named",
305
+ namedImports: parseNamedImports(namedString),
306
+ line: getLineNumber(source, match.index),
307
+ column: getColumnNumber(source, match.index)
308
+ });
309
+ }
310
+ const defaultRegex = new RegExp(IMPORT_PATTERNS.default.source, "g");
311
+ while ((match = defaultRegex.exec(source)) !== null) {
312
+ const [statement, defaultName, specifier] = match;
313
+ const afterMatch = source.slice(match.index + match[0].length - specifier.length - 2);
314
+ if (afterMatch.startsWith(",")) continue;
315
+ addImport({
316
+ statement,
317
+ specifier,
318
+ type: "default",
319
+ defaultImport: defaultName,
320
+ line: getLineNumber(source, match.index),
321
+ column: getColumnNumber(source, match.index)
322
+ });
323
+ }
324
+ const namespaceRegex = new RegExp(IMPORT_PATTERNS.namespace.source, "g");
325
+ while ((match = namespaceRegex.exec(source)) !== null) {
326
+ const [statement, namespaceName, specifier] = match;
327
+ addImport({
328
+ statement,
329
+ specifier,
330
+ type: "namespace",
331
+ namespaceImport: namespaceName,
332
+ line: getLineNumber(source, match.index),
333
+ column: getColumnNumber(source, match.index)
334
+ });
335
+ }
336
+ const sideEffectRegex = new RegExp(IMPORT_PATTERNS.sideEffect.source, "g");
337
+ while ((match = sideEffectRegex.exec(source)) !== null) {
338
+ const [statement, specifier] = match;
339
+ const beforeMatch = source.slice(Math.max(0, match.index - 50), match.index);
340
+ if (beforeMatch.includes("from")) continue;
341
+ addImport({
342
+ statement,
343
+ specifier,
344
+ type: "side-effect",
345
+ line: getLineNumber(source, match.index),
346
+ column: getColumnNumber(source, match.index)
347
+ });
348
+ }
349
+ const dynamicRegex = new RegExp(IMPORT_PATTERNS.dynamic.source, "g");
350
+ while ((match = dynamicRegex.exec(source)) !== null) {
351
+ const [statement, specifier] = match;
352
+ addImport({
353
+ statement,
354
+ specifier,
355
+ type: "dynamic",
356
+ line: getLineNumber(source, match.index),
357
+ column: getColumnNumber(source, match.index)
358
+ });
359
+ }
360
+ const reExportRegex = new RegExp(IMPORT_PATTERNS.reExport.source, "g");
361
+ while ((match = reExportRegex.exec(source)) !== null) {
362
+ const [statement, specifier] = match;
363
+ addImport({
364
+ statement,
365
+ specifier,
366
+ type: "named",
367
+ line: getLineNumber(source, match.index),
368
+ column: getColumnNumber(source, match.index)
369
+ });
370
+ }
371
+ const reExportAllRegex = new RegExp(IMPORT_PATTERNS.reExportAll.source, "g");
372
+ while ((match = reExportAllRegex.exec(source)) !== null) {
373
+ const [statement, specifier] = match;
374
+ addImport({
375
+ statement,
376
+ specifier,
377
+ type: "namespace",
378
+ line: getLineNumber(source, match.index),
379
+ column: getColumnNumber(source, match.index)
380
+ });
381
+ }
382
+ const externalImports = imports.filter((imp) => isExternalImport(imp.specifier));
383
+ const relativeImports = imports.filter((imp) => isRelativeImport(imp.specifier));
384
+ const externalPackages = [...new Set(externalImports.map((imp) => getPackageName(imp.specifier)))];
385
+ return {
386
+ imports,
387
+ externalImports,
388
+ relativeImports,
389
+ externalPackages
390
+ };
391
+ }
392
+
393
+ // libs/uipack/src/resolver/esm-sh.resolver.ts
394
+ var DEFAULT_FALLBACK_CDN = "https://esm.sh";
395
+ function createEsmShResolver(options = {}) {
396
+ const {
397
+ fallbackCdnBase = DEFAULT_FALLBACK_CDN,
398
+ registry = DEFAULT_CDN_REGISTRY,
399
+ providerOrder = ["esm.sh", "cloudflare", "jsdelivr", "unpkg"]
400
+ } = options;
401
+ return {
402
+ resolve(specifier, _context) {
403
+ if (specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/")) {
404
+ return null;
405
+ }
406
+ if (specifier.startsWith("node:") || specifier.startsWith("#")) {
407
+ return null;
408
+ }
409
+ const pkgName = getPackageName(specifier);
410
+ const entry = lookupPackage(pkgName, registry);
411
+ if (entry) {
412
+ for (const provider of providerOrder) {
413
+ const config = entry.providers[provider];
414
+ if (config?.url) {
415
+ const subpath = specifier.slice(pkgName.length);
416
+ if (subpath && config.url.includes("esm.sh/")) {
417
+ return {
418
+ value: config.url + subpath,
419
+ type: "url",
420
+ integrity: config.integrity
421
+ };
422
+ }
423
+ if (subpath) {
424
+ return {
425
+ value: `${fallbackCdnBase}/${specifier}`,
426
+ type: "url"
427
+ };
428
+ }
429
+ if (config.global && !config.esm) {
430
+ return {
431
+ value: config.url,
432
+ type: "url",
433
+ integrity: config.integrity
434
+ };
435
+ }
436
+ return {
437
+ value: config.url,
438
+ type: "url",
439
+ integrity: config.integrity
440
+ };
441
+ }
442
+ }
443
+ }
444
+ return {
445
+ value: `${fallbackCdnBase}/${specifier}`,
446
+ type: "url"
447
+ };
448
+ }
449
+ };
450
+ }
451
+
452
+ // libs/uipack/src/utils/index.ts
453
+ function escapeScriptClose(jsonString) {
454
+ return jsonString.replace(/<\//g, "<\\/");
455
+ }
456
+ function safeJsonForScript(value) {
457
+ if (value === void 0) {
458
+ return "null";
459
+ }
460
+ try {
461
+ const jsonString = JSON.stringify(value, (_key, val) => {
462
+ if (typeof val === "bigint") {
463
+ return val.toString();
464
+ }
465
+ return val;
466
+ });
467
+ if (jsonString === void 0) {
468
+ return "null";
469
+ }
470
+ return escapeScriptClose(jsonString);
471
+ } catch {
472
+ return '{"error":"Value could not be serialized"}';
473
+ }
474
+ }
475
+
476
+ // libs/uipack/src/component/transpiler.ts
477
+ function transpileReactSource(source, filename) {
478
+ const esbuild = require("esbuild");
479
+ const loader = filename?.endsWith(".tsx") ? "tsx" : "jsx";
480
+ const result = esbuild.transformSync(source, {
481
+ loader,
482
+ jsx: "transform",
483
+ jsxFactory: "React.createElement",
484
+ jsxFragment: "React.Fragment",
485
+ format: "esm",
486
+ target: "es2020",
487
+ define: { "process.env.NODE_ENV": '"production"' }
488
+ });
489
+ return result.code;
490
+ }
491
+ function bundleFileSource(source, filename, resolveDir, componentName) {
492
+ const esbuild = require("esbuild");
493
+ const mountCode = `
494
+ // --- Auto-generated mount ---
495
+ import { createRoot } from 'react-dom/client';
496
+ import { McpBridgeProvider } from '@frontmcp/ui/react';
497
+ import React from 'react';
498
+ const __root = document.getElementById('root');
499
+ if (__root) {
500
+ createRoot(__root).render(
501
+ React.createElement(McpBridgeProvider, null,
502
+ React.createElement(${componentName})
503
+ )
504
+ );
505
+ }`;
506
+ const loader = {
507
+ ".tsx": "tsx",
508
+ ".jsx": "jsx"
509
+ };
510
+ const stdinLoader = filename.endsWith(".tsx") ? "tsx" : "jsx";
511
+ try {
512
+ const result = esbuild.buildSync({
513
+ stdin: {
514
+ contents: source + "\n" + mountCode,
515
+ loader: stdinLoader,
516
+ resolveDir,
517
+ sourcefile: filename
518
+ },
519
+ bundle: true,
520
+ write: false,
521
+ format: "esm",
522
+ target: "es2020",
523
+ jsx: "transform",
524
+ jsxFactory: "React.createElement",
525
+ jsxFragment: "React.Fragment",
526
+ external: ["react", "react-dom"],
527
+ define: { "process.env.NODE_ENV": '"production"' },
528
+ platform: "browser",
529
+ treeShaking: true,
530
+ logLevel: "warning",
531
+ loader
532
+ });
533
+ return { code: result.outputFiles[0].text };
534
+ } catch (err) {
535
+ const message = err instanceof Error ? err.message : String(err);
536
+ throw new Error(
537
+ `Failed to bundle FileSource "${filename}": ${message}. Ensure workspace packages are built (e.g. nx build ui).`
538
+ );
539
+ }
540
+ }
541
+ function extractDefaultExportName(code) {
542
+ let match = code.match(/export\s+default\s+(?:function|class)\s+(\w+)/);
543
+ if (match) return match[1];
544
+ match = code.match(/export\s+default\s+(\w+)\s*;/);
545
+ if (match) return match[1];
546
+ return null;
547
+ }
548
+
549
+ // libs/uipack/src/component/loader.ts
550
+ var DEFAULT_META = {
551
+ mcpAware: false,
552
+ renderer: "auto"
553
+ };
554
+ function resolveUISource(source, options) {
555
+ const resolver = options?.resolver ?? createEsmShResolver();
556
+ if (isNpmSource(source)) {
557
+ return resolveNpmSource(source, resolver);
558
+ }
559
+ if (isImportSource(source)) {
560
+ return resolveImportSource(source);
561
+ }
562
+ if (isFileSource(source)) {
563
+ return resolveFileSource(source);
564
+ }
565
+ if (isFunctionSource(source)) {
566
+ return resolveFunctionSource(source, options?.input, options?.output);
567
+ }
568
+ throw new Error("Unknown UISource type");
569
+ }
570
+ function resolveNpmSource(source, resolver) {
571
+ const specifier = source.version ? `${source.npm}@${source.version}` : source.npm;
572
+ const pkgName = getPackageName(source.npm);
573
+ const resolved = resolver.resolve(specifier);
574
+ const url = resolved?.value ?? `https://esm.sh/${specifier}`;
575
+ const peerDeps = [];
576
+ if (pkgName !== "react" && pkgName !== "react-dom") {
577
+ peerDeps.push("react", "react-dom");
578
+ }
579
+ return {
580
+ mode: "module",
581
+ url,
582
+ exportName: source.exportName ?? "default",
583
+ meta: { ...DEFAULT_META, renderer: "react" },
584
+ peerDependencies: peerDeps
585
+ };
586
+ }
587
+ function resolveImportSource(source) {
588
+ return {
589
+ mode: "module",
590
+ url: source.import,
591
+ exportName: source.exportName ?? "default",
592
+ meta: { ...DEFAULT_META },
593
+ peerDependencies: []
594
+ };
595
+ }
596
+ function resolveFileSource(source) {
597
+ const path = require("path");
598
+ const ext = path.extname(source.file).toLowerCase();
599
+ if (ext === ".tsx" || ext === ".jsx") {
600
+ const fs = require("fs");
601
+ const filePath = path.isAbsolute(source.file) ? source.file : path.resolve(process.cwd(), source.file);
602
+ const rawSource = fs.readFileSync(filePath, "utf-8");
603
+ const componentName = source.exportName || extractDefaultExportName(rawSource) || "Component";
604
+ const bundled = bundleFileSource(rawSource, source.file, path.dirname(filePath), componentName);
605
+ const parsed = parseImports(bundled.code);
606
+ return {
607
+ mode: "module",
608
+ code: bundled.code,
609
+ imports: [...new Set(parsed.externalImports.map((i) => i.specifier))],
610
+ exportName: componentName,
611
+ meta: { mcpAware: true, renderer: "react" },
612
+ peerDependencies: source.peerDependencies || ["react", "react-dom"],
613
+ bundled: true
614
+ };
615
+ }
616
+ if (source.inline) {
617
+ return {
618
+ mode: "inline",
619
+ html: `<!-- File source: ${source.file} (inline mode - content to be resolved at build time) -->`,
620
+ exportName: "default",
621
+ meta: { ...DEFAULT_META, renderer: "html" },
622
+ peerDependencies: []
623
+ };
624
+ }
625
+ return {
626
+ mode: "module",
627
+ url: source.file,
628
+ exportName: "default",
629
+ meta: { ...DEFAULT_META },
630
+ peerDependencies: []
631
+ };
632
+ }
633
+ function resolveFunctionSource(source, input, output) {
634
+ const html = source(input, output);
635
+ return {
636
+ mode: "inline",
637
+ html,
638
+ exportName: "default",
639
+ meta: { mcpAware: false, renderer: "html" },
640
+ peerDependencies: []
641
+ };
642
+ }
643
+ function generateMountScript(resolved, propsMapping) {
644
+ if (resolved.mode !== "module" || !resolved.url) {
645
+ return "";
646
+ }
647
+ const componentImport = resolved.exportName === "default" ? `import Component from '${resolved.url}';` : `import { ${resolved.exportName} as Component } from '${resolved.url}';`;
648
+ if (resolved.meta.mcpAware) {
649
+ return `${componentImport}
650
+ import React from 'react';
651
+ import { createRoot } from 'react-dom/client';
652
+ createRoot(document.getElementById('root'))
653
+ .render(React.createElement(Component));`;
654
+ }
655
+ const propsCode = propsMapping ? generateMappedPropsCode(propsMapping) : "window.__mcpToolOutput";
656
+ return `${componentImport}
657
+ import React from 'react';
658
+ import { createRoot } from 'react-dom/client';
659
+ const output = window.__mcpToolOutput;
660
+ const props = ${propsCode};
661
+ createRoot(document.getElementById('root'))
662
+ .render(React.createElement(Component, props));`;
663
+ }
664
+ function generateMappedPropsCode(mapping) {
665
+ const entries = Object.entries(mapping).map(([prop, path]) => {
666
+ const accessPath = path.split(".").map((part) => `[${safeJsonForScript(part)}]`).join("");
667
+ return `${safeJsonForScript(prop)}: output${accessPath}`;
668
+ }).join(", ");
669
+ return `({ ${entries} })`;
670
+ }
671
+
672
+ // libs/uipack/src/shell/csp.ts
673
+ var DEFAULT_CDN_DOMAINS = [
674
+ "https://cdn.jsdelivr.net",
675
+ "https://cdnjs.cloudflare.com",
676
+ "https://fonts.googleapis.com",
677
+ "https://fonts.gstatic.com",
678
+ "https://esm.sh"
679
+ ];
680
+ var DEFAULT_CSP_DIRECTIVES = [
681
+ "default-src 'none'",
682
+ `script-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
683
+ `style-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
684
+ `img-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
685
+ `font-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
686
+ `connect-src ${DEFAULT_CDN_DOMAINS.join(" ")}`,
687
+ "object-src 'self' data:"
688
+ ];
689
+ function buildCSPDirectives(csp) {
690
+ if (!csp) {
691
+ return [...DEFAULT_CSP_DIRECTIVES];
692
+ }
693
+ const validResourceDomains = sanitizeCSPDomains(csp.resourceDomains);
694
+ const validConnectDomains = sanitizeCSPDomains(csp.connectDomains);
695
+ const allResourceDomains = [.../* @__PURE__ */ new Set([...DEFAULT_CDN_DOMAINS, ...validResourceDomains])];
696
+ const directives = [
697
+ "default-src 'none'",
698
+ `script-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`,
699
+ `style-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`
700
+ ];
701
+ const imgSources = ["'self'", "data:", ...allResourceDomains];
702
+ directives.push(`img-src ${imgSources.join(" ")}`);
703
+ const fontSources = ["'self'", "data:", ...allResourceDomains];
704
+ directives.push(`font-src ${fontSources.join(" ")}`);
705
+ if (validConnectDomains.length) {
706
+ directives.push(`connect-src ${validConnectDomains.join(" ")}`);
707
+ } else {
708
+ directives.push(`connect-src ${allResourceDomains.join(" ")}`);
709
+ }
710
+ directives.push("object-src 'self' data:");
711
+ return directives;
712
+ }
713
+ function buildCSPMetaTag(csp) {
714
+ const directives = buildCSPDirectives(csp);
715
+ const content = directives.join("; ");
716
+ return `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(content)}">`;
717
+ }
718
+ function validateCSPDomain(domain) {
719
+ if (domain.startsWith("https://*.")) {
720
+ const rest = domain.slice(10);
721
+ return /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.[a-zA-Z]{2,}$/.test(rest);
722
+ }
723
+ try {
724
+ const url = new URL(domain);
725
+ return url.protocol === "https:";
726
+ } catch {
727
+ return false;
728
+ }
729
+ }
730
+ function sanitizeCSPDomains(domains) {
731
+ if (!domains) return [];
732
+ const valid = [];
733
+ for (const domain of domains) {
734
+ if (validateCSPDomain(domain)) {
735
+ valid.push(domain);
736
+ } else {
737
+ console.warn(`Invalid CSP domain ignored: ${domain}`);
738
+ }
739
+ }
740
+ return valid;
741
+ }
742
+ function escapeAttribute(str) {
743
+ return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
744
+ }
745
+
746
+ // libs/uipack/src/shell/data-injector.ts
747
+ function buildDataInjectionScript(options) {
748
+ const { toolName, input, output, structuredContent } = options;
749
+ const lines = [
750
+ `window.__mcpToolName = ${safeJsonForScript(toolName)};`,
751
+ `window.__mcpToolInput = ${safeJsonForScript(input ?? null)};`,
752
+ `window.__mcpToolOutput = ${safeJsonForScript(output ?? null)};`,
753
+ `window.__mcpStructuredContent = ${safeJsonForScript(structuredContent ?? null)};`
754
+ ];
755
+ return `<script>
756
+ ${lines.join("\n")}
757
+ </script>`;
758
+ }
759
+
760
+ // libs/uipack/src/bridge-runtime/iife-generator.ts
761
+ function generateBridgeIIFE(options = {}) {
762
+ const { debug = false, trustedOrigins = [], minify = false } = options;
763
+ const adapters = options.adapters || ["openai", "ext-apps", "claude", "gemini", "generic"];
764
+ const parts = [];
765
+ parts.push("(function() {");
766
+ parts.push('"use strict";');
767
+ parts.push("");
768
+ if (debug) {
769
+ parts.push('function log(msg) { console.log("[FrontMcpBridge] " + msg); }');
770
+ } else {
771
+ parts.push("function log() {}");
772
+ }
773
+ parts.push("");
774
+ parts.push("var DEFAULT_SAFE_AREA = { top: 0, bottom: 0, left: 0, right: 0 };");
775
+ parts.push("");
776
+ parts.push(generateContextDetection());
777
+ parts.push("");
778
+ parts.push(generateBaseCapabilities());
779
+ parts.push("");
780
+ if (adapters.includes("openai")) {
781
+ parts.push(generateOpenAIAdapter());
782
+ parts.push("");
783
+ }
784
+ if (adapters.includes("ext-apps")) {
785
+ parts.push(generateExtAppsAdapter(trustedOrigins));
786
+ parts.push("");
787
+ }
788
+ if (adapters.includes("claude")) {
789
+ parts.push(generateClaudeAdapter());
790
+ parts.push("");
791
+ }
792
+ if (adapters.includes("gemini")) {
793
+ parts.push(generateGeminiAdapter());
794
+ parts.push("");
795
+ }
796
+ if (adapters.includes("generic")) {
797
+ parts.push(generateGenericAdapter());
798
+ parts.push("");
799
+ }
800
+ parts.push(generatePlatformDetection(adapters));
801
+ parts.push("");
802
+ parts.push(generateBridgeClass());
803
+ parts.push("");
804
+ parts.push("var bridge = new FrontMcpBridge();");
805
+ parts.push("bridge.initialize().then(function() {");
806
+ parts.push(' log("Bridge initialized with adapter: " + bridge.adapterId);');
807
+ parts.push(' window.dispatchEvent(new CustomEvent("bridge:ready", { detail: { adapter: bridge.adapterId } }));');
808
+ parts.push("}).catch(function(err) {");
809
+ parts.push(' console.error("[FrontMcpBridge] Init failed:", err);');
810
+ parts.push(' window.dispatchEvent(new CustomEvent("bridge:error", { detail: { error: err } }));');
811
+ parts.push("});");
812
+ parts.push("");
813
+ parts.push("window.FrontMcpBridge = bridge;");
814
+ parts.push("})();");
815
+ const code = parts.join("\n");
816
+ if (minify) {
817
+ return minifyJS(code);
818
+ }
819
+ return code;
820
+ }
821
+ function generateContextDetection() {
822
+ return `
823
+ function detectTheme() {
824
+ if (typeof window !== 'undefined' && window.matchMedia) {
825
+ return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
826
+ }
827
+ return 'light';
828
+ }
829
+
830
+ function detectLocale() {
831
+ if (typeof navigator !== 'undefined') {
832
+ return navigator.language || 'en-US';
833
+ }
834
+ return 'en-US';
835
+ }
836
+
837
+ function detectUserAgent() {
838
+ if (typeof navigator === 'undefined') {
839
+ return { type: 'web', hover: true, touch: false };
840
+ }
841
+ var ua = navigator.userAgent || '';
842
+ var isMobile = /iPhone|iPad|iPod|Android/i.test(ua);
843
+ var hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
844
+ var hasHover = window.matchMedia && window.matchMedia('(hover: hover)').matches;
845
+ return { type: isMobile ? 'mobile' : 'web', hover: hasHover !== false, touch: hasTouch };
846
+ }
847
+
848
+ function detectViewport() {
849
+ if (typeof window !== 'undefined') {
850
+ return { width: window.innerWidth, height: window.innerHeight };
851
+ }
852
+ return undefined;
853
+ }
854
+
855
+ function readInjectedData() {
856
+ var data = { toolInput: {}, toolOutput: undefined, structuredContent: undefined };
857
+ if (typeof window !== 'undefined') {
858
+ if (window.__mcpToolInput) data.toolInput = window.__mcpToolInput;
859
+ if (window.__mcpToolOutput) data.toolOutput = window.__mcpToolOutput;
860
+ if (window.__mcpStructuredContent) data.structuredContent = window.__mcpStructuredContent;
861
+ }
862
+ return data;
863
+ }
864
+ `.trim();
865
+ }
866
+ function generateBaseCapabilities() {
867
+ return `
868
+ var DEFAULT_CAPABILITIES = {
869
+ canCallTools: false,
870
+ canSendMessages: false,
871
+ canOpenLinks: false,
872
+ canPersistState: true,
873
+ hasNetworkAccess: true,
874
+ supportsDisplayModes: false,
875
+ supportsTheme: true
876
+ };
877
+ `.trim();
878
+ }
879
+ function generateOpenAIAdapter() {
880
+ return `
881
+ var OpenAIAdapter = {
882
+ id: 'openai',
883
+ name: 'OpenAI ChatGPT',
884
+ priority: 100,
885
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
886
+ canCallTools: true,
887
+ canSendMessages: true,
888
+ canOpenLinks: true,
889
+ supportsDisplayModes: true
890
+ }),
891
+ canHandle: function() {
892
+ if (typeof window === 'undefined') return false;
893
+ // Check for window.openai.callTool (the actual OpenAI SDK API)
894
+ if (window.openai && typeof window.openai.callTool === 'function') return true;
895
+ // Also check if we're being injected with tool metadata (OpenAI injects toolOutput)
896
+ if (window.openai && (window.openai.toolOutput !== undefined || window.openai.toolInput !== undefined)) return true;
897
+ return false;
898
+ },
899
+ initialize: function(context) {
900
+ var sdk = window.openai;
901
+ context.sdk = sdk;
902
+ // OpenAI SDK exposes theme and displayMode directly as properties
903
+ if (sdk.theme) {
904
+ context.hostContext.theme = sdk.theme;
905
+ }
906
+ if (sdk.displayMode) {
907
+ context.hostContext.displayMode = sdk.displayMode;
908
+ }
909
+ // Note: OpenAI SDK does not have an onContextChange equivalent
910
+ return Promise.resolve();
911
+ },
912
+ callTool: function(context, name, args) {
913
+ return context.sdk.callTool(name, args);
914
+ },
915
+ sendMessage: function(context, content) {
916
+ if (typeof context.sdk.sendFollowUpMessage === 'function') {
917
+ return context.sdk.sendFollowUpMessage(content);
918
+ }
919
+ return Promise.reject(new Error('Messages not supported'));
920
+ },
921
+ openLink: function(context, url) {
922
+ window.open(url, '_blank', 'noopener,noreferrer');
923
+ return Promise.resolve();
924
+ },
925
+ requestDisplayMode: function(context, mode) {
926
+ return Promise.resolve();
927
+ },
928
+ requestClose: function(context) {
929
+ return Promise.resolve();
930
+ }
931
+ };
932
+ `.trim();
933
+ }
934
+ function generateExtAppsAdapter(trustedOrigins) {
935
+ const originsArray = trustedOrigins.length > 0 ? JSON.stringify(trustedOrigins) : "[]";
936
+ return `
937
+ var ExtAppsAdapter = {
938
+ id: 'ext-apps',
939
+ name: 'ext-apps (SEP-1865)',
940
+ priority: 80,
941
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, { canPersistState: true, hasNetworkAccess: true }),
942
+ trustedOrigins: ${originsArray},
943
+ trustedOrigin: null,
944
+ originTrustPending: false,
945
+ pendingRequests: {},
946
+ requestId: 0,
947
+ hostCapabilities: {},
948
+ canHandle: function() {
949
+ if (typeof window === 'undefined') return false;
950
+ if (window.parent === window) return false;
951
+
952
+ // Check for OpenAI SDK - defer to OpenAIAdapter
953
+ if (window.openai && window.openai.canvas) return false;
954
+ if (window.openai && typeof window.openai.callTool === 'function') return false;
955
+
956
+ // Explicit ext-apps marker
957
+ if (window.__mcpPlatform === 'ext-apps') return true;
958
+ if (window.__extAppsInitialized) return true;
959
+
960
+ // Claude MCP Apps mode (2026+) - uses ext-apps protocol
961
+ if (window.__mcpAppsEnabled) return true;
962
+
963
+ // Legacy Claude detection - defer to ClaudeAdapter
964
+ if (window.claude) return false;
965
+ if (window.__claudeArtifact) return false;
966
+ if (window.__mcpPlatform === 'claude') return false;
967
+ if (typeof location !== 'undefined') {
968
+ try {
969
+ var url = new URL(location.href);
970
+ var hostname = url.hostname.toLowerCase();
971
+ var isClaudeHost = hostname === 'claude.ai' || (hostname.length > 10 && hostname.slice(-10) === '.claude.ai');
972
+ var isAnthropicHost = hostname === 'anthropic.com' || (hostname.length > 14 && hostname.slice(-14) === '.anthropic.com');
973
+ if (isClaudeHost || isAnthropicHost) return false;
974
+ } catch (e) {
975
+ // If URL parsing fails, fall through to other checks
976
+ }
977
+ }
978
+
979
+ // Do NOT default to true for any iframe
980
+ return false;
981
+ },
982
+ initialize: function(context) {
983
+ var self = this;
984
+ context.extApps = this;
985
+
986
+ window.addEventListener('message', function(event) {
987
+ self.handleMessage(context, event);
988
+ });
989
+
990
+ return self.performHandshake(context);
991
+ },
992
+ handleMessage: function(context, event) {
993
+ if (!this.isOriginTrusted(event.origin)) return;
994
+ var data = event.data;
995
+ if (!data || typeof data !== 'object' || data.jsonrpc !== '2.0') return;
996
+
997
+ if ('id' in data && (data.result !== undefined || data.error !== undefined)) {
998
+ var pending = this.pendingRequests[data.id];
999
+ if (pending) {
1000
+ clearTimeout(pending.timeout);
1001
+ delete this.pendingRequests[data.id];
1002
+ if (data.error) {
1003
+ pending.reject(new Error(data.error.message + ' (code: ' + data.error.code + ')'));
1004
+ } else {
1005
+ pending.resolve(data.result);
1006
+ }
1007
+ }
1008
+ return;
1009
+ }
1010
+
1011
+ if ('method' in data && !('id' in data)) {
1012
+ this.handleNotification(context, data);
1013
+ }
1014
+ },
1015
+ handleNotification: function(context, notification) {
1016
+ var params = notification.params || {};
1017
+ switch (notification.method) {
1018
+ case 'ui/notifications/tool-input':
1019
+ context.toolInput = params.arguments || {};
1020
+ window.dispatchEvent(new CustomEvent('tool:input', { detail: { arguments: context.toolInput } }));
1021
+ break;
1022
+ case 'ui/notifications/tool-input-partial':
1023
+ // Streaming: merge partial input with existing
1024
+ context.toolInput = Object.assign({}, context.toolInput, params.arguments || {});
1025
+ window.dispatchEvent(new CustomEvent('tool:input-partial', { detail: { arguments: context.toolInput } }));
1026
+ break;
1027
+ case 'ui/notifications/tool-result':
1028
+ context.toolOutput = params.content;
1029
+ context.structuredContent = params.structuredContent;
1030
+ context.notifyToolResult(params.content);
1031
+ window.dispatchEvent(new CustomEvent('tool:result', { detail: params }));
1032
+ break;
1033
+ case 'ui/notifications/host-context-changed':
1034
+ Object.assign(context.hostContext, params);
1035
+ context.notifyContextChange(params);
1036
+ break;
1037
+ case 'ui/notifications/cancelled':
1038
+ window.dispatchEvent(new CustomEvent('tool:cancelled', { detail: { reason: params.reason } }));
1039
+ break;
1040
+ }
1041
+ },
1042
+ isOriginTrusted: function(origin) {
1043
+ if (this.trustedOrigins.length > 0) {
1044
+ return this.trustedOrigins.indexOf(origin) !== -1;
1045
+ }
1046
+ // Trust-on-first-use: trust first message origin.
1047
+ // SECURITY WARNING: For production, always configure trustedOrigins.
1048
+ if (!this.trustedOrigin) {
1049
+ // Guard against race condition where multiple messages arrive simultaneously
1050
+ if (this.originTrustPending) {
1051
+ return false;
1052
+ }
1053
+ if (window.parent !== window && origin) {
1054
+ this.originTrustPending = true;
1055
+ this.trustedOrigin = origin;
1056
+ this.originTrustPending = false; // Reset after successful trust establishment
1057
+ return true;
1058
+ }
1059
+ return false;
1060
+ }
1061
+ return this.trustedOrigin === origin;
1062
+ },
1063
+ sendRequest: function(method, params) {
1064
+ var self = this;
1065
+ return new Promise(function(resolve, reject) {
1066
+ // Security: Require trusted origin before sending requests to prevent message leaks
1067
+ if (!self.trustedOrigin && self.trustedOrigins.length === 0) {
1068
+ reject(new Error('Cannot send request: no trusted origin established'));
1069
+ return;
1070
+ }
1071
+
1072
+ var id = ++self.requestId;
1073
+ var timeout = setTimeout(function() {
1074
+ delete self.pendingRequests[id];
1075
+ reject(new Error('Request ' + method + ' timed out'));
1076
+ }, 10000);
1077
+
1078
+ self.pendingRequests[id] = { resolve: resolve, reject: reject, timeout: timeout };
1079
+
1080
+ var targetOrigin = self.trustedOrigin || self.trustedOrigins[0];
1081
+ window.parent.postMessage({ jsonrpc: '2.0', id: id, method: method, params: params }, targetOrigin);
1082
+ });
1083
+ },
1084
+ performHandshake: function(context) {
1085
+ var self = this;
1086
+ var params = {
1087
+ appInfo: { name: 'FrontMCP Widget', version: '1.0.0' },
1088
+ appCapabilities: { tools: { listChanged: false } },
1089
+ protocolVersion: '2024-11-05'
1090
+ };
1091
+
1092
+ return this.sendRequest('ui/initialize', params).then(function(result) {
1093
+ self.hostCapabilities = result.hostCapabilities || {};
1094
+ self.capabilities = Object.assign({}, self.capabilities, {
1095
+ canCallTools: Boolean(self.hostCapabilities.serverToolProxy),
1096
+ canSendMessages: true,
1097
+ canOpenLinks: Boolean(self.hostCapabilities.openLink),
1098
+ supportsDisplayModes: true
1099
+ });
1100
+ if (result.hostContext) {
1101
+ Object.assign(context.hostContext, result.hostContext);
1102
+ }
1103
+ });
1104
+ },
1105
+ callTool: function(context, name, args) {
1106
+ if (!this.hostCapabilities.serverToolProxy) {
1107
+ return Promise.reject(new Error('Server tool proxy not supported'));
1108
+ }
1109
+ return this.sendRequest('ui/callServerTool', { name: name, arguments: args });
1110
+ },
1111
+ sendMessage: function(context, content) {
1112
+ return this.sendRequest('ui/message', { content: content });
1113
+ },
1114
+ openLink: function(context, url) {
1115
+ if (!this.hostCapabilities.openLink) {
1116
+ window.open(url, '_blank', 'noopener,noreferrer');
1117
+ return Promise.resolve();
1118
+ }
1119
+ return this.sendRequest('ui/openLink', { url: url });
1120
+ },
1121
+ requestDisplayMode: function(context, mode) {
1122
+ return this.sendRequest('ui/setDisplayMode', { mode: mode });
1123
+ },
1124
+ requestClose: function(context) {
1125
+ return this.sendRequest('ui/close', {});
1126
+ },
1127
+ // Extended ext-apps methods (full specification)
1128
+ updateModelContext: function(context, data, merge) {
1129
+ if (!this.hostCapabilities.modelContextUpdate) {
1130
+ return Promise.reject(new Error('Model context update not supported'));
1131
+ }
1132
+ return this.sendRequest('ui/updateModelContext', { context: data, merge: merge !== false });
1133
+ },
1134
+ log: function(context, level, message, data) {
1135
+ if (!this.hostCapabilities.logging) {
1136
+ // Fallback to console logging if host doesn't support it
1137
+ var logFn = console[level] || console.log;
1138
+ logFn('[Widget] ' + message, data);
1139
+ return Promise.resolve();
1140
+ }
1141
+ return this.sendRequest('ui/log', { level: level, message: message, data: data });
1142
+ },
1143
+ registerTool: function(context, name, description, inputSchema) {
1144
+ if (!this.hostCapabilities.widgetTools) {
1145
+ return Promise.reject(new Error('Widget tool registration not supported'));
1146
+ }
1147
+ return this.sendRequest('ui/registerTool', { name: name, description: description, inputSchema: inputSchema });
1148
+ },
1149
+ unregisterTool: function(context, name) {
1150
+ if (!this.hostCapabilities.widgetTools) {
1151
+ return Promise.reject(new Error('Widget tool unregistration not supported'));
1152
+ }
1153
+ return this.sendRequest('ui/unregisterTool', { name: name });
1154
+ }
1155
+ };
1156
+ `.trim();
1157
+ }
1158
+ function generateClaudeAdapter() {
1159
+ return `
1160
+ var ClaudeAdapter = {
1161
+ id: 'claude',
1162
+ name: 'Claude (Anthropic)',
1163
+ priority: 60,
1164
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
1165
+ canCallTools: false,
1166
+ canSendMessages: false,
1167
+ canOpenLinks: true,
1168
+ hasNetworkAccess: false,
1169
+ supportsDisplayModes: false
1170
+ }),
1171
+ canHandle: function() {
1172
+ if (typeof window === 'undefined') return false;
1173
+
1174
+ // If MCP Apps is enabled, let ext-apps adapter handle it
1175
+ if (window.__mcpAppsEnabled) return false;
1176
+ if (window.__mcpPlatform === 'ext-apps') return false;
1177
+ if (window.__extAppsInitialized) return false;
1178
+
1179
+ // Legacy Claude detection
1180
+ if (window.__mcpPlatform === 'claude') return true;
1181
+ if (window.claude) return true;
1182
+ if (window.__claudeArtifact) return true;
1183
+ if (typeof location !== 'undefined') {
1184
+ try {
1185
+ var url = new URL(location.href);
1186
+ var hostname = url.hostname.toLowerCase();
1187
+ var isClaudeHost = hostname === 'claude.ai' || (hostname.length > 10 && hostname.slice(-10) === '.claude.ai');
1188
+ var isAnthropicHost = hostname === 'anthropic.com' || (hostname.length > 14 && hostname.slice(-14) === '.anthropic.com');
1189
+ if (isClaudeHost || isAnthropicHost) return true;
1190
+ } catch (e) {
1191
+ // If URL parsing fails, fall through
1192
+ }
1193
+ }
1194
+ return false;
1195
+ },
1196
+ initialize: function(context) {
1197
+ return Promise.resolve();
1198
+ },
1199
+ callTool: function() {
1200
+ return Promise.reject(new Error('Tool calls not supported in Claude'));
1201
+ },
1202
+ sendMessage: function() {
1203
+ return Promise.reject(new Error('Messages not supported in Claude'));
1204
+ },
1205
+ openLink: function(context, url) {
1206
+ window.open(url, '_blank', 'noopener,noreferrer');
1207
+ return Promise.resolve();
1208
+ },
1209
+ requestDisplayMode: function() {
1210
+ return Promise.resolve();
1211
+ },
1212
+ requestClose: function() {
1213
+ return Promise.resolve();
1214
+ }
1215
+ };
1216
+ `.trim();
1217
+ }
1218
+ function generateGeminiAdapter() {
1219
+ return `
1220
+ var GeminiAdapter = {
1221
+ id: 'gemini',
1222
+ name: 'Google Gemini',
1223
+ priority: 40,
1224
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
1225
+ canOpenLinks: true,
1226
+ hasNetworkAccess: true
1227
+ }),
1228
+ canHandle: function() {
1229
+ if (typeof window === 'undefined') return false;
1230
+ if (window.__mcpPlatform === 'gemini') return true;
1231
+ if (window.gemini) return true;
1232
+ if (typeof location !== 'undefined') {
1233
+ var href = location.href;
1234
+ if (href.indexOf('gemini.google.com') !== -1 || href.indexOf('bard.google.com') !== -1) return true;
1235
+ }
1236
+ return false;
1237
+ },
1238
+ initialize: function(context) {
1239
+ if (window.gemini && window.gemini.ui && window.gemini.ui.getTheme) {
1240
+ context.hostContext.theme = window.gemini.ui.getTheme() === 'dark' ? 'dark' : 'light';
1241
+ }
1242
+ return Promise.resolve();
1243
+ },
1244
+ callTool: function() {
1245
+ return Promise.reject(new Error('Tool calls not supported in Gemini'));
1246
+ },
1247
+ sendMessage: function(context, content) {
1248
+ if (window.gemini && window.gemini.ui && window.gemini.ui.sendMessage) {
1249
+ return window.gemini.ui.sendMessage(content);
1250
+ }
1251
+ return Promise.reject(new Error('Messages not supported in Gemini'));
1252
+ },
1253
+ openLink: function(context, url) {
1254
+ if (window.gemini && window.gemini.ui && window.gemini.ui.openLink) {
1255
+ return window.gemini.ui.openLink(url);
1256
+ }
1257
+ window.open(url, '_blank', 'noopener,noreferrer');
1258
+ return Promise.resolve();
1259
+ },
1260
+ requestDisplayMode: function() {
1261
+ return Promise.resolve();
1262
+ },
1263
+ requestClose: function() {
1264
+ return Promise.resolve();
1265
+ }
1266
+ };
1267
+ `.trim();
1268
+ }
1269
+ function generateGenericAdapter() {
1270
+ return `
1271
+ var GenericAdapter = {
1272
+ id: 'generic',
1273
+ name: 'Generic Web',
1274
+ priority: 0,
1275
+ capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
1276
+ canOpenLinks: true,
1277
+ hasNetworkAccess: true
1278
+ }),
1279
+ canHandle: function() {
1280
+ return typeof window !== 'undefined';
1281
+ },
1282
+ initialize: function(context) {
1283
+ return Promise.resolve();
1284
+ },
1285
+ callTool: function() {
1286
+ return Promise.reject(new Error('Tool calls not supported'));
1287
+ },
1288
+ sendMessage: function() {
1289
+ return Promise.reject(new Error('Messages not supported'));
1290
+ },
1291
+ openLink: function(context, url) {
1292
+ window.open(url, '_blank', 'noopener,noreferrer');
1293
+ return Promise.resolve();
1294
+ },
1295
+ requestDisplayMode: function() {
1296
+ return Promise.resolve();
1297
+ },
1298
+ requestClose: function() {
1299
+ return Promise.resolve();
1300
+ }
1301
+ };
1302
+ `.trim();
1303
+ }
1304
+ function generatePlatformDetection(adapters) {
1305
+ const adapterVars = adapters.map((a) => {
1306
+ switch (a) {
1307
+ case "openai":
1308
+ return "OpenAIAdapter";
1309
+ case "ext-apps":
1310
+ return "ExtAppsAdapter";
1311
+ case "claude":
1312
+ return "ClaudeAdapter";
1313
+ case "gemini":
1314
+ return "GeminiAdapter";
1315
+ case "generic":
1316
+ return "GenericAdapter";
1317
+ default:
1318
+ return "";
1319
+ }
1320
+ }).filter(Boolean);
1321
+ return `
1322
+ var ADAPTERS = [${adapterVars.join(", ")}].sort(function(a, b) { return b.priority - a.priority; });
1323
+
1324
+ function detectPlatform() {
1325
+ for (var i = 0; i < ADAPTERS.length; i++) {
1326
+ if (ADAPTERS[i].canHandle()) {
1327
+ log('Detected platform: ' + ADAPTERS[i].id);
1328
+ return ADAPTERS[i];
1329
+ }
1330
+ }
1331
+ log('No platform detected, using generic');
1332
+ return GenericAdapter;
1333
+ }
1334
+ `.trim();
1335
+ }
1336
+ function generateBridgeClass() {
1337
+ return `
1338
+ function FrontMcpBridge() {
1339
+ this._adapter = null;
1340
+ this._initialized = false;
1341
+ this._context = {
1342
+ hostContext: {
1343
+ theme: detectTheme(),
1344
+ displayMode: 'inline',
1345
+ locale: detectLocale(),
1346
+ userAgent: detectUserAgent(),
1347
+ safeArea: DEFAULT_SAFE_AREA,
1348
+ viewport: detectViewport()
1349
+ },
1350
+ toolInput: {},
1351
+ toolOutput: undefined,
1352
+ structuredContent: undefined,
1353
+ widgetState: {},
1354
+ contextListeners: [],
1355
+ toolResultListeners: [],
1356
+ notifyContextChange: function(changes) {
1357
+ Object.assign(this.hostContext, changes);
1358
+ for (var i = 0; i < this.contextListeners.length; i++) {
1359
+ try { this.contextListeners[i](changes); } catch(e) {}
1360
+ }
1361
+ },
1362
+ notifyToolResult: function(result) {
1363
+ this.toolOutput = result;
1364
+ for (var i = 0; i < this.toolResultListeners.length; i++) {
1365
+ try { this.toolResultListeners[i](result); } catch(e) {}
1366
+ }
1367
+ }
1368
+ };
1369
+
1370
+ var injected = readInjectedData();
1371
+ this._context.toolInput = injected.toolInput;
1372
+ this._context.toolOutput = injected.toolOutput;
1373
+ this._context.structuredContent = injected.structuredContent;
1374
+
1375
+ this._loadWidgetState();
1376
+ }
1377
+
1378
+ FrontMcpBridge.prototype._loadWidgetState = function() {
1379
+ try {
1380
+ var key = 'frontmcp:widget:' + (window.__mcpToolName || 'unknown');
1381
+ var stored = localStorage.getItem(key);
1382
+ if (stored) this._context.widgetState = JSON.parse(stored);
1383
+ } catch(e) {}
1384
+ };
1385
+
1386
+ FrontMcpBridge.prototype._saveWidgetState = function() {
1387
+ try {
1388
+ var key = 'frontmcp:widget:' + (window.__mcpToolName || 'unknown');
1389
+ localStorage.setItem(key, JSON.stringify(this._context.widgetState));
1390
+ } catch(e) {}
1391
+ };
1392
+
1393
+ FrontMcpBridge.prototype.initialize = function() {
1394
+ if (this._initialized) return Promise.resolve();
1395
+ var self = this;
1396
+ this._adapter = detectPlatform();
1397
+ return this._adapter.initialize(this._context).then(function() {
1398
+ self._initialized = true;
1399
+ // Set up the data-tool-call click handler after initialization
1400
+ self._setupDataToolCallHandler();
1401
+ });
1402
+ };
1403
+
1404
+ Object.defineProperty(FrontMcpBridge.prototype, 'initialized', { get: function() { return this._initialized; } });
1405
+ Object.defineProperty(FrontMcpBridge.prototype, 'adapterId', { get: function() { return this._adapter ? this._adapter.id : undefined; } });
1406
+ Object.defineProperty(FrontMcpBridge.prototype, 'capabilities', { get: function() { return this._adapter ? this._adapter.capabilities : DEFAULT_CAPABILITIES; } });
1407
+
1408
+ FrontMcpBridge.prototype.getTheme = function() { return this._context.hostContext.theme; };
1409
+ FrontMcpBridge.prototype.getDisplayMode = function() { return this._context.hostContext.displayMode; };
1410
+ FrontMcpBridge.prototype.getToolInput = function() { return this._context.toolInput; };
1411
+ FrontMcpBridge.prototype.getToolOutput = function() { return this._context.toolOutput; };
1412
+ FrontMcpBridge.prototype.getStructuredContent = function() { return this._context.structuredContent; };
1413
+ FrontMcpBridge.prototype.getWidgetState = function() { return this._context.widgetState; };
1414
+ FrontMcpBridge.prototype.getHostContext = function() { return Object.assign({}, this._context.hostContext); };
1415
+ FrontMcpBridge.prototype.hasCapability = function(cap) { return this._adapter && this._adapter.capabilities[cap] === true; };
1416
+
1417
+ // Get tool response metadata (platform-agnostic)
1418
+ // Used by inline mode widgets to detect when ui/html arrives
1419
+ FrontMcpBridge.prototype.getToolResponseMetadata = function() {
1420
+ // OpenAI injects toolResponseMetadata for widget-producing tools
1421
+ if (typeof window !== 'undefined' && window.openai && window.openai.toolResponseMetadata) {
1422
+ return window.openai.toolResponseMetadata;
1423
+ }
1424
+ // Claude (future support)
1425
+ if (typeof window !== 'undefined' && window.claude && window.claude.toolResponseMetadata) {
1426
+ return window.claude.toolResponseMetadata;
1427
+ }
1428
+ // FrontMCP direct injection (for testing/ext-apps)
1429
+ if (typeof window !== 'undefined' && window.__mcpToolResponseMetadata) {
1430
+ return window.__mcpToolResponseMetadata;
1431
+ }
1432
+ return null;
1433
+ };
1434
+
1435
+ // Subscribe to tool response metadata changes (for inline mode injection)
1436
+ FrontMcpBridge.prototype.onToolResponseMetadata = function(callback) {
1437
+ var self = this;
1438
+ var called = false;
1439
+
1440
+ // Check if already available
1441
+ var existing = self.getToolResponseMetadata();
1442
+ if (existing) {
1443
+ called = true;
1444
+ callback(existing);
1445
+ }
1446
+
1447
+ // Set up property interceptors for OpenAI
1448
+ if (typeof window !== 'undefined') {
1449
+ // OpenAI: Intercept toolResponseMetadata assignment
1450
+ if (!window.__frontmcpMetadataIntercepted) {
1451
+ window.__frontmcpMetadataIntercepted = true;
1452
+ window.__frontmcpMetadataCallbacks = [];
1453
+
1454
+ // Create openai object if it doesn't exist
1455
+ if (!window.openai) window.openai = {};
1456
+
1457
+ var originalMetadata = window.openai.toolResponseMetadata;
1458
+ Object.defineProperty(window.openai, 'toolResponseMetadata', {
1459
+ get: function() { return originalMetadata; },
1460
+ set: function(val) {
1461
+ originalMetadata = val;
1462
+ log('toolResponseMetadata set, notifying ' + window.__frontmcpMetadataCallbacks.length + ' listeners');
1463
+ for (var i = 0; i < window.__frontmcpMetadataCallbacks.length; i++) {
1464
+ try { window.__frontmcpMetadataCallbacks[i](val); } catch(e) {}
1465
+ }
1466
+ },
1467
+ configurable: true
1468
+ });
1469
+ }
1470
+
1471
+ // Register callback wrapper (store reference for unsubscribe)
1472
+ var wrapper = function(metadata) {
1473
+ if (!called) {
1474
+ called = true;
1475
+ callback(metadata);
1476
+ }
1477
+ };
1478
+ window.__frontmcpMetadataCallbacks.push(wrapper);
1479
+
1480
+ // Return unsubscribe function that removes the wrapper (not the original callback)
1481
+ return function() {
1482
+ if (window.__frontmcpMetadataCallbacks) {
1483
+ var idx = window.__frontmcpMetadataCallbacks.indexOf(wrapper);
1484
+ if (idx !== -1) window.__frontmcpMetadataCallbacks.splice(idx, 1);
1485
+ }
1486
+ };
1487
+ }
1488
+
1489
+ // Return no-op unsubscribe for non-window environments
1490
+ return function() {};
1491
+ };
1492
+
1493
+ FrontMcpBridge.prototype.callTool = function(name, args) {
1494
+ // Priority 1: Direct OpenAI SDK call (most reliable in OpenAI iframe)
1495
+ // This bypasses adapter abstraction for maximum compatibility
1496
+ if (typeof window !== 'undefined' && window.openai && typeof window.openai.callTool === 'function') {
1497
+ log('callTool: Using OpenAI SDK directly');
1498
+ return window.openai.callTool(name, args);
1499
+ }
1500
+
1501
+ // Priority 2: Use adapter (if initialized and supports tool calls)
1502
+ if (this._adapter && this._adapter.capabilities && this._adapter.capabilities.canCallTools) {
1503
+ log('callTool: Using adapter ' + this._adapter.id);
1504
+ return this._adapter.callTool(this._context, name, args);
1505
+ }
1506
+
1507
+ // Not initialized or no tool support
1508
+ if (!this._adapter) {
1509
+ return Promise.reject(new Error('Bridge not initialized. Wait for bridge:ready event.'));
1510
+ }
1511
+ return Promise.reject(new Error('Tool calls not supported on this platform (' + this._adapter.id + ')'));
1512
+ };
1513
+
1514
+ FrontMcpBridge.prototype.sendMessage = function(content) {
1515
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1516
+ return this._adapter.sendMessage(this._context, content);
1517
+ };
1518
+
1519
+ FrontMcpBridge.prototype.openLink = function(url) {
1520
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1521
+ return this._adapter.openLink(this._context, url);
1522
+ };
1523
+
1524
+ FrontMcpBridge.prototype.requestDisplayMode = function(mode) {
1525
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1526
+ var self = this;
1527
+ return this._adapter.requestDisplayMode(this._context, mode).then(function() {
1528
+ self._context.hostContext.displayMode = mode;
1529
+ });
1530
+ };
1531
+
1532
+ FrontMcpBridge.prototype.requestClose = function() {
1533
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1534
+ return this._adapter.requestClose(this._context);
1535
+ };
1536
+
1537
+ // Extended ext-apps methods (full specification)
1538
+ FrontMcpBridge.prototype.updateModelContext = function(context, merge) {
1539
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1540
+ if (!this._adapter.updateModelContext) {
1541
+ return Promise.reject(new Error('updateModelContext not supported on this platform'));
1542
+ }
1543
+ return this._adapter.updateModelContext(this._context, context, merge);
1544
+ };
1545
+
1546
+ FrontMcpBridge.prototype.log = function(level, message, data) {
1547
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1548
+ if (!this._adapter.log) {
1549
+ // Fallback to console
1550
+ var logFn = console[level] || console.log;
1551
+ logFn('[Widget] ' + message, data);
1552
+ return Promise.resolve();
1553
+ }
1554
+ return this._adapter.log(this._context, level, message, data);
1555
+ };
1556
+
1557
+ FrontMcpBridge.prototype.registerTool = function(name, description, inputSchema) {
1558
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1559
+ if (!this._adapter.registerTool) {
1560
+ return Promise.reject(new Error('registerTool not supported on this platform'));
1561
+ }
1562
+ return this._adapter.registerTool(this._context, name, description, inputSchema);
1563
+ };
1564
+
1565
+ FrontMcpBridge.prototype.unregisterTool = function(name) {
1566
+ if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1567
+ if (!this._adapter.unregisterTool) {
1568
+ return Promise.reject(new Error('unregisterTool not supported on this platform'));
1569
+ }
1570
+ return this._adapter.unregisterTool(this._context, name);
1571
+ };
1572
+
1573
+ FrontMcpBridge.prototype.setWidgetState = function(state) {
1574
+ Object.assign(this._context.widgetState, state);
1575
+ this._saveWidgetState();
1576
+ };
1577
+
1578
+ FrontMcpBridge.prototype.onContextChange = function(callback) {
1579
+ var listeners = this._context.contextListeners;
1580
+ listeners.push(callback);
1581
+ return function() {
1582
+ var idx = listeners.indexOf(callback);
1583
+ if (idx !== -1) listeners.splice(idx, 1);
1584
+ };
1585
+ };
1586
+
1587
+ FrontMcpBridge.prototype.onToolResult = function(callback) {
1588
+ var listeners = this._context.toolResultListeners;
1589
+ listeners.push(callback);
1590
+ return function() {
1591
+ var idx = listeners.indexOf(callback);
1592
+ if (idx !== -1) listeners.splice(idx, 1);
1593
+ };
1594
+ };
1595
+
1596
+ // ==================== data-tool-call Click Handler ====================
1597
+
1598
+ FrontMcpBridge.prototype._setupDataToolCallHandler = function() {
1599
+ var self = this;
1600
+
1601
+ document.addEventListener('click', function(e) {
1602
+ // Find the closest element with data-tool-call attribute
1603
+ var target = e.target;
1604
+ while (target && target !== document) {
1605
+ if (target.hasAttribute && target.hasAttribute('data-tool-call')) {
1606
+ var toolName = target.getAttribute('data-tool-call');
1607
+ var argsAttr = target.getAttribute('data-tool-args');
1608
+ var args = {};
1609
+
1610
+ try {
1611
+ if (argsAttr) {
1612
+ args = JSON.parse(argsAttr);
1613
+ }
1614
+ } catch (parseErr) {
1615
+ console.error('[frontmcp] Failed to parse data-tool-args:', parseErr);
1616
+ }
1617
+
1618
+ log('data-tool-call clicked: ' + toolName);
1619
+
1620
+ // Show loading state - save original content first
1621
+ var originalContent = target.innerHTML;
1622
+ var originalDisabled = target.disabled;
1623
+ target.disabled = true;
1624
+ target.classList.add('opacity-50', 'cursor-not-allowed');
1625
+
1626
+ // Add spinner for buttons
1627
+ 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>';
1628
+ if (target.tagName === 'BUTTON') {
1629
+ target.innerHTML = spinner + 'Loading...';
1630
+ }
1631
+
1632
+ // Helper to reset button state
1633
+ function resetButton() {
1634
+ target.innerHTML = originalContent;
1635
+ target.disabled = originalDisabled;
1636
+ target.classList.remove('opacity-50', 'cursor-not-allowed');
1637
+ }
1638
+
1639
+ // Determine how to call the tool
1640
+ var toolCallPromise;
1641
+
1642
+ // Priority 1: Direct OpenAI SDK call (bypasses adapter abstraction)
1643
+ if (typeof window !== 'undefined' && window.openai && typeof window.openai.callTool === 'function') {
1644
+ log('Using OpenAI SDK directly for tool call');
1645
+ toolCallPromise = window.openai.callTool(toolName, args);
1646
+ }
1647
+ // Priority 2: Use adapter (if it supports tool calls)
1648
+ else if (self.hasCapability('canCallTools')) {
1649
+ log('Using adapter for tool call');
1650
+ toolCallPromise = self.callTool(toolName, args);
1651
+ }
1652
+ // No tool call capability
1653
+ else {
1654
+ console.error('[frontmcp] Tool calls not supported on this platform (' + self.adapterId + ')');
1655
+ resetButton();
1656
+ target.dispatchEvent(new CustomEvent('tool:error', {
1657
+ detail: { name: toolName, args: args, error: 'Tool calls not supported on this platform' },
1658
+ bubbles: true
1659
+ }));
1660
+ e.preventDefault();
1661
+ return;
1662
+ }
1663
+
1664
+ // Handle the tool call result
1665
+ toolCallPromise.then(function(result) {
1666
+ log('Tool call succeeded: ' + toolName);
1667
+ resetButton();
1668
+
1669
+ // Update bridge state to trigger widget re-render
1670
+ // React isn't hydrated in OpenAI iframe, so useState doesn't work
1671
+ // Instead, we use the bridge's reactive state system
1672
+ if (result && window.__frontmcp && window.__frontmcp.bridge && typeof window.__frontmcp.bridge.setWidgetState === 'function') {
1673
+ var newData = result.structuredContent || result;
1674
+ log('Updating bridge state with new data');
1675
+ window.__frontmcp.bridge.setWidgetState(newData);
1676
+ }
1677
+
1678
+ // Dispatch success event
1679
+ target.dispatchEvent(new CustomEvent('tool:success', {
1680
+ detail: { name: toolName, args: args, result: result },
1681
+ bubbles: true
1682
+ }));
1683
+ }).catch(function(err) {
1684
+ console.error('[frontmcp] Tool call failed: ' + toolName, err);
1685
+ resetButton();
1686
+ // Dispatch error event
1687
+ target.dispatchEvent(new CustomEvent('tool:error', {
1688
+ detail: { name: toolName, args: args, error: err.message || err },
1689
+ bubbles: true
1690
+ }));
1691
+ });
1692
+
1693
+ // Prevent default behavior (e.g., form submission)
1694
+ e.preventDefault();
1695
+ return;
1696
+ }
1697
+ target = target.parentElement;
1698
+ }
1699
+ }, true); // Use capture phase to handle before React handlers
1700
+ };
1701
+ `.trim();
1702
+ }
1703
+ var MAX_MINIFY_CODE_LENGTH = 5e5;
1704
+ function minifyJS(code) {
1705
+ if (code.length > MAX_MINIFY_CODE_LENGTH) {
1706
+ return code;
1707
+ }
1708
+ return code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/\s+/g, " ").replace(/\s*([{};,:()[\]])\s*/g, "$1").replace(/;\}/g, "}").trim();
1709
+ }
1710
+ function generatePlatformBundle(platform, options = {}) {
1711
+ const platformAdapters = {
1712
+ chatgpt: ["openai", "generic"],
1713
+ claude: ["claude", "generic"],
1714
+ gemini: ["gemini", "generic"],
1715
+ universal: ["openai", "ext-apps", "claude", "gemini", "generic"]
1716
+ };
1717
+ return generateBridgeIIFE({
1718
+ ...options,
1719
+ adapters: platformAdapters[platform]
1720
+ });
1721
+ }
1722
+ var UNIVERSAL_BRIDGE_SCRIPT = generateBridgeIIFE();
1723
+ var BRIDGE_SCRIPT_TAGS = {
1724
+ universal: `<script>${UNIVERSAL_BRIDGE_SCRIPT}</script>`,
1725
+ chatgpt: `<script>${generatePlatformBundle("chatgpt")}</script>`,
1726
+ claude: `<script>${generatePlatformBundle("claude")}</script>`,
1727
+ gemini: `<script>${generatePlatformBundle("gemini")}</script>`
1728
+ };
1729
+
1730
+ // libs/uipack/src/shell/custom-shell-types.ts
1731
+ var SHELL_PLACEHOLDER_NAMES = ["CSP", "DATA", "BRIDGE", "CONTENT", "TITLE"];
1732
+ var SHELL_PLACEHOLDERS = {
1733
+ CSP: "{{CSP}}",
1734
+ DATA: "{{DATA}}",
1735
+ BRIDGE: "{{BRIDGE}}",
1736
+ CONTENT: "{{CONTENT}}",
1737
+ TITLE: "{{TITLE}}"
1738
+ };
1739
+ var REQUIRED_PLACEHOLDERS = ["CONTENT"];
1740
+ var OPTIONAL_PLACEHOLDERS = ["CSP", "DATA", "BRIDGE", "TITLE"];
1741
+
1742
+ // libs/uipack/src/shell/custom-shell-validator.ts
1743
+ function validateShellTemplate(template) {
1744
+ const found = {};
1745
+ for (const name of SHELL_PLACEHOLDER_NAMES) {
1746
+ found[name] = template.includes(SHELL_PLACEHOLDERS[name]);
1747
+ }
1748
+ const missingRequired = REQUIRED_PLACEHOLDERS.filter((name) => !found[name]);
1749
+ const missingOptional = OPTIONAL_PLACEHOLDERS.filter((name) => !found[name]);
1750
+ return {
1751
+ valid: missingRequired.length === 0,
1752
+ found,
1753
+ missingRequired,
1754
+ missingOptional
1755
+ };
1756
+ }
1757
+
1758
+ // libs/uipack/src/shell/custom-shell-applier.ts
1759
+ function applyShellTemplate(template, values) {
1760
+ let result = template;
1761
+ result = result.replaceAll(SHELL_PLACEHOLDERS.CSP, values.csp);
1762
+ result = result.replaceAll(SHELL_PLACEHOLDERS.DATA, values.data);
1763
+ result = result.replaceAll(SHELL_PLACEHOLDERS.BRIDGE, values.bridge);
1764
+ result = result.replaceAll(SHELL_PLACEHOLDERS.CONTENT, values.content);
1765
+ result = result.replaceAll(SHELL_PLACEHOLDERS.TITLE, values.title);
1766
+ return result;
1767
+ }
1768
+
1769
+ // libs/uipack/src/shell/builder.ts
1770
+ function buildShell(content, config) {
1771
+ const { toolName, csp, withShell = true, input, output, structuredContent, includeBridge = true, title } = config;
1772
+ const { customShell } = config;
1773
+ const dataScript = buildDataInjectionScript({ toolName, input, output, structuredContent });
1774
+ if (!withShell) {
1775
+ const html2 = `${dataScript}
1776
+ ${content}`;
1777
+ return {
1778
+ html: html2,
1779
+ hash: simpleHash(html2),
1780
+ size: Buffer.byteLength(html2, "utf-8")
1781
+ };
1782
+ }
1783
+ if (customShell) {
1784
+ return buildCustomShell(content, customShell, {
1785
+ csp,
1786
+ toolName,
1787
+ input,
1788
+ output,
1789
+ structuredContent,
1790
+ includeBridge,
1791
+ title
1792
+ });
1793
+ }
1794
+ const headParts = [
1795
+ '<meta charset="UTF-8">',
1796
+ '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
1797
+ ];
1798
+ if (title) {
1799
+ headParts.push(`<title>${escapeHtmlForTag(title)}</title>`);
1800
+ }
1801
+ headParts.push(buildCSPMetaTag(csp));
1802
+ headParts.push(dataScript);
1803
+ if (includeBridge) {
1804
+ const bridgeScript = generateBridgeIIFE({ minify: true });
1805
+ headParts.push(`<script>${bridgeScript}</script>`);
1806
+ }
1807
+ const html = `<!DOCTYPE html>
1808
+ <html lang="en">
1809
+ <head>
1810
+ ${headParts.map((p) => ` ${p}`).join("\n")}
1811
+ </head>
1812
+ <body>
1813
+ ${content}
1814
+ </body>
1815
+ </html>`;
1816
+ return {
1817
+ html,
1818
+ hash: simpleHash(html),
1819
+ size: Buffer.byteLength(html, "utf-8")
1820
+ };
1821
+ }
1822
+ function buildCustomShell(content, customShell, ctx) {
1823
+ let template;
1824
+ if (typeof customShell === "string") {
1825
+ const validation = validateShellTemplate(customShell);
1826
+ if (!validation.valid) {
1827
+ throw new Error(
1828
+ `Custom shell template is missing required placeholder(s): ${validation.missingRequired.map((n) => `{{${n}}}`).join(", ")}`
1829
+ );
1830
+ }
1831
+ template = customShell;
1832
+ } else {
1833
+ template = customShell.template;
1834
+ }
1835
+ const cspTag = buildCSPMetaTag(ctx.csp);
1836
+ const dataScript = buildDataInjectionScript({
1837
+ toolName: ctx.toolName,
1838
+ input: ctx.input,
1839
+ output: ctx.output,
1840
+ structuredContent: ctx.structuredContent
1841
+ });
1842
+ let bridgeHtml = "";
1843
+ if (ctx.includeBridge) {
1844
+ const bridgeScript = generateBridgeIIFE({ minify: true });
1845
+ bridgeHtml = `<script>${bridgeScript}</script>`;
1846
+ }
1847
+ const html = applyShellTemplate(template, {
1848
+ csp: cspTag,
1849
+ data: dataScript,
1850
+ bridge: bridgeHtml,
1851
+ content,
1852
+ title: ctx.title ? escapeHtmlForTag(ctx.title) : ""
1853
+ });
1854
+ return {
1855
+ html,
1856
+ hash: simpleHash(html),
1857
+ size: Buffer.byteLength(html, "utf-8")
1858
+ };
1859
+ }
1860
+ function simpleHash(str) {
1861
+ let hash = 0;
1862
+ for (let i = 0; i < str.length; i++) {
1863
+ const char = str.charCodeAt(i);
1864
+ hash = (hash << 5) - hash + char | 0;
1865
+ }
1866
+ return Math.abs(hash).toString(16).padStart(8, "0");
1867
+ }
1868
+ function escapeHtmlForTag(str) {
1869
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1870
+ }
1871
+
1872
+ // libs/uipack/src/resolver/import-map.ts
1873
+ function createImportMapFromResolved(resolved) {
1874
+ const imports = {};
1875
+ const integrity = {};
1876
+ for (const [specifier, res] of Object.entries(resolved)) {
1877
+ if (res.type === "url") {
1878
+ imports[specifier] = res.value;
1879
+ if (res.integrity) {
1880
+ integrity[res.value] = res.integrity;
1881
+ }
1882
+ }
1883
+ }
1884
+ return {
1885
+ imports,
1886
+ integrity: Object.keys(integrity).length > 0 ? integrity : void 0
1887
+ };
1888
+ }
1889
+ function generateImportMapScriptTag(map) {
1890
+ const json = JSON.stringify(map, null, 2).replace(/<\//g, "<\\/");
1891
+ return `<script type="importmap">
1892
+ ${json}
1893
+ </script>`;
1894
+ }
1895
+
1896
+ // libs/uipack/src/component/renderer.ts
1897
+ function renderComponent(config, shellConfig) {
1898
+ const resolver = shellConfig.resolver ?? createEsmShResolver();
1899
+ const resolved = resolveUISource(config.source, {
1900
+ resolver,
1901
+ input: shellConfig.input,
1902
+ output: shellConfig.output
1903
+ });
1904
+ const mergedShellConfig = {
1905
+ ...shellConfig,
1906
+ withShell: config.withShell ?? shellConfig.withShell,
1907
+ includeBridge: config.includeBridge ?? shellConfig.includeBridge,
1908
+ customShell: config.customShell ?? shellConfig.customShell
1909
+ };
1910
+ if (resolved.mode === "inline") {
1911
+ return buildShell(resolved.html ?? "", mergedShellConfig);
1912
+ }
1913
+ const content = buildModuleContent(resolved, resolver, config.props);
1914
+ return buildShell(content, mergedShellConfig);
1915
+ }
1916
+ function buildModuleContent(resolved, resolver, propsMapping) {
1917
+ const parts = [];
1918
+ if (resolved.code && resolved.bundled) {
1919
+ const importEntries = {};
1920
+ for (const spec of resolved.imports || []) {
1921
+ const depResolved = resolver.resolve(spec);
1922
+ if (depResolved) {
1923
+ importEntries[spec] = depResolved;
1924
+ }
1925
+ }
1926
+ if (Object.keys(importEntries).length > 0) {
1927
+ const importMap = createImportMapFromResolved(importEntries);
1928
+ parts.push(generateImportMapScriptTag(importMap));
1929
+ }
1930
+ parts.push('<div id="root"></div>');
1931
+ parts.push(`<script type="module">
1932
+ ${resolved.code}
1933
+ </script>`);
1934
+ } else if (resolved.code) {
1935
+ const importEntries = {};
1936
+ const allSpecifiers = /* @__PURE__ */ new Set([
1937
+ ...resolved.imports || [],
1938
+ "react-dom/client",
1939
+ // needed by mount script
1940
+ "@frontmcp/ui/react",
1941
+ // needed for McpBridgeProvider
1942
+ // React subpath entries needed by esm.sh externalized modules:
1943
+ "react/jsx-runtime",
1944
+ "react/jsx-dev-runtime",
1945
+ "react-dom/server",
1946
+ "react-dom/static"
1947
+ ]);
1948
+ const coreDeps = /* @__PURE__ */ new Set([
1949
+ "react",
1950
+ "react-dom",
1951
+ "react-dom/client",
1952
+ "react/jsx-runtime",
1953
+ "react/jsx-dev-runtime",
1954
+ "react-dom/server",
1955
+ "react-dom/static"
1956
+ ]);
1957
+ for (const spec of allSpecifiers) {
1958
+ const depResolved = resolver.resolve(spec);
1959
+ if (depResolved) {
1960
+ if (!coreDeps.has(spec) && depResolved.value?.includes("esm.sh")) {
1961
+ importEntries[spec] = {
1962
+ ...depResolved,
1963
+ value: addExternalParam(depResolved.value, ["react", "react-dom"])
1964
+ };
1965
+ } else {
1966
+ importEntries[spec] = depResolved;
1967
+ }
1968
+ }
1969
+ }
1970
+ if (importEntries["react-dom"] && !importEntries["react-dom/client"]) {
1971
+ const rdc = resolver.resolve("react-dom/client");
1972
+ if (rdc) importEntries["react-dom/client"] = rdc;
1973
+ }
1974
+ if (Object.keys(importEntries).length > 0) {
1975
+ const importMap = createImportMapFromResolved(importEntries);
1976
+ parts.push(generateImportMapScriptTag(importMap));
1977
+ }
1978
+ parts.push('<div id="root"></div>');
1979
+ const mountCode = generateInlineMountCode(resolved.exportName);
1980
+ parts.push(`<script type="module">
1981
+ ${resolved.code}
1982
+ ${mountCode}
1983
+ </script>`);
1984
+ } else {
1985
+ const importEntries = {};
1986
+ for (const dep of resolved.peerDependencies) {
1987
+ const depResolved = resolver.resolve(dep);
1988
+ if (depResolved) {
1989
+ importEntries[dep] = depResolved;
1990
+ }
1991
+ }
1992
+ if (importEntries["react-dom"]) {
1993
+ const reactDomClient = resolver.resolve("react-dom/client");
1994
+ if (reactDomClient) {
1995
+ importEntries["react-dom/client"] = reactDomClient;
1996
+ }
1997
+ }
1998
+ if (Object.keys(importEntries).length > 0) {
1999
+ const importMap = createImportMapFromResolved(importEntries);
2000
+ parts.push(generateImportMapScriptTag(importMap));
2001
+ }
2002
+ parts.push('<div id="root"></div>');
2003
+ const mountScript = generateMountScript(resolved, propsMapping);
2004
+ if (mountScript) {
2005
+ parts.push(`<script type="module">
2006
+ ${mountScript}
2007
+ </script>`);
2008
+ }
2009
+ }
2010
+ return parts.join("\n");
2011
+ }
2012
+ function addExternalParam(url, externals) {
2013
+ const sep = url.includes("?") ? "&" : "?";
2014
+ return `${url}${sep}external=${externals.join(",")}`;
2015
+ }
2016
+ function generateInlineMountCode(componentName) {
2017
+ return `
2018
+ // --- Mount ---
2019
+ import { createRoot as __createRoot } from 'react-dom/client';
2020
+ import { McpBridgeProvider as __McpBridgeProvider } from '@frontmcp/ui/react';
2021
+ const __root = document.getElementById('root');
2022
+ if (__root) {
2023
+ __createRoot(__root).render(
2024
+ React.createElement(__McpBridgeProvider, null,
2025
+ React.createElement(${componentName})
2026
+ )
2027
+ );
2028
+ }`;
2029
+ }
2030
+ // Annotate the CommonJS export names for ESM import in node:
2031
+ 0 && (module.exports = {
2032
+ FRONTMCP_META_KEY,
2033
+ bundleFileSource,
2034
+ extractDefaultExportName,
2035
+ generateMountScript,
2036
+ isFileSource,
2037
+ isFunctionSource,
2038
+ isImportSource,
2039
+ isNpmSource,
2040
+ renderComponent,
2041
+ resolveUISource,
2042
+ transpileReactSource
2043
+ });