@melt-js/libs-core 2026.11.15 → 2026.11.16-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +73 -16
  2. package/dist/browser.d.mts +3 -0
  3. package/dist/browser.mjs +1 -50
  4. package/dist/browser.mjs.gz +0 -0
  5. package/dist/cdn/browser.umd.cjs +2 -0
  6. package/dist/cdn/browser.umd.cjs.gz +0 -0
  7. package/dist/cdn/demo-browser.umd.cjs +2 -0
  8. package/dist/cdn/demo-browser.umd.cjs.gz +0 -0
  9. package/dist/cdn/demo.umd.cjs +2 -0
  10. package/dist/cdn/demo.umd.cjs.gz +0 -0
  11. package/dist/cdn/example-esm.html +1 -0
  12. package/dist/cdn/example-umd.html +1 -0
  13. package/dist/cdn/index.umd.cjs +2 -0
  14. package/dist/cdn/index.umd.cjs.gz +0 -0
  15. package/dist/cdn/manifest.json +141 -0
  16. package/dist/cdn/vendor.umd.cjs +16 -0
  17. package/dist/cdn/vendor.umd.cjs.gz +0 -0
  18. package/dist/cdn.d.mts +3 -0
  19. package/dist/cdn.mjs +1 -0
  20. package/dist/demo/browser.d.mts +1 -0
  21. package/dist/demo/browser.mjs +1 -0
  22. package/dist/demo/browser.mjs.gz +0 -0
  23. package/dist/demo/clipboard.d.mts +6 -0
  24. package/dist/demo/clipboard.mjs +1 -0
  25. package/{src → dist}/demo/docs.d.mts +3 -0
  26. package/dist/demo/docs.mjs +1 -0
  27. package/dist/demo/docs.mjs.gz +0 -0
  28. package/{src → dist}/demo/download.d.mts +10 -2
  29. package/dist/demo/download.mjs +1 -0
  30. package/dist/demo/download.mjs.gz +0 -0
  31. package/dist/demo/fullscreen.mjs +1 -0
  32. package/dist/demo/highlight.d.mts +2 -0
  33. package/dist/demo/highlight.mjs +1 -0
  34. package/dist/demo/index.d.mts +10 -0
  35. package/dist/demo/index.mjs +1 -0
  36. package/dist/demo/model.mjs +1 -0
  37. package/dist/demo/remote-debug.d.mts +9 -0
  38. package/dist/demo/remote-debug.mjs +1 -0
  39. package/{src → dist}/demo/runtime.mjs +92 -104
  40. package/dist/demo/split-pane.d.mts +8 -0
  41. package/dist/demo/split-pane.mjs +1 -0
  42. package/dist/demo/standalone.d.mts +12 -0
  43. package/dist/demo/standalone.mjs +1 -0
  44. package/dist/demo/standalone.mjs.gz +0 -0
  45. package/dist/demo/tabs.d.mts +15 -0
  46. package/dist/demo/tabs.mjs +1 -0
  47. package/{src/index.ts → dist/index.d.ts} +1 -1
  48. package/dist/loading.mjs +1 -0
  49. package/dist/loading.mjs.gz +0 -0
  50. package/dist/remote-address.cjs +2 -0
  51. package/{src → dist}/remote.d.mts +20 -2
  52. package/dist/remote.mjs +1 -0
  53. package/dist/remote.mjs.gz +0 -0
  54. package/dist/vendor/hel-runtime.mjs +16 -0
  55. package/dist/vendor/hel-runtime.mjs.gz +0 -0
  56. package/package.json +41 -25
  57. package/scripts/browser-formats.mjs +357 -0
  58. package/scripts/build-browser.mjs +59 -13
  59. package/scripts/build-protected-esm.mjs +54 -0
  60. package/scripts/cdn-runtime.cjs +30 -0
  61. package/scripts/check-tdz.mjs +327 -324
  62. package/scripts/client-build-security.cjs +48 -0
  63. package/scripts/comps-bundle-obfuscation.cjs +269 -262
  64. package/scripts/comps-obfuscator-options.cjs +7 -1
  65. package/scripts/hel-build-paths.cjs +49 -48
  66. package/scripts/obfuscator-split-strings.cjs +22 -0
  67. package/scripts/package-artifacts.mjs +206 -0
  68. package/scripts/package-env.cjs +156 -193
  69. package/scripts/publish-stage.mjs +50 -42
  70. package/scripts/webpack-bundle-obfuscation.cjs +125 -121
  71. package/demo/index.js +0 -1
  72. package/dist/hel-deployment.json +0 -8
  73. package/src/browser.d.mts +0 -2
  74. package/src/browser.mjs +0 -3
  75. package/src/demo/docs.mjs +0 -75
  76. package/src/demo/download.mjs +0 -118
  77. package/src/demo/fullscreen.mjs +0 -80
  78. package/src/demo/index.d.mts +0 -4
  79. package/src/demo/index.mjs +0 -4
  80. package/src/demo/model.mjs +0 -203
  81. package/src/remote.mjs +0 -286
  82. package/tsconfig.json +0 -13
  83. /package/{src → dist}/demo/fullscreen.d.mts +0 -0
  84. /package/{src → dist}/demo/model.d.mts +0 -0
  85. /package/{src → scripts}/remote-address.cjs +0 -0
