@frontmcp/uipack 0.12.2 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. package/CLAUDE.md +56 -154
  2. package/README.md +367 -62
  3. package/adapters/base-template.d.ts +30 -0
  4. package/adapters/base-template.d.ts.map +1 -0
  5. package/adapters/cdn-info.d.ts +34 -0
  6. package/adapters/cdn-info.d.ts.map +1 -0
  7. package/adapters/constants.d.ts +18 -0
  8. package/adapters/constants.d.ts.map +1 -0
  9. package/adapters/content-detector.d.ts +19 -0
  10. package/adapters/content-detector.d.ts.map +1 -0
  11. package/adapters/content-renderers.d.ts +27 -0
  12. package/adapters/content-renderers.d.ts.map +1 -0
  13. package/adapters/index.d.ts +14 -7
  14. package/adapters/index.d.ts.map +1 -1
  15. package/adapters/index.js +2343 -426
  16. package/adapters/render-failure.d.ts +18 -0
  17. package/adapters/render-failure.d.ts.map +1 -0
  18. package/adapters/response-builder.d.ts +34 -104
  19. package/adapters/response-builder.d.ts.map +1 -1
  20. package/adapters/serving-mode.d.ts +28 -91
  21. package/adapters/serving-mode.d.ts.map +1 -1
  22. package/adapters/template-renderer.d.ts +50 -0
  23. package/adapters/template-renderer.d.ts.map +1 -0
  24. package/adapters/type-detector.d.ts +18 -0
  25. package/adapters/type-detector.d.ts.map +1 -0
  26. package/bridge-runtime/index.js +1 -1
  27. package/component/index.d.ts +14 -0
  28. package/component/index.d.ts.map +1 -0
  29. package/component/index.js +2043 -0
  30. package/component/loader.d.ts +36 -0
  31. package/component/loader.d.ts.map +1 -0
  32. package/component/renderer.d.ts +30 -0
  33. package/component/renderer.d.ts.map +1 -0
  34. package/component/transpiler.d.ts +49 -0
  35. package/component/transpiler.d.ts.map +1 -0
  36. package/component/types.d.ts +82 -0
  37. package/component/types.d.ts.map +1 -0
  38. package/esm/adapters/index.mjs +2337 -422
  39. package/esm/bridge-runtime/index.mjs +1 -1
  40. package/esm/component/index.mjs +2013 -0
  41. package/esm/index.mjs +3446 -13935
  42. package/esm/package.json +3 -12
  43. package/esm/resolver/index.mjs +661 -0
  44. package/esm/shell/index.mjs +1406 -0
  45. package/esm/types/index.mjs +11 -11
  46. package/esm/utils/index.mjs +53 -8
  47. package/index.d.ts +12 -40
  48. package/index.d.ts.map +1 -1
  49. package/index.js +3579 -14218
  50. package/package.json +3 -12
  51. package/resolver/cdn-registry.d.ts +39 -0
  52. package/resolver/cdn-registry.d.ts.map +1 -0
  53. package/resolver/esm-sh.resolver.d.ts +54 -0
  54. package/resolver/esm-sh.resolver.d.ts.map +1 -0
  55. package/resolver/import-map.d.ts +47 -0
  56. package/resolver/import-map.d.ts.map +1 -0
  57. package/resolver/import-parser.d.ts +28 -0
  58. package/resolver/import-parser.d.ts.map +1 -0
  59. package/resolver/import-rewriter.d.ts +29 -0
  60. package/resolver/import-rewriter.d.ts.map +1 -0
  61. package/resolver/index.d.ts +15 -0
  62. package/resolver/index.d.ts.map +1 -0
  63. package/resolver/index.js +708 -0
  64. package/resolver/types.d.ts +191 -0
  65. package/resolver/types.d.ts.map +1 -0
  66. package/shell/builder.d.ts +31 -0
  67. package/shell/builder.d.ts.map +1 -0
  68. package/shell/csp.d.ts +37 -0
  69. package/shell/csp.d.ts.map +1 -0
  70. package/shell/custom-shell-applier.d.ts +33 -0
  71. package/shell/custom-shell-applier.d.ts.map +1 -0
  72. package/shell/custom-shell-resolver.d.ts +47 -0
  73. package/shell/custom-shell-resolver.d.ts.map +1 -0
  74. package/shell/custom-shell-types.d.ts +75 -0
  75. package/shell/custom-shell-types.d.ts.map +1 -0
  76. package/shell/custom-shell-validator.d.ts +26 -0
  77. package/shell/custom-shell-validator.d.ts.map +1 -0
  78. package/shell/data-injector.d.ts +40 -0
  79. package/shell/data-injector.d.ts.map +1 -0
  80. package/shell/index.d.ts +19 -0
  81. package/shell/index.d.ts.map +1 -0
  82. package/shell/index.js +1453 -0
  83. package/shell/types.d.ts +54 -0
  84. package/shell/types.d.ts.map +1 -0
  85. package/types/index.d.ts +1 -3
  86. package/types/index.d.ts.map +1 -1
  87. package/types/index.js +11 -11
  88. package/types/ui-config.d.ts +50 -11
  89. package/types/ui-config.d.ts.map +1 -1
  90. package/types/ui-runtime.d.ts +8 -82
  91. package/types/ui-runtime.d.ts.map +1 -1
  92. package/utils/index.d.ts +9 -3
  93. package/utils/index.d.ts.map +1 -1
  94. package/utils/index.js +59 -7
  95. package/adapters/platform-meta.constants.d.ts +0 -26
  96. package/adapters/platform-meta.constants.d.ts.map +0 -1
  97. package/adapters/platform-meta.d.ts +0 -234
  98. package/adapters/platform-meta.d.ts.map +0 -1
  99. package/base-template/bridge.d.ts +0 -90
  100. package/base-template/bridge.d.ts.map +0 -1
  101. package/base-template/default-base-template.d.ts +0 -91
  102. package/base-template/default-base-template.d.ts.map +0 -1
  103. package/base-template/index.d.ts +0 -15
  104. package/base-template/index.d.ts.map +0 -1
  105. package/base-template/index.js +0 -1393
  106. package/base-template/polyfills.d.ts +0 -31
  107. package/base-template/polyfills.d.ts.map +0 -1
  108. package/base-template/theme-styles.d.ts +0 -74
  109. package/base-template/theme-styles.d.ts.map +0 -1
  110. package/build/builders/base-builder.d.ts +0 -124
  111. package/build/builders/base-builder.d.ts.map +0 -1
  112. package/build/builders/esbuild-config.d.ts +0 -94
  113. package/build/builders/esbuild-config.d.ts.map +0 -1
  114. package/build/builders/hybrid-builder.d.ts +0 -93
  115. package/build/builders/hybrid-builder.d.ts.map +0 -1
  116. package/build/builders/index.d.ts +0 -17
  117. package/build/builders/index.d.ts.map +0 -1
  118. package/build/builders/inline-builder.d.ts +0 -83
  119. package/build/builders/inline-builder.d.ts.map +0 -1
  120. package/build/builders/static-builder.d.ts +0 -78
  121. package/build/builders/static-builder.d.ts.map +0 -1
  122. package/build/builders/types.d.ts +0 -341
  123. package/build/builders/types.d.ts.map +0 -1
  124. package/build/cdn-resources.d.ts +0 -244
  125. package/build/cdn-resources.d.ts.map +0 -1
  126. package/build/hybrid-data.d.ts +0 -127
  127. package/build/hybrid-data.d.ts.map +0 -1
  128. package/build/index.d.ts +0 -299
  129. package/build/index.d.ts.map +0 -1
  130. package/build/index.js +0 -8699
  131. package/build/ui-components-browser.d.ts +0 -64
  132. package/build/ui-components-browser.d.ts.map +0 -1
  133. package/build/widget-manifest.d.ts +0 -362
  134. package/build/widget-manifest.d.ts.map +0 -1
  135. package/bundler/cache.d.ts +0 -173
  136. package/bundler/cache.d.ts.map +0 -1
  137. package/bundler/file-cache/component-builder.d.ts +0 -167
  138. package/bundler/file-cache/component-builder.d.ts.map +0 -1
  139. package/bundler/file-cache/hash-calculator.d.ts +0 -155
  140. package/bundler/file-cache/hash-calculator.d.ts.map +0 -1
  141. package/bundler/file-cache/index.d.ts +0 -12
  142. package/bundler/file-cache/index.d.ts.map +0 -1
  143. package/bundler/file-cache/storage/filesystem.d.ts +0 -149
  144. package/bundler/file-cache/storage/filesystem.d.ts.map +0 -1
  145. package/bundler/file-cache/storage/index.d.ts +0 -11
  146. package/bundler/file-cache/storage/index.d.ts.map +0 -1
  147. package/bundler/file-cache/storage/interface.d.ts +0 -152
  148. package/bundler/file-cache/storage/interface.d.ts.map +0 -1
  149. package/bundler/file-cache/storage/redis.d.ts +0 -139
  150. package/bundler/file-cache/storage/redis.d.ts.map +0 -1
  151. package/bundler/index.d.ts +0 -35
  152. package/bundler/index.d.ts.map +0 -1
  153. package/bundler/index.js +0 -2953
  154. package/bundler/sandbox/enclave-adapter.d.ts +0 -121
  155. package/bundler/sandbox/enclave-adapter.d.ts.map +0 -1
  156. package/bundler/sandbox/executor.d.ts +0 -14
  157. package/bundler/sandbox/executor.d.ts.map +0 -1
  158. package/bundler/sandbox/policy.d.ts +0 -62
  159. package/bundler/sandbox/policy.d.ts.map +0 -1
  160. package/bundler/types.d.ts +0 -702
  161. package/bundler/types.d.ts.map +0 -1
  162. package/dependency/cdn-registry.d.ts +0 -98
  163. package/dependency/cdn-registry.d.ts.map +0 -1
  164. package/dependency/import-map.d.ts +0 -186
  165. package/dependency/import-map.d.ts.map +0 -1
  166. package/dependency/import-parser.d.ts +0 -82
  167. package/dependency/import-parser.d.ts.map +0 -1
  168. package/dependency/index.d.ts +0 -17
  169. package/dependency/index.d.ts.map +0 -1
  170. package/dependency/index.js +0 -3180
  171. package/dependency/resolver.d.ts +0 -164
  172. package/dependency/resolver.d.ts.map +0 -1
  173. package/dependency/schemas.d.ts +0 -486
  174. package/dependency/schemas.d.ts.map +0 -1
  175. package/dependency/template-loader.d.ts +0 -204
  176. package/dependency/template-loader.d.ts.map +0 -1
  177. package/dependency/template-processor.d.ts +0 -118
  178. package/dependency/template-processor.d.ts.map +0 -1
  179. package/dependency/types.d.ts +0 -739
  180. package/dependency/types.d.ts.map +0 -1
  181. package/esm/base-template/index.mjs +0 -1359
  182. package/esm/build/index.mjs +0 -8601
  183. package/esm/bundler/index.mjs +0 -2895
  184. package/esm/dependency/index.mjs +0 -3068
  185. package/esm/handlebars/index.mjs +0 -587
  186. package/esm/registry/index.mjs +0 -6305
  187. package/esm/renderers/index.mjs +0 -1557
  188. package/esm/runtime/index.mjs +0 -5361
  189. package/esm/styles/index.mjs +0 -171
  190. package/esm/theme/index.mjs +0 -756
  191. package/esm/tool-template/index.mjs +0 -3652
  192. package/esm/validation/index.mjs +0 -542
  193. package/handlebars/expression-extractor.d.ts +0 -147
  194. package/handlebars/expression-extractor.d.ts.map +0 -1
  195. package/handlebars/helpers.d.ts +0 -339
  196. package/handlebars/helpers.d.ts.map +0 -1
  197. package/handlebars/index.d.ts +0 -195
  198. package/handlebars/index.d.ts.map +0 -1
  199. package/handlebars/index.js +0 -659
  200. package/preview/claude-preview.d.ts +0 -67
  201. package/preview/claude-preview.d.ts.map +0 -1
  202. package/preview/generic-preview.d.ts +0 -66
  203. package/preview/generic-preview.d.ts.map +0 -1
  204. package/preview/index.d.ts +0 -36
  205. package/preview/index.d.ts.map +0 -1
  206. package/preview/openai-preview.d.ts +0 -70
  207. package/preview/openai-preview.d.ts.map +0 -1
  208. package/preview/types.d.ts +0 -199
  209. package/preview/types.d.ts.map +0 -1
  210. package/registry/index.d.ts +0 -46
  211. package/registry/index.d.ts.map +0 -1
  212. package/registry/index.js +0 -6342
  213. package/registry/render-template.d.ts +0 -91
  214. package/registry/render-template.d.ts.map +0 -1
  215. package/registry/tool-ui.registry.d.ts +0 -294
  216. package/registry/tool-ui.registry.d.ts.map +0 -1
  217. package/registry/uri-utils.d.ts +0 -56
  218. package/registry/uri-utils.d.ts.map +0 -1
  219. package/renderers/cache.d.ts +0 -145
  220. package/renderers/cache.d.ts.map +0 -1
  221. package/renderers/html.renderer.d.ts +0 -123
  222. package/renderers/html.renderer.d.ts.map +0 -1
  223. package/renderers/index.d.ts +0 -36
  224. package/renderers/index.d.ts.map +0 -1
  225. package/renderers/index.js +0 -1603
  226. package/renderers/mdx-client.renderer.d.ts +0 -124
  227. package/renderers/mdx-client.renderer.d.ts.map +0 -1
  228. package/renderers/registry.d.ts +0 -133
  229. package/renderers/registry.d.ts.map +0 -1
  230. package/renderers/types.d.ts +0 -343
  231. package/renderers/types.d.ts.map +0 -1
  232. package/renderers/utils/detect.d.ts +0 -107
  233. package/renderers/utils/detect.d.ts.map +0 -1
  234. package/renderers/utils/hash.d.ts +0 -40
  235. package/renderers/utils/hash.d.ts.map +0 -1
  236. package/renderers/utils/index.d.ts +0 -9
  237. package/renderers/utils/index.d.ts.map +0 -1
  238. package/renderers/utils/transpiler.d.ts +0 -70
  239. package/renderers/utils/transpiler.d.ts.map +0 -1
  240. package/runtime/adapters/html.adapter.d.ts +0 -59
  241. package/runtime/adapters/html.adapter.d.ts.map +0 -1
  242. package/runtime/adapters/index.d.ts +0 -26
  243. package/runtime/adapters/index.d.ts.map +0 -1
  244. package/runtime/adapters/mdx.adapter.d.ts +0 -73
  245. package/runtime/adapters/mdx.adapter.d.ts.map +0 -1
  246. package/runtime/adapters/types.d.ts +0 -95
  247. package/runtime/adapters/types.d.ts.map +0 -1
  248. package/runtime/csp.d.ts +0 -48
  249. package/runtime/csp.d.ts.map +0 -1
  250. package/runtime/index.d.ts +0 -17
  251. package/runtime/index.d.ts.map +0 -1
  252. package/runtime/index.js +0 -5432
  253. package/runtime/mcp-bridge.d.ts +0 -101
  254. package/runtime/mcp-bridge.d.ts.map +0 -1
  255. package/runtime/renderer-runtime.d.ts +0 -133
  256. package/runtime/renderer-runtime.d.ts.map +0 -1
  257. package/runtime/sanitizer.d.ts +0 -180
  258. package/runtime/sanitizer.d.ts.map +0 -1
  259. package/runtime/types.d.ts +0 -415
  260. package/runtime/types.d.ts.map +0 -1
  261. package/runtime/wrapper.d.ts +0 -421
  262. package/runtime/wrapper.d.ts.map +0 -1
  263. package/styles/index.d.ts +0 -8
  264. package/styles/index.d.ts.map +0 -1
  265. package/styles/index.js +0 -222
  266. package/styles/variants.d.ts +0 -51
  267. package/styles/variants.d.ts.map +0 -1
  268. package/theme/cdn.d.ts +0 -195
  269. package/theme/cdn.d.ts.map +0 -1
  270. package/theme/css-to-theme.d.ts +0 -64
  271. package/theme/css-to-theme.d.ts.map +0 -1
  272. package/theme/index.d.ts +0 -19
  273. package/theme/index.d.ts.map +0 -1
  274. package/theme/index.js +0 -814
  275. package/theme/platforms.d.ts +0 -102
  276. package/theme/platforms.d.ts.map +0 -1
  277. package/theme/presets/github-openai.d.ts +0 -50
  278. package/theme/presets/github-openai.d.ts.map +0 -1
  279. package/theme/presets/index.d.ts +0 -11
  280. package/theme/presets/index.d.ts.map +0 -1
  281. package/theme/theme.d.ts +0 -396
  282. package/theme/theme.d.ts.map +0 -1
  283. package/tool-template/builder.d.ts +0 -213
  284. package/tool-template/builder.d.ts.map +0 -1
  285. package/tool-template/index.d.ts +0 -16
  286. package/tool-template/index.d.ts.map +0 -1
  287. package/tool-template/index.js +0 -3690
  288. package/validation/error-box.d.ts +0 -56
  289. package/validation/error-box.d.ts.map +0 -1
  290. package/validation/index.d.ts +0 -13
  291. package/validation/index.d.ts.map +0 -1
  292. package/validation/index.js +0 -576
  293. package/validation/schema-paths.d.ts +0 -118
  294. package/validation/schema-paths.d.ts.map +0 -1
  295. package/validation/template-validator.d.ts +0 -143
  296. package/validation/template-validator.d.ts.map +0 -1
  297. package/validation/wrapper.d.ts +0 -97
  298. package/validation/wrapper.d.ts.map +0 -1
