@frontmcp/uipack 1.10.8 → 1.10.9-rc.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.
@@ -1,619 +1,9 @@
1
1
  var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : undefined;
2
2
  const require = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || 'file:///') : undefined;
3
3
  // __frontmcpCreateRequire
4
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
- }) : x)(function(x) {
7
- if (typeof require !== "undefined") return require.apply(this, arguments);
8
- throw Error('Dynamic require of "' + x + '" is not supported');
9
- });
10
-
11
- // libs/uipack/src/adapters/constants.ts
12
- var MCP_APPS_MIME_TYPE = "text/html;profile=mcp-app";
13
- var MCP_APPS_EXTENSION_ID = "io.modelcontextprotocol/ui";
14
-
15
- // libs/uipack/src/adapters/serving-mode.ts
16
- function resolveServingMode(options) {
17
- const { configuredMode, platformType } = options;
18
- if (platformType === "gemini") {
19
- return {
20
- mode: configuredMode,
21
- supportsUI: false,
22
- effectiveMode: null,
23
- useStructuredContent: false,
24
- reason: "Gemini does not support MCP Apps UI"
25
- };
26
- }
27
- const effectiveMode = configuredMode === "auto" ? "inline" : configuredMode;
28
- if (effectiveMode === "hybrid") {
29
- const hybridCapable = platformType === "openai" || platformType === "ext-apps" || platformType === "cursor";
30
- if (!hybridCapable) {
31
- return {
32
- mode: configuredMode,
33
- supportsUI: false,
34
- effectiveMode: null,
35
- useStructuredContent: false,
36
- reason: `Platform ${platformType} does not support hybrid serving mode`
37
- };
38
- }
39
- }
40
- const useStructuredContent = platformType === "openai" || platformType === "ext-apps" || platformType === "generic-mcp" || platformType === "unknown";
41
- return {
42
- mode: configuredMode,
43
- supportsUI: true,
44
- effectiveMode,
45
- useStructuredContent,
46
- reason: `Platform ${platformType} supports UI, mode: ${effectiveMode}`
47
- };
48
- }
49
-
50
- // libs/uipack/src/adapters/response-builder.ts
51
- function buildToolResponseContent(options) {
52
- const { rawOutput, htmlContent, servingMode, useStructuredContent, platformType } = options;
53
- const textSummary = typeof rawOutput === "string" ? rawOutput : rawOutput !== null && rawOutput !== void 0 ? JSON.stringify(rawOutput) : "";
54
- const result = {
55
- content: [{ type: "text", text: textSummary }]
56
- };
57
- if (useStructuredContent && rawOutput !== null && rawOutput !== void 0) {
58
- const structured = typeof rawOutput === "object" && !Array.isArray(rawOutput) ? rawOutput : { value: rawOutput };
59
- result.structuredContent = structured;
60
- }
61
- if (htmlContent && servingMode === "inline") {
62
- const htmlKey = "ui/html";
63
- result._meta = {
64
- [htmlKey]: htmlContent
65
- };
66
- result.format = "html";
67
- }
68
- return result;
69
- }
70
-
71
- // libs/uipack/src/adapters/render-failure.ts
72
- function isUIRenderFailure(result) {
73
- if (typeof result !== "object" || result === null) {
74
- return false;
75
- }
76
- const rec = result;
77
- return typeof rec["reason"] === "string" && !("meta" in rec);
78
- }
79
-
80
- // libs/uipack/src/resolver/cdn-registry.ts
81
- var DEFAULT_CDN_REGISTRY = {
82
- react: {
83
- packageName: "react",
84
- defaultVersion: "19.2.4",
85
- providers: {
86
- cloudflare: {
87
- url: "https://cdnjs.cloudflare.com/ajax/libs/react/19.2.4/umd/react.production.min.js",
88
- global: "React",
89
- crossorigin: "anonymous"
90
- },
91
- jsdelivr: {
92
- url: "https://cdn.jsdelivr.net/npm/react@19.2.4/umd/react.production.min.js",
93
- global: "React",
94
- crossorigin: "anonymous"
95
- },
96
- unpkg: {
97
- url: "https://unpkg.com/react@19.2.4/umd/react.production.min.js",
98
- global: "React",
99
- crossorigin: "anonymous"
100
- },
101
- "esm.sh": {
102
- url: "https://esm.sh/react@19.2.4",
103
- esm: true,
104
- crossorigin: "anonymous"
105
- }
106
- },
107
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
108
- metadata: {
109
- description: "A JavaScript library for building user interfaces",
110
- homepage: "https://react.dev",
111
- license: "MIT"
112
- }
113
- },
114
- "react-dom": {
115
- packageName: "react-dom",
116
- defaultVersion: "19.2.4",
117
- providers: {
118
- cloudflare: {
119
- url: "https://cdnjs.cloudflare.com/ajax/libs/react-dom/19.2.4/umd/react-dom.production.min.js",
120
- global: "ReactDOM",
121
- crossorigin: "anonymous",
122
- peerDependencies: ["react"]
123
- },
124
- jsdelivr: {
125
- url: "https://cdn.jsdelivr.net/npm/react-dom@19.2.4/umd/react-dom.production.min.js",
126
- global: "ReactDOM",
127
- crossorigin: "anonymous",
128
- peerDependencies: ["react"]
129
- },
130
- unpkg: {
131
- url: "https://unpkg.com/react-dom@19.2.4/umd/react-dom.production.min.js",
132
- global: "ReactDOM",
133
- crossorigin: "anonymous",
134
- peerDependencies: ["react"]
135
- },
136
- "esm.sh": {
137
- url: "https://esm.sh/react-dom@19.2.4",
138
- esm: true,
139
- crossorigin: "anonymous",
140
- peerDependencies: ["react"]
141
- }
142
- },
143
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
144
- metadata: {
145
- description: "React package for working with the DOM",
146
- homepage: "https://react.dev",
147
- license: "MIT"
148
- }
149
- },
150
- "chart.js": {
151
- packageName: "chart.js",
152
- defaultVersion: "4.5.1",
153
- providers: {
154
- cloudflare: {
155
- url: "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.1/chart.umd.min.js",
156
- global: "Chart",
157
- crossorigin: "anonymous"
158
- },
159
- jsdelivr: {
160
- url: "https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js",
161
- global: "Chart",
162
- crossorigin: "anonymous"
163
- },
164
- unpkg: {
165
- url: "https://unpkg.com/chart.js@4.5.1/dist/chart.umd.min.js",
166
- global: "Chart",
167
- crossorigin: "anonymous"
168
- }
169
- },
170
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
171
- metadata: {
172
- description: "Simple yet flexible JavaScript charting library",
173
- homepage: "https://www.chartjs.org",
174
- license: "MIT"
175
- }
176
- },
177
- d3: {
178
- packageName: "d3",
179
- defaultVersion: "7.9.0",
180
- providers: {
181
- cloudflare: {
182
- url: "https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js",
183
- integrity: "sha512-vc58qvvBdrDR4etbxMdlTt4GBQk1qjvyORR2nrsPsFPyrs+/u5c3+1Ct6upOgdZoIl7eq6k3a1UPDSNAQi/32A==",
184
- global: "d3",
185
- crossorigin: "anonymous"
186
- },
187
- jsdelivr: {
188
- url: "https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js",
189
- global: "d3",
190
- crossorigin: "anonymous"
191
- },
192
- unpkg: {
193
- url: "https://unpkg.com/d3@7.9.0/dist/d3.min.js",
194
- global: "d3",
195
- crossorigin: "anonymous"
196
- }
197
- },
198
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
199
- metadata: {
200
- description: "Data-Driven Documents",
201
- homepage: "https://d3js.org",
202
- license: "ISC"
203
- }
204
- },
205
- lodash: {
206
- packageName: "lodash",
207
- defaultVersion: "4.17.21",
208
- providers: {
209
- cloudflare: {
210
- url: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js",
211
- integrity: "sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==",
212
- global: "_",
213
- crossorigin: "anonymous"
214
- },
215
- jsdelivr: {
216
- url: "https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js",
217
- global: "_",
218
- crossorigin: "anonymous"
219
- },
220
- unpkg: {
221
- url: "https://unpkg.com/lodash@4.17.21/lodash.min.js",
222
- global: "_",
223
- crossorigin: "anonymous"
224
- }
225
- },
226
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
227
- metadata: {
228
- description: "A modern JavaScript utility library",
229
- homepage: "https://lodash.com",
230
- license: "MIT"
231
- }
232
- }
233
- };
234
- function lookupPackage(packageName, registry = DEFAULT_CDN_REGISTRY) {
235
- return registry[packageName];
236
- }
237
-
238
- // libs/uipack/src/resolver/import-parser.ts
239
- var IMPORT_PATTERNS = {
240
- named: /import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,
241
- default: /import\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
242
- namespace: /import\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
243
- sideEffect: /import\s*['"]([^'"]+)['"]/g,
244
- dynamic: /(?:await\s+)?import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
245
- defaultAndNamed: /import\s+(\w+)\s*,\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,
246
- defaultAndNamespace: /import\s+(\w+)\s*,\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
247
- reExport: /export\s*\{[^}]+\}\s*from\s*['"]([^'"]+)['"]/g,
248
- reExportAll: /export\s*\*\s*from\s*['"]([^'"]+)['"]/g
249
- };
250
- function parseNamedImports(namedString) {
251
- return namedString.split(",").map((s) => s.trim()).filter((s) => s.length > 0).map((s) => {
252
- const asMatch = s.match(/^(\w+)\s+as\s+\w+$/);
253
- return asMatch ? asMatch[1] : s;
254
- });
255
- }
256
- function isRelativeImport(specifier) {
257
- return specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/");
258
- }
259
- function isExternalImport(specifier) {
260
- return !isRelativeImport(specifier) && !specifier.startsWith("#");
261
- }
262
- function getPackageName(specifier) {
263
- if (specifier.startsWith("@")) {
264
- const parts = specifier.split("/");
265
- if (parts.length >= 2) {
266
- return `${parts[0]}/${parts[1]}`;
267
- }
268
- return specifier;
269
- }
270
- const firstSlash = specifier.indexOf("/");
271
- return firstSlash === -1 ? specifier : specifier.slice(0, firstSlash);
272
- }
273
- function getLineNumber(source, index) {
274
- let line = 1;
275
- for (let i = 0; i < index && i < source.length; i++) {
276
- if (source[i] === "\n") {
277
- line++;
278
- }
279
- }
280
- return line;
281
- }
282
- function getColumnNumber(source, index) {
283
- let column = 0;
284
- for (let i = index - 1; i >= 0 && source[i] !== "\n"; i--) {
285
- column++;
286
- }
287
- return column;
288
- }
289
- function parseImports(source) {
290
- const imports = [];
291
- const seenStatements = /* @__PURE__ */ new Set();
292
- const addImport = (imp) => {
293
- const key = `${imp.type}:${imp.specifier}:${imp.statement}`;
294
- if (!seenStatements.has(key)) {
295
- seenStatements.add(key);
296
- imports.push(imp);
297
- }
298
- };
299
- let match;
300
- const defaultAndNamedRegex = new RegExp(IMPORT_PATTERNS.defaultAndNamed.source, "g");
301
- while ((match = defaultAndNamedRegex.exec(source)) !== null) {
302
- const [statement, defaultName, namedString, specifier] = match;
303
- addImport({
304
- statement,
305
- specifier,
306
- type: "default",
307
- defaultImport: defaultName,
308
- namedImports: parseNamedImports(namedString),
309
- line: getLineNumber(source, match.index),
310
- column: getColumnNumber(source, match.index)
311
- });
312
- }
313
- const defaultAndNamespaceRegex = new RegExp(IMPORT_PATTERNS.defaultAndNamespace.source, "g");
314
- while ((match = defaultAndNamespaceRegex.exec(source)) !== null) {
315
- const [statement, defaultName, namespaceName, specifier] = match;
316
- addImport({
317
- statement,
318
- specifier,
319
- type: "default",
320
- defaultImport: defaultName,
321
- namespaceImport: namespaceName,
322
- line: getLineNumber(source, match.index),
323
- column: getColumnNumber(source, match.index)
324
- });
325
- }
326
- const namedRegex = new RegExp(IMPORT_PATTERNS.named.source, "g");
327
- while ((match = namedRegex.exec(source)) !== null) {
328
- const [statement, namedString, specifier] = match;
329
- addImport({
330
- statement,
331
- specifier,
332
- type: "named",
333
- namedImports: parseNamedImports(namedString),
334
- line: getLineNumber(source, match.index),
335
- column: getColumnNumber(source, match.index)
336
- });
337
- }
338
- const defaultRegex = new RegExp(IMPORT_PATTERNS.default.source, "g");
339
- while ((match = defaultRegex.exec(source)) !== null) {
340
- const [statement, defaultName, specifier] = match;
341
- const afterMatch = source.slice(match.index + match[0].length - specifier.length - 2);
342
- if (afterMatch.startsWith(",")) continue;
343
- addImport({
344
- statement,
345
- specifier,
346
- type: "default",
347
- defaultImport: defaultName,
348
- line: getLineNumber(source, match.index),
349
- column: getColumnNumber(source, match.index)
350
- });
351
- }
352
- const namespaceRegex = new RegExp(IMPORT_PATTERNS.namespace.source, "g");
353
- while ((match = namespaceRegex.exec(source)) !== null) {
354
- const [statement, namespaceName, specifier] = match;
355
- addImport({
356
- statement,
357
- specifier,
358
- type: "namespace",
359
- namespaceImport: namespaceName,
360
- line: getLineNumber(source, match.index),
361
- column: getColumnNumber(source, match.index)
362
- });
363
- }
364
- const sideEffectRegex = new RegExp(IMPORT_PATTERNS.sideEffect.source, "g");
365
- while ((match = sideEffectRegex.exec(source)) !== null) {
366
- const [statement, specifier] = match;
367
- const beforeMatch = source.slice(Math.max(0, match.index - 50), match.index);
368
- if (beforeMatch.includes("from")) continue;
369
- addImport({
370
- statement,
371
- specifier,
372
- type: "side-effect",
373
- line: getLineNumber(source, match.index),
374
- column: getColumnNumber(source, match.index)
375
- });
376
- }
377
- const dynamicRegex = new RegExp(IMPORT_PATTERNS.dynamic.source, "g");
378
- while ((match = dynamicRegex.exec(source)) !== null) {
379
- const [statement, specifier] = match;
380
- addImport({
381
- statement,
382
- specifier,
383
- type: "dynamic",
384
- line: getLineNumber(source, match.index),
385
- column: getColumnNumber(source, match.index)
386
- });
387
- }
388
- const reExportRegex = new RegExp(IMPORT_PATTERNS.reExport.source, "g");
389
- while ((match = reExportRegex.exec(source)) !== null) {
390
- const [statement, specifier] = match;
391
- addImport({
392
- statement,
393
- specifier,
394
- type: "named",
395
- line: getLineNumber(source, match.index),
396
- column: getColumnNumber(source, match.index)
397
- });
398
- }
399
- const reExportAllRegex = new RegExp(IMPORT_PATTERNS.reExportAll.source, "g");
400
- while ((match = reExportAllRegex.exec(source)) !== null) {
401
- const [statement, specifier] = match;
402
- addImport({
403
- statement,
404
- specifier,
405
- type: "namespace",
406
- line: getLineNumber(source, match.index),
407
- column: getColumnNumber(source, match.index)
408
- });
409
- }
410
- const externalImports = imports.filter((imp) => isExternalImport(imp.specifier));
411
- const relativeImports = imports.filter((imp) => isRelativeImport(imp.specifier));
412
- const externalPackages = [...new Set(externalImports.map((imp) => getPackageName(imp.specifier)))];
413
- return {
414
- imports,
415
- externalImports,
416
- relativeImports,
417
- externalPackages
418
- };
419
- }
420
-
421
- // libs/uipack/src/resolver/esm-sh.resolver.ts
422
- var DEFAULT_FALLBACK_CDN = "https://esm.sh";
423
- function createEsmShResolver(options = {}) {
424
- const {
425
- fallbackCdnBase = DEFAULT_FALLBACK_CDN,
426
- registry = DEFAULT_CDN_REGISTRY,
427
- providerOrder = ["esm.sh", "cloudflare", "jsdelivr", "unpkg"]
428
- } = options;
429
- return {
430
- resolve(specifier, _context) {
431
- if (specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/")) {
432
- return null;
433
- }
434
- if (specifier.startsWith("node:") || specifier.startsWith("#")) {
435
- return null;
436
- }
437
- const pkgName = getPackageName(specifier);
438
- const entry = lookupPackage(pkgName, registry);
439
- if (entry) {
440
- for (const provider of providerOrder) {
441
- const config = entry.providers[provider];
442
- if (config?.url) {
443
- const subpath = specifier.slice(pkgName.length);
444
- if (subpath && config.url.includes("esm.sh/")) {
445
- return {
446
- value: config.url + subpath,
447
- type: "url",
448
- integrity: config.integrity
449
- };
450
- }
451
- if (subpath) {
452
- return {
453
- value: `${fallbackCdnBase}/${specifier}`,
454
- type: "url"
455
- };
456
- }
457
- if (config.global && !config.esm) {
458
- return {
459
- value: config.url,
460
- type: "url",
461
- integrity: config.integrity
462
- };
463
- }
464
- return {
465
- value: config.url,
466
- type: "url",
467
- integrity: config.integrity
468
- };
469
- }
470
- }
471
- }
472
- return {
473
- value: `${fallbackCdnBase}/${specifier}`,
474
- type: "url"
475
- };
476
- }
477
- };
478
- }
479
-
480
- // libs/uipack/src/utils/index.ts
481
- function escapeHtml(str) {
482
- if (str === null || str === void 0) {
483
- return "";
484
- }
485
- const s = String(str);
486
- 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");
487
- }
488
- var SCRIPT_UNSAFE_CHARACTERS = /[<>&\u2028\u2029]/g;
489
- function toUnicodeEscape(character) {
490
- return `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
491
- }
492
- function safeJsonForScript(value) {
493
- if (value === void 0) {
494
- return "null";
495
- }
496
- try {
497
- const jsonString = JSON.stringify(value, (_key, val) => {
498
- if (typeof val === "bigint") {
499
- return val.toString();
500
- }
501
- return val;
502
- });
503
- if (jsonString === void 0) {
504
- return "null";
505
- }
506
- return jsonString.replace(SCRIPT_UNSAFE_CHARACTERS, toUnicodeEscape);
507
- } catch {
508
- return '{"error":"Value could not be serialized"}';
509
- }
510
- }
511
-
512
- // libs/uipack/src/resolver/import-map.ts
513
- function createImportMapFromResolved(resolved) {
514
- const imports = {};
515
- const integrity = {};
516
- for (const [specifier, res] of Object.entries(resolved)) {
517
- if (res.type === "url") {
518
- imports[specifier] = res.value;
519
- if (res.integrity) {
520
- integrity[res.value] = res.integrity;
521
- }
522
- }
523
- }
524
- return {
525
- imports,
526
- integrity: Object.keys(integrity).length > 0 ? integrity : void 0
527
- };
528
- }
529
- function generateImportMapScriptTag(map) {
530
- const json = JSON.stringify(map, null, 2).replace(/<\//g, "<\\/");
531
- return `<script type="importmap">
4
+ var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var MCP_APPS_MIME_TYPE="text/html;profile=mcp-app";var MCP_APPS_EXTENSION_ID="io.modelcontextprotocol/ui";function resolveServingMode(options){const{configuredMode,platformType}=options;if(platformType==="gemini"){return{mode:configuredMode,supportsUI:false,effectiveMode:null,useStructuredContent:false,reason:"Gemini does not support MCP Apps UI"}}const effectiveMode=configuredMode==="auto"?"inline":configuredMode;if(effectiveMode==="hybrid"){const hybridCapable=platformType==="openai"||platformType==="ext-apps"||platformType==="cursor";if(!hybridCapable){return{mode:configuredMode,supportsUI:false,effectiveMode:null,useStructuredContent:false,reason:`Platform ${platformType} does not support hybrid serving mode`}}}const useStructuredContent=platformType==="openai"||platformType==="ext-apps"||platformType==="generic-mcp"||platformType==="unknown";return{mode:configuredMode,supportsUI:true,effectiveMode,useStructuredContent,reason:`Platform ${platformType} supports UI, mode: ${effectiveMode}`}}function buildToolResponseContent(options){const{rawOutput,htmlContent,servingMode,useStructuredContent,platformType}=options;const textSummary=typeof rawOutput==="string"?rawOutput:rawOutput!==null&&rawOutput!==void 0?JSON.stringify(rawOutput):"";const result={content:[{type:"text",text:textSummary}]};if(useStructuredContent&&rawOutput!==null&&rawOutput!==void 0){const structured=typeof rawOutput==="object"&&!Array.isArray(rawOutput)?rawOutput:{value:rawOutput};result.structuredContent=structured}if(htmlContent&&servingMode==="inline"){const htmlKey="ui/html";result._meta={[htmlKey]:htmlContent};result.format="html"}return result}function isUIRenderFailure(result){if(typeof result!=="object"||result===null){return false}const rec=result;return typeof rec["reason"]==="string"&&!("meta"in rec)}var DEFAULT_CDN_REGISTRY={react:{packageName:"react",defaultVersion:"19.2.4",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/react/19.2.4/umd/react.production.min.js",global:"React",crossorigin:"anonymous"},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/react@19.2.4/umd/react.production.min.js",global:"React",crossorigin:"anonymous"},unpkg:{url:"https://unpkg.com/react@19.2.4/umd/react.production.min.js",global:"React",crossorigin:"anonymous"},"esm.sh":{url:"https://esm.sh/react@19.2.4",esm:true,crossorigin:"anonymous"}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"A JavaScript library for building user interfaces",homepage:"https://react.dev",license:"MIT"}},"react-dom":{packageName:"react-dom",defaultVersion:"19.2.4",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/react-dom/19.2.4/umd/react-dom.production.min.js",global:"ReactDOM",crossorigin:"anonymous",peerDependencies:["react"]},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/react-dom@19.2.4/umd/react-dom.production.min.js",global:"ReactDOM",crossorigin:"anonymous",peerDependencies:["react"]},unpkg:{url:"https://unpkg.com/react-dom@19.2.4/umd/react-dom.production.min.js",global:"ReactDOM",crossorigin:"anonymous",peerDependencies:["react"]},"esm.sh":{url:"https://esm.sh/react-dom@19.2.4",esm:true,crossorigin:"anonymous",peerDependencies:["react"]}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"React package for working with the DOM",homepage:"https://react.dev",license:"MIT"}},"chart.js":{packageName:"chart.js",defaultVersion:"4.5.1",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.1/chart.umd.min.js",global:"Chart",crossorigin:"anonymous"},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js",global:"Chart",crossorigin:"anonymous"},unpkg:{url:"https://unpkg.com/chart.js@4.5.1/dist/chart.umd.min.js",global:"Chart",crossorigin:"anonymous"}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"Simple yet flexible JavaScript charting library",homepage:"https://www.chartjs.org",license:"MIT"}},d3:{packageName:"d3",defaultVersion:"7.9.0",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js",integrity:"sha512-vc58qvvBdrDR4etbxMdlTt4GBQk1qjvyORR2nrsPsFPyrs+/u5c3+1Ct6upOgdZoIl7eq6k3a1UPDSNAQi/32A==",global:"d3",crossorigin:"anonymous"},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js",global:"d3",crossorigin:"anonymous"},unpkg:{url:"https://unpkg.com/d3@7.9.0/dist/d3.min.js",global:"d3",crossorigin:"anonymous"}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"Data-Driven Documents",homepage:"https://d3js.org",license:"ISC"}},lodash:{packageName:"lodash",defaultVersion:"4.17.21",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js",integrity:"sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==",global:"_",crossorigin:"anonymous"},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js",global:"_",crossorigin:"anonymous"},unpkg:{url:"https://unpkg.com/lodash@4.17.21/lodash.min.js",global:"_",crossorigin:"anonymous"}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"A modern JavaScript utility library",homepage:"https://lodash.com",license:"MIT"}}};function lookupPackage(packageName,registry=DEFAULT_CDN_REGISTRY){return registry[packageName]}var IMPORT_PATTERNS={named:/import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,default:/import\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,namespace:/import\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,sideEffect:/import\s*['"]([^'"]+)['"]/g,dynamic:/(?:await\s+)?import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,defaultAndNamed:/import\s+(\w+)\s*,\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,defaultAndNamespace:/import\s+(\w+)\s*,\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,reExport:/export\s*\{[^}]+\}\s*from\s*['"]([^'"]+)['"]/g,reExportAll:/export\s*\*\s*from\s*['"]([^'"]+)['"]/g};function parseNamedImports(namedString){return namedString.split(",").map(s=>s.trim()).filter(s=>s.length>0).map(s=>{const asMatch=s.match(/^(\w+)\s+as\s+\w+$/);return asMatch?asMatch[1]:s})}function isRelativeImport(specifier){return specifier.startsWith("./")||specifier.startsWith("../")||specifier.startsWith("/")}function isExternalImport(specifier){return!isRelativeImport(specifier)&&!specifier.startsWith("#")}function getPackageName(specifier){if(specifier.startsWith("@")){const parts=specifier.split("/");if(parts.length>=2){return`${parts[0]}/${parts[1]}`}return specifier}const firstSlash=specifier.indexOf("/");return firstSlash===-1?specifier:specifier.slice(0,firstSlash)}function getLineNumber(source,index){let line=1;for(let i=0;i<index&&i<source.length;i++){if(source[i]==="\n"){line++}}return line}function getColumnNumber(source,index){let column=0;for(let i=index-1;i>=0&&source[i]!=="\n";i--){column++}return column}function parseImports(source){const imports=[];const seenStatements=new Set;const addImport=imp=>{const key=`${imp.type}:${imp.specifier}:${imp.statement}`;if(!seenStatements.has(key)){seenStatements.add(key);imports.push(imp)}};let match;const defaultAndNamedRegex=new RegExp(IMPORT_PATTERNS.defaultAndNamed.source,"g");while((match=defaultAndNamedRegex.exec(source))!==null){const[statement,defaultName,namedString,specifier]=match;addImport({statement,specifier,type:"default",defaultImport:defaultName,namedImports:parseNamedImports(namedString),line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const defaultAndNamespaceRegex=new RegExp(IMPORT_PATTERNS.defaultAndNamespace.source,"g");while((match=defaultAndNamespaceRegex.exec(source))!==null){const[statement,defaultName,namespaceName,specifier]=match;addImport({statement,specifier,type:"default",defaultImport:defaultName,namespaceImport:namespaceName,line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const namedRegex=new RegExp(IMPORT_PATTERNS.named.source,"g");while((match=namedRegex.exec(source))!==null){const[statement,namedString,specifier]=match;addImport({statement,specifier,type:"named",namedImports:parseNamedImports(namedString),line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const defaultRegex=new RegExp(IMPORT_PATTERNS.default.source,"g");while((match=defaultRegex.exec(source))!==null){const[statement,defaultName,specifier]=match;const afterMatch=source.slice(match.index+match[0].length-specifier.length-2);if(afterMatch.startsWith(","))continue;addImport({statement,specifier,type:"default",defaultImport:defaultName,line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const namespaceRegex=new RegExp(IMPORT_PATTERNS.namespace.source,"g");while((match=namespaceRegex.exec(source))!==null){const[statement,namespaceName,specifier]=match;addImport({statement,specifier,type:"namespace",namespaceImport:namespaceName,line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const sideEffectRegex=new RegExp(IMPORT_PATTERNS.sideEffect.source,"g");while((match=sideEffectRegex.exec(source))!==null){const[statement,specifier]=match;const beforeMatch=source.slice(Math.max(0,match.index-50),match.index);if(beforeMatch.includes("from"))continue;addImport({statement,specifier,type:"side-effect",line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const dynamicRegex=new RegExp(IMPORT_PATTERNS.dynamic.source,"g");while((match=dynamicRegex.exec(source))!==null){const[statement,specifier]=match;addImport({statement,specifier,type:"dynamic",line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const reExportRegex=new RegExp(IMPORT_PATTERNS.reExport.source,"g");while((match=reExportRegex.exec(source))!==null){const[statement,specifier]=match;addImport({statement,specifier,type:"named",line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const reExportAllRegex=new RegExp(IMPORT_PATTERNS.reExportAll.source,"g");while((match=reExportAllRegex.exec(source))!==null){const[statement,specifier]=match;addImport({statement,specifier,type:"namespace",line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const externalImports=imports.filter(imp=>isExternalImport(imp.specifier));const relativeImports=imports.filter(imp=>isRelativeImport(imp.specifier));const externalPackages=[...new Set(externalImports.map(imp=>getPackageName(imp.specifier)))];return{imports,externalImports,relativeImports,externalPackages}}var DEFAULT_FALLBACK_CDN="https://esm.sh";function createEsmShResolver(options={}){const{fallbackCdnBase=DEFAULT_FALLBACK_CDN,registry=DEFAULT_CDN_REGISTRY,providerOrder=["esm.sh","cloudflare","jsdelivr","unpkg"]}=options;return{resolve(specifier,_context){if(specifier.startsWith("./")||specifier.startsWith("../")||specifier.startsWith("/")){return null}if(specifier.startsWith("node:")||specifier.startsWith("#")){return null}const pkgName=getPackageName(specifier);const entry=lookupPackage(pkgName,registry);if(entry){for(const provider of providerOrder){const config=entry.providers[provider];if(config?.url){const subpath=specifier.slice(pkgName.length);if(subpath&&config.url.includes("esm.sh/")){return{value:config.url+subpath,type:"url",integrity:config.integrity}}if(subpath){return{value:`${fallbackCdnBase}/${specifier}`,type:"url"}}if(config.global&&!config.esm){return{value:config.url,type:"url",integrity:config.integrity}}return{value:config.url,type:"url",integrity:config.integrity}}}}return{value:`${fallbackCdnBase}/${specifier}`,type:"url"}}}}function escapeHtml(str){if(str===null||str===void 0){return""}const s=String(str);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")}var SCRIPT_UNSAFE_CHARACTERS=/[<>&\u2028\u2029]/g;function toUnicodeEscape(character){return`\\u${character.charCodeAt(0).toString(16).padStart(4,"0")}`}function safeJsonForScript(value){if(value===void 0){return"null"}try{const jsonString=JSON.stringify(value,(_key,val)=>{if(typeof val==="bigint"){return val.toString()}return val});if(jsonString===void 0){return"null"}return jsonString.replace(SCRIPT_UNSAFE_CHARACTERS,toUnicodeEscape)}catch{return'{"error":"Value could not be serialized"}'}}function createImportMapFromResolved(resolved){const imports={};const integrity={};for(const[specifier,res]of Object.entries(resolved)){if(res.type==="url"){imports[specifier]=res.value;if(res.integrity){integrity[res.value]=res.integrity}}}return{imports,integrity:Object.keys(integrity).length>0?integrity:void 0}}function generateImportMapScriptTag(map){const json=JSON.stringify(map,null,2).replace(/<\//g,"<\\/");return`<script type="importmap">
532
5
  ${json}
533
- </script>`;
534
- }
535
-
536
- // libs/uipack/src/bridge-runtime/iife-generator.ts
537
- var WIDGET_CALL_META_KEY = "frontmcp/widgetCall";
538
- var MCP_APPS_DISPLAY_MODES = ["inline", "fullscreen", "pip"];
539
- function generateBridgeIIFE(options = {}) {
540
- const { debug = false, trustedOrigins = [], minify = false } = options;
541
- const adapters = options.adapters || ["openai", "ext-apps", "claude", "gemini", "generic"];
542
- const parts = [];
543
- parts.push("(function() {");
544
- parts.push('"use strict";');
545
- parts.push("");
546
- if (debug) {
547
- parts.push('function log(msg) { console.log("[FrontMcpBridge] " + msg); }');
548
- } else {
549
- parts.push("function log() {}");
550
- }
551
- parts.push("");
552
- parts.push("var DEFAULT_SAFE_AREA = { top: 0, bottom: 0, left: 0, right: 0 };");
553
- parts.push("");
554
- parts.push(generateContextDetection());
555
- parts.push("");
556
- parts.push(generateBaseCapabilities());
557
- parts.push("");
558
- if (adapters.includes("openai")) {
559
- parts.push(generateOpenAIAdapter());
560
- parts.push("");
561
- }
562
- if (adapters.includes("ext-apps")) {
563
- parts.push(generateExtAppsAdapter(trustedOrigins));
564
- parts.push("");
565
- }
566
- if (adapters.includes("claude")) {
567
- parts.push(generateClaudeAdapter());
568
- parts.push("");
569
- }
570
- if (adapters.includes("gemini")) {
571
- parts.push(generateGeminiAdapter());
572
- parts.push("");
573
- }
574
- if (adapters.includes("generic")) {
575
- parts.push(generateGenericAdapter());
576
- parts.push("");
577
- }
578
- parts.push(generatePlatformDetection(adapters));
579
- parts.push("");
580
- parts.push(generateBridgeClass());
581
- parts.push("");
582
- parts.push("var bridge = new FrontMcpBridge();");
583
- parts.push("bridge.initialize().then(function() {");
584
- parts.push(' log("Bridge initialized with adapter: " + bridge.adapterId);');
585
- parts.push(' window.dispatchEvent(new CustomEvent("bridge:ready", { detail: { adapter: bridge.adapterId } }));');
586
- parts.push(" if (window.__mcpDisplayMode) bridge.requestDisplayMode(window.__mcpDisplayMode).catch(function() {});");
587
- parts.push("}).catch(function(err) {");
588
- parts.push(' console.error("[FrontMcpBridge] Init failed:", err);');
589
- parts.push(' window.dispatchEvent(new CustomEvent("bridge:error", { detail: { error: err } }));');
590
- parts.push("});");
591
- parts.push("");
592
- parts.push("window.FrontMcpBridge = bridge;");
593
- parts.push("");
594
- parts.push(generateAutoResize());
595
- parts.push("function __showLoading() {");
596
- parts.push(' var root = document.getElementById("root");');
597
- parts.push(" if (root && !root.hasChildNodes()) {");
598
- parts.push(
599
- ` root.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;padding:2rem;color:#6b7280;font-family:system-ui,sans-serif"><div style="text-align:center"><div style="width:24px;height:24px;border:2px solid #e5e7eb;border-top-color:#3b82f6;border-radius:50%;animation:__spin 0.6s linear infinite;margin:0 auto 12px"></div><div style="font-size:0.875rem">Loading widget...</div></div></div><style>@keyframes __spin{to{transform:rotate(360deg)}}</style>';`
600
- );
601
- parts.push(" }");
602
- parts.push("}");
603
- parts.push('if (document.readyState === "loading") {');
604
- parts.push(' document.addEventListener("DOMContentLoaded", __showLoading);');
605
- parts.push("} else {");
606
- parts.push(" __showLoading();");
607
- parts.push("}");
608
- parts.push("})();");
609
- const code = parts.join("\n");
610
- if (minify) {
611
- return minifyJS(code);
612
- }
613
- return code;
614
- }
615
- function generateAutoResize() {
616
- return `
6
+ </script>`}var WIDGET_CALL_META_KEY="frontmcp/widgetCall";var MCP_APPS_DISPLAY_MODES=["inline","fullscreen","pip"];function generateBridgeIIFE(options={}){const{debug=false,trustedOrigins=[],minify=false}=options;const adapters=options.adapters||["openai","ext-apps","claude","gemini","generic"];const parts=[];parts.push("(function() {");parts.push('"use strict";');parts.push("");if(debug){parts.push('function log(msg) { console.log("[FrontMcpBridge] " + msg); }')}else{parts.push("function log() {}")}parts.push("");parts.push("var DEFAULT_SAFE_AREA = { top: 0, bottom: 0, left: 0, right: 0 };");parts.push("");parts.push(generateContextDetection());parts.push("");parts.push(generateBaseCapabilities());parts.push("");if(adapters.includes("openai")){parts.push(generateOpenAIAdapter());parts.push("")}if(adapters.includes("ext-apps")){parts.push(generateExtAppsAdapter(trustedOrigins));parts.push("")}if(adapters.includes("claude")){parts.push(generateClaudeAdapter());parts.push("")}if(adapters.includes("gemini")){parts.push(generateGeminiAdapter());parts.push("")}if(adapters.includes("generic")){parts.push(generateGenericAdapter());parts.push("")}parts.push(generatePlatformDetection(adapters));parts.push("");parts.push(generateBridgeClass());parts.push("");parts.push("var bridge = new FrontMcpBridge();");parts.push("bridge.initialize().then(function() {");parts.push(' log("Bridge initialized with adapter: " + bridge.adapterId);');parts.push(' window.dispatchEvent(new CustomEvent("bridge:ready", { detail: { adapter: bridge.adapterId } }));');parts.push(" if (window.__mcpDisplayMode) bridge.requestDisplayMode(window.__mcpDisplayMode).catch(function() {});");parts.push("}).catch(function(err) {");parts.push(' console.error("[FrontMcpBridge] Init failed:", err);');parts.push(' window.dispatchEvent(new CustomEvent("bridge:error", { detail: { error: err } }));');parts.push("});");parts.push("");parts.push("window.FrontMcpBridge = bridge;");parts.push("");parts.push(generateAutoResize());parts.push("function __showLoading() {");parts.push(' var root = document.getElementById("root");');parts.push(" if (root && !root.hasChildNodes()) {");parts.push(` root.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;padding:2rem;color:#6b7280;font-family:system-ui,sans-serif"><div style="text-align:center"><div style="width:24px;height:24px;border:2px solid #e5e7eb;border-top-color:#3b82f6;border-radius:50%;animation:__spin 0.6s linear infinite;margin:0 auto 12px"></div><div style="font-size:0.875rem">Loading widget...</div></div></div><style>@keyframes __spin{to{transform:rotate(360deg)}}</style>';`);parts.push(" }");parts.push("}");parts.push('if (document.readyState === "loading") {');parts.push(' document.addEventListener("DOMContentLoaded", __showLoading);');parts.push("} else {");parts.push(" __showLoading();");parts.push("}");parts.push("})();");const code=parts.join("\n");if(minify){return minifyJS(code)}return code}function generateAutoResize(){return`
617
7
  function __applySizingCss(sizing) {
618
8
  if (typeof document === 'undefined' || !document.documentElement) return;
619
9
  function toLen(v) { return typeof v === 'number' ? v + 'px' : v; }
@@ -748,10 +138,7 @@ function __initAutoResize() {
748
138
  }
749
139
  }
750
140
  __initAutoResize();
751
- `.trim();
752
- }
753
- function generateContextDetection() {
754
- return `
141
+ `.trim()}function generateContextDetection(){return`
755
142
  function detectTheme() {
756
143
  if (typeof window !== 'undefined' && window.matchMedia) {
757
144
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
@@ -838,10 +225,7 @@ function readInjectedData() {
838
225
  }
839
226
  return data;
840
227
  }
841
- `.trim();
842
- }
843
- function generateBaseCapabilities() {
844
- return `
228
+ `.trim()}function generateBaseCapabilities(){return`
845
229
  var DEFAULT_CAPABILITIES = {
846
230
  canCallTools: false,
847
231
  canSendMessages: false,
@@ -851,10 +235,7 @@ var DEFAULT_CAPABILITIES = {
851
235
  supportsDisplayModes: false,
852
236
  supportsTheme: true
853
237
  };
854
- `.trim();
855
- }
856
- function generateOpenAIAdapter() {
857
- return `
238
+ `.trim()}function generateOpenAIAdapter(){return`
858
239
  var OpenAIAdapter = {
859
240
  id: 'openai',
860
241
  name: 'OpenAI ChatGPT',
@@ -939,11 +320,7 @@ var OpenAIAdapter = {
939
320
  return Promise.resolve();
940
321
  }
941
322
  };
942
- `.trim();
943
- }
944
- function generateExtAppsAdapter(trustedOrigins) {
945
- const originsArray = trustedOrigins.length > 0 ? JSON.stringify(trustedOrigins) : "[]";
946
- return `
323
+ `.trim()}function generateExtAppsAdapter(trustedOrigins){const originsArray=trustedOrigins.length>0?JSON.stringify(trustedOrigins):"[]";return`
947
324
  var ExtAppsAdapter = {
948
325
  id: 'ext-apps',
949
326
  name: 'ext-apps (SEP-1865)',
@@ -1286,10 +663,7 @@ var ExtAppsAdapter = {
1286
663
  return this.sendRequest('ui/unregisterTool', { name: name });
1287
664
  }
1288
665
  };
1289
- `.trim();
1290
- }
1291
- function generateClaudeAdapter() {
1292
- return `
666
+ `.trim()}function generateClaudeAdapter(){return`
1293
667
  var ClaudeAdapter = {
1294
668
  id: 'claude',
1295
669
  name: 'Claude (Anthropic)',
@@ -1350,10 +724,7 @@ var ClaudeAdapter = {
1350
724
  return Promise.resolve();
1351
725
  }
1352
726
  };
1353
- `.trim();
1354
- }
1355
- function generateGeminiAdapter() {
1356
- return `
727
+ `.trim()}function generateGeminiAdapter(){return`
1357
728
  var GeminiAdapter = {
1358
729
  id: 'gemini',
1359
730
  name: 'Google Gemini',
@@ -1404,10 +775,7 @@ var GeminiAdapter = {
1404
775
  return Promise.resolve();
1405
776
  }
1406
777
  };
1407
- `.trim();
1408
- }
1409
- function generateGenericAdapter() {
1410
- return `
778
+ `.trim()}function generateGenericAdapter(){return`
1411
779
  var GenericAdapter = {
1412
780
  id: 'generic',
1413
781
  name: 'Generic Web',
@@ -1442,26 +810,7 @@ var GenericAdapter = {
1442
810
  return Promise.resolve();
1443
811
  }
1444
812
  };
1445
- `.trim();
1446
- }
1447
- function generatePlatformDetection(adapters) {
1448
- const adapterVars = adapters.map((a) => {
1449
- switch (a) {
1450
- case "openai":
1451
- return "OpenAIAdapter";
1452
- case "ext-apps":
1453
- return "ExtAppsAdapter";
1454
- case "claude":
1455
- return "ClaudeAdapter";
1456
- case "gemini":
1457
- return "GeminiAdapter";
1458
- case "generic":
1459
- return "GenericAdapter";
1460
- default:
1461
- return "";
1462
- }
1463
- }).filter(Boolean);
1464
- return `
813
+ `.trim()}function generatePlatformDetection(adapters){const adapterVars=adapters.map(a=>{switch(a){case"openai":return"OpenAIAdapter";case"ext-apps":return"ExtAppsAdapter";case"claude":return"ClaudeAdapter";case"gemini":return"GeminiAdapter";case"generic":return"GenericAdapter";default:return""}}).filter(Boolean);return`
1465
814
  var ADAPTERS = [${adapterVars.join(", ")}].sort(function(a, b) { return b.priority - a.priority; });
1466
815
 
1467
816
  function detectPlatform() {
@@ -1474,10 +823,7 @@ function detectPlatform() {
1474
823
  log('No platform detected, using generic');
1475
824
  return GenericAdapter;
1476
825
  }
1477
- `.trim();
1478
- }
1479
- function generateBridgeClass() {
1480
- return `
826
+ `.trim()}function generateBridgeClass(){return`
1481
827
  function FrontMcpBridge() {
1482
828
  this._adapter = null;
1483
829
  this._initialized = false;
@@ -1853,504 +1199,19 @@ FrontMcpBridge.prototype._setupDataToolCallHandler = function() {
1853
1199
  }
1854
1200
  }, true); // Use capture phase to handle before React handlers
1855
1201
  };
1856
- `.trim();
1857
- }
1858
- var MAX_MINIFY_CODE_LENGTH = 5e5;
1859
- function minifyJS(code) {
1860
- if (code.length > MAX_MINIFY_CODE_LENGTH) {
1861
- return code;
1862
- }
1863
- const out = [];
1864
- let inBlockComment = false;
1865
- for (const raw of code.split("\n")) {
1866
- const line = raw.trim();
1867
- if (inBlockComment) {
1868
- if (line.includes("*/")) inBlockComment = false;
1869
- continue;
1870
- }
1871
- if (line === "" || line.startsWith("//")) continue;
1872
- if (line.startsWith("/*")) {
1873
- if (!line.includes("*/")) inBlockComment = true;
1874
- continue;
1875
- }
1876
- out.push(line);
1877
- }
1878
- return out.join("\n");
1879
- }
1880
- function generatePlatformBundle(platform, options = {}) {
1881
- const platformAdapters = {
1882
- chatgpt: ["openai", "generic"],
1883
- claude: ["claude", "generic"],
1884
- gemini: ["gemini", "generic"],
1885
- universal: ["openai", "ext-apps", "claude", "gemini", "generic"]
1886
- };
1887
- return generateBridgeIIFE({
1888
- ...options,
1889
- adapters: platformAdapters[platform]
1890
- });
1891
- }
1892
- var UNIVERSAL_BRIDGE_SCRIPT = generateBridgeIIFE();
1893
- var BRIDGE_SCRIPT_TAGS = {
1894
- universal: `<script>${UNIVERSAL_BRIDGE_SCRIPT}</script>`,
1895
- chatgpt: `<script>${generatePlatformBundle("chatgpt")}</script>`,
1896
- claude: `<script>${generatePlatformBundle("claude")}</script>`,
1897
- gemini: `<script>${generatePlatformBundle("gemini")}</script>`
1898
- };
1899
-
1900
- // libs/uipack/src/shell/csp.ts
1901
- var DEFAULT_CDN_DOMAINS = [
1902
- "https://cdn.jsdelivr.net",
1903
- "https://cdnjs.cloudflare.com",
1904
- "https://fonts.googleapis.com",
1905
- "https://fonts.gstatic.com",
1906
- "https://esm.sh"
1907
- ];
1908
- var DEFAULT_CSP_DIRECTIVES = [
1909
- "default-src 'none'",
1910
- `script-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1911
- `style-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1912
- `img-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1913
- `font-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1914
- `connect-src ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1915
- "object-src 'self' data:"
1916
- ];
1917
- function buildCSPDirectives(csp) {
1918
- if (!csp) {
1919
- return [...DEFAULT_CSP_DIRECTIVES];
1920
- }
1921
- const validResourceDomains = sanitizeCSPDomains(csp.resourceDomains);
1922
- const validConnectDomains = sanitizeCSPDomains(csp.connectDomains);
1923
- const allResourceDomains = [.../* @__PURE__ */ new Set([...DEFAULT_CDN_DOMAINS, ...validResourceDomains])];
1924
- const directives = [
1925
- "default-src 'none'",
1926
- `script-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`,
1927
- `style-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`
1928
- ];
1929
- const imgSources = ["'self'", "data:", ...allResourceDomains];
1930
- directives.push(`img-src ${imgSources.join(" ")}`);
1931
- const fontSources = ["'self'", "data:", ...allResourceDomains];
1932
- directives.push(`font-src ${fontSources.join(" ")}`);
1933
- const connectSources = [.../* @__PURE__ */ new Set([...allResourceDomains, ...validConnectDomains])];
1934
- directives.push(`connect-src ${connectSources.join(" ")}`);
1935
- directives.push("object-src 'self' data:");
1936
- return directives;
1937
- }
1938
- function buildCSPMetaTag(csp) {
1939
- const directives = buildCSPDirectives(csp);
1940
- const content = directives.join("; ");
1941
- return `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(content)}">`;
1942
- }
1943
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
1944
- function validateCSPDomain(domain) {
1945
- if (typeof domain !== "string" || /[\s;,'"]/.test(domain)) return false;
1946
- if (/[?#]/.test(domain)) return false;
1947
- if (domain.includes("*")) {
1948
- const wildcard = /^(?:https|wss):\/\/\*\.(.*)$/.exec(domain);
1949
- return wildcard !== null && /^([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/.test(wildcard[1]);
1950
- }
1951
- try {
1952
- const url = new URL(domain);
1953
- if (url.protocol === "https:" || url.protocol === "wss:") return true;
1954
- return (url.protocol === "http:" || url.protocol === "ws:") && LOOPBACK_HOSTS.has(url.hostname);
1955
- } catch {
1956
- return false;
1957
- }
1958
- }
1959
- var reportedInvalidDomains = /* @__PURE__ */ new Set();
1960
- function sanitizeCSPDomains(domains) {
1961
- if (!domains) return [];
1962
- const valid = [];
1963
- for (const domain of domains) {
1964
- if (validateCSPDomain(domain)) {
1965
- valid.push(domain);
1966
- } else if (!reportedInvalidDomains.has(domain)) {
1967
- reportedInvalidDomains.add(domain);
1968
- console.warn(
1969
- `Invalid CSP domain ignored: ${domain} (expected an https:// or wss:// origin, or http:// / ws:// on localhost)`
1970
- );
1971
- }
1972
- }
1973
- return valid;
1974
- }
1975
- function escapeAttribute(str) {
1976
- return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1977
- }
1978
-
1979
- // libs/uipack/src/shell/custom-shell-types.ts
1980
- var SHELL_PLACEHOLDER_NAMES = ["CSP", "DATA", "BRIDGE", "CONTENT", "TITLE"];
1981
- var SHELL_PLACEHOLDERS = {
1982
- CSP: "{{CSP}}",
1983
- DATA: "{{DATA}}",
1984
- BRIDGE: "{{BRIDGE}}",
1985
- CONTENT: "{{CONTENT}}",
1986
- TITLE: "{{TITLE}}"
1987
- };
1988
- var REQUIRED_PLACEHOLDERS = ["CONTENT"];
1989
- var OPTIONAL_PLACEHOLDERS = ["CSP", "DATA", "BRIDGE", "TITLE"];
1990
-
1991
- // libs/uipack/src/shell/custom-shell-applier.ts
1992
- var PLACEHOLDER_PATTERN = new RegExp(`\\{\\{(${SHELL_PLACEHOLDER_NAMES.join("|")})\\}\\}`, "g");
1993
- var VALUE_KEYS = {
1994
- CSP: "csp",
1995
- DATA: "data",
1996
- BRIDGE: "bridge",
1997
- CONTENT: "content",
1998
- TITLE: "title"
1999
- };
2000
- function applyShellTemplate(template, values) {
2001
- return template.replace(PLACEHOLDER_PATTERN, (_token, name) => values[VALUE_KEYS[name]]);
2002
- }
2003
-
2004
- // libs/uipack/src/shell/custom-shell-validator.ts
2005
- function validateShellTemplate(template) {
2006
- const found = {};
2007
- for (const name of SHELL_PLACEHOLDER_NAMES) {
2008
- found[name] = template.includes(SHELL_PLACEHOLDERS[name]);
2009
- }
2010
- const missingRequired = REQUIRED_PLACEHOLDERS.filter((name) => !found[name]);
2011
- const missingOptional = OPTIONAL_PLACEHOLDERS.filter((name) => !found[name]);
2012
- return {
2013
- valid: missingRequired.length === 0,
2014
- found,
2015
- missingRequired,
2016
- missingOptional
2017
- };
2018
- }
2019
-
2020
- // libs/uipack/src/shell/trusted-html.ts
2021
- var TRUSTED_HTML = /* @__PURE__ */ Symbol.for("@frontmcp/uipack/trusted-html");
2022
- function trustedHtml(markup) {
2023
- const value = String(markup);
2024
- return Object.freeze({ [TRUSTED_HTML]: value, toString: () => value });
2025
- }
2026
- function isTrustedHtml(value) {
2027
- return typeof value === "object" && value !== null && typeof value[TRUSTED_HTML] === "string";
2028
- }
2029
- function interpolate(value) {
2030
- if (isTrustedHtml(value)) return value[TRUSTED_HTML];
2031
- if (Array.isArray(value)) return value.map(interpolate).join("");
2032
- if (value === false) return "";
2033
- return escapeHtml(value);
2034
- }
2035
- function html(strings, ...values) {
2036
- let markup = strings[0];
2037
- for (let index = 0; index < values.length; index++) {
2038
- markup += interpolate(values[index]) + strings[index + 1];
2039
- }
2040
- return trustedHtml(markup);
2041
- }
2042
-
2043
- // libs/uipack/src/shell/data-injector.ts
2044
- function hasSizing(sizing) {
2045
- if (!sizing) return false;
2046
- return sizing.preferredHeight !== void 0 || sizing.minHeight !== void 0 || sizing.maxHeight !== void 0 || sizing.aspectRatio !== void 0 || sizing.autoResize !== void 0;
2047
- }
2048
- function buildDataInjectionScript(options) {
2049
- const { toolName, input, output, structuredContent, sizing, displayMode } = options;
2050
- const lines = [
2051
- `window.__mcpAppsEnabled = true;`,
2052
- `window.__mcpToolName = ${safeJsonForScript(toolName)};`,
2053
- `window.__mcpToolInput = ${safeJsonForScript(input ?? null)};`,
2054
- `window.__mcpToolOutput = ${safeJsonForScript(output ?? null)};`,
2055
- `window.__mcpStructuredContent = ${safeJsonForScript(structuredContent ?? null)};`
2056
- ];
2057
- if (hasSizing(sizing)) {
2058
- lines.push(`window.__mcpWidgetSizing = ${safeJsonForScript(sizing)};`);
2059
- }
2060
- if (displayMode && displayMode !== "inline") {
2061
- lines.push(`window.__mcpDisplayMode = ${safeJsonForScript(displayMode)};`);
2062
- }
2063
- return `<script>
1202
+ `.trim()}var MAX_MINIFY_CODE_LENGTH=5e5;function minifyJS(code){if(code.length>MAX_MINIFY_CODE_LENGTH){return code}const out=[];let inBlockComment=false;for(const raw of code.split("\n")){const line=raw.trim();if(inBlockComment){if(line.includes("*/"))inBlockComment=false;continue}if(line===""||line.startsWith("//"))continue;if(line.startsWith("/*")){if(!line.includes("*/"))inBlockComment=true;continue}out.push(line)}return out.join("\n")}function generatePlatformBundle(platform,options={}){const platformAdapters={chatgpt:["openai","generic"],claude:["claude","generic"],gemini:["gemini","generic"],universal:["openai","ext-apps","claude","gemini","generic"]};return generateBridgeIIFE({...options,adapters:platformAdapters[platform]})}var UNIVERSAL_BRIDGE_SCRIPT=generateBridgeIIFE();var BRIDGE_SCRIPT_TAGS={universal:`<script>${UNIVERSAL_BRIDGE_SCRIPT}</script>`,chatgpt:`<script>${generatePlatformBundle("chatgpt")}</script>`,claude:`<script>${generatePlatformBundle("claude")}</script>`,gemini:`<script>${generatePlatformBundle("gemini")}</script>`};var DEFAULT_CDN_DOMAINS=["https://cdn.jsdelivr.net","https://cdnjs.cloudflare.com","https://fonts.googleapis.com","https://fonts.gstatic.com","https://esm.sh"];var DEFAULT_CSP_DIRECTIVES=["default-src 'none'",`script-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,`style-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,`img-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,`font-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,`connect-src ${DEFAULT_CDN_DOMAINS.join(" ")}`,"object-src 'self' data:"];function buildCSPDirectives(csp){if(!csp){return[...DEFAULT_CSP_DIRECTIVES]}const validResourceDomains=sanitizeCSPDomains(csp.resourceDomains);const validConnectDomains=sanitizeCSPDomains(csp.connectDomains);const allResourceDomains=[...new Set([...DEFAULT_CDN_DOMAINS,...validResourceDomains])];const directives=["default-src 'none'",`script-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`,`style-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`];const imgSources=["'self'","data:",...allResourceDomains];directives.push(`img-src ${imgSources.join(" ")}`);const fontSources=["'self'","data:",...allResourceDomains];directives.push(`font-src ${fontSources.join(" ")}`);const connectSources=[...new Set([...allResourceDomains,...validConnectDomains])];directives.push(`connect-src ${connectSources.join(" ")}`);directives.push("object-src 'self' data:");return directives}function buildCSPMetaTag(csp){const directives=buildCSPDirectives(csp);const content=directives.join("; ");return`<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(content)}">`}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function validateCSPDomain(domain){if(typeof domain!=="string"||/[\s;,'"]/.test(domain))return false;if(/[?#]/.test(domain))return false;if(domain.includes("*")){const wildcard=/^(?:https|wss):\/\/\*\.(.*)$/.exec(domain);return wildcard!==null&&/^([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/.test(wildcard[1])}try{const url=new URL(domain);if(url.protocol==="https:"||url.protocol==="wss:")return true;return(url.protocol==="http:"||url.protocol==="ws:")&&LOOPBACK_HOSTS.has(url.hostname)}catch{return false}}var reportedInvalidDomains=new Set;function sanitizeCSPDomains(domains){if(!domains)return[];const valid=[];for(const domain of domains){if(validateCSPDomain(domain)){valid.push(domain)}else if(!reportedInvalidDomains.has(domain)){reportedInvalidDomains.add(domain);console.warn(`Invalid CSP domain ignored: ${domain} (expected an https:// or wss:// origin, or http:// / ws:// on localhost)`)}}return valid}function escapeAttribute(str){return str.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var SHELL_PLACEHOLDER_NAMES=["CSP","DATA","BRIDGE","CONTENT","TITLE"];var SHELL_PLACEHOLDERS={CSP:"{{CSP}}",DATA:"{{DATA}}",BRIDGE:"{{BRIDGE}}",CONTENT:"{{CONTENT}}",TITLE:"{{TITLE}}"};var REQUIRED_PLACEHOLDERS=["CONTENT"];var OPTIONAL_PLACEHOLDERS=["CSP","DATA","BRIDGE","TITLE"];var PLACEHOLDER_PATTERN=new RegExp(`\\{\\{(${SHELL_PLACEHOLDER_NAMES.join("|")})\\}\\}`,"g");var VALUE_KEYS={CSP:"csp",DATA:"data",BRIDGE:"bridge",CONTENT:"content",TITLE:"title"};function applyShellTemplate(template,values){return template.replace(PLACEHOLDER_PATTERN,(_token,name)=>values[VALUE_KEYS[name]])}function validateShellTemplate(template){const found={};for(const name of SHELL_PLACEHOLDER_NAMES){found[name]=template.includes(SHELL_PLACEHOLDERS[name])}const missingRequired=REQUIRED_PLACEHOLDERS.filter(name=>!found[name]);const missingOptional=OPTIONAL_PLACEHOLDERS.filter(name=>!found[name]);return{valid:missingRequired.length===0,found,missingRequired,missingOptional}}var TRUSTED_HTML=Symbol.for("@frontmcp/uipack/trusted-html");function trustedHtml(markup){const value=String(markup);return Object.freeze({[TRUSTED_HTML]:value,toString:()=>value})}function isTrustedHtml(value){return typeof value==="object"&&value!==null&&typeof value[TRUSTED_HTML]==="string"}function interpolate(value){if(isTrustedHtml(value))return value[TRUSTED_HTML];if(Array.isArray(value))return value.map(interpolate).join("");if(value===false)return"";return escapeHtml(value)}function html(strings,...values){let markup=strings[0];for(let index=0;index<values.length;index++){markup+=interpolate(values[index])+strings[index+1]}return trustedHtml(markup)}function hasSizing(sizing){if(!sizing)return false;return sizing.preferredHeight!==void 0||sizing.minHeight!==void 0||sizing.maxHeight!==void 0||sizing.aspectRatio!==void 0||sizing.autoResize!==void 0}function buildDataInjectionScript(options){const{toolName,input,output,structuredContent,sizing,displayMode}=options;const lines=[`window.__mcpAppsEnabled = true;`,`window.__mcpToolName = ${safeJsonForScript(toolName)};`,`window.__mcpToolInput = ${safeJsonForScript(input??null)};`,`window.__mcpToolOutput = ${safeJsonForScript(output??null)};`,`window.__mcpStructuredContent = ${safeJsonForScript(structuredContent??null)};`];if(hasSizing(sizing)){lines.push(`window.__mcpWidgetSizing = ${safeJsonForScript(sizing)};`)}if(displayMode&&displayMode!=="inline"){lines.push(`window.__mcpDisplayMode = ${safeJsonForScript(displayMode)};`)}return`<script>
2064
1203
  ${lines.join("\n")}
2065
- </script>`;
2066
- }
2067
- function buildCustomDataInjectionScript(descriptor) {
2068
- if (descriptor.script !== void 0) {
2069
- return descriptor.script;
2070
- }
2071
- if (descriptor.globalKey !== void 0) {
2072
- return `<script>window[${safeJsonForScript(descriptor.globalKey)}] = ${safeJsonForScript(
2073
- descriptor.value ?? null
2074
- )};</script>`;
2075
- }
2076
- return "";
2077
- }
2078
- var _uniqueIdCounter = 0;
2079
- function createTemplateHelpers() {
2080
- return {
2081
- escapeHtml: (str) => escapeHtml(str),
2082
- formatDate: (date, format) => {
2083
- const d = date instanceof Date ? date : new Date(date);
2084
- if (isNaN(d.getTime())) return String(date);
2085
- if (format === "iso") return d.toISOString();
2086
- if (format === "date") return d.toLocaleDateString();
2087
- if (format === "time") return d.toLocaleTimeString();
2088
- return d.toLocaleString();
2089
- },
2090
- formatCurrency: (amount, currency = "USD") => {
2091
- return new Intl.NumberFormat("en-US", {
2092
- style: "currency",
2093
- currency
2094
- }).format(amount);
2095
- },
2096
- uniqueId: (prefix = "mcp") => {
2097
- return `${prefix}-${++_uniqueIdCounter}`;
2098
- },
2099
- jsonEmbed: (data) => safeJsonForScript(data),
2100
- html,
2101
- trustedHtml
2102
- };
2103
- }
2104
-
2105
- // libs/uipack/src/shell/sizing-css.ts
2106
- function sanitizeCssValue(value) {
2107
- return value.replace(/[<>{};]/g, "").trim();
2108
- }
2109
- function toCssLength(value) {
2110
- return typeof value === "number" ? `${value}px` : sanitizeCssValue(value);
2111
- }
2112
- function buildSizingStyleTag(sizing) {
2113
- if (!hasSizing(sizing)) return "";
2114
- const hasCssSizing = sizing.preferredHeight !== void 0 || sizing.minHeight !== void 0 || sizing.maxHeight !== void 0 || sizing.aspectRatio !== void 0;
2115
- if (!hasCssSizing) return "";
2116
- const rootRules = [];
2117
- const docRules = ["margin: 0;"];
2118
- if (sizing.preferredHeight !== void 0) {
2119
- const h = toCssLength(sizing.preferredHeight);
2120
- docRules.push(`height: ${h};`);
2121
- rootRules.push(`min-height: ${h};`);
2122
- }
2123
- if (sizing.minHeight !== void 0) {
2124
- const mh = toCssLength(sizing.minHeight);
2125
- docRules.push(`min-height: ${mh};`);
2126
- rootRules.push(`min-height: ${mh};`);
2127
- }
2128
- if (sizing.maxHeight !== void 0) {
2129
- const mx = toCssLength(sizing.maxHeight);
2130
- docRules.push(`max-height: ${mx};`);
2131
- rootRules.push(`max-height: ${mx};`);
2132
- }
2133
- if (sizing.aspectRatio !== void 0) {
2134
- const ar = typeof sizing.aspectRatio === "number" ? String(sizing.aspectRatio) : sanitizeCssValue(sizing.aspectRatio);
2135
- if (ar) rootRules.push(`aspect-ratio: ${ar};`);
2136
- }
2137
- const parts = [`html, body { ${docRules.join(" ")} }`];
2138
- if (rootRules.length > 0) {
2139
- parts.push(`#root { ${rootRules.join(" ")} }`);
2140
- }
2141
- return `<style>${parts.join("\n")}</style>`;
2142
- }
2143
-
2144
- // libs/uipack/src/shell/builder.ts
2145
- function resolveDataInjectionScript(args) {
2146
- if (args.dataInjection) {
2147
- return buildCustomDataInjectionScript(args.dataInjection);
2148
- }
2149
- return buildDataInjectionScript({
2150
- toolName: args.toolName,
2151
- input: args.input,
2152
- output: args.output,
2153
- structuredContent: args.structuredContent,
2154
- sizing: args.sizing,
2155
- displayMode: args.displayMode
2156
- });
2157
- }
2158
- function buildShell(content, config) {
2159
- const {
2160
- toolName,
2161
- csp,
2162
- withShell = true,
2163
- input,
2164
- output,
2165
- structuredContent,
2166
- includeBridge = true,
2167
- title,
2168
- sizing,
2169
- displayMode
2170
- } = config;
2171
- const { customShell, dataInjection } = config;
2172
- const dataScript = resolveDataInjectionScript({
2173
- dataInjection,
2174
- toolName,
2175
- input,
2176
- output,
2177
- structuredContent,
2178
- sizing,
2179
- displayMode
2180
- });
2181
- if (!withShell) {
2182
- const html3 = `${dataScript}
2183
- ${content}`;
2184
- return {
2185
- html: html3,
2186
- hash: simpleHash(html3),
2187
- size: Buffer.byteLength(html3, "utf-8")
2188
- };
2189
- }
2190
- if (customShell) {
2191
- return buildCustomShell(content, customShell, {
2192
- csp,
2193
- toolName,
2194
- input,
2195
- output,
2196
- structuredContent,
2197
- includeBridge,
2198
- title,
2199
- sizing,
2200
- displayMode,
2201
- dataInjection
2202
- });
2203
- }
2204
- const headParts = [
2205
- '<meta charset="UTF-8">',
2206
- '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
2207
- ];
2208
- if (title) {
2209
- headParts.push(`<title>${escapeHtmlForTag(title)}</title>`);
2210
- }
2211
- headParts.push(buildCSPMetaTag(csp));
2212
- headParts.push(dataScript);
2213
- const sizingStyle = buildSizingStyleTag(sizing);
2214
- if (sizingStyle) {
2215
- headParts.push(sizingStyle);
2216
- }
2217
- if (includeBridge) {
2218
- const bridgeScript = generateBridgeIIFE({ minify: true });
2219
- headParts.push(`<script>${bridgeScript}</script>`);
2220
- }
2221
- const html2 = `<!DOCTYPE html>
1204
+ </script>`}function buildCustomDataInjectionScript(descriptor){if(descriptor.script!==void 0){return descriptor.script}if(descriptor.globalKey!==void 0){return`<script>window[${safeJsonForScript(descriptor.globalKey)}] = ${safeJsonForScript(descriptor.value??null)};</script>`}return""}var _uniqueIdCounter=0;function createTemplateHelpers(){return{escapeHtml:str=>escapeHtml(str),formatDate:(date,format)=>{const d=date instanceof Date?date:new Date(date);if(isNaN(d.getTime()))return String(date);if(format==="iso")return d.toISOString();if(format==="date")return d.toLocaleDateString();if(format==="time")return d.toLocaleTimeString();return d.toLocaleString()},formatCurrency:(amount,currency="USD")=>{return new Intl.NumberFormat("en-US",{style:"currency",currency}).format(amount)},uniqueId:(prefix="mcp")=>{return`${prefix}-${++_uniqueIdCounter}`},jsonEmbed:data=>safeJsonForScript(data),html,trustedHtml}}function sanitizeCssValue(value){return value.replace(/[<>{};]/g,"").trim()}function toCssLength(value){return typeof value==="number"?`${value}px`:sanitizeCssValue(value)}function buildSizingStyleTag(sizing){if(!hasSizing(sizing))return"";const hasCssSizing=sizing.preferredHeight!==void 0||sizing.minHeight!==void 0||sizing.maxHeight!==void 0||sizing.aspectRatio!==void 0;if(!hasCssSizing)return"";const rootRules=[];const docRules=["margin: 0;"];if(sizing.preferredHeight!==void 0){const h=toCssLength(sizing.preferredHeight);docRules.push(`height: ${h};`);rootRules.push(`min-height: ${h};`)}if(sizing.minHeight!==void 0){const mh=toCssLength(sizing.minHeight);docRules.push(`min-height: ${mh};`);rootRules.push(`min-height: ${mh};`)}if(sizing.maxHeight!==void 0){const mx=toCssLength(sizing.maxHeight);docRules.push(`max-height: ${mx};`);rootRules.push(`max-height: ${mx};`)}if(sizing.aspectRatio!==void 0){const ar=typeof sizing.aspectRatio==="number"?String(sizing.aspectRatio):sanitizeCssValue(sizing.aspectRatio);if(ar)rootRules.push(`aspect-ratio: ${ar};`)}const parts=[`html, body { ${docRules.join(" ")} }`];if(rootRules.length>0){parts.push(`#root { ${rootRules.join(" ")} }`)}return`<style>${parts.join("\n")}</style>`}function resolveDataInjectionScript(args){if(args.dataInjection){return buildCustomDataInjectionScript(args.dataInjection)}return buildDataInjectionScript({toolName:args.toolName,input:args.input,output:args.output,structuredContent:args.structuredContent,sizing:args.sizing,displayMode:args.displayMode})}function buildShell(content,config){const{toolName,csp,withShell=true,input,output,structuredContent,includeBridge=true,title,sizing,displayMode}=config;const{customShell,dataInjection}=config;const dataScript=resolveDataInjectionScript({dataInjection,toolName,input,output,structuredContent,sizing,displayMode});if(!withShell){const html3=`${dataScript}
1205
+ ${content}`;return{html:html3,hash:simpleHash(html3),size:Buffer.byteLength(html3,"utf-8")}}if(customShell){return buildCustomShell(content,customShell,{csp,toolName,input,output,structuredContent,includeBridge,title,sizing,displayMode,dataInjection})}const headParts=['<meta charset="UTF-8">','<meta name="viewport" content="width=device-width, initial-scale=1.0">'];if(title){headParts.push(`<title>${escapeHtmlForTag(title)}</title>`)}headParts.push(buildCSPMetaTag(csp));headParts.push(dataScript);const sizingStyle=buildSizingStyleTag(sizing);if(sizingStyle){headParts.push(sizingStyle)}if(includeBridge){const bridgeScript=generateBridgeIIFE({minify:true});headParts.push(`<script>${bridgeScript}</script>`)}const html2=`<!DOCTYPE html>
2222
1206
  <html lang="en">
2223
1207
  <head>
2224
- ${headParts.map((p) => ` ${p}`).join("\n")}
1208
+ ${headParts.map(p=>` ${p}`).join("\n")}
2225
1209
  </head>
2226
1210
  <body>
2227
1211
  ${content}
2228
1212
  </body>
2229
- </html>`;
2230
- return {
2231
- html: html2,
2232
- hash: simpleHash(html2),
2233
- size: Buffer.byteLength(html2, "utf-8")
2234
- };
2235
- }
2236
- function buildCustomShell(content, customShell, ctx) {
2237
- let template;
2238
- if (typeof customShell === "string") {
2239
- const validation = validateShellTemplate(customShell);
2240
- if (!validation.valid) {
2241
- throw new Error(
2242
- `Custom shell template is missing required placeholder(s): ${validation.missingRequired.map((n) => `{{${n}}}`).join(", ")}`
2243
- );
2244
- }
2245
- template = customShell;
2246
- } else {
2247
- template = customShell.template;
2248
- }
2249
- const cspTag = buildCSPMetaTag(ctx.csp);
2250
- const dataScript = resolveDataInjectionScript({
2251
- dataInjection: ctx.dataInjection,
2252
- toolName: ctx.toolName,
2253
- input: ctx.input,
2254
- output: ctx.output,
2255
- structuredContent: ctx.structuredContent,
2256
- sizing: ctx.sizing,
2257
- displayMode: ctx.displayMode
2258
- });
2259
- const sizingStyle = buildSizingStyleTag(ctx.sizing);
2260
- const dataWithSizing = sizingStyle ? `${dataScript}
2261
- ${sizingStyle}` : dataScript;
2262
- let bridgeHtml = "";
2263
- if (ctx.includeBridge) {
2264
- const bridgeScript = generateBridgeIIFE({ minify: true });
2265
- bridgeHtml = `<script>${bridgeScript}</script>`;
2266
- }
2267
- const html2 = applyShellTemplate(template, {
2268
- csp: cspTag,
2269
- data: dataWithSizing,
2270
- bridge: bridgeHtml,
2271
- content,
2272
- title: ctx.title ? escapeHtmlForTag(ctx.title) : ""
2273
- });
2274
- return {
2275
- html: html2,
2276
- hash: simpleHash(html2),
2277
- size: Buffer.byteLength(html2, "utf-8")
2278
- };
2279
- }
2280
- function simpleHash(str) {
2281
- let hash = 0;
2282
- for (let i = 0; i < str.length; i++) {
2283
- const char = str.charCodeAt(i);
2284
- hash = (hash << 5) - hash + char | 0;
2285
- }
2286
- return Math.abs(hash).toString(16).padStart(8, "0");
2287
- }
2288
- function escapeHtmlForTag(str) {
2289
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2290
- }
2291
-
2292
- // libs/uipack/src/component/ui-availability.ts
2293
- function isFrontmcpUiResolvable(...candidatePaths) {
2294
- try {
2295
- const nodeFs = __require("fs");
2296
- const nodePath = __require("path");
2297
- const ORG = "@frontmcp";
2298
- const PKG = "ui";
2299
- for (const candidate of candidatePaths) {
2300
- let dir = candidate;
2301
- while (true) {
2302
- const pkgJson = nodePath.join(dir, "node_modules", ORG, PKG, "package.json");
2303
- if (nodeFs.existsSync(pkgJson)) return true;
2304
- const parent = nodePath.dirname(dir);
2305
- if (parent === dir) break;
2306
- dir = parent;
2307
- }
2308
- }
2309
- return false;
2310
- } catch {
2311
- return false;
2312
- }
2313
- }
2314
-
2315
- // libs/uipack/src/component/transpiler.ts
2316
- function loadEsbuild(filename) {
2317
- try {
2318
- return __require("esbuild");
2319
- } catch (err) {
2320
- if (!isMissingEsbuild(err)) throw err;
2321
- const subject = filename ? `FileSource widget "${filename}"` : "A FileSource widget";
2322
- throw new Error(
2323
- `${subject} needs esbuild, which is not installed. @frontmcp/uipack loads esbuild on demand to bundle FileSource widgets (.tsx/.jsx) when the tool is called, so it must be installed where the server runs: \`npm install esbuild\` (in "dependencies", not "devDependencies"). Projects created with \`frontmcp create\` already get it through the \`frontmcp\` package.`,
2324
- { cause: err }
2325
- );
2326
- }
2327
- }
2328
- function isMissingEsbuild(err) {
2329
- if (!(err instanceof Error)) return false;
2330
- return err.code === "MODULE_NOT_FOUND" && /Cannot find module ['"]esbuild['"]/.test(err.message);
2331
- }
2332
- function transpileReactSource(source, filename) {
2333
- const esbuild = loadEsbuild(filename);
2334
- const loader = filename?.endsWith(".tsx") ? "tsx" : "jsx";
2335
- const result = esbuild.transformSync(source, {
2336
- loader,
2337
- jsx: "transform",
2338
- jsxFactory: "React.createElement",
2339
- jsxFragment: "React.Fragment",
2340
- format: "esm",
2341
- target: "es2020",
2342
- define: { "process.env.NODE_ENV": '"production"' }
2343
- });
2344
- return result.code;
2345
- }
2346
- function bundleFileSource(source, filename, resolveDir, componentName, options = {}) {
2347
- if (!isFrontmcpUiResolvable(resolveDir, process.cwd())) {
2348
- throw new Error(
2349
- `FileSource widget "${filename}" requires the @frontmcp/ui package, which provides the React bridge mount that's injected at bundle time. Install it (e.g. \`npm install @frontmcp/ui\` or \`yarn add @frontmcp/ui\`) and try again.`
2350
- );
2351
- }
2352
- const esbuild = loadEsbuild(filename);
2353
- const mountCode = `
1213
+ </html>`;return{html:html2,hash:simpleHash(html2),size:Buffer.byteLength(html2,"utf-8")}}function buildCustomShell(content,customShell,ctx){let template;if(typeof customShell==="string"){const validation=validateShellTemplate(customShell);if(!validation.valid){throw new Error(`Custom shell template is missing required placeholder(s): ${validation.missingRequired.map(n=>`{{${n}}}`).join(", ")}`)}template=customShell}else{template=customShell.template}const cspTag=buildCSPMetaTag(ctx.csp);const dataScript=resolveDataInjectionScript({dataInjection:ctx.dataInjection,toolName:ctx.toolName,input:ctx.input,output:ctx.output,structuredContent:ctx.structuredContent,sizing:ctx.sizing,displayMode:ctx.displayMode});const sizingStyle=buildSizingStyleTag(ctx.sizing);const dataWithSizing=sizingStyle?`${dataScript}
1214
+ ${sizingStyle}`:dataScript;let bridgeHtml="";if(ctx.includeBridge){const bridgeScript=generateBridgeIIFE({minify:true});bridgeHtml=`<script>${bridgeScript}</script>`}const html2=applyShellTemplate(template,{csp:cspTag,data:dataWithSizing,bridge:bridgeHtml,content,title:ctx.title?escapeHtmlForTag(ctx.title):""});return{html:html2,hash:simpleHash(html2),size:Buffer.byteLength(html2,"utf-8")}}function simpleHash(str){let hash=0;for(let i=0;i<str.length;i++){const char=str.charCodeAt(i);hash=(hash<<5)-hash+char|0}return Math.abs(hash).toString(16).padStart(8,"0")}function escapeHtmlForTag(str){return str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function isFrontmcpUiResolvable(...candidatePaths){try{const nodeFs=__require("fs");const nodePath=__require("path");const ORG="@frontmcp";const PKG="ui";for(const candidate of candidatePaths){let dir=candidate;while(true){const pkgJson=nodePath.join(dir,"node_modules",ORG,PKG,"package.json");if(nodeFs.existsSync(pkgJson))return true;const parent=nodePath.dirname(dir);if(parent===dir)break;dir=parent}}return false}catch{return false}}function loadEsbuild(filename){try{return __require("esbuild")}catch(err){if(!isMissingEsbuild(err))throw err;const subject=filename?`FileSource widget "${filename}"`:"A FileSource widget";throw new Error(`${subject} needs esbuild, which is not installed. @frontmcp/uipack loads esbuild on demand to bundle FileSource widgets (.tsx/.jsx) when the tool is called, so it must be installed where the server runs: \`npm install esbuild\` (in "dependencies", not "devDependencies"). Projects created with \`frontmcp create\` already get it through the \`frontmcp\` package.`,{cause:err})}}function isMissingEsbuild(err){if(!(err instanceof Error))return false;return err.code==="MODULE_NOT_FOUND"&&/Cannot find module ['"]esbuild['"]/.test(err.message)}function transpileReactSource(source,filename){const esbuild=loadEsbuild(filename);const loader=filename?.endsWith(".tsx")?"tsx":"jsx";const result=esbuild.transformSync(source,{loader,jsx:"transform",jsxFactory:"React.createElement",jsxFragment:"React.Fragment",format:"esm",target:"es2020",define:{"process.env.NODE_ENV":'"production"'}});return result.code}function bundleFileSource(source,filename,resolveDir,componentName,options={}){if(!isFrontmcpUiResolvable(resolveDir,process.cwd())){throw new Error(`FileSource widget "${filename}" requires the @frontmcp/ui package, which provides the React bridge mount that's injected at bundle time. Install it (e.g. \`npm install @frontmcp/ui\` or \`yarn add @frontmcp/ui\`) and try again.`)}const esbuild=loadEsbuild(filename);const mountCode=`
2354
1215
  // --- Auto-generated mount ---
2355
1216
  import { createElement as __h } from 'react';
2356
1217
  import { createRoot } from 'react-dom/client';
@@ -2392,410 +1253,24 @@ if (__root) {
2392
1253
  if (d) __render(d.structuredContent !== undefined ? d.structuredContent : d.content !== undefined ? d.content : d);
2393
1254
  });
2394
1255
  }
2395
- }`;
2396
- const loader = {
2397
- ".tsx": "tsx",
2398
- ".jsx": "jsx"
2399
- };
2400
- const stdinLoader = filename.endsWith(".tsx") ? "tsx" : "jsx";
2401
- const alias = {};
2402
- try {
2403
- const nodePath = __require("path");
2404
- const nodeFs = __require("fs");
2405
- const candidates = [
2406
- nodePath.join(process.cwd(), "node_modules", "@frontmcp", "ui", "dist", "esm"),
2407
- nodePath.join(resolveDir, "node_modules", "@frontmcp", "ui", "dist", "esm")
2408
- ];
2409
- for (const uiEsmBase of candidates) {
2410
- if (!nodeFs.existsSync(uiEsmBase)) continue;
2411
- const subpaths = ["components", "react", "theme", "bridge", "runtime"];
2412
- for (const sub of subpaths) {
2413
- const mjs = nodePath.join(uiEsmBase, sub, "index.mjs");
2414
- if (nodeFs.existsSync(mjs)) alias[`@frontmcp/ui/${sub}`] = mjs;
2415
- }
2416
- if (Object.keys(alias).length > 0) break;
2417
- }
2418
- } catch {
2419
- }
2420
- try {
2421
- const result = esbuild.buildSync({
2422
- stdin: {
2423
- contents: source + "\n" + mountCode,
2424
- loader: stdinLoader,
2425
- resolveDir,
2426
- sourcefile: filename
2427
- },
2428
- bundle: true,
2429
- write: false,
2430
- format: "esm",
2431
- target: "es2020",
2432
- jsx: "automatic",
2433
- // When `bundleReact` is set (resourceMode: 'inline'), React itself is
2434
- // bundled — required for hosts that block external script execution
2435
- // such as Claude (#454). Otherwise React stays external and is loaded
2436
- // via the import map emitted by the renderer.
2437
- external: options.bundleReact ? [] : ["react", "react-dom", "react/jsx-runtime", "react/jsx-dev-runtime"],
2438
- alias,
2439
- define: { "process.env.NODE_ENV": '"production"' },
2440
- platform: "browser",
2441
- treeShaking: true,
2442
- logLevel: "warning",
2443
- loader
2444
- });
2445
- return { code: result.outputFiles[0].text };
2446
- } catch (err) {
2447
- const message = err instanceof Error ? err.message : String(err);
2448
- throw new Error(
2449
- `Failed to bundle FileSource "${filename}": ${message}. If the error mentions @frontmcp/ui or @frontmcp/uipack, ensure both packages are installed in the consuming project.`,
2450
- { cause: err }
2451
- );
2452
- }
2453
- }
2454
- function extractDefaultExportName(code) {
2455
- let match = code.match(/export\s+default\s+(?:function|class)\s+(\w+)/);
2456
- if (match) return match[1];
2457
- match = code.match(/export\s+default\s+(\w+)\s*;/);
2458
- if (match) return match[1];
2459
- return null;
2460
- }
2461
-
2462
- // libs/uipack/src/component/types.ts
2463
- function isNpmSource(source) {
2464
- return typeof source === "object" && source !== null && "npm" in source;
2465
- }
2466
- function isFileSource(source) {
2467
- return typeof source === "object" && source !== null && "file" in source;
2468
- }
2469
- function isImportSource(source) {
2470
- return typeof source === "object" && source !== null && "import" in source;
2471
- }
2472
- function isFunctionSource(source) {
2473
- return typeof source === "function";
2474
- }
2475
-
2476
- // libs/uipack/src/component/loader.ts
2477
- var DEFAULT_META = {
2478
- mcpAware: false,
2479
- renderer: "auto"
2480
- };
2481
- function resolveUISource(source, options) {
2482
- if (options?.inlineReact && options?.transformOnly) {
2483
- throw new Error("resolveUISource: `inlineReact` and `transformOnly` are mutually exclusive \u2014 set at most one.");
2484
- }
2485
- const resolver = options?.resolver ?? createEsmShResolver();
2486
- if (isNpmSource(source)) {
2487
- return resolveNpmSource(source, resolver);
2488
- }
2489
- if (isImportSource(source)) {
2490
- return resolveImportSource(source);
2491
- }
2492
- if (isFileSource(source)) {
2493
- return resolveFileSource(source, { inlineReact: options?.inlineReact, transformOnly: options?.transformOnly });
2494
- }
2495
- if (isFunctionSource(source)) {
2496
- return resolveFunctionSource(source, options?.input, options?.output);
2497
- }
2498
- throw new Error("Unknown UISource type");
2499
- }
2500
- function resolveNpmSource(source, resolver) {
2501
- const specifier = source.version ? `${source.npm}@${source.version}` : source.npm;
2502
- const pkgName = getPackageName(source.npm);
2503
- const resolved = resolver.resolve(specifier);
2504
- const url = resolved?.value ?? `https://esm.sh/${specifier}`;
2505
- const peerDeps = [];
2506
- if (pkgName !== "react" && pkgName !== "react-dom") {
2507
- peerDeps.push("react", "react-dom");
2508
- }
2509
- return {
2510
- mode: "module",
2511
- url,
2512
- exportName: source.exportName ?? "default",
2513
- meta: { ...DEFAULT_META, renderer: "react" },
2514
- peerDependencies: peerDeps
2515
- };
2516
- }
2517
- function resolveImportSource(source) {
2518
- return {
2519
- mode: "module",
2520
- url: source.import,
2521
- exportName: source.exportName ?? "default",
2522
- meta: { ...DEFAULT_META },
2523
- peerDependencies: []
2524
- };
2525
- }
2526
- var BUILD_DIR_SEGMENTS = /* @__PURE__ */ new Set(["dist", "build", "out"]);
2527
- function missingWidgetError(filePath, cause) {
2528
- const sourceWidget = findSourceWidget(filePath);
2529
- const error = new Error(
2530
- `FileSource widget not found (ENOENT): no file at "${filePath}". The widget source is read from this path when the tool is called, so it has to exist where the compiled tool runs \u2014 a path built from \`__dirname\` or \`import.meta.url\` points into the build output once the tool is compiled. tsc does not copy \`*.widget.tsx\` / \`*.widget.jsx\` files into its output; \`frontmcp build\` does, and any other build needs a step that copies them next to the compiled tool.` + (sourceWidget ? ` The source widget exists at "${sourceWidget}" \u2014 copy it to "${filePath}", or build with \`frontmcp build\`.` : ""),
2531
- { cause }
2532
- );
2533
- error.code = "ENOENT";
2534
- error.path = filePath;
2535
- return error;
2536
- }
2537
- function findSourceWidget(filePath) {
2538
- const path = __require("path");
2539
- const fs = __require("fs");
2540
- const parts = filePath.split(path.sep);
2541
- for (let i = parts.length - 2; i >= 0; i--) {
2542
- if (!BUILD_DIR_SEGMENTS.has(parts[i])) continue;
2543
- const candidates = [[...parts.slice(0, i), "src", ...parts.slice(i + 1)]];
2544
- if (parts.length - i > 2) candidates.push([...parts.slice(0, i), "src", ...parts.slice(i + 2)]);
2545
- candidates.push([...parts.slice(0, i), ...parts.slice(i + 1)]);
2546
- for (const candidate of candidates) {
2547
- const candidatePath = candidate.join(path.sep);
2548
- try {
2549
- if (fs.existsSync(candidatePath)) return candidatePath;
2550
- } catch {
2551
- }
2552
- }
2553
- return void 0;
2554
- }
2555
- return void 0;
2556
- }
2557
- function resolveFileSource(source, options = {}) {
2558
- const path = __require("path");
2559
- const ext = path.extname(source.file).toLowerCase();
2560
- if (ext === ".tsx" || ext === ".jsx") {
2561
- const fs = __require("fs");
2562
- const wasRelative = !path.isAbsolute(source.file);
2563
- const filePath = wasRelative ? path.resolve(process.cwd(), source.file) : source.file;
2564
- let rawSource;
2565
- try {
2566
- rawSource = fs.readFileSync(filePath, "utf-8");
2567
- } catch (err) {
2568
- const isNotFound = err?.code === "ENOENT";
2569
- if (isNotFound && wasRelative) {
2570
- throw new Error(
2571
- `FileSource widget "${source.file}" not found at "${filePath}". Relative paths are resolved against process.cwd() ("${process.cwd()}"), not the tool file's directory. To anchor the path to the tool file, pass an absolute path \u2014 e.g. \`{ file: fileURLToPath(new URL('./widget.tsx', import.meta.url)) }\` from \`node:url\` (see issue #444).`,
2572
- { cause: err }
2573
- );
2574
- }
2575
- if (isNotFound) throw missingWidgetError(filePath, err);
2576
- throw err;
2577
- }
2578
- const componentName = source.exportName || extractDefaultExportName(rawSource) || "Component";
2579
- if (options.transformOnly === true) {
2580
- const code = transpileReactSource(rawSource, path.basename(filePath));
2581
- const parsed2 = parseImports(code);
2582
- return {
2583
- mode: "module",
2584
- code,
2585
- imports: [...new Set(parsed2.externalImports.map((i) => i.specifier))],
2586
- exportName: componentName,
2587
- meta: { mcpAware: true, renderer: "react" },
2588
- peerDependencies: source.peerDependencies || ["react", "react-dom"],
2589
- bundled: false
2590
- };
2591
- }
2592
- const bundled = bundleFileSource(rawSource, source.file, path.dirname(filePath), componentName, {
2593
- bundleReact: options.inlineReact === true
2594
- });
2595
- const parsed = parseImports(bundled.code);
2596
- return {
2597
- mode: "module",
2598
- code: bundled.code,
2599
- imports: [...new Set(parsed.externalImports.map((i) => i.specifier))],
2600
- exportName: componentName,
2601
- meta: { mcpAware: true, renderer: "react" },
2602
- peerDependencies: source.peerDependencies || ["react", "react-dom"],
2603
- bundled: true
2604
- };
2605
- }
2606
- if (source.inline) {
2607
- return {
2608
- mode: "inline",
2609
- html: `<!-- File source: ${source.file} (inline mode - content to be resolved at build time) -->`,
2610
- exportName: "default",
2611
- meta: { ...DEFAULT_META, renderer: "html" },
2612
- peerDependencies: []
2613
- };
2614
- }
2615
- return {
2616
- mode: "module",
2617
- url: source.file,
2618
- exportName: "default",
2619
- meta: { ...DEFAULT_META },
2620
- peerDependencies: []
2621
- };
2622
- }
2623
- function resolveFunctionSource(source, input, output) {
2624
- const html2 = source(input, output);
2625
- return {
2626
- mode: "inline",
2627
- html: html2,
2628
- exportName: "default",
2629
- meta: { mcpAware: false, renderer: "html" },
2630
- peerDependencies: []
2631
- };
2632
- }
2633
- function generateMountScript(resolved, propsMapping) {
2634
- if (resolved.mode !== "module" || !resolved.url) {
2635
- return "";
2636
- }
2637
- const componentImport = resolved.exportName === "default" ? `import Component from '${resolved.url}';` : `import { ${resolved.exportName} as Component } from '${resolved.url}';`;
2638
- if (resolved.meta.mcpAware) {
2639
- return `${componentImport}
1256
+ }`;const loader={".tsx":"tsx",".jsx":"jsx"};const stdinLoader=filename.endsWith(".tsx")?"tsx":"jsx";const alias={};try{const nodePath=__require("path");const nodeFs=__require("fs");const candidates=[nodePath.join(process.cwd(),"node_modules","@frontmcp","ui","dist","esm"),nodePath.join(resolveDir,"node_modules","@frontmcp","ui","dist","esm")];for(const uiEsmBase of candidates){if(!nodeFs.existsSync(uiEsmBase))continue;const subpaths=["components","react","theme","bridge","runtime"];for(const sub of subpaths){const mjs=nodePath.join(uiEsmBase,sub,"index.mjs");if(nodeFs.existsSync(mjs))alias[`@frontmcp/ui/${sub}`]=mjs}if(Object.keys(alias).length>0)break}}catch{}try{const result=esbuild.buildSync({stdin:{contents:source+"\n"+mountCode,loader:stdinLoader,resolveDir,sourcefile:filename},bundle:true,write:false,format:"esm",target:"es2020",jsx:"automatic",external:options.bundleReact?[]:["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime"],alias,define:{"process.env.NODE_ENV":'"production"'},platform:"browser",treeShaking:true,logLevel:"warning",loader});return{code:result.outputFiles[0].text}}catch(err){const message=err instanceof Error?err.message:String(err);throw new Error(`Failed to bundle FileSource "${filename}": ${message}. If the error mentions @frontmcp/ui or @frontmcp/uipack, ensure both packages are installed in the consuming project.`,{cause:err})}}function extractDefaultExportName(code){let match=code.match(/export\s+default\s+(?:function|class)\s+(\w+)/);if(match)return match[1];match=code.match(/export\s+default\s+(\w+)\s*;/);if(match)return match[1];return null}function isNpmSource(source){return typeof source==="object"&&source!==null&&"npm"in source}function isFileSource(source){return typeof source==="object"&&source!==null&&"file"in source}function isImportSource(source){return typeof source==="object"&&source!==null&&"import"in source}function isFunctionSource(source){return typeof source==="function"}var DEFAULT_META={mcpAware:false,renderer:"auto"};function resolveUISource(source,options){if(options?.inlineReact&&options?.transformOnly){throw new Error("resolveUISource: `inlineReact` and `transformOnly` are mutually exclusive \u2014 set at most one.")}const resolver=options?.resolver??createEsmShResolver();if(isNpmSource(source)){return resolveNpmSource(source,resolver)}if(isImportSource(source)){return resolveImportSource(source)}if(isFileSource(source)){return resolveFileSource(source,{inlineReact:options?.inlineReact,transformOnly:options?.transformOnly})}if(isFunctionSource(source)){return resolveFunctionSource(source,options?.input,options?.output)}throw new Error("Unknown UISource type")}function resolveNpmSource(source,resolver){const specifier=source.version?`${source.npm}@${source.version}`:source.npm;const pkgName=getPackageName(source.npm);const resolved=resolver.resolve(specifier);const url=resolved?.value??`https://esm.sh/${specifier}`;const peerDeps=[];if(pkgName!=="react"&&pkgName!=="react-dom"){peerDeps.push("react","react-dom")}return{mode:"module",url,exportName:source.exportName??"default",meta:{...DEFAULT_META,renderer:"react"},peerDependencies:peerDeps}}function resolveImportSource(source){return{mode:"module",url:source.import,exportName:source.exportName??"default",meta:{...DEFAULT_META},peerDependencies:[]}}var BUILD_DIR_SEGMENTS=new Set(["dist","build","out"]);function missingWidgetError(filePath,cause){const sourceWidget=findSourceWidget(filePath);const error=new Error(`FileSource widget not found (ENOENT): no file at "${filePath}". The widget source is read from this path when the tool is called, so it has to exist where the compiled tool runs \u2014 a path built from \`__dirname\` or \`import.meta.url\` points into the build output once the tool is compiled. tsc does not copy \`*.widget.tsx\` / \`*.widget.jsx\` files into its output; \`frontmcp build\` does, and any other build needs a step that copies them next to the compiled tool.`+(sourceWidget?` The source widget exists at "${sourceWidget}" \u2014 copy it to "${filePath}", or build with \`frontmcp build\`.`:""),{cause});error.code="ENOENT";error.path=filePath;return error}function findSourceWidget(filePath){const path=__require("path");const fs=__require("fs");const parts=filePath.split(path.sep);for(let i=parts.length-2;i>=0;i--){if(!BUILD_DIR_SEGMENTS.has(parts[i]))continue;const candidates=[[...parts.slice(0,i),"src",...parts.slice(i+1)]];if(parts.length-i>2)candidates.push([...parts.slice(0,i),"src",...parts.slice(i+2)]);candidates.push([...parts.slice(0,i),...parts.slice(i+1)]);for(const candidate of candidates){const candidatePath=candidate.join(path.sep);try{if(fs.existsSync(candidatePath))return candidatePath}catch{}}return void 0}return void 0}function resolveFileSource(source,options={}){const path=__require("path");const ext=path.extname(source.file).toLowerCase();if(ext===".tsx"||ext===".jsx"){const fs=__require("fs");const wasRelative=!path.isAbsolute(source.file);const filePath=wasRelative?path.resolve(process.cwd(),source.file):source.file;let rawSource;try{rawSource=fs.readFileSync(filePath,"utf-8")}catch(err){const isNotFound=err?.code==="ENOENT";if(isNotFound&&wasRelative){throw new Error(`FileSource widget "${source.file}" not found at "${filePath}". Relative paths are resolved against process.cwd() ("${process.cwd()}"), not the tool file's directory. To anchor the path to the tool file, pass an absolute path \u2014 e.g. \`{ file: fileURLToPath(new URL('./widget.tsx', import.meta.url)) }\` from \`node:url\` (see issue #444).`,{cause:err})}if(isNotFound)throw missingWidgetError(filePath,err);throw err}const componentName=source.exportName||extractDefaultExportName(rawSource)||"Component";if(options.transformOnly===true){const code=transpileReactSource(rawSource,path.basename(filePath));const parsed2=parseImports(code);return{mode:"module",code,imports:[...new Set(parsed2.externalImports.map(i=>i.specifier))],exportName:componentName,meta:{mcpAware:true,renderer:"react"},peerDependencies:source.peerDependencies||["react","react-dom"],bundled:false}}const bundled=bundleFileSource(rawSource,source.file,path.dirname(filePath),componentName,{bundleReact:options.inlineReact===true});const parsed=parseImports(bundled.code);return{mode:"module",code:bundled.code,imports:[...new Set(parsed.externalImports.map(i=>i.specifier))],exportName:componentName,meta:{mcpAware:true,renderer:"react"},peerDependencies:source.peerDependencies||["react","react-dom"],bundled:true}}if(source.inline){return{mode:"inline",html:`<!-- File source: ${source.file} (inline mode - content to be resolved at build time) -->`,exportName:"default",meta:{...DEFAULT_META,renderer:"html"},peerDependencies:[]}}return{mode:"module",url:source.file,exportName:"default",meta:{...DEFAULT_META},peerDependencies:[]}}function resolveFunctionSource(source,input,output){const html2=source(input,output);return{mode:"inline",html:html2,exportName:"default",meta:{mcpAware:false,renderer:"html"},peerDependencies:[]}}function generateMountScript(resolved,propsMapping){if(resolved.mode!=="module"||!resolved.url){return""}const componentImport=resolved.exportName==="default"?`import Component from '${resolved.url}';`:`import { ${resolved.exportName} as Component } from '${resolved.url}';`;if(resolved.meta.mcpAware){return`${componentImport}
2640
1257
  import React from 'react';
2641
1258
  import { createRoot } from 'react-dom/client';
2642
1259
  createRoot(document.getElementById('root'))
2643
- .render(React.createElement(Component));`;
2644
- }
2645
- const propsCode = propsMapping ? generateMappedPropsCode(propsMapping) : "window.__mcpToolOutput";
2646
- return `${componentImport}
1260
+ .render(React.createElement(Component));`}const propsCode=propsMapping?generateMappedPropsCode(propsMapping):"window.__mcpToolOutput";return`${componentImport}
2647
1261
  import React from 'react';
2648
1262
  import { createRoot } from 'react-dom/client';
2649
1263
  const output = window.__mcpToolOutput || {};
2650
1264
  const props = ${propsCode};
2651
1265
  createRoot(document.getElementById('root'))
2652
- .render(React.createElement(Component, props));`;
2653
- }
2654
- function generateMappedPropsCode(mapping) {
2655
- const entries = Object.entries(mapping).map(([prop, path]) => {
2656
- const accessPath = path.split(".").map((part) => `[${safeJsonForScript(part)}]`).join("");
2657
- return `${safeJsonForScript(prop)}: output${accessPath}`;
2658
- }).join(", ");
2659
- return `({ ${entries} })`;
2660
- }
2661
-
2662
- // libs/uipack/src/component/renderer.ts
2663
- var DEFAULT_WIDGET_MOUNT = {
2664
- moduleSpecifier: "@frontmcp/ui/react",
2665
- wrapperImportName: "McpBridgeProvider"
2666
- };
2667
- function renderComponent(config, shellConfig) {
2668
- const resolver = shellConfig.resolver ?? createEsmShResolver();
2669
- const resolved = resolveUISource(config.source, {
2670
- resolver,
2671
- input: shellConfig.input,
2672
- output: shellConfig.output,
2673
- inlineReact: config.inlineReact === true,
2674
- transformOnly: config.transformOnly === true
2675
- });
2676
- const mergedShellConfig = {
2677
- ...shellConfig,
2678
- withShell: config.withShell ?? shellConfig.withShell,
2679
- includeBridge: config.includeBridge ?? shellConfig.includeBridge,
2680
- customShell: config.customShell ?? shellConfig.customShell
2681
- };
2682
- if (resolved.mode === "inline") {
2683
- return buildShell(resolved.html ?? "", mergedShellConfig);
2684
- }
2685
- const content = buildModuleContent(resolved, resolver, config.props, shellConfig.mount);
2686
- return buildShell(content, mergedShellConfig);
2687
- }
2688
- function buildModuleContent(resolved, resolver, propsMapping, mount = DEFAULT_WIDGET_MOUNT) {
2689
- const parts = [];
2690
- if (resolved.code && resolved.bundled) {
2691
- const importEntries = {};
2692
- for (const spec of resolved.imports || []) {
2693
- const depResolved = resolver.resolve(spec);
2694
- if (depResolved) {
2695
- importEntries[spec] = depResolved;
2696
- }
2697
- }
2698
- if (Object.keys(importEntries).length > 0) {
2699
- const importMap = createImportMapFromResolved(importEntries);
2700
- parts.push(generateImportMapScriptTag(importMap));
2701
- }
2702
- parts.push('<div id="root"></div>');
2703
- parts.push(`<script type="module">
1266
+ .render(React.createElement(Component, props));`}function generateMappedPropsCode(mapping){const entries=Object.entries(mapping).map(([prop,path])=>{const accessPath=path.split(".").map(part=>`[${safeJsonForScript(part)}]`).join("");return`${safeJsonForScript(prop)}: output${accessPath}`}).join(", ");return`({ ${entries} })`}var DEFAULT_WIDGET_MOUNT={moduleSpecifier:"@frontmcp/ui/react",wrapperImportName:"McpBridgeProvider"};function renderComponent(config,shellConfig){const resolver=shellConfig.resolver??createEsmShResolver();const resolved=resolveUISource(config.source,{resolver,input:shellConfig.input,output:shellConfig.output,inlineReact:config.inlineReact===true,transformOnly:config.transformOnly===true});const mergedShellConfig={...shellConfig,withShell:config.withShell??shellConfig.withShell,includeBridge:config.includeBridge??shellConfig.includeBridge,customShell:config.customShell??shellConfig.customShell};if(resolved.mode==="inline"){return buildShell(resolved.html??"",mergedShellConfig)}const content=buildModuleContent(resolved,resolver,config.props,shellConfig.mount);return buildShell(content,mergedShellConfig)}function buildModuleContent(resolved,resolver,propsMapping,mount=DEFAULT_WIDGET_MOUNT){const parts=[];if(resolved.code&&resolved.bundled){const importEntries={};for(const spec of resolved.imports||[]){const depResolved=resolver.resolve(spec);if(depResolved){importEntries[spec]=depResolved}}if(Object.keys(importEntries).length>0){const importMap=createImportMapFromResolved(importEntries);parts.push(generateImportMapScriptTag(importMap))}parts.push('<div id="root"></div>');parts.push(`<script type="module">
2704
1267
  ${resolved.code}
2705
- </script>`);
2706
- } else if (resolved.code) {
2707
- const importEntries = {};
2708
- const allSpecifiers = /* @__PURE__ */ new Set([
2709
- ...resolved.imports || [],
2710
- "react-dom/client",
2711
- // needed by mount script
2712
- mount.moduleSpecifier,
2713
- // mounter/provider package (e.g. @frontmcp/ui/react)
2714
- // React subpath entries needed by esm.sh externalized modules:
2715
- "react/jsx-runtime",
2716
- "react/jsx-dev-runtime"
2717
- ]);
2718
- if (mount === DEFAULT_WIDGET_MOUNT) {
2719
- allSpecifiers.add("react-dom/server");
2720
- allSpecifiers.add("react-dom/static");
2721
- }
2722
- const coreDeps = /* @__PURE__ */ new Set([
2723
- "react",
2724
- "react-dom",
2725
- "react-dom/client",
2726
- "react/jsx-runtime",
2727
- "react/jsx-dev-runtime",
2728
- "react-dom/server",
2729
- "react-dom/static"
2730
- ]);
2731
- for (const spec of allSpecifiers) {
2732
- const depResolved = resolver.resolve(spec);
2733
- if (depResolved) {
2734
- if (!coreDeps.has(spec) && depResolved.value?.includes("esm.sh")) {
2735
- importEntries[spec] = {
2736
- ...depResolved,
2737
- value: addExternalParam(depResolved.value, ["react", "react-dom"])
2738
- };
2739
- } else {
2740
- importEntries[spec] = depResolved;
2741
- }
2742
- }
2743
- }
2744
- if (importEntries["react-dom"] && !importEntries["react-dom/client"]) {
2745
- const rdc = resolver.resolve("react-dom/client");
2746
- if (rdc) importEntries["react-dom/client"] = rdc;
2747
- }
2748
- if (Object.keys(importEntries).length > 0) {
2749
- const importMap = createImportMapFromResolved(importEntries);
2750
- parts.push(generateImportMapScriptTag(importMap));
2751
- }
2752
- const mountNodeId = mount.mountNodeId ?? "root";
2753
- parts.push(`<div id="${mountNodeId}">${mount.mountNodeInnerHtml ?? ""}</div>`);
2754
- const mountCode = generateInlineMountCode(resolved.exportName, mount);
2755
- parts.push(`<script type="module">
1268
+ </script>`)}else if(resolved.code){const importEntries={};const allSpecifiers=new Set([...resolved.imports||[],"react-dom/client",mount.moduleSpecifier,"react/jsx-runtime","react/jsx-dev-runtime"]);if(mount===DEFAULT_WIDGET_MOUNT){allSpecifiers.add("react-dom/server");allSpecifiers.add("react-dom/static")}const coreDeps=new Set(["react","react-dom","react-dom/client","react/jsx-runtime","react/jsx-dev-runtime","react-dom/server","react-dom/static"]);for(const spec of allSpecifiers){const depResolved=resolver.resolve(spec);if(depResolved){if(!coreDeps.has(spec)&&depResolved.value?.includes("esm.sh")){importEntries[spec]={...depResolved,value:addExternalParam(depResolved.value,["react","react-dom"])}}else{importEntries[spec]=depResolved}}}if(importEntries["react-dom"]&&!importEntries["react-dom/client"]){const rdc=resolver.resolve("react-dom/client");if(rdc)importEntries["react-dom/client"]=rdc}if(Object.keys(importEntries).length>0){const importMap=createImportMapFromResolved(importEntries);parts.push(generateImportMapScriptTag(importMap))}const mountNodeId=mount.mountNodeId??"root";parts.push(`<div id="${mountNodeId}">${mount.mountNodeInnerHtml??""}</div>`);const mountCode=generateInlineMountCode(resolved.exportName,mount);parts.push(`<script type="module">
2756
1269
  ${resolved.code}
2757
1270
  ${mountCode}
2758
- </script>`);
2759
- } else {
2760
- const importEntries = {};
2761
- for (const dep of resolved.peerDependencies) {
2762
- const depResolved = resolver.resolve(dep);
2763
- if (depResolved) {
2764
- importEntries[dep] = depResolved;
2765
- }
2766
- }
2767
- if (importEntries["react-dom"]) {
2768
- const reactDomClient = resolver.resolve("react-dom/client");
2769
- if (reactDomClient) {
2770
- importEntries["react-dom/client"] = reactDomClient;
2771
- }
2772
- }
2773
- if (Object.keys(importEntries).length > 0) {
2774
- const importMap = createImportMapFromResolved(importEntries);
2775
- parts.push(generateImportMapScriptTag(importMap));
2776
- }
2777
- parts.push('<div id="root"></div>');
2778
- const mountScript = generateMountScript(resolved, propsMapping);
2779
- if (mountScript) {
2780
- parts.push(`<script type="module">
1271
+ </script>`)}else{const importEntries={};for(const dep of resolved.peerDependencies){const depResolved=resolver.resolve(dep);if(depResolved){importEntries[dep]=depResolved}}if(importEntries["react-dom"]){const reactDomClient=resolver.resolve("react-dom/client");if(reactDomClient){importEntries["react-dom/client"]=reactDomClient}}if(Object.keys(importEntries).length>0){const importMap=createImportMapFromResolved(importEntries);parts.push(generateImportMapScriptTag(importMap))}parts.push('<div id="root"></div>');const mountScript=generateMountScript(resolved,propsMapping);if(mountScript){parts.push(`<script type="module">
2781
1272
  ${mountScript}
2782
- </script>`);
2783
- }
2784
- }
2785
- return parts.join("\n");
2786
- }
2787
- function addExternalParam(url, externals) {
2788
- const sep = url.includes("?") ? "&" : "?";
2789
- return `${url}${sep}external=${externals.join(",")}`;
2790
- }
2791
- function generateInlineMountCode(componentName, mount) {
2792
- if (mount.generate) {
2793
- return mount.generate(componentName);
2794
- }
2795
- const wrapperName = mount.wrapperImportName ?? "McpBridgeProvider";
2796
- const wrapperAlias = `__${wrapperName}`;
2797
- const mountNodeId = mount.mountNodeId ?? "root";
2798
- return `
1273
+ </script>`)}}return parts.join("\n")}function addExternalParam(url,externals){const sep=url.includes("?")?"&":"?";return`${url}${sep}external=${externals.join(",")}`}function generateInlineMountCode(componentName,mount){if(mount.generate){return mount.generate(componentName)}const wrapperName=mount.wrapperImportName??"McpBridgeProvider";const wrapperAlias=`__${wrapperName}`;const mountNodeId=mount.mountNodeId??"root";return`
2799
1274
  // --- Mount ---
2800
1275
  import { createRoot as __createRoot } from 'react-dom/client';
2801
1276
  import { ${wrapperName} as ${wrapperAlias} } from '${mount.moduleSpecifier}';
@@ -2806,101 +1281,18 @@ if (__root) {
2806
1281
  React.createElement(${componentName})
2807
1282
  )
2808
1283
  );
2809
- }`;
2810
- }
2811
-
2812
- // libs/uipack/src/adapters/content-detector.ts
2813
- var CHART_TYPES = /* @__PURE__ */ new Set(["bar", "line", "pie", "area", "scatter", "doughnut", "radar", "polarArea", "bubble"]);
2814
- var MERMAID_PREFIXES = [
2815
- "flowchart",
2816
- "graph",
2817
- "sequenceDiagram",
2818
- "classDiagram",
2819
- "stateDiagram",
2820
- "erDiagram",
2821
- "gantt",
2822
- "pie",
2823
- "gitGraph",
2824
- "journey",
2825
- "mindmap",
2826
- "timeline",
2827
- "quadrantChart",
2828
- "sankey",
2829
- "xychart"
2830
- ];
2831
- var PDF_MAGIC = "JVBERi";
2832
- var BASE64_PATTERN = /^[A-Za-z0-9+/=\r\n]+$/;
2833
- function detectContentType(value) {
2834
- if (value === null || value === void 0) {
2835
- return "text";
2836
- }
2837
- if (typeof value === "object" && !Array.isArray(value)) {
2838
- const obj = value;
2839
- if (typeof obj["type"] === "string" && CHART_TYPES.has(obj["type"])) {
2840
- return "chart";
2841
- }
2842
- return "json";
2843
- }
2844
- if (typeof value === "string") {
2845
- const trimmed = value.trimStart();
2846
- if (trimmed.startsWith(PDF_MAGIC)) {
2847
- return BASE64_PATTERN.test(trimmed.trimEnd()) ? "pdf" : "text";
2848
- }
2849
- for (const prefix of MERMAID_PREFIXES) {
2850
- if (trimmed.startsWith(prefix)) {
2851
- return "mermaid";
2852
- }
2853
- }
2854
- if (trimmed.includes("<") && trimmed.includes(">")) {
2855
- return "html";
2856
- }
2857
- return "text";
2858
- }
2859
- return "text";
2860
- }
2861
-
2862
- // libs/uipack/src/adapters/content-renderers.ts
2863
- var CHART_JS_CDN = "https://esm.sh/chart.js@4/auto";
2864
- var MERMAID_CDN = "https://esm.sh/mermaid@11/dist/mermaid.esm.min.mjs";
2865
- function buildChartHtml(chartJson) {
2866
- const chartData = safeJsonForScript(chartJson);
2867
- const content = `
1284
+ }`}var CHART_TYPES=new Set(["bar","line","pie","area","scatter","doughnut","radar","polarArea","bubble"]);var MERMAID_PREFIXES=["flowchart","graph","sequenceDiagram","classDiagram","stateDiagram","erDiagram","gantt","pie","gitGraph","journey","mindmap","timeline","quadrantChart","sankey","xychart"];var PDF_MAGIC="JVBERi";var BASE64_PATTERN=/^[A-Za-z0-9+/=\r\n]+$/;function detectContentType(value){if(value===null||value===void 0){return"text"}if(typeof value==="object"&&!Array.isArray(value)){const obj=value;if(typeof obj["type"]==="string"&&CHART_TYPES.has(obj["type"])){return"chart"}return"json"}if(typeof value==="string"){const trimmed=value.trimStart();if(trimmed.startsWith(PDF_MAGIC)){return BASE64_PATTERN.test(trimmed.trimEnd())?"pdf":"text"}for(const prefix of MERMAID_PREFIXES){if(trimmed.startsWith(prefix)){return"mermaid"}}if(trimmed.includes("<")&&trimmed.includes(">")){return"html"}return"text"}return"text"}var CHART_JS_CDN="https://esm.sh/chart.js@4/auto";var MERMAID_CDN="https://esm.sh/mermaid@11/dist/mermaid.esm.min.mjs";function buildChartHtml(chartJson){const chartData=safeJsonForScript(chartJson);const content=`
2868
1285
  <canvas id="chart" style="max-width:100%;max-height:80vh;"></canvas>
2869
1286
  <script type="module">
2870
1287
  import Chart from '${CHART_JS_CDN}';
2871
1288
  const ctx = document.getElementById('chart').getContext('2d');
2872
1289
  new Chart(ctx, ${chartData});
2873
- </script>`;
2874
- const result = buildShell(content, {
2875
- toolName: "chart",
2876
- csp: {
2877
- resourceDomains: ["https://esm.sh"],
2878
- connectDomains: ["https://esm.sh"]
2879
- },
2880
- includeBridge: false
2881
- });
2882
- return result.html;
2883
- }
2884
- function buildMermaidHtml(mermaidCode) {
2885
- const escaped = escapeHtml(mermaidCode);
2886
- const content = `
1290
+ </script>`;const result=buildShell(content,{toolName:"chart",csp:{resourceDomains:["https://esm.sh"],connectDomains:["https://esm.sh"]},includeBridge:false});return result.html}function buildMermaidHtml(mermaidCode){const escaped=escapeHtml(mermaidCode);const content=`
2887
1291
  <pre class="mermaid">${escaped}</pre>
2888
1292
  <script type="module">
2889
1293
  import mermaid from '${MERMAID_CDN}';
2890
1294
  mermaid.initialize({ startOnLoad: true, theme: 'default' });
2891
- </script>`;
2892
- const result = buildShell(content, {
2893
- toolName: "mermaid",
2894
- csp: {
2895
- resourceDomains: ["https://esm.sh"],
2896
- connectDomains: ["https://esm.sh"]
2897
- },
2898
- includeBridge: false
2899
- });
2900
- return result.html;
2901
- }
2902
- function buildPdfHtml(base64) {
2903
- const content = `
1295
+ </script>`;const result=buildShell(content,{toolName:"mermaid",csp:{resourceDomains:["https://esm.sh"],connectDomains:["https://esm.sh"]},includeBridge:false});return result.html}function buildPdfHtml(base64){const content=`
2904
1296
  <div id="pdf-container" style="width:100%;overflow:auto;text-align:center;"></div>
2905
1297
  <script type="module">
2906
1298
  import * as pdfjsLib from 'https://esm.sh/pdfjs-dist@4/build/pdf.min.mjs';
@@ -2923,319 +1315,8 @@ for (let i = 1; i <= pdf.numPages; i++) {
2923
1315
  container.appendChild(canvas);
2924
1316
  await page.render({ canvasContext: canvas.getContext('2d'), viewport }).promise;
2925
1317
  }
2926
- </script>`;
2927
- const result = buildShell(content, {
2928
- toolName: "pdf",
2929
- csp: {
2930
- resourceDomains: ["https://esm.sh"],
2931
- connectDomains: ["https://esm.sh"]
2932
- },
2933
- includeBridge: false
2934
- });
2935
- return result.html;
2936
- }
2937
- function wrapDetectedContent(value) {
2938
- const contentType = detectContentType(value);
2939
- switch (contentType) {
2940
- case "chart":
2941
- return buildChartHtml(value);
2942
- case "mermaid":
2943
- return buildMermaidHtml(value);
2944
- case "pdf":
2945
- return buildPdfHtml(value);
2946
- case "html":
2947
- return void 0;
2948
- default:
2949
- return void 0;
2950
- }
2951
- }
2952
-
2953
- // libs/uipack/src/adapters/markdown.ts
2954
- var SAFE_HREF = /^(https?:|mailto:|\/|#)/i;
2955
- function emphasis(text) {
2956
- return text.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>");
2957
- }
2958
- function inline(text) {
2959
- const stash = [];
2960
- const hold = (html2) => `\uE000${stash.push(html2) - 1}\uE000`;
2961
- let out = escapeHtml(text.replace(/\uE000/g, "")).replace(
2962
- /`([^`]+)`/g,
2963
- (_m, code) => hold(`<code>${code}</code>`)
2964
- );
2965
- out = out.replace(
2966
- /\[([^\]]+)\]\(([^)\s]+)\)/g,
2967
- (_m, label, href) => SAFE_HREF.test(href) ? hold(`<a href="${href}" rel="noopener noreferrer">${emphasis(label)}</a>`) : label
2968
- );
2969
- out = emphasis(out);
2970
- for (let i = 0; i < 2; i++) out = out.replace(/\uE000(\d+)\uE000/g, (_m, n) => stash[Number(n)]);
2971
- return out;
2972
- }
2973
- function markdownToHtml(source) {
2974
- const lines = source.replace(/\r\n?/g, "\n").split("\n");
2975
- const blocks = [];
2976
- let paragraph = [];
2977
- let list;
2978
- const flushParagraph = () => {
2979
- if (paragraph.length > 0) blocks.push(`<p>${inline(paragraph.join(" "))}</p>`);
2980
- paragraph = [];
2981
- };
2982
- const flushList = () => {
2983
- if (list)
2984
- blocks.push(`<${list.tag}>${list.items.map((item) => `<li>${inline(item)}</li>`).join("")}</${list.tag}>`);
2985
- list = void 0;
2986
- };
2987
- for (let i = 0; i < lines.length; i++) {
2988
- const line = lines[i];
2989
- const fence = /^\s*(`{3,})/.exec(line);
2990
- if (fence) {
2991
- flushParagraph();
2992
- flushList();
2993
- const fenceLength = fence[1].length;
2994
- const isClosing = (l) => {
2995
- const m = /^\s*(`{3,})\s*$/.exec(l);
2996
- return m !== null && m[1].length >= fenceLength;
2997
- };
2998
- const code = [];
2999
- for (i++; i < lines.length && !isClosing(lines[i]); i++) code.push(lines[i]);
3000
- blocks.push(`<pre><code>${escapeHtml(code.join("\n"))}
3001
- </code></pre>`);
3002
- continue;
3003
- }
3004
- const heading = /^(#{1,6})\s+(.*)$/.exec(line);
3005
- if (heading) {
3006
- flushParagraph();
3007
- flushList();
3008
- blocks.push(`<h${heading[1].length}>${inline(heading[2].trim())}</h${heading[1].length}>`);
3009
- continue;
3010
- }
3011
- const item = /^\s*([-*+]|\d+\.)\s+(.*)$/.exec(line);
3012
- if (item) {
3013
- flushParagraph();
3014
- const tag = /\d/.test(item[1]) ? "ol" : "ul";
3015
- if (list && list.tag !== tag) flushList();
3016
- list ??= { tag, items: [] };
3017
- list.items.push(item[2]);
3018
- continue;
3019
- }
3020
- if (line.trim() === "") {
3021
- flushParagraph();
3022
- flushList();
3023
- continue;
3024
- }
3025
- flushList();
3026
- paragraph.push(line.trim());
3027
- }
3028
- flushParagraph();
3029
- flushList();
3030
- return blocks.join("\n");
3031
- }
3032
-
3033
- // libs/uipack/src/adapters/type-detector.ts
3034
- function detectUIType(template) {
3035
- if (template === null || template === void 0) {
3036
- return "auto";
3037
- }
3038
- if (typeof template === "object" && template !== null && "file" in template) {
3039
- const file = template.file;
3040
- if (/\.(tsx|jsx)$/i.test(file)) return "react";
3041
- }
3042
- if (typeof template === "function") {
3043
- const proto = template.prototype;
3044
- if (proto && typeof proto.render === "function") {
3045
- return "react";
3046
- }
3047
- const asRecord = template;
3048
- if (asRecord["$$typeof"] !== void 0) {
3049
- return "react";
3050
- }
3051
- if (template.name && /^[A-Z]/.test(template.name)) {
3052
- return "react";
3053
- }
3054
- return "html";
3055
- }
3056
- if (typeof template === "string") {
3057
- if (template.includes("<") && template.includes(">")) {
3058
- return "html";
3059
- }
3060
- return "markdown";
3061
- }
3062
- return "auto";
3063
- }
3064
-
3065
- // libs/uipack/src/adapters/template-renderer.ts
3066
- function buildCspConfig(resolver, extra) {
3067
- const cspResourceDomains = ["https://esm.sh"];
3068
- const cspConnectDomains = ["https://esm.sh"];
3069
- for (const domain of extra?.resourceDomains ?? []) {
3070
- if (!cspResourceDomains.includes(domain)) cspResourceDomains.push(domain);
3071
- }
3072
- for (const domain of extra?.connectDomains ?? []) {
3073
- if (!cspConnectDomains.includes(domain)) cspConnectDomains.push(domain);
3074
- }
3075
- if (resolver && "overrides" in resolver) {
3076
- const overrides = resolver.overrides;
3077
- if (overrides) {
3078
- for (const url of Object.values(overrides)) {
3079
- try {
3080
- const origin = new URL(url).origin;
3081
- if (!cspResourceDomains.includes(origin)) cspResourceDomains.push(origin);
3082
- if (!cspConnectDomains.includes(origin)) cspConnectDomains.push(origin);
3083
- } catch {
3084
- }
3085
- }
3086
- }
3087
- }
3088
- return { resourceDomains: cspResourceDomains, connectDomains: cspConnectDomains };
3089
- }
3090
- var STRING_RESULT_DOCS = "https://frontmcp.dev/learn/your-first-widget";
3091
- var noticedStringResultTools = /* @__PURE__ */ new Set();
3092
- function noticeStringResult(toolName, logger) {
3093
- if (noticedStringResultTools.has(toolName)) return;
3094
- noticedStringResultTools.add(toolName);
3095
- logger.warn(
3096
- `[frontmcp] The UI template of tool "${toolName}" returned a plain string containing markup. Since 1.9.2, FrontMCP HTML-escapes plain string results by default, so it is shown as text. Build the markup with ctx.helpers.html\`\u2026\` (interpolated values are escaped) or wrap safe markup with ctx.helpers.trustedHtml(). Set ui.escapeStringResults: false to render plain strings as markup, or true to silence this notice. See ${STRING_RESULT_DOCS}`
3097
- );
3098
- }
3099
- function renderUnwrappedResult(rawResult, options) {
3100
- if (isTrustedHtml(rawResult)) {
3101
- return String(rawResult);
3102
- }
3103
- if (typeof rawResult !== "string") {
3104
- return `<pre>${escapeHtml(JSON.stringify(rawResult, null, 2))}</pre>`;
3105
- }
3106
- const looksLikeMarkup = detectContentType(rawResult) === "html";
3107
- if (looksLikeMarkup && options.escapeStringResults === false) {
3108
- return rawResult;
3109
- }
3110
- if (looksLikeMarkup && options.escapeStringResults === void 0) {
3111
- noticeStringResult(options.toolName, options.logger ?? console);
3112
- }
3113
- return escapeHtml(rawResult);
3114
- }
3115
- var warnedComponentReferences = /* @__PURE__ */ new WeakMap();
3116
- function warnComponentReference(template, toolName, logger) {
3117
- const warned = warnedComponentReferences.get(template) ?? /* @__PURE__ */ new Set();
3118
- if (warned.has(toolName)) return;
3119
- warned.add(toolName);
3120
- warnedComponentReferences.set(template, warned);
3121
- logger.warn(
3122
- `[FrontMCP] Tool "${toolName}": \`ui.template\` is a React component reference, which cannot be bundled (there is no source file to compile), so the widget would render an empty page. Use \`template: { file: './widget.tsx' }\` instead.`
3123
- );
3124
- }
3125
- var COMPILED_JSX_PATTERN = /\b(?:React\.createElement|_?jsx(?:s|DEV)?)\)?\s*\(/;
3126
- function isComponentReference(template) {
3127
- if (isReactTypedObject(template)) return true;
3128
- if (typeof template !== "function" || detectUIType(template) !== "react") return false;
3129
- return isDefinitelyReactComponent(template) || COMPILED_JSX_PATTERN.test(Function.prototype.toString.call(template));
3130
- }
3131
- function warnIfComponentReference(toolName, template, logger = console) {
3132
- if (!isComponentReference(template)) return false;
3133
- warnComponentReference(template, toolName, logger);
3134
- return true;
3135
- }
3136
- function isReactTypedObject(value) {
3137
- return typeof value === "object" && value !== null && "$$typeof" in value;
3138
- }
3139
- function isDefinitelyReactComponent(template) {
3140
- if (typeof template !== "function") return false;
3141
- const proto = template.prototype;
3142
- return typeof proto?.render === "function" || template["$$typeof"] !== void 0;
3143
- }
3144
- function renderToolTemplate(options) {
3145
- const { toolName, input, output, template, resolver, platformType, sizing } = options;
3146
- const uiType = detectUIType(template);
3147
- const resourceMode = options.resourceMode ?? (platformType === "claude" ? "inline" : "cdn");
3148
- const shellConfig = {
3149
- toolName,
3150
- input,
3151
- output,
3152
- includeBridge: true,
3153
- resolver,
3154
- sizing,
3155
- displayMode: options.displayMode,
3156
- csp: options.csp ? buildCspConfig(resolver, options.csp) : void 0
3157
- };
3158
- let html2;
3159
- let hash = "";
3160
- let size = 0;
3161
- if (typeof template === "object" && template !== null && "file" in template) {
3162
- const result = renderComponent(
3163
- { source: template, inlineReact: resourceMode === "inline" },
3164
- { ...shellConfig, csp: buildCspConfig(resolver, options.csp) }
3165
- );
3166
- html2 = result.html;
3167
- hash = result.hash;
3168
- size = result.size;
3169
- } else if (typeof template === "function") {
3170
- const helpers = createTemplateHelpers();
3171
- const ctx = { input: input ?? {}, output: output ?? {}, helpers };
3172
- let rawResult;
3173
- let isHtmlBuilder = uiType !== "react" || !isDefinitelyReactComponent(template);
3174
- if (isHtmlBuilder) {
3175
- try {
3176
- rawResult = template(ctx);
3177
- isHtmlBuilder = !isReactTypedObject(rawResult);
3178
- } catch (error) {
3179
- if (uiType !== "react") throw error;
3180
- isHtmlBuilder = false;
3181
- }
3182
- }
3183
- if (!isHtmlBuilder) {
3184
- warnComponentReference(template, toolName, options.logger ?? console);
3185
- const shellResult = buildShell('<div id="root"></div>', shellConfig);
3186
- html2 = shellResult.html;
3187
- hash = shellResult.hash;
3188
- size = shellResult.size;
3189
- } else {
3190
- const wrapped = isTrustedHtml(rawResult) ? void 0 : wrapDetectedContent(rawResult);
3191
- if (wrapped) {
3192
- html2 = wrapped;
3193
- } else {
3194
- const shellResult = buildShell(renderUnwrappedResult(rawResult, options), shellConfig);
3195
- html2 = shellResult.html;
3196
- hash = shellResult.hash;
3197
- size = shellResult.size;
3198
- }
3199
- }
3200
- } else if (typeof template === "string") {
3201
- const shellResult = buildShell(uiType === "markdown" ? markdownToHtml(template) : template, shellConfig);
3202
- html2 = shellResult.html;
3203
- hash = shellResult.hash;
3204
- size = shellResult.size;
3205
- } else {
3206
- if (isReactTypedObject(template)) warnComponentReference(template, toolName, options.logger ?? console);
3207
- const shellResult = buildShell('<div id="root"></div>', shellConfig);
3208
- html2 = shellResult.html;
3209
- hash = shellResult.hash;
3210
- size = shellResult.size;
3211
- }
3212
- const htmlKey = "ui/html";
3213
- const meta = {
3214
- [htmlKey]: html2,
3215
- "ui/type": uiType,
3216
- "ui/mimeType": MCP_APPS_MIME_TYPE
3217
- };
3218
- if (hasSizing(sizing)) {
3219
- if (sizing.preferredHeight !== void 0) meta["ui/preferredHeight"] = sizing.preferredHeight;
3220
- if (sizing.minHeight !== void 0) meta["ui/minHeight"] = sizing.minHeight;
3221
- if (sizing.maxHeight !== void 0) meta["ui/maxHeight"] = sizing.maxHeight;
3222
- if (sizing.aspectRatio !== void 0) meta["ui/aspectRatio"] = sizing.aspectRatio;
3223
- }
3224
- return {
3225
- html: html2,
3226
- uiType,
3227
- hash,
3228
- size: size || Buffer.byteLength(html2, "utf8"),
3229
- meta
3230
- };
3231
- }
3232
-
3233
- // libs/uipack/src/adapters/base-template.ts
3234
- function createDefaultBaseTemplate(options) {
3235
- const { toolName } = options;
3236
- const safeToolName = escapeHtml(toolName);
3237
- const bridgeScript = `<script>${generateBridgeIIFE({ minify: true })}</script>`;
3238
- const content = `
1318
+ </script>`;const result=buildShell(content,{toolName:"pdf",csp:{resourceDomains:["https://esm.sh"],connectDomains:["https://esm.sh"]},includeBridge:false});return result.html}function wrapDetectedContent(value){const contentType=detectContentType(value);switch(contentType){case"chart":return buildChartHtml(value);case"mermaid":return buildMermaidHtml(value);case"pdf":return buildPdfHtml(value);case"html":return void 0;default:return void 0}}var SAFE_HREF=/^(https?:|mailto:|\/|#)/i;function emphasis(text){return text.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>").replace(/\*([^*]+)\*/g,"<em>$1</em>")}function inline(text){const stash=[];const hold=html2=>`\uE000${stash.push(html2)-1}\uE000`;let out=escapeHtml(text.replace(/\uE000/g,"")).replace(/`([^`]+)`/g,(_m,code)=>hold(`<code>${code}</code>`));out=out.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(_m,label,href)=>SAFE_HREF.test(href)?hold(`<a href="${href}" rel="noopener noreferrer">${emphasis(label)}</a>`):label);out=emphasis(out);for(let i=0;i<2;i++)out=out.replace(/\uE000(\d+)\uE000/g,(_m,n)=>stash[Number(n)]);return out}function markdownToHtml(source){const lines=source.replace(/\r\n?/g,"\n").split("\n");const blocks=[];let paragraph=[];let list;const flushParagraph=()=>{if(paragraph.length>0)blocks.push(`<p>${inline(paragraph.join(" "))}</p>`);paragraph=[]};const flushList=()=>{if(list)blocks.push(`<${list.tag}>${list.items.map(item=>`<li>${inline(item)}</li>`).join("")}</${list.tag}>`);list=void 0};for(let i=0;i<lines.length;i++){const line=lines[i];const fence=/^\s*(`{3,})/.exec(line);if(fence){flushParagraph();flushList();const fenceLength=fence[1].length;const isClosing=l=>{const m=/^\s*(`{3,})\s*$/.exec(l);return m!==null&&m[1].length>=fenceLength};const code=[];for(i++;i<lines.length&&!isClosing(lines[i]);i++)code.push(lines[i]);blocks.push(`<pre><code>${escapeHtml(code.join("\n"))}
1319
+ </code></pre>`);continue}const heading=/^(#{1,6})\s+(.*)$/.exec(line);if(heading){flushParagraph();flushList();blocks.push(`<h${heading[1].length}>${inline(heading[2].trim())}</h${heading[1].length}>`);continue}const item=/^\s*([-*+]|\d+\.)\s+(.*)$/.exec(line);if(item){flushParagraph();const tag=/\d/.test(item[1])?"ol":"ul";if(list&&list.tag!==tag)flushList();list??={tag,items:[]};list.items.push(item[2]);continue}if(line.trim()===""){flushParagraph();flushList();continue}flushList();paragraph.push(line.trim())}flushParagraph();flushList();return blocks.join("\n")}function detectUIType(template){if(template===null||template===void 0){return"auto"}if(typeof template==="object"&&template!==null&&"file"in template){const file=template.file;if(/\.(tsx|jsx)$/i.test(file))return"react"}if(typeof template==="function"){const proto=template.prototype;if(proto&&typeof proto.render==="function"){return"react"}const asRecord=template;if(asRecord["$$typeof"]!==void 0){return"react"}if(template.name&&/^[A-Z]/.test(template.name)){return"react"}return"html"}if(typeof template==="string"){if(template.includes("<")&&template.includes(">")){return"html"}return"markdown"}return"auto"}function buildCspConfig(resolver,extra){const cspResourceDomains=["https://esm.sh"];const cspConnectDomains=["https://esm.sh"];for(const domain of extra?.resourceDomains??[]){if(!cspResourceDomains.includes(domain))cspResourceDomains.push(domain)}for(const domain of extra?.connectDomains??[]){if(!cspConnectDomains.includes(domain))cspConnectDomains.push(domain)}if(resolver&&"overrides"in resolver){const overrides=resolver.overrides;if(overrides){for(const url of Object.values(overrides)){try{const origin=new URL(url).origin;if(!cspResourceDomains.includes(origin))cspResourceDomains.push(origin);if(!cspConnectDomains.includes(origin))cspConnectDomains.push(origin)}catch{}}}}return{resourceDomains:cspResourceDomains,connectDomains:cspConnectDomains}}var STRING_RESULT_DOCS="https://frontmcp.dev/learn/your-first-widget";var noticedStringResultTools=new Set;function noticeStringResult(toolName,logger){if(noticedStringResultTools.has(toolName))return;noticedStringResultTools.add(toolName);logger.warn(`[frontmcp] The UI template of tool "${toolName}" returned a plain string containing markup. Since 1.9.2, FrontMCP HTML-escapes plain string results by default, so it is shown as text. Build the markup with ctx.helpers.html\`\u2026\` (interpolated values are escaped) or wrap safe markup with ctx.helpers.trustedHtml(). Set ui.escapeStringResults: false to render plain strings as markup, or true to silence this notice. See ${STRING_RESULT_DOCS}`)}function renderUnwrappedResult(rawResult,options){if(isTrustedHtml(rawResult)){return String(rawResult)}if(typeof rawResult!=="string"){return`<pre>${escapeHtml(JSON.stringify(rawResult,null,2))}</pre>`}const looksLikeMarkup=detectContentType(rawResult)==="html";if(looksLikeMarkup&&options.escapeStringResults===false){return rawResult}if(looksLikeMarkup&&options.escapeStringResults===void 0){noticeStringResult(options.toolName,options.logger??console)}return escapeHtml(rawResult)}var warnedComponentReferences=new WeakMap;function warnComponentReference(template,toolName,logger){const warned=warnedComponentReferences.get(template)??new Set;if(warned.has(toolName))return;warned.add(toolName);warnedComponentReferences.set(template,warned);logger.warn(`[FrontMCP] Tool "${toolName}": \`ui.template\` is a React component reference, which cannot be bundled (there is no source file to compile), so the widget would render an empty page. Use \`template: { file: './widget.tsx' }\` instead.`)}var COMPILED_JSX_PATTERN=/\b(?:React\.createElement|_?jsx(?:s|DEV)?)\)?\s*\(/;function isComponentReference(template){if(isReactTypedObject(template))return true;if(typeof template!=="function"||detectUIType(template)!=="react")return false;return isDefinitelyReactComponent(template)||COMPILED_JSX_PATTERN.test(Function.prototype.toString.call(template))}function warnIfComponentReference(toolName,template,logger=console){if(!isComponentReference(template))return false;warnComponentReference(template,toolName,logger);return true}function isReactTypedObject(value){return typeof value==="object"&&value!==null&&"$$typeof"in value}function isDefinitelyReactComponent(template){if(typeof template!=="function")return false;const proto=template.prototype;return typeof proto?.render==="function"||template["$$typeof"]!==void 0}function renderToolTemplate(options){const{toolName,input,output,template,resolver,platformType,sizing}=options;const uiType=detectUIType(template);const resourceMode=options.resourceMode??(platformType==="claude"?"inline":"cdn");const shellConfig={toolName,input,output,includeBridge:true,resolver,sizing,displayMode:options.displayMode,csp:options.csp?buildCspConfig(resolver,options.csp):void 0};let html2;let hash="";let size=0;if(typeof template==="object"&&template!==null&&"file"in template){const result=renderComponent({source:template,inlineReact:resourceMode==="inline"},{...shellConfig,csp:buildCspConfig(resolver,options.csp)});html2=result.html;hash=result.hash;size=result.size}else if(typeof template==="function"){const helpers=createTemplateHelpers();const ctx={input:input??{},output:output??{},helpers};let rawResult;let isHtmlBuilder=uiType!=="react"||!isDefinitelyReactComponent(template);if(isHtmlBuilder){try{rawResult=template(ctx);isHtmlBuilder=!isReactTypedObject(rawResult)}catch(error){if(uiType!=="react")throw error;isHtmlBuilder=false}}if(!isHtmlBuilder){warnComponentReference(template,toolName,options.logger??console);const shellResult=buildShell('<div id="root"></div>',shellConfig);html2=shellResult.html;hash=shellResult.hash;size=shellResult.size}else{const wrapped=isTrustedHtml(rawResult)?void 0:wrapDetectedContent(rawResult);if(wrapped){html2=wrapped}else{const shellResult=buildShell(renderUnwrappedResult(rawResult,options),shellConfig);html2=shellResult.html;hash=shellResult.hash;size=shellResult.size}}}else if(typeof template==="string"){const shellResult=buildShell(uiType==="markdown"?markdownToHtml(template):template,shellConfig);html2=shellResult.html;hash=shellResult.hash;size=shellResult.size}else{if(isReactTypedObject(template))warnComponentReference(template,toolName,options.logger??console);const shellResult=buildShell('<div id="root"></div>',shellConfig);html2=shellResult.html;hash=shellResult.hash;size=shellResult.size}const htmlKey="ui/html";const meta={[htmlKey]:html2,"ui/type":uiType,"ui/mimeType":MCP_APPS_MIME_TYPE};if(hasSizing(sizing)){if(sizing.preferredHeight!==void 0)meta["ui/preferredHeight"]=sizing.preferredHeight;if(sizing.minHeight!==void 0)meta["ui/minHeight"]=sizing.minHeight;if(sizing.maxHeight!==void 0)meta["ui/maxHeight"]=sizing.maxHeight;if(sizing.aspectRatio!==void 0)meta["ui/aspectRatio"]=sizing.aspectRatio}return{html:html2,uiType,hash,size:size||Buffer.byteLength(html2,"utf8"),meta}}function createDefaultBaseTemplate(options){const{toolName}=options;const safeToolName=escapeHtml(toolName);const bridgeScript=`<script>${generateBridgeIIFE({minify:true})}</script>`;const content=`
3239
1320
  ${bridgeScript}
3240
1321
  <div id="root">
3241
1322
  <div style="font-family:system-ui,sans-serif;padding:1rem;color:#374151;">
@@ -3261,62 +1342,4 @@ ${bridgeScript}
3261
1342
  });
3262
1343
  }
3263
1344
  })();
3264
- </script>`;
3265
- const result = buildShell(content, {
3266
- toolName,
3267
- includeBridge: false,
3268
- // Bridge already included via inline script above
3269
- title: `Widget: ${toolName}`
3270
- });
3271
- return result.html;
3272
- }
3273
-
3274
- // libs/uipack/src/adapters/cdn-info.ts
3275
- var ESM_SH_BASE = "https://esm.sh";
3276
- var REACT_DEPS = [
3277
- { name: "react", url: `${ESM_SH_BASE}/react@18` },
3278
- { name: "react-dom", url: `${ESM_SH_BASE}/react-dom@18` }
3279
- ];
3280
- function buildCDNInfoForUIType(uiType) {
3281
- const deps = [];
3282
- switch (uiType) {
3283
- case "react":
3284
- deps.push(...REACT_DEPS);
3285
- break;
3286
- case "mdx":
3287
- deps.push(...REACT_DEPS);
3288
- deps.push({ name: "marked", url: `${ESM_SH_BASE}/marked@latest` });
3289
- break;
3290
- case "markdown":
3291
- deps.push({ name: "marked", url: `${ESM_SH_BASE}/marked@latest` });
3292
- break;
3293
- case "auto":
3294
- deps.push(...REACT_DEPS);
3295
- deps.push({ name: "marked", url: `${ESM_SH_BASE}/marked@latest` });
3296
- break;
3297
- case "html":
3298
- default:
3299
- break;
3300
- }
3301
- return {
3302
- base: ESM_SH_BASE,
3303
- dependencies: deps
3304
- };
3305
- }
3306
- export {
3307
- MCP_APPS_EXTENSION_ID,
3308
- MCP_APPS_MIME_TYPE,
3309
- buildCDNInfoForUIType,
3310
- buildChartHtml,
3311
- buildMermaidHtml,
3312
- buildPdfHtml,
3313
- buildToolResponseContent,
3314
- createDefaultBaseTemplate,
3315
- detectContentType,
3316
- detectUIType,
3317
- isUIRenderFailure,
3318
- renderToolTemplate,
3319
- resolveServingMode,
3320
- warnIfComponentReference,
3321
- wrapDetectedContent
3322
- };
1345
+ </script>`;const result=buildShell(content,{toolName,includeBridge:false,title:`Widget: ${toolName}`});return result.html}var ESM_SH_BASE="https://esm.sh";var REACT_DEPS=[{name:"react",url:`${ESM_SH_BASE}/react@18`},{name:"react-dom",url:`${ESM_SH_BASE}/react-dom@18`}];function buildCDNInfoForUIType(uiType){const deps=[];switch(uiType){case"react":deps.push(...REACT_DEPS);break;case"mdx":deps.push(...REACT_DEPS);deps.push({name:"marked",url:`${ESM_SH_BASE}/marked@latest`});break;case"markdown":deps.push({name:"marked",url:`${ESM_SH_BASE}/marked@latest`});break;case"auto":deps.push(...REACT_DEPS);deps.push({name:"marked",url:`${ESM_SH_BASE}/marked@latest`});break;case"html":default:break}return{base:ESM_SH_BASE,dependencies:deps}}export{MCP_APPS_EXTENSION_ID,MCP_APPS_MIME_TYPE,buildCDNInfoForUIType,buildChartHtml,buildMermaidHtml,buildPdfHtml,buildToolResponseContent,createDefaultBaseTemplate,detectContentType,detectUIType,isUIRenderFailure,renderToolTemplate,resolveServingMode,warnIfComponentReference,wrapDetectedContent};