@@ -1,121 +1,125 @@
1
- const { createHash } = require('node:crypto')
2
- const { createModuleClassifier } = require('./comps-bundle-obfuscation.cjs')
3
- const defaults = require('./comps-obfuscator-options.cjs')
4
- const hash = source => createHash('sha256').update(source).digest('hex')
5
- const excluded = /(?:^|\/)(?:vendor|runtime)(?:[-.\/]|$)/
6
-
7
- function webpackBundlePolicy({ root, Obfuscator, enabled = true }) {
8
- const classify = createModuleClassifier(root)
9
- const settings = { ...defaults, seed: 1, renameGlobals: false, renameProperties: false, sourceMap: false }
10
- const reports = []
11
- const reportChunks = new Map()
12
- const plugin = new Obfuscator(settings, ['**/vendor*.js', 'vendor*.js', '**/runtime*.js', 'runtime*.js'])
13
- const guard = {
14
- name: 'hel:webpack-bundle-boundaries', api: { reports, classify },
15
- apply(compiler) {
16
- const inspect = compilation => {
17
- reports.length = 0
18
- reportChunks.clear()
19
- for (const chunk of compilation.chunks) {
20
- const modules = compilation.chunkGraph ? [...compilation.chunkGraph.getChunkModulesIterable(chunk)] : [...chunk.modulesIterable]
21
- const entries = modules.flatMap(module => module.modules ? [...module.modules] : [module])
22
- .filter(module => module.resource && !module.externalType)
23
- .map(module => ({ id: module.resource.replaceAll('\\', '/'), kind: classify(module.resource) }))
24
- const protectedModules = entries.filter(module => ['own', 'related'].includes(module.kind)).length
25
- const thirdPartyModules = entries.filter(module => module.kind === 'thirdParty').length
26
- for (const filename of chunk.files) {
27
- if (!filename.endsWith('.js')) continue
28
- if (protectedModules && thirdPartyModules) throw new Error('Mixed business/vendor chunk: ' + filename)
29
- if (thirdPartyModules && !excluded.test(filename)) throw new Error('Vendor chunk not excluded: ' + filename)
30
- if (protectedModules && excluded.test(filename)) throw new Error('Protected module in excluded chunk: ' + filename)
31
- const report = { fileName: filename, modules: entries, protectedModules, thirdPartyModules, excluded: excluded.test(filename), beforeHash: hash(compilation.assets[filename].source()) }
32
- reports.push(report)
33
- reportChunks.set(report, chunk)
34
- }
35
- }
36
- }
37
- const verify = compilation => {
38
- for (const report of reports) {
39
- const code = compilation.assets[report.fileName].source().toString()
40
- report.afterHash = hash(code)
41
- report.identifiers = (code.match(/\b_0x[\da-f]+\b/g) || []).length
42
- report.obfuscated = report.beforeHash !== report.afterHash
43
- if (report.excluded && report.obfuscated) throw new Error('Excluded vendor changed: ' + report.fileName)
44
- if (enabled && report.protectedModules && (!report.obfuscated || !report.identifiers)) throw new Error('Final business chunk is not obfuscated: ' + report.fileName)
45
- console.log(`[hel:webpack-bundle] ${report.fileName}: protected=${report.protectedModules}, third-party=${report.thirdPartyModules}, _0x=${report.identifiers}`)
46
- }
47
- }
48
- // webpack-obfuscator v2 uses emit; v3 uses processAssets DEV_TOOLING.
49
- // Compression plugins can also use DEV_TOOLING, so pin obfuscation directly
50
- // after minimizers and before transfer compression, independent of array order.
51
- const modern = Boolean(compiler.webpack?.Compilation)
52
- if (modern) {
53
- compiler.hooks.compilation.tap('hel:webpack-bundle-boundaries', compilation => {
54
- const stage = compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1
55
- compilation.hooks.processAssets.tap({ name: 'hel:webpack-before', stage }, () => inspect(compilation))
56
- if (enabled) {
57
- const facade = Object.create(compiler)
58
- facade.hooks = { ...compiler.hooks, compilation: { tap(_name, callback) {
59
- const proxy = Object.create(compilation)
60
- proxy.hooks = { ...compilation.hooks, processAssets: Object.fromEntries(
61
- ['tap', 'tapPromise', 'tapAsync'].map(method => [method, (options, handler) => {
62
- compilation.hooks.processAssets[method]({ ...(typeof options === 'string' ? { name: options } : options), stage: stage + 1 }, handler)
63
- }]),
64
- ) }
65
- callback(proxy)
66
- } } }
67
- plugin.apply(facade)
68
- }
69
- compilation.hooks.processAssets.tap({ name: 'hel:webpack-after', stage: stage + 2 }, () => verify(compilation))
70
- // RealContentHashPlugin can rename assets and rewrite runtime URLs later.
71
- // Report final filenames/bytes after all processAssets stages, not stale pre-hash names.
72
- compilation.hooks.afterProcessAssets.tap('hel:webpack-final-bytes', () => {
73
- for (const report of reports) {
74
- const files = [...reportChunks.get(report).files].filter(file => file.endsWith('.js'))
75
- if (files.length !== 1) throw new Error('Expected one JS asset per audited chunk')
76
- report.fileName = files[0]
77
- const code = compilation.assets[report.fileName].source().toString()
78
- report.afterHash = hash(code)
79
- report.identifiers = (code.match(/\b_0x[\da-f]+\b/g) || []).length
80
- if (enabled && report.protectedModules && !report.identifiers) throw new Error('Final business identifiers were lost: ' + report.fileName)
81
- }
82
- })
83
- })
84
- } else {
85
- compiler.hooks.emit.tap({ name: 'hel:webpack-before', stage: -200 }, inspect)
86
- if (enabled) {
87
- const facade = Object.create(compiler)
88
- facade.hooks = { ...compiler.hooks, emit: { tap(name, callback) {
89
- compiler.hooks.emit.tap({ name: typeof name === 'string' ? name : name.name, stage: -190 }, callback)
90
- } } }
91
- plugin.apply(facade)
92
- }
93
- compiler.hooks.emit.tap({ name: 'hel:webpack-after', stage: -180 }, verify)
94
- }
95
- },
96
- }
97
- return {
98
- plugin: guard,
99
- optimization: {
100
- // Do not let a concatenated module obscure business/vendor provenance.
101
- concatenateModules: false,
102
- runtimeChunk: { name: 'runtime' },
103
- splitChunks: { chunks: 'all', minSize: 0, cacheGroups: {
104
- default: false, defaultVendors: false, vendors: false,
105
- helVendor: { name: 'vendor', chunks: 'all', enforce: true, priority: 100,
106
- test: module => Boolean(module.resource) && classify(module.resource) === 'thirdParty' },
107
- } },
108
- },
109
- }
110
- }
111
-
112
- function applyWebpackBundlePolicy(config, { root, Obfuscator, enabled = process.env.HEL_OBFUSCATE !== '0' }) {
113
- if (process.env.NODE_ENV !== 'production' && config.mode !== 'production') return config
114
- const policy = webpackBundlePolicy({ root, Obfuscator, enabled })
115
- config.devtool = false
116
- config.plugins = (config.plugins || []).filter(plugin => plugin?.constructor?.name !== 'LimitChunkCountPlugin')
117
- config.optimization = { ...config.optimization, ...policy.optimization }
118
- config.plugins.push(policy.plugin)
119
- return config
120
- }
121
- module.exports = { webpackBundlePolicy, applyWebpackBundlePolicy }
1
+ const { createHash } = require('node:crypto')
2
+ const { createModuleClassifier } = require('./comps-bundle-obfuscation.cjs')
3
+ const defaults = require('./comps-obfuscator-options.cjs')
4
+ const { splitStringsChunkLength } = require('./obfuscator-split-strings.cjs')
5
+ const { applyWebpackClientSecurity } = require('./client-build-security.cjs')
6
+ const hash = source => createHash('sha256').update(source).digest('hex')
7
+ const excluded = /(?:^|\/)(?:vendor|runtime)(?:[-.\/]|$)/
8
+
9
+ function webpackBundlePolicy({ root, Obfuscator, enabled = true }) {
10
+ const classify = createModuleClassifier(root)
11
+ const settings = { ...defaults, splitStringsChunkLength: splitStringsChunkLength(root),
12
+ seed: 1, renameGlobals: false, renameProperties: false, sourceMap: false }
13
+ const reports = []
14
+ const reportChunks = new Map()
15
+ const plugin = new Obfuscator(settings, ['**/vendor*.js', 'vendor*.js', '**/runtime*.js', 'runtime*.js'])
16
+ const guard = {
17
+ name: 'hel:webpack-bundle-boundaries', api: { reports, classify },
18
+ apply(compiler) {
19
+ const inspect = compilation => {
20
+ reports.length = 0
21
+ reportChunks.clear()
22
+ for (const chunk of compilation.chunks) {
23
+ const modules = compilation.chunkGraph ? [...compilation.chunkGraph.getChunkModulesIterable(chunk)] : [...chunk.modulesIterable]
24
+ const entries = modules.flatMap(module => module.modules ? [...module.modules] : [module])
25
+ .filter(module => module.resource && !module.externalType)
26
+ .map(module => ({ id: module.resource.replaceAll('\\', '/'), kind: classify(module.resource) }))
27
+ const protectedModules = entries.filter(module => ['own', 'related'].includes(module.kind)).length
28
+ const thirdPartyModules = entries.filter(module => module.kind === 'thirdParty').length
29
+ for (const filename of chunk.files) {
30
+ if (!filename.endsWith('.js')) continue
31
+ if (protectedModules && thirdPartyModules) throw new Error('Mixed business/vendor chunk: ' + filename)
32
+ if (thirdPartyModules && !excluded.test(filename)) throw new Error('Vendor chunk not excluded: ' + filename)
33
+ if (protectedModules && excluded.test(filename)) throw new Error('Protected module in excluded chunk: ' + filename)
34
+ const report = { fileName: filename, modules: entries, protectedModules, thirdPartyModules, excluded: excluded.test(filename), beforeHash: hash(compilation.assets[filename].source()) }
35
+ reports.push(report)
36
+ reportChunks.set(report, chunk)
37
+ }
38
+ }
39
+ }
40
+ const verify = compilation => {
41
+ for (const report of reports) {
42
+ const code = compilation.assets[report.fileName].source().toString()
43
+ report.afterHash = hash(code)
44
+ report.identifiers = (code.match(/\b_0x[\da-f]+\b/g) || []).length
45
+ report.obfuscated = report.beforeHash !== report.afterHash
46
+ if (report.excluded && report.obfuscated) throw new Error('Excluded vendor changed: ' + report.fileName)
47
+ if (enabled && report.protectedModules && (!report.obfuscated || !report.identifiers)) throw new Error('Final business chunk is not obfuscated: ' + report.fileName)
48
+ console.log(`[hel:webpack-bundle] ${report.fileName}: protected=${report.protectedModules}, third-party=${report.thirdPartyModules}, _0x=${report.identifiers}`)
49
+ }
50
+ }
51
+ // webpack-obfuscator v2 uses emit; v3 uses processAssets DEV_TOOLING.
52
+ // Compression plugins can also use DEV_TOOLING, so pin obfuscation directly
53
+ // after minimizers and before transfer compression, independent of array order.
54
+ const modern = Boolean(compiler.webpack?.Compilation)
55
+ if (modern) {
56
+ compiler.hooks.compilation.tap('hel:webpack-bundle-boundaries', compilation => {
57
+ const stage = compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1
58
+ compilation.hooks.processAssets.tap({ name: 'hel:webpack-before', stage }, () => inspect(compilation))
59
+ if (enabled) {
60
+ const facade = Object.create(compiler)
61
+ facade.hooks = { ...compiler.hooks, compilation: { tap(_name, callback) {
62
+ const proxy = Object.create(compilation)
63
+ proxy.hooks = { ...compilation.hooks, processAssets: Object.fromEntries(
64
+ ['tap', 'tapPromise', 'tapAsync'].map(method => [method, (options, handler) => {
65
+ compilation.hooks.processAssets[method]({ ...(typeof options === 'string' ? { name: options } : options), stage: stage + 1 }, handler)
66
+ }]),
67
+ ) }
68
+ callback(proxy)
69
+ } } }
70
+ plugin.apply(facade)
71
+ }
72
+ compilation.hooks.processAssets.tap({ name: 'hel:webpack-after', stage: stage + 2 }, () => verify(compilation))
73
+ // RealContentHashPlugin can rename assets and rewrite runtime URLs later.
74
+ // Report final filenames/bytes after all processAssets stages, not stale pre-hash names.
75
+ compilation.hooks.afterProcessAssets.tap('hel:webpack-final-bytes', () => {
76
+ for (const report of reports) {
77
+ const files = [...reportChunks.get(report).files].filter(file => file.endsWith('.js'))
78
+ if (files.length !== 1) throw new Error('Expected one JS asset per audited chunk')
79
+ report.fileName = files[0]
80
+ const code = compilation.assets[report.fileName].source().toString()
81
+ report.afterHash = hash(code)
82
+ report.identifiers = (code.match(/\b_0x[\da-f]+\b/g) || []).length
83
+ if (enabled && report.protectedModules && !report.identifiers) throw new Error('Final business identifiers were lost: ' + report.fileName)
84
+ }
85
+ })
86
+ })
87
+ } else {
88
+ compiler.hooks.emit.tap({ name: 'hel:webpack-before', stage: -200 }, inspect)
89
+ if (enabled) {
90
+ const facade = Object.create(compiler)
91
+ facade.hooks = { ...compiler.hooks, emit: { tap(name, callback) {
92
+ compiler.hooks.emit.tap({ name: typeof name === 'string' ? name : name.name, stage: -190 }, callback)
93
+ } } }
94
+ plugin.apply(facade)
95
+ }
96
+ compiler.hooks.emit.tap({ name: 'hel:webpack-after', stage: -180 }, verify)
97
+ }
98
+ },
99
+ }
100
+ return {
101
+ plugin: guard,
102
+ optimization: {
103
+ // Do not let a concatenated module obscure business/vendor provenance.
104
+ concatenateModules: false,
105
+ runtimeChunk: { name: 'runtime' },
106
+ splitChunks: { chunks: 'all', minSize: 0, cacheGroups: {
107
+ default: false, defaultVendors: false, vendors: false,
108
+ helVendor: { name: 'vendor', chunks: 'all', enforce: true, priority: 100,
109
+ test: module => Boolean(module.resource) && classify(module.resource) === 'thirdParty' },
110
+ } },
111
+ },
112
+ }
113
+ }
114
+
115
+ function applyWebpackBundlePolicy(config, { root, Obfuscator, enabled = process.env.HEL_OBFUSCATE !== '0' }) {
116
+ if (process.env.NODE_ENV !== 'production' && config.mode !== 'production') return config
117
+ applyWebpackClientSecurity(config)
118
+ const policy = webpackBundlePolicy({ root, Obfuscator, enabled })
119
+ config.devtool = false
120
+ config.plugins = (config.plugins || []).filter(plugin => plugin?.constructor?.name !== 'LimitChunkCountPlugin')
121
+ config.optimization = { ...config.optimization, ...policy.optimization }
122
+ config.plugins.push(policy.plugin)
123
+ return config
124
+ }
125
+ module.exports = { webpackBundlePolicy, applyWebpackBundlePolicy }
package/demo/index.js DELETED
@@ -1 +0,0 @@
1
- export * from '../src/demo/index.mjs'
@@ -1,8 +0,0 @@
1
- {
2
- "target": "unpkg",
3
- "name": "@melt-js/libs-core",
4
- "version": "2026.11.15",
5
- "publicUrl": "https://unpkg.com/@melt-js/libs-core@2026.11.15/dist",
6
- "homePage": "/@melt-js/libs-core@2026.11.15/dist",
7
- "remotes": {}
8
- }
package/src/browser.d.mts DELETED
@@ -1,2 +0,0 @@
1
- export * from './remote.mjs'
2
- export { bindReactRuntime } from 'hel-micro'
package/src/browser.mjs DELETED
@@ -1,3 +0,0 @@
1
- // A bundled, native ESM entry for HTML hosts without a package bundler.
2
- export * from './remote.mjs'
3
- export { bindReactRuntime } from 'hel-micro'
package/src/demo/docs.mjs DELETED
@@ -1,75 +0,0 @@
1
- const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key)
2
- const kebab = name => name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()
3
- const handlerName = name => 'on' + name.replace(/(^|[^a-zA-Z0-9])([a-zA-Z0-9])/g, (_, __, letter) => letter.toUpperCase())
4
- const attr = value => String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '&#10;')
5
-
6
- function literal(value) {
7
- if (typeof value === 'function') return '() => {}'
8
- if (value === undefined) return 'undefined'
9
- try {
10
- const result = JSON.stringify(value, (_, item) => typeof item === 'function' ? undefined : typeof item === 'bigint' ? String(item) : item)
11
- return result === undefined ? 'undefined' : result
12
- }
13
- catch { return 'undefined /* 请提供可序列化的值 */' }
14
- }
15
-
16
- /** Schema defaults describe the API; values describe the current live example. */
17
- export function buildComponentDocs({ name = 'Component', schema = [], values = {}, framework = 'vue3', events = [], slotHtml = {}, description = '', requirements = [], code, models = [] } = {}) {
18
- const props = schema.filter(prop => !prop.isEvent).map(prop => ({
19
- name: prop.name, type: prop.type || 'unknown',
20
- default: prop.default === undefined || prop.default === '' ? '—' : String(prop.default),
21
- required: prop.required === true || prop.required === 'true', description: prop.description || '—',
22
- }))
23
- const eventMap = new Map()
24
- for (const event of [...schema.filter(prop => prop.isEvent), ...events]) {
25
- const item = typeof event === 'string' ? { name: event } : event
26
- if (item && item.name) eventMap.set(item.name, { ...eventMap.get(item.name), ...item })
27
- }
28
- const eventRows = [...eventMap.values()].map(event => ({
29
- name: event.name, type: event.type || '未声明参数类型', description: event.description || '—',
30
- }))
31
- const entries = Object.entries(values).filter(([key]) => !eventMap.has(key))
32
- let usage
33
- if (framework === 'react') {
34
- const attributes = entries.filter(([key]) => key !== 'children').map(([key, value]) =>
35
- typeof value === 'string' ? ` ${key}="${attr(value)}"` : ` ${key}={${literal(value)}}`)
36
- for (const event of eventRows) {
37
- const key = /^on[A-Z]/.test(event.name) ? event.name : handlerName(event.name)
38
- attributes.push(` ${key}={(...args) => { /* 处理 ${event.name} */ }}`)
39
- }
40
- const child = slotHtml.default !== undefined ? `{${literal(slotHtml.default)}}` : hasOwn(values, 'children') ? `{${literal(values.children)}}` : ''
41
- // Slot HTML is explicit, rather than silently treating an HTML string as JSX.
42
- const content = slotHtml.default && /<[a-z][\s\S]*>/i.test(slotHtml.default)
43
- ? `<span dangerouslySetInnerHTML={{ __html: ${literal(slotHtml.default)} }} />` : child
44
- usage = `<${name}${attributes.length ? '\n' + attributes.join('\n') + '\n' : ''}${content ? `>\n ${content}\n</${name}>` : ' />'}`
45
- } else {
46
- const attributes = entries.map(([key, value]) => models.some(model => model.prop === key)
47
- ? ` :${kebab(key)}="${attr(key)}"`
48
- : typeof value === 'string' ? ` ${kebab(key)}="${attr(value)}"` : ` :${kebab(key)}="${attr(literal(value))}"`)
49
- for (const model of models) {
50
- if (!eventMap.has(model.event)) eventRows.push({ name: model.event, type: '模型值', description: `同步 ${model.prop}` })
51
- }
52
- for (const event of eventRows) {
53
- const model = models.find(item => item.event === event.name)
54
- attributes.push(` @${event.name}="${model ? `${model.prop} = $event` : handlerName(event.name)}"`)
55
- }
56
- const slots = Object.entries(slotHtml).map(([key, html]) => key === 'default' ? String(html) : `<template #${key}>${html}</template>`).join('\n ')
57
- usage = `<${kebab(name)}${attributes.length ? '\n' + attributes.join('\n') + '\n' : ''}>${slots ? '\n ' + slots + '\n' : ''}</${kebab(name)}>`
58
- const handlers = eventRows.filter(event => !models.some(model => model.event === event.name))
59
- if (models.length || handlers.length) {
60
- const data = Object.fromEntries(models.map(model => [model.prop, values[model.prop]]))
61
- const script = framework === 'vue3'
62
- ? [models.length ? "import { ref } from 'vue'" : '', ...models.map(model => `const ${model.prop} = ref(${literal(values[model.prop])})`), ...handlers.map(event => `function ${handlerName(event.name)}(...args) { /* 处理 ${event.name} */ }`)].filter(Boolean).join('\n')
63
- : `export default {\n data: () => (${literal(data)}),\n methods: {\n${handlers.map(event => ` ${handlerName(event.name)}(...args) { /* 处理 ${event.name} */ },`).join('\n')}\n },\n}`
64
- usage = `<template>\n${usage}\n</template>\n\n<script${framework === 'vue3' ? ' setup' : ''}>\n${script}\n</script>`
65
- }
66
- }
67
- return { name, props, events: eventRows, description, requirements, code: code || usage }
68
- }
69
-
70
- /** Only declared events and configured listeners are listed, never guessed APIs. */
71
- export function componentEvents(component, listeners = {}) {
72
- const options = (component && component.options) || component || {}
73
- const declared = options.emits || []
74
- return [...new Set([...(Array.isArray(declared) ? declared : Object.keys(declared)), ...Object.keys(listeners)])]
75
- }
@@ -1,118 +0,0 @@
1
- import { resolveHelDep } from '../remote.mjs'
2
- import * as runtime from './runtime.mjs'
3
-
4
- export const DOWNLOAD_HINT = '下载当前示例(HTML + unpkg CDN 单文件,联网后可直接打开)'
5
- export const EXAMPLE_HINT = '本示例的框架、加载器、适配层和远程组件均从 unpkg 加载。保存为 HTML 后可直接打开,需要联网。'
6
-
7
- const cdn = (name, file) => 'https://unpkg.com/' + name + '/' + file
8
- const escapeHtml = value => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
9
- const scriptJson = value => JSON.stringify(value, null, 2).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')
10
- const moduleData = source => 'data:text/javascript,' + encodeURIComponent(source)
11
-
12
- function dependencies(framework) {
13
- const imports = {
14
- '@melt-js/libs-core': cdn('@melt-js/libs-core', 'dist/browser.mjs'),
15
- ['@melt-js/libs-core-' + framework]: cdn('@melt-js/libs-core-' + framework, 'src/index.mjs'),
16
- }
17
- let scripts
18
- if (framework === 'react') {
19
- imports.react = moduleData('export default window.React;')
20
- scripts = [
21
- cdn('react@18.3.1', 'umd/react.production.min.js'),
22
- cdn('react-dom@18.3.1', 'umd/react-dom.production.min.js'),
23
- cdn('react-is@18.3.1', 'umd/react-is.production.min.js'),
24
- ]
25
- } else if (framework === 'vue2') {
26
- imports.vue = moduleData('export default window.Vue;')
27
- scripts = [cdn('vue@2.7.16', 'dist/vue.min.js')]
28
- } else {
29
- imports.vue = moduleData('export default window.Vue; export const { defineComponent, h, onBeforeUnmount, onErrorCaptured, onMounted, shallowRef } = window.Vue;')
30
- scripts = [cdn('vue@3.5.45', 'dist/vue.global.prod.js')]
31
- }
32
- return { imports, scripts }
33
- }
34
-
35
- /** Demo hosts provide data only. Deployment/local-server addresses never enter the HTML. */
36
- export function buildDownloadFile(input, { framework, libName = input && input.libName } = {}) {
37
- if (!['vue2', 'vue3', 'react'].includes(framework)) throw new Error('需要指定示例框架:vue2 / vue3 / react')
38
- if (!input || typeof libName !== 'string' || !libName.trim()) throw new Error('需要指定远程组件包 libName')
39
- const packageName = libName.startsWith('@') ? libName : '@melt-js/' + libName
40
- const dep = resolveHelDep(packageName, { type: 'unpkg' })
41
- const example = framework === 'react'
42
- ? { title: input.title, packageName, items: input.items.map(({ name, label, props, slotHtml }) => ({ name, label, props: props || {}, ...(slotHtml ? { slotHtml } : {}) })),
43
- ...(input.panelSchema ? { panelSchema: input.panelSchema } : {}), propsPanel: !!input.propsPanel }
44
- : { title: input.component, packageName, component: input.component, props: input.props || {},
45
- slotHtml: input.slotHtml || '', openProp: input.openProp || '' }
46
- if (framework === 'react' ? !example.items.length : !example.component) throw new Error('示例缺少组件')
47
- const { imports, scripts } = dependencies(framework)
48
- const resources = [...scripts, ...Object.values(imports).filter(url => url.startsWith('https:')), dep.host]
49
- if (example.panelSchema) resources.push(resolveHelDep('@melt-js/libs-react-leva').host)
50
- const snippet = [
51
- `import { defineHelComponent${framework === 'react' ? ', loadHelLib, bindReactRuntime' : example.openProp ? ', loadHelComponent' : ''} } from '@melt-js/libs-core-${framework}'`,
52
- "const example = JSON.parse(document.getElementById('demo-config').textContent)",
53
- runtime[framework !== 'react' && example.openProp ? framework + 'Modal' : framework],
54
- ].join('\n')
55
- const styles = [input.background ? 'background:' + input.background : '', input.stageHeight ? 'height:' + input.stageHeight : ''].filter(Boolean).join(';')
56
- const bootstrap = [
57
- ...scripts.map(url => `<script src="${escapeHtml(url)}" crossorigin="anonymous"></script>`),
58
- `<script type="importmap">${scriptJson({ imports })}</script>`,
59
- `<script type="module">${snippet}</script>`,
60
- ].join('\n')
61
- const html = [
62
- '<!doctype html><html lang="zh-CN"><head>',
63
- '<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">',
64
- '<base href="https://unpkg.com/">',
65
- `<title>${escapeHtml(example.title)} · HTML + unpkg</title>`,
66
- '<style>body{margin:0;padding:28px;color:#1f2937;background:#f5f7fa;font:15px/1.7 system-ui,sans-serif}main{max-width:1100px;margin:auto}#app{box-sizing:border-box;min-height:240px;padding:24px;background:#fff;border-radius:12px;overflow:auto}pre{padding:20px;overflow:auto;background:#0f172a;color:#e2e8f0;border-radius:12px;font:13px/1.7 monospace}.example-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px}.example-item{min-width:0}a{overflow-wrap:anywhere}h1{font-size:26px}</style>',
67
- `</head><body><main><h1>${escapeHtml(example.title)}</h1><p>${EXAMPLE_HINT}</p>`,
68
- `<div id="app" style="${escapeHtml(styles)}"><div id="demo-root">正在加载远程组件…</div></div><p id="example-load-error" role="alert" hidden></p>`,
69
- '<h2>引用的 unpkg CDN</h2><ul>' + resources.map(url => `<li><a href="${escapeHtml(url)}">${escapeHtml(url)}</a></li>`).join('') + '</ul>',
70
- '<h2>HTML 引用与懒加载示例</h2><pre>' + escapeHtml(bootstrap) + '</pre>',
71
- '<h2>示例参数</h2><pre>' + escapeHtml(JSON.stringify(example, null, 2)) + '</pre></main>',
72
- `<script id="demo-config" type="application/json">${scriptJson(example)}</script>`,
73
- '<script>function showLoadError(message){const target=document.getElementById("example-load-error");if(target){target.hidden=false;target.textContent="加载失败:"+message}}window.addEventListener("error",function(event){if(event.target&&event.target!==window&&!/^(SCRIPT|LINK)$/.test(event.target.tagName))return;showLoadError(event.message||"unpkg 资源加载失败")},true);window.addEventListener("unhandledrejection",function(event){showLoadError(String(event.reason))})</script>',
74
- bootstrap,
75
- '</body></html>',
76
- ].join('\n')
77
- const slug = (input.component || dep.name + '-' + (input.items ? input.items.map(item => item.name).join('-') : 'example'))
78
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/[^a-z0-9_-]/gi, '-').toLowerCase()
79
- return { fileName: 'hel-micro-' + slug + '.html', html }
80
- }
81
-
82
- /** Shared status, copy and object-URL lifetime for all three Leva buttons. */
83
- export function createDownloadController(onChange = () => {}) {
84
- let timer
85
- let disposed = false
86
- const update = state => { if (!disposed) onChange(state) }
87
- const reset = () => { clearTimeout(timer); update({ downloaded: '', error: '' }) }
88
- return {
89
- reset,
90
- dispose() { disposed = true; clearTimeout(timer) },
91
- download(example, options) {
92
- let objectUrl = ''
93
- let link
94
- try {
95
- const file = buildDownloadFile(example, options)
96
- objectUrl = URL.createObjectURL(new Blob([file.html], { type: 'text/html;charset=utf-8' }))
97
- link = document.createElement('a')
98
- link.href = objectUrl
99
- link.download = file.fileName
100
- link.rel = 'noopener'
101
- document.body.appendChild(link)
102
- link.click()
103
- // Allow the browser to take over the download before releasing its URL.
104
- setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)
105
- clearTimeout(timer)
106
- update({ downloaded: file.fileName, error: '' })
107
- timer = setTimeout(reset, 2000)
108
- return file
109
- } catch (error) {
110
- if (objectUrl) URL.revokeObjectURL(objectUrl)
111
- clearTimeout(timer)
112
- update({ downloaded: '', error: '下载失败:' + String(error) })
113
- } finally {
114
- if (link) link.remove()
115
- }
116
- },
117
- }
118
- }
@@ -1,80 +0,0 @@
1
- // The registry is shared across separately bundled remote libraries in one document.
2
- const key = Symbol.for('@melt-js/demo-fullscreen')
3
-
4
- /** Page fullscreen works in embedded browsers and preserves the live component DOM. */
5
- export function createDemoFullscreen({ target = '[data-demo-preview]', onChange = () => {} } = {}) {
6
- let cleanup = null
7
- let disposed = false
8
- const resolve = () => {
9
- const value = typeof target === 'function' ? target() : target
10
- return typeof value === 'string' ? document.querySelector(value) : value
11
- }
12
- const controller = {
13
- get active() { return !!cleanup },
14
- enter(trigger) {
15
- if (disposed || cleanup) return
16
- const element = resolve()
17
- if (!element || !element.isConnected || element === document.body || element === document.documentElement) throw new Error('没有找到需要全屏的组件预览区')
18
- if (document[key]) document[key].exit()
19
- const marker = document.createComment('demo fullscreen position')
20
- element.before(marker)
21
- const attributes = ['role', 'aria-modal', 'aria-label'].map(name => [name, element.getAttribute(name)])
22
- const overflow = document.body.style.overflow
23
- const previousFocus = trigger || document.activeElement
24
- const scroll = [window.scrollX, window.scrollY]
25
- const hadClass = element.classList.contains('leva-demo-fullscreen')
26
- const exitButton = document.createElement('button')
27
- exitButton.type = 'button'
28
- exitButton.className = 'leva-fullscreen-exit'
29
- exitButton.textContent = '退出全屏(Esc)'
30
- exitButton.setAttribute('aria-label', '退出全屏')
31
- exitButton.addEventListener('click', () => controller.exit())
32
- document.body.appendChild(element)
33
- element.classList.add('leva-demo-fullscreen')
34
- element.setAttribute('role', 'dialog')
35
- element.setAttribute('aria-modal', 'true')
36
- element.setAttribute('aria-label', '组件全屏预览')
37
- element.appendChild(exitButton)
38
- document.body.style.overflow = 'hidden'
39
- const siblings = [...document.body.children].filter(item => item !== element && item.tagName !== 'SCRIPT' && item.tagName !== 'STYLE')
40
- const inert = siblings.map(item => [item, item.inert])
41
- for (const [item] of inert) item.inert = true
42
- function keydown(event) {
43
- if (event.key === 'Escape') { event.preventDefault(); controller.exit(); return }
44
- if (event.key !== 'Tab') return
45
- const focusable = [...element.querySelectorAll('a[href],button,input,select,textarea,[tabindex]')]
46
- .filter(item => item.tabIndex >= 0 && !item.matches(':disabled,[hidden]') && !item.closest('[inert]') && item.getClientRects().length)
47
- const first = focusable[0] || exitButton
48
- const last = focusable[focusable.length - 1] || exitButton
49
- if (event.shiftKey && (document.activeElement === first || !element.contains(document.activeElement))) { event.preventDefault(); last.focus() }
50
- else if (!event.shiftKey && (document.activeElement === last || !element.contains(document.activeElement))) { event.preventDefault(); first.focus() }
51
- }
52
- document.addEventListener('keydown', keydown)
53
- cleanup = () => {
54
- document.removeEventListener('keydown', keydown)
55
- exitButton.remove()
56
- if (!hadClass) element.classList.remove('leva-demo-fullscreen')
57
- for (const [name, value] of attributes) value === null ? element.removeAttribute(name) : element.setAttribute(name, value)
58
- if (marker.parentNode) marker.replaceWith(element)
59
- document.body.style.overflow = overflow
60
- for (const [item, value] of inert) item.inert = value
61
- if (previousFocus && previousFocus.isConnected && previousFocus.focus) previousFocus.focus({ preventScroll: true })
62
- window.scrollTo(...scroll)
63
- }
64
- document[key] = controller
65
- exitButton.focus({ preventScroll: true })
66
- onChange(true)
67
- },
68
- exit() {
69
- if (!cleanup) return
70
- const restore = cleanup
71
- cleanup = null
72
- restore()
73
- if (document[key] === controller) delete document[key]
74
- onChange(false)
75
- },
76
- toggle(trigger) { if (cleanup) controller.exit(); else controller.enter(trigger) },
77
- dispose() { controller.exit(); disposed = true },
78
- }
79
- return controller
80
- }
@@ -1,4 +0,0 @@
1
- export * from './download.mjs'
2
- export * from './docs.mjs'
3
- export * from './fullscreen.mjs'
4
- export * from './model.mjs'
@@ -1,4 +0,0 @@
1
- export * from './download.mjs'
2
- export * from './docs.mjs'
3
- export * from './fullscreen.mjs'
4
- export * from './model.mjs'