@@ -1,3180 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // libs/uipack/src/dependency/index.ts
31
- var dependency_exports = {};
32
- __export(dependency_exports, {
33
- CDN_PROVIDER_PRIORITY: () => CDN_PROVIDER_PRIORITY,
34
- DEFAULT_CDN_REGISTRY: () => DEFAULT_CDN_REGISTRY,
35
- DependencyResolutionError: () => DependencyResolutionError,
36
- DependencyResolver: () => DependencyResolver,
37
- NoProviderError: () => NoProviderError,
38
- addScope: () => addScope,
39
- buildManifestMetadataSchema: () => buildManifestMetadataSchema,
40
- buildManifestOutputsSchema: () => buildManifestOutputsSchema,
41
- bundleTargetSchema: () => bundleTargetSchema,
42
- cacheStatsSchema: () => cacheStatsSchema,
43
- cdnDependencySchema: () => cdnDependencySchema,
44
- cdnPlatformTypeSchema: () => cdnPlatformTypeSchema,
45
- cdnProviderConfigSchema: () => cdnProviderConfigSchema,
46
- cdnProviderSchema: () => cdnProviderSchema,
47
- cdnRegistryEntrySchema: () => cdnRegistryEntrySchema,
48
- clearHandlebarsCache: () => clearHandlebarsCache,
49
- clearUrlCache: () => clearUrlCache,
50
- componentBuildManifestSchema: () => componentBuildManifestSchema,
51
- createClaudeResolver: () => createClaudeResolver,
52
- createImportMap: () => createImportMap,
53
- createImportMapFromOverrides: () => createImportMapFromOverrides,
54
- createOpenAIResolver: () => createOpenAIResolver,
55
- createResolver: () => createResolver,
56
- dependencyResolverOptionsSchema: () => dependencyResolverOptionsSchema,
57
- detectFormatFromPath: () => detectFormatFromPath,
58
- detectFormatFromUrl: () => detectFormatFromUrl,
59
- detectTemplateMode: () => detectTemplateMode,
60
- detectTemplateSource: () => detectTemplateSource,
61
- extractExternalPackages: () => extractExternalPackages,
62
- fetchTemplateFromUrl: () => fetchTemplateFromUrl,
63
- fileBundleOptionsSchema: () => fileBundleOptionsSchema,
64
- fileTemplateConfigSchema: () => fileTemplateConfigSchema,
65
- filterImportsByPackages: () => filterImportsByPackages,
66
- generateCDNScriptTags: () => generateCDNScriptTags,
67
- generateDependencyHTML: () => generateDependencyHTML,
68
- generateESMScriptTags: () => generateESMScriptTags,
69
- generateImportMapForPackages: () => generateImportMapForPackages,
70
- generateImportMapScriptTag: () => generateImportMapScriptTag,
71
- generateImportMapScriptTagMinified: () => generateImportMapScriptTagMinified,
72
- generateUMDShim: () => generateUMDShim,
73
- getImportStats: () => getImportStats,
74
- getPackageCDNDependency: () => getPackageCDNDependency,
75
- getPackageCDNUrl: () => getPackageCDNUrl,
76
- getPackageName: () => getPackageName,
77
- getPackagePeerDependencies: () => getPackagePeerDependencies,
78
- getRegisteredPackages: () => getRegisteredPackages,
79
- getUrlCache: () => getUrlCache,
80
- importMapSchema: () => importMapSchema,
81
- importTypeSchema: () => importTypeSchema,
82
- invalidateUrlCache: () => invalidateUrlCache,
83
- isFileBasedTemplate: () => isFileBasedTemplate,
84
- isMarkedAvailable: () => isMarkedAvailable,
85
- isPackageRegistered: () => isPackageRegistered,
86
- lookupPackage: () => lookupPackage,
87
- mergeImportMaps: () => mergeImportMaps,
88
- mergeRegistries: () => mergeRegistries,
89
- needsRefetch: () => needsRefetch,
90
- packageMetadataSchema: () => packageMetadataSchema,
91
- parseImports: () => parseImports,
92
- parsedImportResultSchema: () => parsedImportResultSchema,
93
- parsedImportSchema: () => parsedImportSchema,
94
- processHtmlTemplate: () => processHtmlTemplate,
95
- processMarkdownTemplate: () => processMarkdownTemplate,
96
- processMdxTemplate: () => processMdxTemplate,
97
- processTemplate: () => processTemplate,
98
- processTemplates: () => processTemplates,
99
- producesHtml: () => producesHtml,
100
- readTemplateFromFile: () => readTemplateFromFile,
101
- requiresBundling: () => requiresBundling,
102
- resolveAllDependencies: () => resolveAllDependencies,
103
- resolveDependencies: () => resolveDependencies,
104
- resolveFilePath: () => resolveFilePath,
105
- resolveTemplate: () => resolveTemplate,
106
- resolvedDependencySchema: () => resolvedDependencySchema,
107
- safeParseBuildManifest: () => safeParseBuildManifest,
108
- safeParseCDNDependency: () => safeParseCDNDependency,
109
- safeParseFileTemplateConfig: () => safeParseFileTemplateConfig,
110
- supportsHandlebars: () => supportsHandlebars,
111
- validateBuildManifest: () => validateBuildManifest,
112
- validateCDNDependency: () => validateCDNDependency,
113
- validateFileTemplateConfig: () => validateFileTemplateConfig,
114
- validateImportMap: () => validateImportMap,
115
- validateTemplateUrl: () => validateTemplateUrl
116
- });
117
- module.exports = __toCommonJS(dependency_exports);
118
-
119
- // libs/uipack/src/dependency/types.ts
120
- function detectTemplateMode(template) {
121
- if (typeof template === "function") {
122
- return "inline-function";
123
- }
124
- if (typeof template === "string") {
125
- if (template.startsWith("http://") || template.startsWith("https://")) {
126
- return "url";
127
- }
128
- const looksLikeFilePath = (
129
- // Relative paths
130
- template.startsWith("./") || template.startsWith("../") || // Absolute paths (Unix)
131
- template.startsWith("/") || // Windows-style paths (C:\, D:\, etc.)
132
- /^[A-Za-z]:\\/.test(template) || // File extensions (must not contain spaces to avoid false positives)
133
- /\.(tsx?|jsx?|mdx?)$/i.test(template) && !template.includes(" ")
134
- );
135
- if (looksLikeFilePath && template.length < 500 && !template.includes("\n") && !template.includes("<")) {
136
- return "file-path";
137
- }
138
- }
139
- return "inline-string";
140
- }
141
- function detectFormatFromPath(pathOrUrl) {
142
- const lower = pathOrUrl.toLowerCase();
143
- if (lower.endsWith(".tsx") || lower.endsWith(".jsx")) {
144
- return "react";
145
- }
146
- if (lower.endsWith(".mdx")) {
147
- return "mdx";
148
- }
149
- if (lower.endsWith(".md")) {
150
- return "markdown";
151
- }
152
- return "html";
153
- }
154
-
155
- // libs/uipack/src/dependency/schemas.ts
156
- var import_zod = require("zod");
157
- var cdnProviderSchema = import_zod.z.enum(["cloudflare", "jsdelivr", "unpkg", "esm.sh", "skypack"]);
158
- var cdnPlatformTypeSchema = import_zod.z.enum(["claude", "openai", "cursor", "gemini", "continue", "cody", "unknown"]);
159
- var cdnDependencySchema = import_zod.z.object({
160
- /**
161
- * CDN URL (must be HTTPS).
162
- */
163
- url: import_zod.z.string().url().refine((url) => url.startsWith("https://"), {
164
- message: "CDN URLs must use HTTPS"
165
- }),
166
- /**
167
- * SRI integrity hash.
168
- */
169
- integrity: import_zod.z.string().regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/, {
170
- message: "Invalid SRI hash format. Must be sha256-, sha384-, or sha512- followed by base64"
171
- }).optional(),
172
- /**
173
- * Global variable name for UMD builds.
174
- */
175
- global: import_zod.z.string().min(1).optional(),
176
- /**
177
- * Named exports from the library.
178
- */
179
- exports: import_zod.z.array(import_zod.z.string().min(1)).optional(),
180
- /**
181
- * Whether this is an ES module.
182
- */
183
- esm: import_zod.z.boolean().optional(),
184
- /**
185
- * Cross-origin attribute.
186
- */
187
- crossorigin: import_zod.z.enum(["anonymous", "use-credentials"]).optional(),
188
- /**
189
- * Peer dependencies (npm package names).
190
- */
191
- peerDependencies: import_zod.z.array(import_zod.z.string().min(1)).optional()
192
- }).strict();
193
- var bundleTargetSchema = import_zod.z.enum(["es2018", "es2019", "es2020", "es2021", "es2022", "esnext"]);
194
- var fileBundleOptionsSchema = import_zod.z.object({
195
- /**
196
- * Minify output.
197
- */
198
- minify: import_zod.z.boolean().optional(),
199
- /**
200
- * Generate source maps.
201
- */
202
- sourceMaps: import_zod.z.boolean().optional(),
203
- /**
204
- * Target JavaScript version.
205
- */
206
- target: bundleTargetSchema.optional(),
207
- /**
208
- * Enable tree shaking.
209
- */
210
- treeShake: import_zod.z.boolean().optional(),
211
- /**
212
- * JSX factory function.
213
- */
214
- jsxFactory: import_zod.z.string().min(1).optional(),
215
- /**
216
- * JSX fragment factory.
217
- */
218
- jsxFragment: import_zod.z.string().min(1).optional(),
219
- /**
220
- * JSX import source.
221
- */
222
- jsxImportSource: import_zod.z.string().min(1).optional()
223
- }).strict();
224
- var fileTemplateConfigSchema = import_zod.z.object({
225
- /**
226
- * Packages to load from CDN.
227
- */
228
- externals: import_zod.z.array(import_zod.z.string().min(1)).optional(),
229
- /**
230
- * Explicit CDN dependency overrides.
231
- */
232
- dependencies: import_zod.z.record(import_zod.z.string().min(1), cdnDependencySchema).optional(),
233
- /**
234
- * Bundle options.
235
- */
236
- bundleOptions: fileBundleOptionsSchema.optional()
237
- }).strict();
238
- var importMapSchema = import_zod.z.object({
239
- /**
240
- * Module specifier to URL mappings.
241
- */
242
- imports: import_zod.z.record(
243
- import_zod.z.string().min(1),
244
- import_zod.z.string().url().refine((url) => url.startsWith("https://"), {
245
- message: "Import map URLs must use HTTPS"
246
- })
247
- ),
248
- /**
249
- * Scoped mappings.
250
- */
251
- scopes: import_zod.z.record(
252
- import_zod.z.string().min(1),
253
- import_zod.z.record(
254
- import_zod.z.string().min(1),
255
- import_zod.z.string().url().refine((url) => url.startsWith("https://"), {
256
- message: "Scoped import URLs must use HTTPS"
257
- })
258
- )
259
- ).optional(),
260
- /**
261
- * Integrity hashes.
262
- */
263
- integrity: import_zod.z.record(import_zod.z.string().url(), import_zod.z.string().regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/)).optional()
264
- }).strict();
265
- var resolvedDependencySchema = import_zod.z.object({
266
- packageName: import_zod.z.string().min(1),
267
- version: import_zod.z.string().min(1),
268
- cdnUrl: import_zod.z.string().url(),
269
- integrity: import_zod.z.string().optional(),
270
- global: import_zod.z.string().optional(),
271
- esm: import_zod.z.boolean(),
272
- provider: cdnProviderSchema
273
- }).strict();
274
- var buildManifestMetadataSchema = import_zod.z.object({
275
- createdAt: import_zod.z.string().datetime(),
276
- buildTimeMs: import_zod.z.number().nonnegative(),
277
- totalSize: import_zod.z.number().nonnegative(),
278
- bundlerVersion: import_zod.z.string().optional()
279
- }).strict();
280
- var buildManifestOutputsSchema = import_zod.z.object({
281
- code: import_zod.z.string(),
282
- sourceMap: import_zod.z.string().optional(),
283
- ssrHtml: import_zod.z.string().optional()
284
- }).strict();
285
- var componentBuildManifestSchema = import_zod.z.object({
286
- version: import_zod.z.literal("1.0"),
287
- buildId: import_zod.z.string().uuid(),
288
- toolName: import_zod.z.string().min(1),
289
- entryPath: import_zod.z.string().min(1),
290
- contentHash: import_zod.z.string().regex(/^[a-f0-9]{64}$/, {
291
- message: "Content hash must be a 64-character SHA-256 hex string"
292
- }),
293
- dependencies: import_zod.z.array(resolvedDependencySchema),
294
- outputs: buildManifestOutputsSchema,
295
- importMap: importMapSchema,
296
- metadata: buildManifestMetadataSchema
297
- }).strict();
298
- var cdnProviderConfigSchema = import_zod.z.record(cdnProviderSchema, cdnDependencySchema);
299
- var packageMetadataSchema = import_zod.z.object({
300
- description: import_zod.z.string().optional(),
301
- homepage: import_zod.z.string().url().optional(),
302
- license: import_zod.z.string().optional()
303
- }).strict();
304
- var cdnRegistryEntrySchema = import_zod.z.object({
305
- packageName: import_zod.z.string().min(1),
306
- defaultVersion: import_zod.z.string().min(1),
307
- providers: cdnProviderConfigSchema,
308
- preferredProviders: import_zod.z.array(cdnProviderSchema).optional(),
309
- metadata: packageMetadataSchema.optional()
310
- }).strict();
311
- var dependencyResolverOptionsSchema = import_zod.z.object({
312
- platform: cdnPlatformTypeSchema.optional(),
313
- preferredProviders: import_zod.z.array(cdnProviderSchema).optional(),
314
- customRegistry: import_zod.z.record(import_zod.z.string().min(1), cdnRegistryEntrySchema).optional(),
315
- strictMode: import_zod.z.boolean().optional(),
316
- requireIntegrity: import_zod.z.boolean().optional()
317
- }).strict();
318
- var importTypeSchema = import_zod.z.enum(["named", "default", "namespace", "side-effect", "dynamic"]);
319
- var parsedImportSchema = import_zod.z.object({
320
- statement: import_zod.z.string(),
321
- specifier: import_zod.z.string().min(1),
322
- type: importTypeSchema,
323
- namedImports: import_zod.z.array(import_zod.z.string().min(1)).optional(),
324
- defaultImport: import_zod.z.string().min(1).optional(),
325
- namespaceImport: import_zod.z.string().min(1).optional(),
326
- line: import_zod.z.number().int().positive(),
327
- column: import_zod.z.number().int().nonnegative()
328
- }).strict();
329
- var parsedImportResultSchema = import_zod.z.object({
330
- imports: import_zod.z.array(parsedImportSchema),
331
- externalImports: import_zod.z.array(parsedImportSchema),
332
- relativeImports: import_zod.z.array(parsedImportSchema),
333
- externalPackages: import_zod.z.array(import_zod.z.string().min(1))
334
- }).strict();
335
- var cacheStatsSchema = import_zod.z.object({
336
- entries: import_zod.z.number().int().nonnegative(),
337
- totalSize: import_zod.z.number().nonnegative(),
338
- hits: import_zod.z.number().int().nonnegative(),
339
- misses: import_zod.z.number().int().nonnegative(),
340
- hitRate: import_zod.z.number().min(0).max(1)
341
- }).strict();
342
- function validateCDNDependency(data) {
343
- return cdnDependencySchema.parse(data);
344
- }
345
- function safeParseCDNDependency(data) {
346
- return cdnDependencySchema.safeParse(data);
347
- }
348
- function validateFileTemplateConfig(data) {
349
- return fileTemplateConfigSchema.parse(data);
350
- }
351
- function safeParseFileTemplateConfig(data) {
352
- return fileTemplateConfigSchema.safeParse(data);
353
- }
354
- function validateBuildManifest(data) {
355
- return componentBuildManifestSchema.parse(data);
356
- }
357
- function safeParseBuildManifest(data) {
358
- return componentBuildManifestSchema.safeParse(data);
359
- }
360
-
361
- // libs/uipack/src/dependency/cdn-registry.ts
362
- var DEFAULT_CDN_REGISTRY = {
363
- // ============================================
364
- // React Ecosystem
365
- // ============================================
366
- react: {
367
- packageName: "react",
368
- defaultVersion: "18.3.1",
369
- providers: {
370
- cloudflare: {
371
- url: "https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js",
372
- integrity: "sha512-Qp8J4Xr8LBZ5CXNJQc/HmLqFrpXz6lNkbzMYkYHKzQx5p1q1yOqPQHntXKoYgPPE/n9m0QF1OkJdXa2ePpO4fw==",
373
- global: "React",
374
- crossorigin: "anonymous"
375
- },
376
- jsdelivr: {
377
- url: "https://cdn.jsdelivr.net/npm/react@18.3.1/umd/react.production.min.js",
378
- global: "React",
379
- crossorigin: "anonymous"
380
- },
381
- unpkg: {
382
- url: "https://unpkg.com/react@18.3.1/umd/react.production.min.js",
383
- global: "React",
384
- crossorigin: "anonymous"
385
- },
386
- "esm.sh": {
387
- url: "https://esm.sh/react@18.3.1",
388
- esm: true,
389
- crossorigin: "anonymous"
390
- }
391
- },
392
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg", "esm.sh"],
393
- metadata: {
394
- description: "A JavaScript library for building user interfaces",
395
- homepage: "https://react.dev",
396
- license: "MIT"
397
- }
398
- },
399
- "react-dom": {
400
- packageName: "react-dom",
401
- defaultVersion: "18.3.1",
402
- providers: {
403
- cloudflare: {
404
- url: "https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js",
405
- integrity: "sha512-6s2gVRdS3aT+FDdZTRJSzKlzIPqDXWyYl/5hPQb6hSgzKPGFcQyZhbqjbWVxGrs2dYNrINFXb0k0UD3d+CKPJA==",
406
- global: "ReactDOM",
407
- crossorigin: "anonymous",
408
- peerDependencies: ["react"]
409
- },
410
- jsdelivr: {
411
- url: "https://cdn.jsdelivr.net/npm/react-dom@18.3.1/umd/react-dom.production.min.js",
412
- global: "ReactDOM",
413
- crossorigin: "anonymous",
414
- peerDependencies: ["react"]
415
- },
416
- unpkg: {
417
- url: "https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js",
418
- global: "ReactDOM",
419
- crossorigin: "anonymous",
420
- peerDependencies: ["react"]
421
- },
422
- "esm.sh": {
423
- url: "https://esm.sh/react-dom@18.3.1",
424
- esm: true,
425
- crossorigin: "anonymous",
426
- peerDependencies: ["react"]
427
- }
428
- },
429
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg", "esm.sh"],
430
- metadata: {
431
- description: "React package for working with the DOM",
432
- homepage: "https://react.dev",
433
- license: "MIT"
434
- }
435
- },
436
- // ============================================
437
- // Charting Libraries
438
- // ============================================
439
- "chart.js": {
440
- packageName: "chart.js",
441
- defaultVersion: "4.4.7",
442
- providers: {
443
- cloudflare: {
444
- url: "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.7/chart.umd.min.js",
445
- integrity: "sha512-dMDjIoZjJD6gs0KPBhFYjLQrH3kIohSEn6HzWs6Y6GiO0+L9kk/bM3cR5KNEDK1KvMNpTIZG6pHK9SZfCJHRpQ==",
446
- global: "Chart",
447
- crossorigin: "anonymous"
448
- },
449
- jsdelivr: {
450
- url: "https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js",
451
- global: "Chart",
452
- crossorigin: "anonymous"
453
- },
454
- unpkg: {
455
- url: "https://unpkg.com/chart.js@4.4.7/dist/chart.umd.min.js",
456
- global: "Chart",
457
- crossorigin: "anonymous"
458
- }
459
- },
460
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg"],
461
- metadata: {
462
- description: "Simple yet flexible JavaScript charting library",
463
- homepage: "https://www.chartjs.org",
464
- license: "MIT"
465
- }
466
- },
467
- "react-chartjs-2": {
468
- packageName: "react-chartjs-2",
469
- defaultVersion: "5.3.0",
470
- providers: {
471
- cloudflare: {
472
- url: "https://cdnjs.cloudflare.com/ajax/libs/react-chartjs-2/5.3.0/react-chartjs-2.min.js",
473
- global: "ReactChartjs2",
474
- crossorigin: "anonymous",
475
- peerDependencies: ["react", "chart.js"]
476
- },
477
- jsdelivr: {
478
- url: "https://cdn.jsdelivr.net/npm/react-chartjs-2@5.3.0/dist/index.umd.js",
479
- global: "ReactChartjs2",
480
- crossorigin: "anonymous",
481
- peerDependencies: ["react", "chart.js"]
482
- },
483
- "esm.sh": {
484
- url: "https://esm.sh/react-chartjs-2@5.3.0",
485
- esm: true,
486
- crossorigin: "anonymous",
487
- peerDependencies: ["react", "chart.js"]
488
- }
489
- },
490
- preferredProviders: ["cloudflare", "jsdelivr", "esm.sh"],
491
- metadata: {
492
- description: "React components for Chart.js",
493
- homepage: "https://react-chartjs-2.js.org",
494
- license: "MIT"
495
- }
496
- },
497
- // ============================================
498
- // D3.js
499
- // ============================================
500
- d3: {
501
- packageName: "d3",
502
- defaultVersion: "7.9.0",
503
- providers: {
504
- cloudflare: {
505
- url: "https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js",
506
- integrity: "sha512-vc58qvvBdrDR4etbxMdlTt4GBQk1qjvyORR2nrsPsFPyrs+/u5c3+1Ct6upOgdZoIl7eq6k3a1UPDSNAQi/32A==",
507
- global: "d3",
508
- crossorigin: "anonymous"
509
- },
510
- jsdelivr: {
511
- url: "https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js",
512
- global: "d3",
513
- crossorigin: "anonymous"
514
- },
515
- unpkg: {
516
- url: "https://unpkg.com/d3@7.9.0/dist/d3.min.js",
517
- global: "d3",
518
- crossorigin: "anonymous"
519
- }
520
- },
521
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg"],
522
- metadata: {
523
- description: "Data-Driven Documents",
524
- homepage: "https://d3js.org",
525
- license: "ISC"
526
- }
527
- },
528
- // ============================================
529
- // Utility Libraries
530
- // ============================================
531
- lodash: {
532
- packageName: "lodash",
533
- defaultVersion: "4.17.21",
534
- providers: {
535
- cloudflare: {
536
- url: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js",
537
- integrity: "sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==",
538
- global: "_",
539
- crossorigin: "anonymous"
540
- },
541
- jsdelivr: {
542
- url: "https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js",
543
- global: "_",
544
- crossorigin: "anonymous"
545
- },
546
- unpkg: {
547
- url: "https://unpkg.com/lodash@4.17.21/lodash.min.js",
548
- global: "_",
549
- crossorigin: "anonymous"
550
- }
551
- },
552
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg"],
553
- metadata: {
554
- description: "A modern JavaScript utility library",
555
- homepage: "https://lodash.com",
556
- license: "MIT"
557
- }
558
- },
559
- "lodash-es": {
560
- packageName: "lodash-es",
561
- defaultVersion: "4.17.21",
562
- providers: {
563
- "esm.sh": {
564
- url: "https://esm.sh/lodash-es@4.17.21",
565
- esm: true,
566
- crossorigin: "anonymous"
567
- },
568
- jsdelivr: {
569
- url: "https://cdn.jsdelivr.net/npm/lodash-es@4.17.21/+esm",
570
- esm: true,
571
- crossorigin: "anonymous"
572
- }
573
- },
574
- preferredProviders: ["esm.sh", "jsdelivr"],
575
- metadata: {
576
- description: "Lodash exported as ES modules",
577
- homepage: "https://lodash.com",
578
- license: "MIT"
579
- }
580
- },
581
- dayjs: {
582
- packageName: "dayjs",
583
- defaultVersion: "1.11.13",
584
- providers: {
585
- cloudflare: {
586
- url: "https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.13/dayjs.min.js",
587
- integrity: "sha512-Ot7ArUEhJDU0cwoBNNnWe487kjL5wAOsIYig8llY/l0P2TUFwgsAHVmrZMHsT8NGo+HwkjTJsNErS6QqIkBxDw==",
588
- global: "dayjs",
589
- crossorigin: "anonymous"
590
- },
591
- jsdelivr: {
592
- url: "https://cdn.jsdelivr.net/npm/dayjs@1.11.13/dayjs.min.js",
593
- global: "dayjs",
594
- crossorigin: "anonymous"
595
- },
596
- unpkg: {
597
- url: "https://unpkg.com/dayjs@1.11.13/dayjs.min.js",
598
- global: "dayjs",
599
- crossorigin: "anonymous"
600
- }
601
- },
602
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg"],
603
- metadata: {
604
- description: "Fast 2kB alternative to Moment.js with the same modern API",
605
- homepage: "https://day.js.org",
606
- license: "MIT"
607
- }
608
- },
609
- "date-fns": {
610
- packageName: "date-fns",
611
- defaultVersion: "4.1.0",
612
- providers: {
613
- "esm.sh": {
614
- url: "https://esm.sh/date-fns@4.1.0",
615
- esm: true,
616
- crossorigin: "anonymous"
617
- },
618
- jsdelivr: {
619
- url: "https://cdn.jsdelivr.net/npm/date-fns@4.1.0/+esm",
620
- esm: true,
621
- crossorigin: "anonymous"
622
- }
623
- },
624
- preferredProviders: ["esm.sh", "jsdelivr"],
625
- metadata: {
626
- description: "Modern JavaScript date utility library",
627
- homepage: "https://date-fns.org",
628
- license: "MIT"
629
- }
630
- },
631
- // ============================================
632
- // Animation Libraries
633
- // ============================================
634
- "framer-motion": {
635
- packageName: "framer-motion",
636
- defaultVersion: "11.15.0",
637
- providers: {
638
- "esm.sh": {
639
- url: "https://esm.sh/framer-motion@11.15.0",
640
- esm: true,
641
- crossorigin: "anonymous",
642
- peerDependencies: ["react", "react-dom"]
643
- },
644
- jsdelivr: {
645
- url: "https://cdn.jsdelivr.net/npm/framer-motion@11.15.0/dist/framer-motion.js",
646
- global: "Motion",
647
- crossorigin: "anonymous",
648
- peerDependencies: ["react", "react-dom"]
649
- }
650
- },
651
- preferredProviders: ["esm.sh", "jsdelivr"],
652
- metadata: {
653
- description: "Production-ready motion library for React",
654
- homepage: "https://www.framer.com/motion/",
655
- license: "MIT"
656
- }
657
- },
658
- // ============================================
659
- // UI Component Libraries
660
- // ============================================
661
- "lucide-react": {
662
- packageName: "lucide-react",
663
- defaultVersion: "0.468.0",
664
- providers: {
665
- "esm.sh": {
666
- url: "https://esm.sh/lucide-react@0.468.0",
667
- esm: true,
668
- crossorigin: "anonymous",
669
- peerDependencies: ["react"]
670
- },
671
- jsdelivr: {
672
- url: "https://cdn.jsdelivr.net/npm/lucide-react@0.468.0/dist/esm/lucide-react.js",
673
- esm: true,
674
- crossorigin: "anonymous",
675
- peerDependencies: ["react"]
676
- }
677
- },
678
- preferredProviders: ["esm.sh", "jsdelivr"],
679
- metadata: {
680
- description: "Beautiful & consistent icon toolkit for React",
681
- homepage: "https://lucide.dev",
682
- license: "ISC"
683
- }
684
- },
685
- // ============================================
686
- // Markdown/Syntax Highlighting
687
- // ============================================
688
- marked: {
689
- packageName: "marked",
690
- defaultVersion: "15.0.4",
691
- providers: {
692
- cloudflare: {
693
- url: "https://cdnjs.cloudflare.com/ajax/libs/marked/15.0.4/marked.min.js",
694
- integrity: "sha512-Rn/d0sGeizGbk3VJEiYNDt/mMcfuzYoFkia3iBffv+HX8VUrHMo/0cKjZuxWGoZLPh/VxUcC9ais+RBFZW9EBg==",
695
- global: "marked",
696
- crossorigin: "anonymous"
697
- },
698
- jsdelivr: {
699
- url: "https://cdn.jsdelivr.net/npm/marked@15.0.4/marked.min.js",
700
- global: "marked",
701
- crossorigin: "anonymous"
702
- },
703
- unpkg: {
704
- url: "https://unpkg.com/marked@15.0.4/marked.min.js",
705
- global: "marked",
706
- crossorigin: "anonymous"
707
- }
708
- },
709
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg"],
710
- metadata: {
711
- description: "A markdown parser and compiler",
712
- homepage: "https://marked.js.org",
713
- license: "MIT"
714
- }
715
- },
716
- "highlight.js": {
717
- packageName: "highlight.js",
718
- defaultVersion: "11.10.0",
719
- providers: {
720
- cloudflare: {
721
- url: "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.10.0/highlight.min.js",
722
- integrity: "sha512-6yoqbrcLAHDWAdQmiRlHG4+m0g/CT/V9AGyxabG8j7Jk8j3v3k6mIP1iN/PvSofcWet2tf8SRn/j3L/+pb7LRQ==",
723
- global: "hljs",
724
- crossorigin: "anonymous"
725
- },
726
- jsdelivr: {
727
- url: "https://cdn.jsdelivr.net/npm/highlight.js@11.10.0/lib/core.min.js",
728
- global: "hljs",
729
- crossorigin: "anonymous"
730
- },
731
- unpkg: {
732
- url: "https://unpkg.com/highlight.js@11.10.0/lib/core.min.js",
733
- global: "hljs",
734
- crossorigin: "anonymous"
735
- }
736
- },
737
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg"],
738
- metadata: {
739
- description: "Syntax highlighting for the web",
740
- homepage: "https://highlightjs.org",
741
- license: "BSD-3-Clause"
742
- }
743
- },
744
- // ============================================
745
- // Interactive Libraries
746
- // ============================================
747
- "htmx.org": {
748
- packageName: "htmx.org",
749
- defaultVersion: "2.0.4",
750
- providers: {
751
- cloudflare: {
752
- url: "https://cdnjs.cloudflare.com/ajax/libs/htmx/2.0.4/htmx.min.js",
753
- integrity: "sha512-2kIcAizYXhIn5IyXrMC72f2nh0JAtESHRpOieVw5dYPYeHwLCC2eKCqvdZDYRSEgasKrPpEPpRFjL8gqwBZWAA==",
754
- global: "htmx",
755
- crossorigin: "anonymous"
756
- },
757
- jsdelivr: {
758
- url: "https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js",
759
- global: "htmx",
760
- crossorigin: "anonymous"
761
- },
762
- unpkg: {
763
- url: "https://unpkg.com/htmx.org@2.0.4/dist/htmx.min.js",
764
- global: "htmx",
765
- crossorigin: "anonymous"
766
- }
767
- },
768
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg"],
769
- metadata: {
770
- description: "High power tools for HTML",
771
- homepage: "https://htmx.org",
772
- license: "BSD-2-Clause"
773
- }
774
- },
775
- alpinejs: {
776
- packageName: "alpinejs",
777
- defaultVersion: "3.14.3",
778
- providers: {
779
- cloudflare: {
780
- url: "https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.14.3/cdn.min.js",
781
- integrity: "sha512-lrQ8FHgsWKFSuQFq8NKPJicjlvJFEIrCqEj8zeX7ZOUlHWltN/Iow4jND+x84jqTdDf9n+hvQpJjGDvOl/eDRA==",
782
- global: "Alpine",
783
- crossorigin: "anonymous"
784
- },
785
- jsdelivr: {
786
- url: "https://cdn.jsdelivr.net/npm/alpinejs@3.14.3/dist/cdn.min.js",
787
- global: "Alpine",
788
- crossorigin: "anonymous"
789
- },
790
- unpkg: {
791
- url: "https://unpkg.com/alpinejs@3.14.3/dist/cdn.min.js",
792
- global: "Alpine",
793
- crossorigin: "anonymous"
794
- }
795
- },
796
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg"],
797
- metadata: {
798
- description: "A rugged, minimal framework for composing behavior directly in your markup",
799
- homepage: "https://alpinejs.dev",
800
- license: "MIT"
801
- }
802
- },
803
- // ============================================
804
- // Templating Libraries
805
- // ============================================
806
- handlebars: {
807
- packageName: "handlebars",
808
- defaultVersion: "4.7.8",
809
- providers: {
810
- cloudflare: {
811
- url: "https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.8/handlebars.min.js",
812
- integrity: "sha512-E1dSFxg+wsfJ4HKjutk/WaCzK7S2wv1POn1RRPGh8ZK+ag9l244Vqxji3r6wgz9YBf6+vhQEYJZpSjqWFPg9gg==",
813
- global: "Handlebars",
814
- crossorigin: "anonymous"
815
- },
816
- jsdelivr: {
817
- url: "https://cdn.jsdelivr.net/npm/handlebars@4.7.8/dist/handlebars.min.js",
818
- global: "Handlebars",
819
- crossorigin: "anonymous"
820
- },
821
- unpkg: {
822
- url: "https://unpkg.com/handlebars@4.7.8/dist/handlebars.min.js",
823
- global: "Handlebars",
824
- crossorigin: "anonymous"
825
- }
826
- },
827
- preferredProviders: ["cloudflare", "jsdelivr", "unpkg"],
828
- metadata: {
829
- description: "Minimal templating on steroids",
830
- homepage: "https://handlebarsjs.com",
831
- license: "MIT"
832
- }
833
- }
834
- };
835
- var CDN_PROVIDER_PRIORITY = {
836
- claude: ["cloudflare"],
837
- // ONLY cloudflare for Claude
838
- openai: ["cloudflare", "jsdelivr", "unpkg", "esm.sh"],
839
- cursor: ["cloudflare", "jsdelivr", "unpkg", "esm.sh"],
840
- gemini: ["cloudflare", "jsdelivr", "unpkg", "esm.sh"],
841
- continue: ["cloudflare", "jsdelivr", "unpkg", "esm.sh"],
842
- cody: ["cloudflare", "jsdelivr", "unpkg", "esm.sh"],
843
- unknown: ["cloudflare", "jsdelivr", "unpkg", "esm.sh"]
844
- // Default to cloudflare first
845
- };
846
- function lookupPackage(packageName, registry = DEFAULT_CDN_REGISTRY) {
847
- return registry[packageName];
848
- }
849
- function getPackageCDNUrl(packageName, platform = "unknown", registry = DEFAULT_CDN_REGISTRY) {
850
- const entry = lookupPackage(packageName, registry);
851
- if (!entry) return void 0;
852
- const providerPriority = CDN_PROVIDER_PRIORITY[platform];
853
- for (const provider of providerPriority) {
854
- const config = entry.providers[provider];
855
- if (config?.url) {
856
- return config.url;
857
- }
858
- }
859
- for (const provider of Object.keys(entry.providers)) {
860
- const config = entry.providers[provider];
861
- if (config?.url) {
862
- return config.url;
863
- }
864
- }
865
- return void 0;
866
- }
867
- function getPackageCDNDependency(packageName, platform = "unknown", registry = DEFAULT_CDN_REGISTRY) {
868
- const entry = lookupPackage(packageName, registry);
869
- if (!entry) return void 0;
870
- const providerPriority = CDN_PROVIDER_PRIORITY[platform];
871
- for (const provider of providerPriority) {
872
- const config = entry.providers[provider];
873
- if (config?.url) {
874
- return { provider, dependency: config };
875
- }
876
- }
877
- for (const provider of Object.keys(entry.providers)) {
878
- const config = entry.providers[provider];
879
- if (config?.url) {
880
- return { provider, dependency: config };
881
- }
882
- }
883
- return void 0;
884
- }
885
- function getRegisteredPackages(registry = DEFAULT_CDN_REGISTRY) {
886
- return Object.keys(registry);
887
- }
888
- function isPackageRegistered(packageName, registry = DEFAULT_CDN_REGISTRY) {
889
- return packageName in registry;
890
- }
891
- function mergeRegistries(customRegistry) {
892
- return {
893
- ...DEFAULT_CDN_REGISTRY,
894
- ...customRegistry
895
- };
896
- }
897
- function getPackagePeerDependencies(packageName, registry = DEFAULT_CDN_REGISTRY) {
898
- const entry = lookupPackage(packageName, registry);
899
- if (!entry) return [];
900
- for (const provider of Object.keys(entry.providers)) {
901
- const config = entry.providers[provider];
902
- if (config?.peerDependencies) {
903
- return config.peerDependencies;
904
- }
905
- }
906
- return [];
907
- }
908
- function resolveAllDependencies(packageNames, _platform = "unknown", registry = DEFAULT_CDN_REGISTRY) {
909
- const resolved = /* @__PURE__ */ new Set();
910
- const queue = [...packageNames];
911
- while (queue.length > 0) {
912
- const packageName = queue.shift();
913
- if (!packageName) continue;
914
- if (resolved.has(packageName)) continue;
915
- resolved.add(packageName);
916
- const peers = getPackagePeerDependencies(packageName, registry);
917
- for (const peer of peers) {
918
- if (!resolved.has(peer)) {
919
- queue.push(peer);
920
- }
921
- }
922
- }
923
- const result = [];
924
- const remaining = new Set(resolved);
925
- while (remaining.size > 0) {
926
- let added = false;
927
- for (const pkg of remaining) {
928
- const peers = getPackagePeerDependencies(pkg, registry);
929
- const allPeersResolved = peers.every((peer) => !remaining.has(peer) || result.includes(peer));
930
- if (allPeersResolved) {
931
- if (!result.includes(pkg)) {
932
- result.push(pkg);
933
- }
934
- remaining.delete(pkg);
935
- added = true;
936
- }
937
- }
938
- if (!added && remaining.size > 0) {
939
- const next = remaining.values().next().value;
940
- if (next !== void 0) {
941
- if (!result.includes(next)) {
942
- result.push(next);
943
- }
944
- remaining.delete(next);
945
- }
946
- }
947
- }
948
- return result;
949
- }
950
-
951
- // libs/uipack/src/dependency/import-parser.ts
952
- var IMPORT_PATTERNS = {
953
- /**
954
- * Named imports: import { foo, bar } from 'module'
955
- * Also handles renamed imports: import { foo as f } from 'module'
956
- */
957
- named: /import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,
958
- /**
959
- * Default imports: import foo from 'module'
960
- */
961
- default: /import\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
962
- /**
963
- * Namespace imports: import * as foo from 'module'
964
- */
965
- namespace: /import\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
966
- /**
967
- * Side-effect imports: import 'module'
968
- */
969
- sideEffect: /import\s*['"]([^'"]+)['"]/g,
970
- /**
971
- * Dynamic imports: import('module') or await import('module')
972
- */
973
- dynamic: /(?:await\s+)?import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
974
- /**
975
- * Combined default and named: import foo, { bar } from 'module'
976
- */
977
- defaultAndNamed: /import\s+(\w+)\s*,\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,
978
- /**
979
- * Combined default and namespace: import foo, * as bar from 'module'
980
- */
981
- defaultAndNamespace: /import\s+(\w+)\s*,\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
982
- /**
983
- * Re-exports: export { foo } from 'module'
984
- */
985
- reExport: /export\s*\{[^}]+\}\s*from\s*['"]([^'"]+)['"]/g,
986
- /**
987
- * Re-export all: export * from 'module'
988
- */
989
- reExportAll: /export\s*\*\s*from\s*['"]([^'"]+)['"]/g
990
- };
991
- function parseNamedImports(namedString) {
992
- return namedString.split(",").map((s) => s.trim()).filter((s) => s.length > 0).map((s) => {
993
- const asMatch = s.match(/^(\w+)\s+as\s+\w+$/);
994
- return asMatch ? asMatch[1] : s;
995
- });
996
- }
997
- function isRelativeImport(specifier) {
998
- return specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/");
999
- }
1000
- function isExternalImport(specifier) {
1001
- return !isRelativeImport(specifier) && !specifier.startsWith("#");
1002
- }
1003
- function getPackageName(specifier) {
1004
- if (specifier.startsWith("@")) {
1005
- const parts = specifier.split("/");
1006
- if (parts.length >= 2) {
1007
- return `${parts[0]}/${parts[1]}`;
1008
- }
1009
- return specifier;
1010
- }
1011
- const firstSlash = specifier.indexOf("/");
1012
- return firstSlash === -1 ? specifier : specifier.slice(0, firstSlash);
1013
- }
1014
- function getLineNumber(source, index) {
1015
- let line = 1;
1016
- for (let i = 0; i < index && i < source.length; i++) {
1017
- if (source[i] === "\n") {
1018
- line++;
1019
- }
1020
- }
1021
- return line;
1022
- }
1023
- function getColumnNumber(source, index) {
1024
- let column = 0;
1025
- for (let i = index - 1; i >= 0 && source[i] !== "\n"; i--) {
1026
- column++;
1027
- }
1028
- return column;
1029
- }
1030
- function parseImports(source) {
1031
- const imports = [];
1032
- const seenStatements = /* @__PURE__ */ new Set();
1033
- const addImport = (imp) => {
1034
- const key = `${imp.type}:${imp.specifier}:${imp.statement}`;
1035
- if (!seenStatements.has(key)) {
1036
- seenStatements.add(key);
1037
- imports.push(imp);
1038
- }
1039
- };
1040
- let match;
1041
- const defaultAndNamedRegex = new RegExp(IMPORT_PATTERNS.defaultAndNamed.source, "g");
1042
- while ((match = defaultAndNamedRegex.exec(source)) !== null) {
1043
- const [statement, defaultName, namedString, specifier] = match;
1044
- const namedImports = parseNamedImports(namedString);
1045
- addImport({
1046
- statement,
1047
- specifier,
1048
- type: "default",
1049
- defaultImport: defaultName,
1050
- namedImports,
1051
- line: getLineNumber(source, match.index),
1052
- column: getColumnNumber(source, match.index)
1053
- });
1054
- }
1055
- const defaultAndNamespaceRegex = new RegExp(IMPORT_PATTERNS.defaultAndNamespace.source, "g");
1056
- while ((match = defaultAndNamespaceRegex.exec(source)) !== null) {
1057
- const [statement, defaultName, namespaceName, specifier] = match;
1058
- addImport({
1059
- statement,
1060
- specifier,
1061
- type: "default",
1062
- defaultImport: defaultName,
1063
- namespaceImport: namespaceName,
1064
- line: getLineNumber(source, match.index),
1065
- column: getColumnNumber(source, match.index)
1066
- });
1067
- }
1068
- const namedRegex = new RegExp(IMPORT_PATTERNS.named.source, "g");
1069
- while ((match = namedRegex.exec(source)) !== null) {
1070
- const [statement, namedString, specifier] = match;
1071
- const namedImports = parseNamedImports(namedString);
1072
- addImport({
1073
- statement,
1074
- specifier,
1075
- type: "named",
1076
- namedImports,
1077
- line: getLineNumber(source, match.index),
1078
- column: getColumnNumber(source, match.index)
1079
- });
1080
- }
1081
- const defaultRegex = new RegExp(IMPORT_PATTERNS.default.source, "g");
1082
- while ((match = defaultRegex.exec(source)) !== null) {
1083
- const [statement, defaultName, specifier] = match;
1084
- const afterMatch = source.slice(match.index + match[0].length - specifier.length - 2);
1085
- if (afterMatch.startsWith(",")) continue;
1086
- addImport({
1087
- statement,
1088
- specifier,
1089
- type: "default",
1090
- defaultImport: defaultName,
1091
- line: getLineNumber(source, match.index),
1092
- column: getColumnNumber(source, match.index)
1093
- });
1094
- }
1095
- const namespaceRegex = new RegExp(IMPORT_PATTERNS.namespace.source, "g");
1096
- while ((match = namespaceRegex.exec(source)) !== null) {
1097
- const [statement, namespaceName, specifier] = match;
1098
- addImport({
1099
- statement,
1100
- specifier,
1101
- type: "namespace",
1102
- namespaceImport: namespaceName,
1103
- line: getLineNumber(source, match.index),
1104
- column: getColumnNumber(source, match.index)
1105
- });
1106
- }
1107
- const sideEffectRegex = new RegExp(IMPORT_PATTERNS.sideEffect.source, "g");
1108
- while ((match = sideEffectRegex.exec(source)) !== null) {
1109
- const [statement, specifier] = match;
1110
- const beforeMatch = source.slice(Math.max(0, match.index - 50), match.index);
1111
- if (beforeMatch.includes("from")) continue;
1112
- addImport({
1113
- statement,
1114
- specifier,
1115
- type: "side-effect",
1116
- line: getLineNumber(source, match.index),
1117
- column: getColumnNumber(source, match.index)
1118
- });
1119
- }
1120
- const dynamicRegex = new RegExp(IMPORT_PATTERNS.dynamic.source, "g");
1121
- while ((match = dynamicRegex.exec(source)) !== null) {
1122
- const [statement, specifier] = match;
1123
- addImport({
1124
- statement,
1125
- specifier,
1126
- type: "dynamic",
1127
- line: getLineNumber(source, match.index),
1128
- column: getColumnNumber(source, match.index)
1129
- });
1130
- }
1131
- const reExportRegex = new RegExp(IMPORT_PATTERNS.reExport.source, "g");
1132
- while ((match = reExportRegex.exec(source)) !== null) {
1133
- const [statement, specifier] = match;
1134
- addImport({
1135
- statement,
1136
- specifier,
1137
- type: "named",
1138
- line: getLineNumber(source, match.index),
1139
- column: getColumnNumber(source, match.index)
1140
- });
1141
- }
1142
- const reExportAllRegex = new RegExp(IMPORT_PATTERNS.reExportAll.source, "g");
1143
- while ((match = reExportAllRegex.exec(source)) !== null) {
1144
- const [statement, specifier] = match;
1145
- addImport({
1146
- statement,
1147
- specifier,
1148
- type: "namespace",
1149
- line: getLineNumber(source, match.index),
1150
- column: getColumnNumber(source, match.index)
1151
- });
1152
- }
1153
- const externalImports = imports.filter((imp) => isExternalImport(imp.specifier));
1154
- const relativeImports = imports.filter((imp) => isRelativeImport(imp.specifier));
1155
- const externalPackages = [...new Set(externalImports.map((imp) => getPackageName(imp.specifier)))];
1156
- return {
1157
- imports,
1158
- externalImports,
1159
- relativeImports,
1160
- externalPackages
1161
- };
1162
- }
1163
- function extractExternalPackages(source) {
1164
- const result = parseImports(source);
1165
- return result.externalPackages;
1166
- }
1167
- function filterImportsByPackages(result, packages) {
1168
- const packageSet = new Set(packages);
1169
- return result.externalImports.filter((imp) => {
1170
- const pkgName = getPackageName(imp.specifier);
1171
- return packageSet.has(pkgName);
1172
- });
1173
- }
1174
- function getImportStats(source) {
1175
- const result = parseImports(source);
1176
- const byType = {
1177
- named: 0,
1178
- default: 0,
1179
- namespace: 0,
1180
- "side-effect": 0,
1181
- dynamic: 0
1182
- };
1183
- for (const imp of result.imports) {
1184
- byType[imp.type] = (byType[imp.type] || 0) + 1;
1185
- }
1186
- return {
1187
- total: result.imports.length,
1188
- external: result.externalImports.length,
1189
- relative: result.relativeImports.length,
1190
- byType,
1191
- packages: result.externalPackages
1192
- };
1193
- }
1194
-
1195
- // libs/uipack/src/utils/index.ts
1196
- var import_utils = require("@frontmcp/utils");
1197
-
1198
- // libs/uipack/src/dependency/import-map.ts
1199
- function createImportMap(dependencies) {
1200
- const imports = {};
1201
- const integrity = {};
1202
- for (const dep of dependencies) {
1203
- imports[dep.packageName] = dep.cdnUrl;
1204
- if (dep.integrity) {
1205
- integrity[dep.cdnUrl] = dep.integrity;
1206
- }
1207
- }
1208
- return {
1209
- imports,
1210
- integrity: Object.keys(integrity).length > 0 ? integrity : void 0
1211
- };
1212
- }
1213
- function createImportMapFromOverrides(dependencies) {
1214
- const imports = {};
1215
- const integrity = {};
1216
- for (const [pkgName, config] of Object.entries(dependencies)) {
1217
- imports[pkgName] = config.url;
1218
- if (config.integrity) {
1219
- integrity[config.url] = config.integrity;
1220
- }
1221
- }
1222
- return {
1223
- imports,
1224
- integrity: Object.keys(integrity).length > 0 ? integrity : void 0
1225
- };
1226
- }
1227
- function mergeImportMaps(...maps) {
1228
- const imports = {};
1229
- const integrity = {};
1230
- const scopes = {};
1231
- for (const map of maps) {
1232
- Object.assign(imports, map.imports);
1233
- if (map.integrity) {
1234
- Object.assign(integrity, map.integrity);
1235
- }
1236
- if (map.scopes) {
1237
- for (const [scope, mappings] of Object.entries(map.scopes)) {
1238
- scopes[scope] = { ...scopes[scope], ...mappings };
1239
- }
1240
- }
1241
- }
1242
- return {
1243
- imports,
1244
- integrity: Object.keys(integrity).length > 0 ? integrity : void 0,
1245
- scopes: Object.keys(scopes).length > 0 ? scopes : void 0
1246
- };
1247
- }
1248
- function addScope(map, scopeUrl, mappings) {
1249
- return {
1250
- ...map,
1251
- scopes: {
1252
- ...map.scopes,
1253
- [scopeUrl]: { ...map.scopes?.[scopeUrl] ?? {}, ...mappings }
1254
- }
1255
- };
1256
- }
1257
- function generateImportMapScriptTag(map) {
1258
- const json2 = JSON.stringify(map, null, 2).replace(/<\//g, "<\\/");
1259
- return `<script type="importmap">
1260
- ${json2}
1261
- </script>`;
1262
- }
1263
- function generateImportMapScriptTagMinified(map) {
1264
- const json2 = JSON.stringify(map).replace(/<\//g, "<\\/");
1265
- return `<script type="importmap">${json2}</script>`;
1266
- }
1267
- function generateUMDShim(dependencies, options = {}) {
1268
- const { safe = true, minify = false } = options;
1269
- const depsWithGlobals = dependencies.filter((d) => d.global && !d.esm);
1270
- if (depsWithGlobals.length === 0) {
1271
- return "";
1272
- }
1273
- const entries = depsWithGlobals.map((dep) => {
1274
- const global = dep.global;
1275
- return `'${dep.packageName}': { default: window.${global}, ...window.${global} }`;
1276
- });
1277
- const shimObject = `{
1278
- ${entries.join(",\n ")}
1279
- }`;
1280
- const code = safe ? `(function() {
1281
- try {
1282
- window.__esm_shim = ${shimObject};
1283
- } catch (e) {
1284
- console.warn('UMD shim failed:', e);
1285
- }
1286
- })();` : `window.__esm_shim = ${shimObject};`;
1287
- if (minify && code.length <= 1e5) {
1288
- return code.replace(/\s+/g, " ").replace(/\s*([{},:])\s*/g, "$1");
1289
- }
1290
- return code;
1291
- }
1292
- function generateCDNScriptTags(dependencies) {
1293
- return dependencies.filter((dep) => !dep.esm).map((dep) => {
1294
- const attrs = [`src="${(0, import_utils.escapeHtmlAttr)(dep.cdnUrl)}"`];
1295
- if (dep.integrity) {
1296
- attrs.push(`integrity="${(0, import_utils.escapeHtmlAttr)(dep.integrity)}"`);
1297
- }
1298
- attrs.push('crossorigin="anonymous"');
1299
- return `<script ${attrs.join(" ")}></script>`;
1300
- });
1301
- }
1302
- function generateESMScriptTags(dependencies) {
1303
- return dependencies.filter((dep) => dep.esm).map((dep) => {
1304
- const attrs = ['type="module"', `src="${(0, import_utils.escapeHtmlAttr)(dep.cdnUrl)}"`];
1305
- if (dep.integrity) {
1306
- attrs.push(`integrity="${(0, import_utils.escapeHtmlAttr)(dep.integrity)}"`);
1307
- }
1308
- attrs.push('crossorigin="anonymous"');
1309
- return `<script ${attrs.join(" ")}></script>`;
1310
- });
1311
- }
1312
- function generateDependencyHTML(dependencies, options = {}) {
1313
- const { minify = false, includeShim = true } = options;
1314
- const parts = [];
1315
- const importMap = createImportMap(dependencies);
1316
- const importMapTag = minify ? generateImportMapScriptTagMinified(importMap) : generateImportMapScriptTag(importMap);
1317
- parts.push(importMapTag);
1318
- const umdTags = generateCDNScriptTags(dependencies);
1319
- parts.push(...umdTags);
1320
- if (includeShim) {
1321
- const shim = generateUMDShim(dependencies, { minify });
1322
- if (shim) {
1323
- parts.push(`<script>${shim}</script>`);
1324
- }
1325
- }
1326
- const esmTags = generateESMScriptTags(dependencies);
1327
- parts.push(...esmTags);
1328
- return parts.join(minify ? "" : "\n");
1329
- }
1330
- function validateImportMap(map) {
1331
- const errors = [];
1332
- if (typeof map !== "object" || map === null) {
1333
- return { valid: false, errors: ["Import map must be an object"] };
1334
- }
1335
- const obj = map;
1336
- if (!obj["imports"]) {
1337
- errors.push('Import map must have an "imports" field');
1338
- } else if (typeof obj["imports"] !== "object" || obj["imports"] === null) {
1339
- errors.push('"imports" must be an object');
1340
- } else {
1341
- const imports = obj["imports"];
1342
- for (const [key, value] of Object.entries(imports)) {
1343
- if (typeof value !== "string") {
1344
- errors.push(`Import "${key}" must map to a string URL`);
1345
- } else if (!value.startsWith("https://")) {
1346
- errors.push(`Import "${key}" URL must use HTTPS: ${value}`);
1347
- }
1348
- }
1349
- }
1350
- if (obj["integrity"] !== void 0) {
1351
- if (typeof obj["integrity"] !== "object" || obj["integrity"] === null) {
1352
- errors.push('"integrity" must be an object');
1353
- } else {
1354
- const integrity = obj["integrity"];
1355
- for (const [url, hash] of Object.entries(integrity)) {
1356
- if (typeof hash !== "string") {
1357
- errors.push(`Integrity for "${url}" must be a string`);
1358
- } else if (!hash.match(/^sha(256|384|512)-/)) {
1359
- errors.push(`Invalid integrity hash format for "${url}": ${hash}`);
1360
- }
1361
- }
1362
- }
1363
- }
1364
- if (obj["scopes"] !== void 0) {
1365
- if (typeof obj["scopes"] !== "object" || obj["scopes"] === null) {
1366
- errors.push('"scopes" must be an object');
1367
- }
1368
- }
1369
- return { valid: errors.length === 0, errors };
1370
- }
1371
-
1372
- // libs/uipack/src/dependency/resolver.ts
1373
- var DependencyResolutionError = class extends Error {
1374
- constructor(packageName, reason) {
1375
- super(`Failed to resolve dependency "${packageName}": ${reason}`);
1376
- this.packageName = packageName;
1377
- this.reason = reason;
1378
- this.name = "DependencyResolutionError";
1379
- }
1380
- };
1381
- var NoProviderError = class extends DependencyResolutionError {
1382
- constructor(packageName, platform) {
1383
- super(packageName, `No CDN provider available for platform "${platform}"`);
1384
- this.platform = platform;
1385
- this.name = "NoProviderError";
1386
- }
1387
- };
1388
- var DependencyResolver = class {
1389
- options;
1390
- registry;
1391
- constructor(options = {}) {
1392
- this.options = {
1393
- platform: options.platform ?? "unknown",
1394
- preferredProviders: options.preferredProviders ?? CDN_PROVIDER_PRIORITY[options.platform ?? "unknown"],
1395
- customRegistry: options.customRegistry ?? {},
1396
- strictMode: options.strictMode ?? true,
1397
- requireIntegrity: options.requireIntegrity ?? false
1398
- };
1399
- this.registry = mergeRegistries(this.options.customRegistry);
1400
- }
1401
- /**
1402
- * Resolve a single package to its CDN dependency.
1403
- *
1404
- * @param packageName - NPM package name
1405
- * @param override - Optional explicit CDN dependency override
1406
- * @returns Resolved dependency, or null in non-strict mode if package is not found (should be bundled)
1407
- * @throws DependencyResolutionError if package cannot be resolved in strict mode
1408
- */
1409
- resolve(packageName, override) {
1410
- if (override) {
1411
- return this.createResolvedDependency(packageName, override, "custom");
1412
- }
1413
- const entry = lookupPackage(packageName, this.registry);
1414
- if (!entry) {
1415
- if (this.options.strictMode) {
1416
- throw new DependencyResolutionError(
1417
- packageName,
1418
- 'Package not found in CDN registry. Add it to "dependencies" for explicit CDN configuration.'
1419
- );
1420
- }
1421
- return null;
1422
- }
1423
- const providerPriority = this.options.preferredProviders;
1424
- for (const provider of providerPriority) {
1425
- const config = entry.providers[provider];
1426
- if (config?.url) {
1427
- if (this.options.requireIntegrity && !config.integrity) {
1428
- continue;
1429
- }
1430
- return this.createResolvedDependency(packageName, config, provider, entry.defaultVersion);
1431
- }
1432
- }
1433
- throw new NoProviderError(packageName, this.options.platform);
1434
- }
1435
- /**
1436
- * Resolve multiple packages.
1437
- *
1438
- * @param packageNames - Array of package names
1439
- * @param overrides - Optional explicit overrides for specific packages
1440
- * @returns Array of resolved dependencies (in dependency order)
1441
- */
1442
- resolveMany(packageNames, overrides) {
1443
- const allPackages = resolveAllDependencies(packageNames, this.options.platform, this.registry);
1444
- const resolved = [];
1445
- for (const pkgName of allPackages) {
1446
- try {
1447
- const override = overrides?.[pkgName];
1448
- const dep = this.resolve(pkgName, override);
1449
- if (dep) {
1450
- resolved.push(dep);
1451
- }
1452
- } catch (error) {
1453
- if (this.options.strictMode) {
1454
- throw error;
1455
- }
1456
- }
1457
- }
1458
- return resolved;
1459
- }
1460
- /**
1461
- * Resolve dependencies from source code.
1462
- *
1463
- * Parses the source to extract imports, then resolves external packages
1464
- * that are in the externals list.
1465
- *
1466
- * @param source - Source code to parse
1467
- * @param externals - Package names to resolve from CDN (others are bundled)
1468
- * @param overrides - Optional explicit CDN overrides
1469
- * @returns Resolved dependencies
1470
- */
1471
- resolveFromSource(source, externals, overrides) {
1472
- const parseResult = parseImports(source);
1473
- const packagesToResolve = parseResult.externalPackages.filter((pkg) => externals.includes(pkg));
1474
- return this.resolveMany(packagesToResolve, overrides);
1475
- }
1476
- /**
1477
- * Generate an import map for resolved dependencies.
1478
- *
1479
- * @param dependencies - Resolved dependencies
1480
- * @returns Browser import map
1481
- */
1482
- generateImportMap(dependencies) {
1483
- return createImportMap(dependencies);
1484
- }
1485
- /**
1486
- * Check if a package can be resolved for the current platform.
1487
- *
1488
- * @param packageName - Package name to check
1489
- * @returns true if the package can be resolved
1490
- */
1491
- canResolve(packageName) {
1492
- try {
1493
- const result = this.resolve(packageName);
1494
- return result !== null;
1495
- } catch {
1496
- return false;
1497
- }
1498
- }
1499
- /**
1500
- * Get the resolved CDN URL for a package.
1501
- *
1502
- * @param packageName - Package name
1503
- * @param override - Optional explicit override
1504
- * @returns CDN URL or undefined if cannot resolve
1505
- */
1506
- getUrl(packageName, override) {
1507
- try {
1508
- const resolved = this.resolve(packageName, override);
1509
- return resolved?.cdnUrl;
1510
- } catch {
1511
- return void 0;
1512
- }
1513
- }
1514
- /**
1515
- * Get peer dependencies for a package.
1516
- */
1517
- getPeerDependencies(packageName) {
1518
- return getPackagePeerDependencies(packageName, this.registry);
1519
- }
1520
- /**
1521
- * Create the current registry (default + custom).
1522
- */
1523
- getRegistry() {
1524
- return this.registry;
1525
- }
1526
- /**
1527
- * Get the current platform.
1528
- */
1529
- getPlatform() {
1530
- return this.options.platform;
1531
- }
1532
- /**
1533
- * Create a resolved dependency object.
1534
- */
1535
- createResolvedDependency(packageName, config, provider, version) {
1536
- return {
1537
- packageName,
1538
- version: version ?? this.extractVersionFromUrl(config.url) ?? "latest",
1539
- cdnUrl: config.url,
1540
- integrity: config.integrity,
1541
- global: config.global,
1542
- esm: config.esm ?? false,
1543
- provider
1544
- };
1545
- }
1546
- /**
1547
- * Try to extract version from CDN URL.
1548
- */
1549
- extractVersionFromUrl(url) {
1550
- const versionMatch = url.match(/@(\d+\.\d+\.\d+(?:-[\w.]+)?)/);
1551
- if (versionMatch) {
1552
- return versionMatch[1];
1553
- }
1554
- const versionMatch2 = url.match(/\/v?(\d+\.\d+\.\d+)\//);
1555
- if (versionMatch2) {
1556
- return versionMatch2[1];
1557
- }
1558
- return void 0;
1559
- }
1560
- };
1561
- function createResolver(platform, options) {
1562
- return new DependencyResolver({
1563
- platform,
1564
- ...options
1565
- });
1566
- }
1567
- function createClaudeResolver(options) {
1568
- return createResolver("claude", options);
1569
- }
1570
- function createOpenAIResolver(options) {
1571
- return createResolver("openai", options);
1572
- }
1573
- function resolveDependencies(source, externals, options) {
1574
- const resolver = new DependencyResolver(options);
1575
- return resolver.resolveFromSource(source, externals);
1576
- }
1577
- function generateImportMapForPackages(externals, options) {
1578
- const resolver = new DependencyResolver(options);
1579
- const resolved = resolver.resolveMany(externals);
1580
- return resolver.generateImportMap(resolved);
1581
- }
1582
-
1583
- // libs/uipack/src/dependency/template-loader.ts
1584
- var import_fs = require("fs");
1585
- var import_path = require("path");
1586
-
1587
- // libs/uipack/src/bundler/file-cache/hash-calculator.ts
1588
- var import_crypto = require("crypto");
1589
- var import_utils3 = require("@frontmcp/utils");
1590
- function sha256(content) {
1591
- return (0, import_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
1592
- }
1593
-
1594
- // libs/uipack/src/dependency/template-loader.ts
1595
- var urlCache = /* @__PURE__ */ new Map();
1596
- function getUrlCache() {
1597
- return urlCache;
1598
- }
1599
- function clearUrlCache() {
1600
- urlCache.clear();
1601
- }
1602
- function detectTemplateSource(template) {
1603
- const mode = detectTemplateMode(template);
1604
- switch (mode) {
1605
- case "url":
1606
- return { type: "url", url: template };
1607
- case "file-path":
1608
- return { type: "file", path: template };
1609
- case "inline-string":
1610
- case "inline-function":
1611
- default:
1612
- return { type: "inline", content: template };
1613
- }
1614
- }
1615
- function isFileBasedTemplate(mode) {
1616
- return mode === "file-path" || mode === "url";
1617
- }
1618
- function validateTemplateUrl(url) {
1619
- const parsed = new URL(url);
1620
- if (parsed.protocol !== "https:") {
1621
- throw new Error(`Template URLs must use HTTPS. Got: ${parsed.protocol}`);
1622
- }
1623
- }
1624
- function detectFormatFromUrl(url) {
1625
- const parsed = new URL(url);
1626
- return detectFormatFromPath(parsed.pathname);
1627
- }
1628
- async function fetchTemplateFromUrl(url, options = {}) {
1629
- validateTemplateUrl(url);
1630
- const { timeout = 3e4, skipCache = false, headers: customHeaders = {} } = options;
1631
- if (!skipCache) {
1632
- const cached = urlCache.get(url);
1633
- if (cached?.etag) {
1634
- const headers = {
1635
- ...customHeaders,
1636
- "If-None-Match": cached.etag
1637
- };
1638
- const controller2 = new AbortController();
1639
- const timeoutId2 = setTimeout(() => controller2.abort(), timeout);
1640
- try {
1641
- const response = await fetch(url, {
1642
- headers,
1643
- signal: controller2.signal
1644
- });
1645
- clearTimeout(timeoutId2);
1646
- if (response.status === 304) {
1647
- return cached;
1648
- }
1649
- return await processFetchResponse(url, response);
1650
- } catch (error) {
1651
- clearTimeout(timeoutId2);
1652
- if (error instanceof Error && error.name === "AbortError") {
1653
- throw new Error(`Template fetch timed out after ${timeout}ms: ${url}`);
1654
- }
1655
- throw error;
1656
- }
1657
- }
1658
- }
1659
- const controller = new AbortController();
1660
- const timeoutId = setTimeout(() => controller.abort(), timeout);
1661
- try {
1662
- const response = await fetch(url, {
1663
- headers: customHeaders,
1664
- signal: controller.signal
1665
- });
1666
- clearTimeout(timeoutId);
1667
- return await processFetchResponse(url, response);
1668
- } catch (error) {
1669
- clearTimeout(timeoutId);
1670
- if (error instanceof Error && error.name === "AbortError") {
1671
- throw new Error(`Template fetch timed out after ${timeout}ms: ${url}`);
1672
- }
1673
- throw error;
1674
- }
1675
- }
1676
- async function processFetchResponse(url, response) {
1677
- if (!response.ok) {
1678
- throw new Error(`Failed to fetch template: ${response.status} ${response.statusText} - ${url}`);
1679
- }
1680
- const content = await response.text();
1681
- const etag = response.headers.get("etag") ?? void 0;
1682
- const contentType = response.headers.get("content-type") ?? void 0;
1683
- const result = {
1684
- content,
1685
- etag,
1686
- contentType,
1687
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
1688
- };
1689
- urlCache.set(url, result);
1690
- return result;
1691
- }
1692
- async function readTemplateFromFile(filePath, options = {}) {
1693
- const { basePath = process.cwd(), encoding = "utf-8" } = options;
1694
- const absolutePath = (0, import_path.isAbsolute)(filePath) ? filePath : (0, import_path.resolve)(basePath, filePath);
1695
- const normalizedBase = (0, import_path.resolve)(basePath);
1696
- if (!absolutePath.startsWith(normalizedBase + import_path.sep) && absolutePath !== normalizedBase) {
1697
- throw new Error(`Template path escapes base directory: ${filePath}`);
1698
- }
1699
- try {
1700
- return await import_fs.promises.readFile(absolutePath, encoding);
1701
- } catch (error) {
1702
- const err = error;
1703
- if (err.code === "ENOENT") {
1704
- throw new Error(`Template file not found: ${absolutePath}`);
1705
- }
1706
- if (err.code === "EACCES") {
1707
- throw new Error(`Permission denied reading template file: ${absolutePath}`);
1708
- }
1709
- throw new Error(`Failed to read template file: ${absolutePath} - ${err.message}`);
1710
- }
1711
- }
1712
- function resolveFilePath(filePath, basePath = process.cwd()) {
1713
- return (0, import_path.isAbsolute)(filePath) ? filePath : (0, import_path.resolve)(basePath, filePath);
1714
- }
1715
- async function resolveTemplate(template, options = {}) {
1716
- const { basePath = process.cwd(), skipCache = false, timeout = 3e4, format: overrideFormat } = options;
1717
- const source = detectTemplateSource(template);
1718
- let content;
1719
- let format;
1720
- let metadata = {};
1721
- switch (source.type) {
1722
- case "inline":
1723
- content = source.content;
1724
- format = overrideFormat ?? "html";
1725
- break;
1726
- case "file": {
1727
- const absolutePath = resolveFilePath(source.path, basePath);
1728
- content = await readTemplateFromFile(absolutePath);
1729
- format = overrideFormat ?? detectFormatFromPath(source.path);
1730
- metadata.resolvedPath = absolutePath;
1731
- break;
1732
- }
1733
- case "url": {
1734
- const fetchResult = await fetchTemplateFromUrl(source.url, {
1735
- skipCache,
1736
- timeout
1737
- });
1738
- content = fetchResult.content;
1739
- format = overrideFormat ?? detectFormatFromUrl(source.url);
1740
- metadata = {
1741
- fetchedAt: fetchResult.fetchedAt,
1742
- etag: fetchResult.etag,
1743
- contentType: fetchResult.contentType
1744
- };
1745
- break;
1746
- }
1747
- }
1748
- const hash = sha256(content);
1749
- return {
1750
- source,
1751
- format,
1752
- content,
1753
- hash,
1754
- metadata: Object.keys(metadata).length > 0 ? metadata : void 0
1755
- };
1756
- }
1757
- var URL_CACHE_TTL_MS = 5 * 60 * 1e3;
1758
- function needsRefetch(resolved) {
1759
- if (resolved.source.type !== "url") {
1760
- return false;
1761
- }
1762
- const cached = urlCache.get(resolved.source.url);
1763
- if (!cached) {
1764
- return true;
1765
- }
1766
- if (cached.etag) {
1767
- return false;
1768
- }
1769
- if (cached.fetchedAt) {
1770
- const fetchedTime = new Date(cached.fetchedAt).getTime();
1771
- const age = Date.now() - fetchedTime;
1772
- return age > URL_CACHE_TTL_MS;
1773
- }
1774
- return true;
1775
- }
1776
- function invalidateUrlCache(url) {
1777
- return urlCache.delete(url);
1778
- }
1779
-
1780
- // libs/uipack/src/handlebars/helpers.ts
1781
- function formatDate(date, format) {
1782
- if (date === null || date === void 0) {
1783
- return "";
1784
- }
1785
- let dateObj;
1786
- if (date instanceof Date) {
1787
- dateObj = date;
1788
- } else if (typeof date === "string" || typeof date === "number") {
1789
- dateObj = new Date(date);
1790
- } else {
1791
- return String(date);
1792
- }
1793
- if (isNaN(dateObj.getTime())) {
1794
- return String(date);
1795
- }
1796
- const options = {};
1797
- switch (format) {
1798
- case "short":
1799
- options.dateStyle = "short";
1800
- break;
1801
- case "medium":
1802
- options.dateStyle = "medium";
1803
- break;
1804
- case "long":
1805
- options.dateStyle = "long";
1806
- break;
1807
- case "full":
1808
- options.dateStyle = "full";
1809
- break;
1810
- case "time":
1811
- options.timeStyle = "short";
1812
- break;
1813
- case "datetime":
1814
- options.dateStyle = "medium";
1815
- options.timeStyle = "short";
1816
- break;
1817
- case "iso":
1818
- return dateObj.toISOString();
1819
- case "relative":
1820
- return formatRelativeDate(dateObj);
1821
- default:
1822
- options.dateStyle = "medium";
1823
- }
1824
- return new Intl.DateTimeFormat("en-US", options).format(dateObj);
1825
- }
1826
- function formatRelativeDate(date) {
1827
- const now = /* @__PURE__ */ new Date();
1828
- const diffMs = now.getTime() - date.getTime();
1829
- const diffSecs = Math.floor(diffMs / 1e3);
1830
- const diffMins = Math.floor(diffSecs / 60);
1831
- const diffHours = Math.floor(diffMins / 60);
1832
- const diffDays = Math.floor(diffHours / 24);
1833
- if (diffSecs < 60) {
1834
- return "just now";
1835
- } else if (diffMins < 60) {
1836
- return `${diffMins} minute${diffMins === 1 ? "" : "s"} ago`;
1837
- } else if (diffHours < 24) {
1838
- return `${diffHours} hour${diffHours === 1 ? "" : "s"} ago`;
1839
- } else if (diffDays < 7) {
1840
- return `${diffDays} day${diffDays === 1 ? "" : "s"} ago`;
1841
- } else {
1842
- return formatDate(date, "medium");
1843
- }
1844
- }
1845
- function formatCurrency(amount, currency) {
1846
- if (amount === null || amount === void 0) {
1847
- return "";
1848
- }
1849
- const num = typeof amount === "number" ? amount : parseFloat(String(amount));
1850
- if (isNaN(num)) {
1851
- return String(amount);
1852
- }
1853
- return new Intl.NumberFormat("en-US", {
1854
- style: "currency",
1855
- currency: typeof currency === "string" ? currency : "USD"
1856
- }).format(num);
1857
- }
1858
- function formatNumber(value, decimals) {
1859
- if (value === null || value === void 0) {
1860
- return "";
1861
- }
1862
- const num = typeof value === "number" ? value : parseFloat(String(value));
1863
- if (isNaN(num)) {
1864
- return String(value);
1865
- }
1866
- const options = {};
1867
- if (typeof decimals === "number") {
1868
- options.minimumFractionDigits = decimals;
1869
- options.maximumFractionDigits = decimals;
1870
- }
1871
- return new Intl.NumberFormat("en-US", options).format(num);
1872
- }
1873
- function jsonEmbed(data) {
1874
- const json2 = JSON.stringify(data ?? null);
1875
- return json2.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1876
- }
1877
- function json(data, pretty) {
1878
- return JSON.stringify(data ?? null, null, pretty ? 2 : void 0);
1879
- }
1880
- function eq(a, b) {
1881
- return a === b;
1882
- }
1883
- function ne(a, b) {
1884
- return a !== b;
1885
- }
1886
- function gt(a, b) {
1887
- return Number(a) > Number(b);
1888
- }
1889
- function gte(a, b) {
1890
- return Number(a) >= Number(b);
1891
- }
1892
- function lt(a, b) {
1893
- return Number(a) < Number(b);
1894
- }
1895
- function lte(a, b) {
1896
- return Number(a) <= Number(b);
1897
- }
1898
- function and(a, b) {
1899
- return Boolean(a) && Boolean(b);
1900
- }
1901
- function or(a, b) {
1902
- return Boolean(a) || Boolean(b);
1903
- }
1904
- function not(value) {
1905
- return !value;
1906
- }
1907
- function first(arr) {
1908
- if (!Array.isArray(arr)) return void 0;
1909
- return arr[0];
1910
- }
1911
- function last(arr) {
1912
- if (!Array.isArray(arr)) return void 0;
1913
- return arr[arr.length - 1];
1914
- }
1915
- function length(value) {
1916
- if (Array.isArray(value)) return value.length;
1917
- if (typeof value === "string") return value.length;
1918
- return 0;
1919
- }
1920
- function includes(arr, value) {
1921
- if (!Array.isArray(arr)) return false;
1922
- return arr.includes(value);
1923
- }
1924
- function join(arr, separator) {
1925
- if (!Array.isArray(arr)) return "";
1926
- return arr.join(typeof separator === "string" ? separator : ", ");
1927
- }
1928
- function uppercase(str) {
1929
- return String(str ?? "").toUpperCase();
1930
- }
1931
- function lowercase(str) {
1932
- return String(str ?? "").toLowerCase();
1933
- }
1934
- function capitalize(str) {
1935
- const s = String(str ?? "");
1936
- return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
1937
- }
1938
- function truncate(str, maxLength, suffix) {
1939
- const s = String(str ?? "");
1940
- const len = typeof maxLength === "number" ? maxLength : 50;
1941
- const suf = typeof suffix === "string" ? suffix : "...";
1942
- if (s.length <= len) return s;
1943
- return s.slice(0, len - suf.length) + suf;
1944
- }
1945
- function defaultValue(value, defaultValue2) {
1946
- return value || defaultValue2;
1947
- }
1948
- var idCounter = 0;
1949
- function uniqueId(prefix) {
1950
- const id = ++idCounter;
1951
- return prefix ? `${prefix}-${id}` : `id-${id}`;
1952
- }
1953
- function classNames(...classes) {
1954
- return classes.filter(Boolean).map(String).join(" ");
1955
- }
1956
- var builtinHelpers = {
1957
- // Escaping
1958
- escapeHtml: import_utils.escapeHtml,
1959
- // Formatting
1960
- formatDate,
1961
- formatCurrency,
1962
- formatNumber,
1963
- json,
1964
- jsonEmbed,
1965
- // Comparison
1966
- eq,
1967
- ne,
1968
- gt,
1969
- gte,
1970
- lt,
1971
- lte,
1972
- // Logical
1973
- and,
1974
- or,
1975
- not,
1976
- // Array
1977
- first,
1978
- last,
1979
- length,
1980
- includes,
1981
- join,
1982
- // String
1983
- uppercase,
1984
- lowercase,
1985
- capitalize,
1986
- truncate,
1987
- // Utility
1988
- default: defaultValue,
1989
- uniqueId,
1990
- classNames
1991
- };
1992
-
1993
- // libs/uipack/src/handlebars/expression-extractor.ts
1994
- var EXPRESSION_REGEX = /\{\{\{?(?!!)(#|\/)?([^}]+?)\}?\}\}/g;
1995
- var PATH_REGEX = /\b(output|input|structuredContent)(\.[a-zA-Z_$][a-zA-Z0-9_$]*|\.\[[^\]]+\])+/g;
1996
- var KEYWORDS = /* @__PURE__ */ new Set(["this", "else", "@index", "@key", "@first", "@last", "@root"]);
1997
- function extractExpressions(template) {
1998
- const expressions = [];
1999
- const positionMap = buildPositionMap(template);
2000
- let match;
2001
- EXPRESSION_REGEX.lastIndex = 0;
2002
- while ((match = EXPRESSION_REGEX.exec(template)) !== null) {
2003
- const fullExpression = match[0];
2004
- const prefix = match[1];
2005
- const content = match[2].trim();
2006
- const position = positionMap.get(match.index) ?? { line: 1, column: 1 };
2007
- let type = "variable";
2008
- let helperName;
2009
- if (prefix === "/") {
2010
- type = "block-close";
2011
- helperName = content;
2012
- } else if (prefix === "#") {
2013
- type = "block";
2014
- const parts = content.split(/\s+/);
2015
- helperName = parts[0];
2016
- } else {
2017
- const parts = content.split(/\s+/);
2018
- if (parts.length > 1 && !content.startsWith("(")) {
2019
- const firstToken = parts[0];
2020
- if (!firstToken.includes(".") && !KEYWORDS.has(firstToken)) {
2021
- type = "helper";
2022
- helperName = firstToken;
2023
- }
2024
- }
2025
- }
2026
- const paths = extractPathsFromContent(content);
2027
- for (const path of paths) {
2028
- expressions.push({
2029
- path,
2030
- fullExpression,
2031
- line: position.line,
2032
- column: position.column,
2033
- type,
2034
- helperName
2035
- });
2036
- }
2037
- if (paths.length === 0 && type === "variable") {
2038
- const cleanContent = content.trim();
2039
- if (!KEYWORDS.has(cleanContent) && !cleanContent.includes(" ") && !cleanContent.startsWith("(")) {
2040
- }
2041
- }
2042
- }
2043
- return expressions;
2044
- }
2045
- function extractPathsFromContent(content) {
2046
- const paths = [];
2047
- let match;
2048
- const regex = new RegExp(PATH_REGEX.source, "g");
2049
- while ((match = regex.exec(content)) !== null) {
2050
- paths.push(match[0]);
2051
- }
2052
- return paths;
2053
- }
2054
- function buildPositionMap(template) {
2055
- const map = /* @__PURE__ */ new Map();
2056
- let line = 1;
2057
- let column = 1;
2058
- for (let i = 0; i < template.length; i++) {
2059
- map.set(i, { line, column });
2060
- if (template[i] === "\n") {
2061
- line++;
2062
- column = 1;
2063
- } else {
2064
- column++;
2065
- }
2066
- }
2067
- return map;
2068
- }
2069
- function extractAll(template) {
2070
- const expressions = extractExpressions(template);
2071
- const paths = [...new Set(expressions.map((e) => e.path))];
2072
- return {
2073
- expressions,
2074
- paths,
2075
- outputPaths: paths.filter((p) => p.startsWith("output.")),
2076
- inputPaths: paths.filter((p) => p.startsWith("input.")),
2077
- structuredContentPaths: paths.filter((p) => p.startsWith("structuredContent."))
2078
- };
2079
- }
2080
- function normalizePath(path) {
2081
- return path.replace(/\.\d+\./g, ".[].").replace(/\.\d+$/g, ".[]").replace(/\[\d+\]/g, ".[]");
2082
- }
2083
-
2084
- // libs/uipack/src/handlebars/index.ts
2085
- var Handlebars = null;
2086
- async function loadHandlebars() {
2087
- if (Handlebars !== null) {
2088
- return Handlebars;
2089
- }
2090
- try {
2091
- Handlebars = await import("handlebars");
2092
- return Handlebars;
2093
- } catch {
2094
- throw new Error("Handlebars is required for template rendering. Install it: npm install handlebars");
2095
- }
2096
- }
2097
- var HandlebarsRenderer = class {
2098
- options;
2099
- compiledTemplates = /* @__PURE__ */ new Map();
2100
- initialized = false;
2101
- hbs = null;
2102
- constructor(options = {}) {
2103
- this.options = {
2104
- strict: false,
2105
- autoEscape: true,
2106
- ...options
2107
- };
2108
- }
2109
- /**
2110
- * Initialize the renderer with Handlebars.
2111
- */
2112
- async init() {
2113
- if (this.initialized) return;
2114
- this.hbs = await loadHandlebars();
2115
- for (const [name, helper] of Object.entries(builtinHelpers)) {
2116
- this.hbs.registerHelper(name, helper);
2117
- }
2118
- if (this.options.helpers) {
2119
- for (const [name, helper] of Object.entries(this.options.helpers)) {
2120
- this.hbs.registerHelper(name, helper);
2121
- }
2122
- }
2123
- if (this.options.partials) {
2124
- for (const [name, template] of Object.entries(this.options.partials)) {
2125
- this.hbs.registerPartial(name, template);
2126
- }
2127
- }
2128
- this.initialized = true;
2129
- }
2130
- /**
2131
- * Render a Handlebars template.
2132
- *
2133
- * @param template - Template string
2134
- * @param context - Render context with input/output
2135
- * @returns Rendered HTML string
2136
- */
2137
- async render(template, context) {
2138
- await this.init();
2139
- if (!this.hbs) {
2140
- throw new Error("Handlebars not initialized");
2141
- }
2142
- let compiled = this.compiledTemplates.get(template);
2143
- if (!compiled) {
2144
- compiled = this.hbs.compile(template, {
2145
- strict: this.options.strict,
2146
- noEscape: !this.options.autoEscape
2147
- });
2148
- this.compiledTemplates.set(template, compiled);
2149
- }
2150
- const data = {
2151
- input: context.input ?? {},
2152
- output: context.output ?? {},
2153
- structuredContent: context.structuredContent,
2154
- // Also expose at root level for convenience
2155
- ...context.input,
2156
- ...typeof context.output === "object" && context.output !== null ? context.output : {}
2157
- };
2158
- try {
2159
- return compiled(data);
2160
- } catch (error) {
2161
- throw new Error(`Template rendering failed: ${error instanceof Error ? error.message : String(error)}`);
2162
- }
2163
- }
2164
- /**
2165
- * Render a template synchronously.
2166
- *
2167
- * Note: Requires Handlebars to be pre-loaded. Use `render()` for async loading.
2168
- *
2169
- * @param template - Template string
2170
- * @param context - Render context
2171
- * @returns Rendered HTML string
2172
- */
2173
- renderSync(template, context) {
2174
- if (!this.initialized || !this.hbs) {
2175
- throw new Error("HandlebarsRenderer not initialized. Call render() first or use initSync().");
2176
- }
2177
- let compiled = this.compiledTemplates.get(template);
2178
- if (!compiled) {
2179
- compiled = this.hbs.compile(template, {
2180
- strict: this.options.strict,
2181
- noEscape: !this.options.autoEscape
2182
- });
2183
- this.compiledTemplates.set(template, compiled);
2184
- }
2185
- const data = {
2186
- input: context.input ?? {},
2187
- output: context.output ?? {},
2188
- structuredContent: context.structuredContent,
2189
- ...context.input,
2190
- ...typeof context.output === "object" && context.output !== null ? context.output : {}
2191
- };
2192
- return compiled(data);
2193
- }
2194
- /**
2195
- * Initialize synchronously (for environments where Handlebars is already loaded).
2196
- */
2197
- initSync(handlebars) {
2198
- this.hbs = handlebars;
2199
- for (const [name, helper] of Object.entries(builtinHelpers)) {
2200
- this.hbs.registerHelper(name, helper);
2201
- }
2202
- if (this.options.helpers) {
2203
- for (const [name, helper] of Object.entries(this.options.helpers)) {
2204
- this.hbs.registerHelper(name, helper);
2205
- }
2206
- }
2207
- if (this.options.partials) {
2208
- for (const [name, template] of Object.entries(this.options.partials)) {
2209
- this.hbs.registerPartial(name, template);
2210
- }
2211
- }
2212
- this.initialized = true;
2213
- }
2214
- /**
2215
- * Register a custom helper.
2216
- *
2217
- * @param name - Helper name
2218
- * @param fn - Helper function
2219
- */
2220
- registerHelper(name, fn) {
2221
- if (this.hbs) {
2222
- this.hbs.registerHelper(name, fn);
2223
- }
2224
- if (!this.options.helpers) {
2225
- this.options.helpers = {};
2226
- }
2227
- this.options.helpers[name] = fn;
2228
- }
2229
- /**
2230
- * Register a partial template.
2231
- *
2232
- * @param name - Partial name
2233
- * @param template - Partial template string
2234
- */
2235
- registerPartial(name, template) {
2236
- if (this.hbs) {
2237
- this.hbs.registerPartial(name, template);
2238
- }
2239
- if (!this.options.partials) {
2240
- this.options.partials = {};
2241
- }
2242
- this.options.partials[name] = template;
2243
- }
2244
- /**
2245
- * Clear compiled template cache.
2246
- */
2247
- clearCache() {
2248
- this.compiledTemplates.clear();
2249
- }
2250
- /**
2251
- * Check if a template string contains Handlebars syntax.
2252
- *
2253
- * @param template - Template string to check
2254
- * @returns true if contains {{...}} syntax
2255
- */
2256
- static containsHandlebars(template) {
2257
- return /\{\{(?!!)[\s\S]*?\}\}/.test(template);
2258
- }
2259
- /**
2260
- * Check if the renderer is initialized.
2261
- */
2262
- get isInitialized() {
2263
- return this.initialized;
2264
- }
2265
- };
2266
- function containsHandlebars(template) {
2267
- return HandlebarsRenderer.containsHandlebars(template);
2268
- }
2269
-
2270
- // libs/uipack/src/renderers/utils/detect.ts
2271
- var MAX_TEMPLATE_LENGTH = 5e4;
2272
- function containsMdxSyntax(source) {
2273
- if (source.length > MAX_TEMPLATE_LENGTH) {
2274
- return false;
2275
- }
2276
- if (/<[A-Z][a-zA-Z0-9]*/.test(source)) {
2277
- return true;
2278
- }
2279
- if (/^(import|export)\s/m.test(source)) {
2280
- return true;
2281
- }
2282
- if (/\s(className|onClick|onChange|onSubmit|htmlFor|dangerouslySetInnerHTML)=/.test(source)) {
2283
- return true;
2284
- }
2285
- if (/\{[^}"'\n]*\}/.test(source) && !/=\s*["'][^"']*\{/.test(source)) {
2286
- return true;
2287
- }
2288
- if (/^---[\s\S]*?---/m.test(source)) {
2289
- return true;
2290
- }
2291
- if (/<>|<\/>/.test(source)) {
2292
- return true;
2293
- }
2294
- return false;
2295
- }
2296
-
2297
- // libs/uipack/src/renderers/utils/hash.ts
2298
- function hashString(source) {
2299
- let hash = 2166136261;
2300
- for (let i = 0; i < source.length; i++) {
2301
- hash ^= source.charCodeAt(i);
2302
- hash = hash * 16777619 >>> 0;
2303
- }
2304
- return hash.toString(36);
2305
- }
2306
-
2307
- // libs/uipack/src/renderers/cache.ts
2308
- var TranspileCache = class {
2309
- cache = /* @__PURE__ */ new Map();
2310
- maxSize;
2311
- ttl;
2312
- /** Cache statistics */
2313
- stats = {
2314
- hits: 0,
2315
- misses: 0,
2316
- evictions: 0
2317
- };
2318
- constructor(options = {}) {
2319
- this.maxSize = options.maxSize ?? 500;
2320
- this.ttl = options.ttl ?? 0;
2321
- }
2322
- /**
2323
- * Get a cached transpile result by source content.
2324
- *
2325
- * @param source - Source code to look up
2326
- * @returns Cached result or undefined if not found/expired
2327
- */
2328
- get(source) {
2329
- const key = hashString(source);
2330
- return this.getByKey(key);
2331
- }
2332
- /**
2333
- * Get a cached transpile result by hash key.
2334
- *
2335
- * @param key - Hash key
2336
- * @returns Cached result or undefined if not found/expired
2337
- */
2338
- getByKey(key) {
2339
- const entry = this.cache.get(key);
2340
- if (!entry) {
2341
- this.stats.misses++;
2342
- return void 0;
2343
- }
2344
- if (this.ttl > 0 && Date.now() - entry.timestamp > this.ttl) {
2345
- this.cache.delete(key);
2346
- this.stats.misses++;
2347
- return void 0;
2348
- }
2349
- this.cache.delete(key);
2350
- entry.accessCount++;
2351
- this.cache.set(key, entry);
2352
- this.stats.hits++;
2353
- return entry.value;
2354
- }
2355
- /**
2356
- * Store a transpile result.
2357
- *
2358
- * @param source - Source code (used to generate key)
2359
- * @param value - Transpile result to cache
2360
- * @returns The hash key used for storage
2361
- */
2362
- set(source, value) {
2363
- const key = hashString(source);
2364
- this.setByKey(key, value);
2365
- return key;
2366
- }
2367
- /**
2368
- * Store a transpile result by hash key.
2369
- *
2370
- * @param key - Hash key
2371
- * @param value - Transpile result to cache
2372
- */
2373
- setByKey(key, value) {
2374
- if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
2375
- const oldestKey = this.cache.keys().next().value;
2376
- if (oldestKey) {
2377
- this.cache.delete(oldestKey);
2378
- this.stats.evictions++;
2379
- }
2380
- }
2381
- this.cache.set(key, {
2382
- value,
2383
- timestamp: Date.now(),
2384
- accessCount: 1
2385
- });
2386
- }
2387
- /**
2388
- * Check if a source is cached.
2389
- *
2390
- * @param source - Source code to check
2391
- * @returns True if cached and not expired
2392
- */
2393
- has(source) {
2394
- const key = hashString(source);
2395
- return this.hasByKey(key);
2396
- }
2397
- /**
2398
- * Check if a key is cached.
2399
- *
2400
- * @param key - Hash key to check
2401
- * @returns True if cached and not expired
2402
- */
2403
- hasByKey(key) {
2404
- const entry = this.cache.get(key);
2405
- if (!entry) return false;
2406
- if (this.ttl > 0 && Date.now() - entry.timestamp > this.ttl) {
2407
- this.cache.delete(key);
2408
- return false;
2409
- }
2410
- return true;
2411
- }
2412
- /**
2413
- * Delete a cached entry by source.
2414
- *
2415
- * @param source - Source code to delete
2416
- * @returns True if entry was deleted
2417
- */
2418
- delete(source) {
2419
- const key = hashString(source);
2420
- return this.cache.delete(key);
2421
- }
2422
- /**
2423
- * Clear all cached entries.
2424
- */
2425
- clear() {
2426
- this.cache.clear();
2427
- this.stats = { hits: 0, misses: 0, evictions: 0 };
2428
- }
2429
- /**
2430
- * Get current cache size.
2431
- */
2432
- get size() {
2433
- return this.cache.size;
2434
- }
2435
- /**
2436
- * Get cache statistics.
2437
- */
2438
- getStats() {
2439
- const total = this.stats.hits + this.stats.misses;
2440
- return {
2441
- ...this.stats,
2442
- size: this.cache.size,
2443
- hitRate: total > 0 ? this.stats.hits / total : 0
2444
- };
2445
- }
2446
- };
2447
- var transpileCache = new TranspileCache({ maxSize: 500 });
2448
- var renderCache = new TranspileCache({
2449
- maxSize: 1e3,
2450
- ttl: 5 * 60 * 1e3
2451
- // 5 minutes
2452
- });
2453
- var ComponentCache = class {
2454
- cache = /* @__PURE__ */ new Map();
2455
- maxSize;
2456
- constructor(maxSize = 200) {
2457
- this.maxSize = maxSize;
2458
- }
2459
- get(key) {
2460
- const entry = this.cache.get(key);
2461
- if (!entry) return void 0;
2462
- this.cache.delete(key);
2463
- this.cache.set(key, entry);
2464
- return entry.value;
2465
- }
2466
- set(key, value) {
2467
- if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
2468
- const oldestKey = this.cache.keys().next().value;
2469
- if (oldestKey) {
2470
- this.cache.delete(oldestKey);
2471
- }
2472
- }
2473
- this.cache.set(key, { value, timestamp: Date.now() });
2474
- }
2475
- has(key) {
2476
- return this.cache.has(key);
2477
- }
2478
- delete(key) {
2479
- return this.cache.delete(key);
2480
- }
2481
- clear() {
2482
- this.cache.clear();
2483
- }
2484
- get size() {
2485
- return this.cache.size;
2486
- }
2487
- };
2488
- var componentCache = new ComponentCache();
2489
-
2490
- // libs/uipack/src/renderers/mdx-client.renderer.ts
2491
- function buildReactCdnUrls(version = "19") {
2492
- return {
2493
- react: `https://esm.sh/react@${version}`,
2494
- reactDom: `https://esm.sh/react-dom@${version}/client`,
2495
- jsxRuntime: `https://esm.sh/react@${version}/jsx-runtime`
2496
- };
2497
- }
2498
- var DEFAULT_CDN = {
2499
- mdx: "https://esm.sh/@mdx-js/mdx@3",
2500
- ...buildReactCdnUrls("19")
2501
- };
2502
- var MdxClientRenderer = class {
2503
- type = "mdx-client";
2504
- priority = 8;
2505
- // Lower than server-side MDX (10)
2506
- /**
2507
- * Check if this renderer can handle the given template.
2508
- */
2509
- canHandle(template) {
2510
- if (typeof template !== "string") {
2511
- return false;
2512
- }
2513
- return containsMdxSyntax(template);
2514
- }
2515
- /**
2516
- * Prepare MDX template for rendering.
2517
- * Caches the template hash for deduplication. Actual MDX compilation
2518
- * happens client-side via CDN-loaded @mdx-js/mdx in the browser.
2519
- */
2520
- async transpile(template, _options) {
2521
- const hash = hashString(template);
2522
- const cached = transpileCache.getByKey(hash);
2523
- if (cached) {
2524
- return { ...cached, cached: true };
2525
- }
2526
- const transpileResult = {
2527
- code: template,
2528
- hash,
2529
- cached: false
2530
- };
2531
- transpileCache.setByKey(hash, transpileResult);
2532
- return transpileResult;
2533
- }
2534
- /**
2535
- * Render MDX template to HTML with CDN scripts.
2536
- *
2537
- * The returned HTML includes:
2538
- * - A container div for the rendered content
2539
- * - Script tags that load React and MDX from CDN
2540
- * - Inline script that compiles and renders the MDX
2541
- */
2542
- async render(template, context, options) {
2543
- const containerId = options?.containerId || "mdx-content";
2544
- const showLoading = options?.showLoading !== false;
2545
- const loadingMessage = options?.loadingMessage || "Loading...";
2546
- const cdn = {
2547
- ...DEFAULT_CDN,
2548
- ...options?.cdn
2549
- };
2550
- const props = {
2551
- input: context.input,
2552
- output: context.output,
2553
- structuredContent: context.structuredContent,
2554
- helpers: context.helpers
2555
- };
2556
- const reservedProps = /* @__PURE__ */ new Set(["input", "output", "structuredContent", "helpers", "components"]);
2557
- const outputProps = typeof context.output === "object" && context.output !== null ? Object.fromEntries(Object.entries(context.output).filter(([key]) => !reservedProps.has(key))) : {};
2558
- const spreadProps = {
2559
- ...outputProps,
2560
- ...props
2561
- };
2562
- const escapedMdx = (0, import_utils.escapeScriptClose)(JSON.stringify(template));
2563
- const escapedProps = (0, import_utils.escapeScriptClose)(JSON.stringify(spreadProps));
2564
- const safeContainerId = (0, import_utils.escapeJsString)(containerId);
2565
- const loadingHtml = showLoading ? `<div class="mdx-loading">${(0, import_utils.escapeHtml)(loadingMessage)}</div>` : "";
2566
- return `
2567
- <div id="${(0, import_utils.escapeHtml)(containerId)}">${loadingHtml}</div>
2568
- <script type="module">
2569
- (async function() {
2570
- try {
2571
- // Load dependencies from CDN
2572
- const [
2573
- { evaluate },
2574
- runtime,
2575
- React,
2576
- { createRoot }
2577
- ] = await Promise.all([
2578
- import('${cdn.mdx}'),
2579
- import('${cdn.jsxRuntime}'),
2580
- import('${cdn.react}'),
2581
- import('${cdn.reactDom}')
2582
- ]);
2583
-
2584
- // MDX content and props
2585
- const mdxSource = ${escapedMdx};
2586
- const props = ${escapedProps};
2587
-
2588
- // Compile and evaluate MDX
2589
- const { default: Content } = await evaluate(mdxSource, {
2590
- ...runtime,
2591
- Fragment: React.Fragment,
2592
- development: false
2593
- });
2594
-
2595
- // Render to DOM
2596
- const container = document.getElementById('${safeContainerId}');
2597
- if (container) {
2598
- const root = createRoot(container);
2599
- root.render(React.createElement(Content, props));
2600
- }
2601
- } catch (error) {
2602
- console.error('[FrontMCP] MDX client rendering failed:', error);
2603
- const container = document.getElementById('${safeContainerId}');
2604
- if (container) {
2605
- container.innerHTML = '<div class="mdx-error">Failed to render MDX content</div>';
2606
- }
2607
- }
2608
- })();
2609
- </script>
2610
- `;
2611
- }
2612
- /**
2613
- * Get runtime scripts - not needed for client renderer since scripts are inline.
2614
- */
2615
- getRuntimeScripts(platform) {
2616
- if (platform.networkMode === "blocked") {
2617
- return {
2618
- headScripts: "",
2619
- inlineScripts: `console.warn('[FrontMCP] Client-side MDX rendering requires network access. Use @frontmcp/ui for SSR.');`,
2620
- isInline: true
2621
- };
2622
- }
2623
- return {
2624
- headScripts: "",
2625
- isInline: false
2626
- };
2627
- }
2628
- };
2629
- var mdxClientRenderer = new MdxClientRenderer();
2630
-
2631
- // libs/uipack/src/validation/schema-paths.ts
2632
- var import_zod2 = require("zod");
2633
- function extractSchemaPaths(schema, prefix = "output", options = {}) {
2634
- const { maxDepth = 10, includeArrayItems = true } = options;
2635
- const paths = [];
2636
- const visited = /* @__PURE__ */ new Set();
2637
- function recurse(currentSchema, currentPath, depth, isOptional, isNullable, isArrayItem) {
2638
- if (depth > maxDepth) return;
2639
- const pathKey = `${currentPath}:${depth}`;
2640
- if (visited.has(pathKey)) return;
2641
- visited.add(pathKey);
2642
- const description = currentSchema.description;
2643
- const innerType = unwrapType(currentSchema);
2644
- paths.push({
2645
- path: currentPath,
2646
- zodType: currentSchema,
2647
- optional: isOptional,
2648
- nullable: isNullable,
2649
- isArrayItem,
2650
- description
2651
- });
2652
- if (innerType instanceof import_zod2.z.ZodObject) {
2653
- const shape = innerType.shape;
2654
- for (const [key, value] of Object.entries(shape)) {
2655
- const childSchema = value;
2656
- const childOptional = isOptional || isOptionalType(childSchema);
2657
- const childNullable = isNullable || isNullableType(childSchema);
2658
- recurse(childSchema, `${currentPath}.${key}`, depth + 1, childOptional, childNullable, false);
2659
- }
2660
- } else if (innerType instanceof import_zod2.z.ZodArray && includeArrayItems) {
2661
- const itemSchema = innerType.element;
2662
- recurse(itemSchema, `${currentPath}.[]`, depth + 1, isOptional, isNullable, true);
2663
- } else if (innerType instanceof import_zod2.z.ZodUnion || innerType instanceof import_zod2.z.ZodDiscriminatedUnion) {
2664
- const options2 = "options" in innerType ? innerType.options : [];
2665
- for (const option of options2) {
2666
- recurse(option, currentPath, depth, isOptional, isNullable, isArrayItem);
2667
- }
2668
- } else if (innerType instanceof import_zod2.z.ZodIntersection) {
2669
- recurse(innerType._def.left, currentPath, depth, isOptional, isNullable, isArrayItem);
2670
- recurse(innerType._def.right, currentPath, depth, isOptional, isNullable, isArrayItem);
2671
- } else if (innerType instanceof import_zod2.z.ZodRecord) {
2672
- const valueSchema = innerType._def.valueType;
2673
- recurse(valueSchema, `${currentPath}.[]`, depth + 1, isOptional, isNullable, true);
2674
- } else if (innerType instanceof import_zod2.z.ZodTuple) {
2675
- const items = innerType._def.items;
2676
- items.forEach((item, index) => {
2677
- recurse(item, `${currentPath}.${index}`, depth + 1, isOptional, isNullable, true);
2678
- });
2679
- }
2680
- }
2681
- recurse(schema, prefix, 0, false, false, false);
2682
- const seen = /* @__PURE__ */ new Set();
2683
- return paths.filter((p) => {
2684
- if (seen.has(p.path)) return false;
2685
- seen.add(p.path);
2686
- return true;
2687
- });
2688
- }
2689
- function unwrapType(schema) {
2690
- if (schema instanceof import_zod2.z.ZodOptional) {
2691
- return unwrapType(schema.unwrap());
2692
- }
2693
- if (schema instanceof import_zod2.z.ZodNullable) {
2694
- return unwrapType(schema.unwrap());
2695
- }
2696
- if (schema instanceof import_zod2.z.ZodDefault) {
2697
- return unwrapType(schema._def.innerType);
2698
- }
2699
- if (schema instanceof import_zod2.z.ZodCatch && "innerType" in schema._def) {
2700
- return unwrapType(schema._def.innerType);
2701
- }
2702
- return schema;
2703
- }
2704
- function isOptionalType(schema) {
2705
- if (schema instanceof import_zod2.z.ZodOptional) return true;
2706
- if (schema instanceof import_zod2.z.ZodDefault) return true;
2707
- if (schema instanceof import_zod2.z.ZodNullable) return isOptionalType(schema.unwrap());
2708
- return false;
2709
- }
2710
- function isNullableType(schema) {
2711
- if (schema instanceof import_zod2.z.ZodNullable) return true;
2712
- if (schema instanceof import_zod2.z.ZodOptional) return isNullableType(schema.unwrap());
2713
- return false;
2714
- }
2715
- function getSchemaPathStrings(schema, prefix = "output") {
2716
- const paths = extractSchemaPaths(schema, prefix);
2717
- return new Set(paths.map((p) => p.path));
2718
- }
2719
-
2720
- // libs/uipack/src/validation/template-validator.ts
2721
- function validateTemplate(template, outputSchema, options = {}) {
2722
- const { inputSchema, warnOnOptional = true, suggestSimilar = true, maxSuggestionDistance = 3 } = options;
2723
- const errors = [];
2724
- const warnings = [];
2725
- const extraction = extractAll(template);
2726
- const expressions = extractExpressions(template);
2727
- const outputPaths = getSchemaPathStrings(outputSchema, "output");
2728
- const inputPaths = inputSchema ? getSchemaPathStrings(inputSchema, "input") : /* @__PURE__ */ new Set();
2729
- const outputPathInfos = extractSchemaPaths(outputSchema, "output");
2730
- const inputPathInfos = inputSchema ? extractSchemaPaths(inputSchema, "input") : [];
2731
- const pathInfoMap = /* @__PURE__ */ new Map();
2732
- for (const info of [...outputPathInfos, ...inputPathInfos]) {
2733
- pathInfoMap.set(info.path, info);
2734
- }
2735
- for (const expr of expressions) {
2736
- const { path, fullExpression, line, column } = expr;
2737
- let validPaths;
2738
- let allPaths;
2739
- if (path.startsWith("output.")) {
2740
- validPaths = outputPaths;
2741
- allPaths = Array.from(outputPaths);
2742
- } else if (path.startsWith("input.")) {
2743
- if (!inputSchema) {
2744
- continue;
2745
- }
2746
- validPaths = inputPaths;
2747
- allPaths = Array.from(inputPaths);
2748
- } else if (path.startsWith("structuredContent.")) {
2749
- continue;
2750
- } else {
2751
- continue;
2752
- }
2753
- const normalizedPath = normalizePath(path);
2754
- const isValid = validPaths.has(path) || validPaths.has(normalizedPath);
2755
- if (!isValid) {
2756
- const isArrayAccess = checkArrayAccess(path, validPaths);
2757
- if (!isArrayAccess) {
2758
- const suggestions = suggestSimilar ? findSimilarPaths(path, allPaths, maxSuggestionDistance) : [];
2759
- errors.push({
2760
- type: "missing_field",
2761
- path,
2762
- expression: fullExpression,
2763
- line,
2764
- column,
2765
- message: `Field '${getFieldName(path)}' does not exist in ${getSchemaName(path)} schema`,
2766
- suggestions
2767
- });
2768
- }
2769
- } else {
2770
- const pathInfo = pathInfoMap.get(path) ?? pathInfoMap.get(normalizedPath);
2771
- if (pathInfo && warnOnOptional) {
2772
- if (pathInfo.optional && expr.type === "variable") {
2773
- const hasGuard = hasConditionalGuard(template, path);
2774
- if (!hasGuard) {
2775
- warnings.push({
2776
- type: "optional_field",
2777
- path,
2778
- expression: fullExpression,
2779
- line,
2780
- message: `Accessing optional field '${getFieldName(path)}' without {{#if}} guard`
2781
- });
2782
- }
2783
- }
2784
- }
2785
- }
2786
- }
2787
- return {
2788
- valid: errors.length === 0,
2789
- errors,
2790
- warnings,
2791
- templatePaths: extraction.paths,
2792
- schemaPaths: [...outputPaths, ...inputPaths]
2793
- };
2794
- }
2795
- function checkArrayAccess(path, validPaths) {
2796
- const parts = path.split(".");
2797
- for (let i = 0; i < parts.length; i++) {
2798
- if (/^\d+$/.test(parts[i])) {
2799
- const wildcardParts = [...parts];
2800
- wildcardParts[i] = "[]";
2801
- const wildcardPath = wildcardParts.join(".");
2802
- if (validPaths.has(wildcardPath)) {
2803
- return true;
2804
- }
2805
- }
2806
- }
2807
- return false;
2808
- }
2809
- function getFieldName(path) {
2810
- const parts = path.split(".");
2811
- return parts[parts.length - 1];
2812
- }
2813
- function getSchemaName(path) {
2814
- if (path.startsWith("output.")) return "output";
2815
- if (path.startsWith("input.")) return "input";
2816
- if (path.startsWith("structuredContent.")) return "structuredContent";
2817
- return "unknown";
2818
- }
2819
- function hasConditionalGuard(template, path) {
2820
- const guardPattern = new RegExp(`\\{\\{#if\\s+${escapeRegex(path)}`, "i");
2821
- return guardPattern.test(template);
2822
- }
2823
- function escapeRegex(str) {
2824
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2825
- }
2826
- function findSimilarPaths(path, validPaths, maxDistance) {
2827
- const fieldName = getFieldName(path);
2828
- const prefix = path.substring(0, path.lastIndexOf(".") + 1);
2829
- const suggestions = [];
2830
- for (const validPath of validPaths) {
2831
- if (!validPath.startsWith(prefix)) continue;
2832
- const validFieldName = getFieldName(validPath);
2833
- const distance = levenshteinDistance(fieldName, validFieldName);
2834
- if (distance <= maxDistance && distance > 0) {
2835
- suggestions.push({ path: validPath, distance });
2836
- }
2837
- }
2838
- return suggestions.sort((a, b) => a.distance - b.distance).slice(0, 3).map((s) => s.path);
2839
- }
2840
- function levenshteinDistance(a, b) {
2841
- const matrix = [];
2842
- for (let i = 0; i <= a.length; i++) {
2843
- matrix[i] = [i];
2844
- }
2845
- for (let j = 0; j <= b.length; j++) {
2846
- matrix[0][j] = j;
2847
- }
2848
- for (let i = 1; i <= a.length; i++) {
2849
- for (let j = 1; j <= b.length; j++) {
2850
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
2851
- matrix[i][j] = Math.min(
2852
- matrix[i - 1][j] + 1,
2853
- // deletion
2854
- matrix[i][j - 1] + 1,
2855
- // insertion
2856
- matrix[i - 1][j - 1] + cost
2857
- // substitution
2858
- );
2859
- }
2860
- }
2861
- return matrix[a.length][b.length];
2862
- }
2863
- function formatValidationWarnings(result, toolName) {
2864
- if (result.valid && result.warnings.length === 0) {
2865
- return "";
2866
- }
2867
- const lines = [];
2868
- if (result.errors.length > 0) {
2869
- lines.push(`[FrontMCP] Template validation warnings for tool "${toolName}":`);
2870
- lines.push("");
2871
- for (const error of result.errors) {
2872
- lines.push(` Line ${error.line}: ${error.expression}`);
2873
- lines.push(` ${error.message}`);
2874
- if (error.suggestions.length > 0) {
2875
- lines.push(` Did you mean: ${error.suggestions.join(", ")}?`);
2876
- }
2877
- lines.push("");
2878
- }
2879
- const outputFields = result.schemaPaths.filter((p) => p.startsWith("output.") && p.split(".").length === 2).map((p) => p.replace("output.", ""));
2880
- if (outputFields.length > 0) {
2881
- lines.push(` Available output fields: ${outputFields.join(", ")}`);
2882
- }
2883
- }
2884
- if (result.warnings.length > 0) {
2885
- if (lines.length > 0) lines.push("");
2886
- lines.push(` Warnings:`);
2887
- for (const warning of result.warnings) {
2888
- lines.push(` Line ${warning.line}: ${warning.message}`);
2889
- }
2890
- }
2891
- return lines.join("\n");
2892
- }
2893
- function logValidationWarnings(result, toolName) {
2894
- const formatted = formatValidationWarnings(result, toolName);
2895
- if (formatted) {
2896
- console.warn(formatted);
2897
- }
2898
- }
2899
-
2900
- // libs/uipack/src/dependency/template-processor.ts
2901
- function safeInputToRecord(input) {
2902
- if (input && typeof input === "object" && !Array.isArray(input)) {
2903
- return input;
2904
- }
2905
- return {};
2906
- }
2907
- var defaultHelpers = {
2908
- escapeHtml: import_utils.escapeHtml,
2909
- formatDate: (date, format) => {
2910
- const d = date instanceof Date ? date : new Date(date);
2911
- if (format === "iso") return d.toISOString();
2912
- if (format === "time") return d.toLocaleTimeString();
2913
- return d.toLocaleDateString();
2914
- },
2915
- formatCurrency: (amount, currency = "USD") => new Intl.NumberFormat("en-US", { style: "currency", currency }).format(amount),
2916
- uniqueId: (prefix = "id") => `${prefix}-${Math.random().toString(36).substring(2, 9)}`,
2917
- jsonEmbed: (data) => JSON.stringify(data).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026")
2918
- };
2919
- function getSourceName(source) {
2920
- switch (source.type) {
2921
- case "file":
2922
- return source.path;
2923
- case "url":
2924
- return source.url;
2925
- case "inline":
2926
- return "inline-template";
2927
- }
2928
- }
2929
- var handlebarsRenderer = null;
2930
- async function getHandlebarsRenderer(customHelpers) {
2931
- if (customHelpers) {
2932
- const freshRenderer = new HandlebarsRenderer();
2933
- for (const [name, fn] of Object.entries(customHelpers)) {
2934
- freshRenderer.registerHelper(name, fn);
2935
- }
2936
- return freshRenderer;
2937
- }
2938
- if (!handlebarsRenderer) {
2939
- handlebarsRenderer = new HandlebarsRenderer();
2940
- }
2941
- return handlebarsRenderer;
2942
- }
2943
- function clearHandlebarsCache() {
2944
- if (handlebarsRenderer) {
2945
- handlebarsRenderer.clearCache();
2946
- }
2947
- }
2948
- var markedModule = null;
2949
- async function loadMarked() {
2950
- if (markedModule) {
2951
- return markedModule;
2952
- }
2953
- try {
2954
- const moduleName = "marked";
2955
- markedModule = await import(
2956
- /* webpackIgnore: true */
2957
- moduleName
2958
- );
2959
- return markedModule;
2960
- } catch {
2961
- throw new Error("marked is required for Markdown rendering. Install it: npm install marked");
2962
- }
2963
- }
2964
- async function isMarkedAvailable() {
2965
- try {
2966
- await loadMarked();
2967
- return true;
2968
- } catch {
2969
- return false;
2970
- }
2971
- }
2972
- async function processTemplate(resolved, options) {
2973
- const { format, content } = resolved;
2974
- const { context, handlebarsHelpers, outputSchema, inputSchema, toolName } = options;
2975
- if (format === "react") {
2976
- return {
2977
- code: content,
2978
- format: "react",
2979
- needsBundling: true
2980
- };
2981
- }
2982
- if (outputSchema && process.env["NODE_ENV"] !== "production" && containsHandlebars(content)) {
2983
- const sourceName = getSourceName(resolved.source);
2984
- const validation = validateTemplate(content, outputSchema, {
2985
- inputSchema,
2986
- warnOnOptional: true,
2987
- suggestSimilar: true,
2988
- toolName: toolName ?? sourceName
2989
- });
2990
- if (!validation.valid || validation.warnings.length > 0) {
2991
- logValidationWarnings(validation, toolName ?? sourceName ?? "unknown");
2992
- }
2993
- }
2994
- let processedContent = content;
2995
- if (containsHandlebars(content)) {
2996
- const hbs = await getHandlebarsRenderer(handlebarsHelpers);
2997
- const renderContext = {
2998
- input: safeInputToRecord(context.input),
2999
- output: context.output,
3000
- structuredContent: context.structuredContent
3001
- };
3002
- processedContent = await hbs.render(content, renderContext);
3003
- }
3004
- switch (format) {
3005
- case "html":
3006
- return {
3007
- html: processedContent,
3008
- format: "html"
3009
- };
3010
- case "markdown": {
3011
- const { marked } = await loadMarked();
3012
- const html = await marked.parse(processedContent);
3013
- return {
3014
- html,
3015
- format: "markdown"
3016
- };
3017
- }
3018
- case "mdx": {
3019
- const templateContext = {
3020
- input: context.input,
3021
- output: context.output,
3022
- structuredContent: context.structuredContent,
3023
- helpers: defaultHelpers
3024
- };
3025
- const html = await mdxClientRenderer.render(processedContent, templateContext);
3026
- return {
3027
- html,
3028
- format: "mdx"
3029
- };
3030
- }
3031
- default:
3032
- return {
3033
- html: processedContent,
3034
- format: "html"
3035
- };
3036
- }
3037
- }
3038
- async function processTemplates(items) {
3039
- return Promise.all(items.map(({ resolved, options }) => processTemplate(resolved, options)));
3040
- }
3041
- function supportsHandlebars(format) {
3042
- return format === "html" || format === "markdown" || format === "mdx";
3043
- }
3044
- function producesHtml(format) {
3045
- return format !== "react";
3046
- }
3047
- function requiresBundling(format) {
3048
- return format === "react";
3049
- }
3050
- async function processHtmlTemplate(content, context, helpers) {
3051
- if (!containsHandlebars(content)) {
3052
- return content;
3053
- }
3054
- const hbs = await getHandlebarsRenderer(helpers);
3055
- const renderContext = {
3056
- input: safeInputToRecord(context.input),
3057
- output: context.output,
3058
- structuredContent: context.structuredContent
3059
- };
3060
- return hbs.render(content, renderContext);
3061
- }
3062
- async function processMarkdownTemplate(content, context, helpers) {
3063
- let processed = content;
3064
- if (containsHandlebars(content)) {
3065
- const hbs = await getHandlebarsRenderer(helpers);
3066
- const renderContext = {
3067
- input: safeInputToRecord(context.input),
3068
- output: context.output,
3069
- structuredContent: context.structuredContent
3070
- };
3071
- processed = await hbs.render(content, renderContext);
3072
- }
3073
- const { marked } = await loadMarked();
3074
- return marked.parse(processed);
3075
- }
3076
- async function processMdxTemplate(content, context, helpers) {
3077
- let processed = content;
3078
- if (containsHandlebars(content)) {
3079
- const hbs = await getHandlebarsRenderer(helpers);
3080
- const renderContext = {
3081
- input: safeInputToRecord(context.input),
3082
- output: context.output,
3083
- structuredContent: context.structuredContent
3084
- };
3085
- processed = await hbs.render(content, renderContext);
3086
- }
3087
- const templateContext = {
3088
- input: context.input,
3089
- output: context.output,
3090
- structuredContent: context.structuredContent,
3091
- helpers: defaultHelpers
3092
- };
3093
- return mdxClientRenderer.render(processed, templateContext);
3094
- }
3095
- // Annotate the CommonJS export names for ESM import in node:
3096
- 0 && (module.exports = {
3097
- CDN_PROVIDER_PRIORITY,
3098
- DEFAULT_CDN_REGISTRY,
3099
- DependencyResolutionError,
3100
- DependencyResolver,
3101
- NoProviderError,
3102
- addScope,
3103
- buildManifestMetadataSchema,
3104
- buildManifestOutputsSchema,
3105
- bundleTargetSchema,
3106
- cacheStatsSchema,
3107
- cdnDependencySchema,
3108
- cdnPlatformTypeSchema,
3109
- cdnProviderConfigSchema,
3110
- cdnProviderSchema,
3111
- cdnRegistryEntrySchema,
3112
- clearHandlebarsCache,
3113
- clearUrlCache,
3114
- componentBuildManifestSchema,
3115
- createClaudeResolver,
3116
- createImportMap,
3117
- createImportMapFromOverrides,
3118
- createOpenAIResolver,
3119
- createResolver,
3120
- dependencyResolverOptionsSchema,
3121
- detectFormatFromPath,
3122
- detectFormatFromUrl,
3123
- detectTemplateMode,
3124
- detectTemplateSource,
3125
- extractExternalPackages,
3126
- fetchTemplateFromUrl,
3127
- fileBundleOptionsSchema,
3128
- fileTemplateConfigSchema,
3129
- filterImportsByPackages,
3130
- generateCDNScriptTags,
3131
- generateDependencyHTML,
3132
- generateESMScriptTags,
3133
- generateImportMapForPackages,
3134
- generateImportMapScriptTag,
3135
- generateImportMapScriptTagMinified,
3136
- generateUMDShim,
3137
- getImportStats,
3138
- getPackageCDNDependency,
3139
- getPackageCDNUrl,
3140
- getPackageName,
3141
- getPackagePeerDependencies,
3142
- getRegisteredPackages,
3143
- getUrlCache,
3144
- importMapSchema,
3145
- importTypeSchema,
3146
- invalidateUrlCache,
3147
- isFileBasedTemplate,
3148
- isMarkedAvailable,
3149
- isPackageRegistered,
3150
- lookupPackage,
3151
- mergeImportMaps,
3152
- mergeRegistries,
3153
- needsRefetch,
3154
- packageMetadataSchema,
3155
- parseImports,
3156
- parsedImportResultSchema,
3157
- parsedImportSchema,
3158
- processHtmlTemplate,
3159
- processMarkdownTemplate,
3160
- processMdxTemplate,
3161
- processTemplate,
3162
- processTemplates,
3163
- producesHtml,
3164
- readTemplateFromFile,
3165
- requiresBundling,
3166
- resolveAllDependencies,
3167
- resolveDependencies,
3168
- resolveFilePath,
3169
- resolveTemplate,
3170
- resolvedDependencySchema,
3171
- safeParseBuildManifest,
3172
- safeParseCDNDependency,
3173
- safeParseFileTemplateConfig,
3174
- supportsHandlebars,
3175
- validateBuildManifest,
3176
- validateCDNDependency,
3177
- validateFileTemplateConfig,
3178
- validateImportMap,
3179
- validateTemplateUrl
3180
- });