@melt-js/libs-core 2026.11.15 → 2026.11.16-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 (103) hide show
  1. package/README.md +45 -4
  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 +129 -0
  16. package/dist/cdn/vendor.umd.cjs +50 -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.mjs +1 -0
  21. package/dist/demo/browser.mjs.gz +0 -0
  22. package/dist/demo/clipboard.d.mts +6 -0
  23. package/dist/demo/clipboard.mjs +1 -0
  24. package/{src → dist}/demo/docs.d.mts +28 -25
  25. package/dist/demo/docs.mjs +1 -0
  26. package/dist/demo/docs.mjs.gz +0 -0
  27. package/{src → dist}/demo/download.d.mts +7 -2
  28. package/dist/demo/download.mjs +1 -0
  29. package/dist/demo/download.mjs.gz +0 -0
  30. package/{src → dist}/demo/fullscreen.d.mts +8 -8
  31. package/dist/demo/fullscreen.mjs +1 -0
  32. package/dist/demo/index.d.mts +9 -0
  33. package/dist/demo/index.mjs +1 -0
  34. package/{src → dist}/demo/model.d.mts +12 -12
  35. package/dist/demo/model.mjs +1 -0
  36. package/dist/demo/remote-debug.d.mts +11 -0
  37. package/dist/demo/remote-debug.mjs +1 -0
  38. package/{src → dist}/demo/runtime.mjs +92 -104
  39. package/dist/demo/split-pane.d.mts +8 -0
  40. package/dist/demo/split-pane.mjs +1 -0
  41. package/dist/demo/standalone.d.mts +9 -0
  42. package/dist/demo/standalone.mjs +1 -0
  43. package/dist/demo/tabs.d.mts +15 -0
  44. package/dist/demo/tabs.mjs +1 -0
  45. package/{src/index.ts → dist/index.d.ts} +1 -1
  46. package/dist/loading.mjs +1 -0
  47. package/dist/remote-address.cjs +2 -0
  48. package/{src → dist}/remote.d.mts +110 -96
  49. package/dist/remote.mjs +1 -0
  50. package/dist/remote.mjs.gz +0 -0
  51. package/dist/vendor/hel-runtime.mjs +50 -0
  52. package/dist/vendor/hel-runtime.mjs.gz +0 -0
  53. package/package.json +41 -25
  54. package/scripts/browser-formats.mjs +355 -0
  55. package/scripts/build-browser.mjs +59 -13
  56. package/scripts/build-protected-esm.mjs +51 -0
  57. package/scripts/cdn-runtime.cjs +30 -0
  58. package/scripts/check-tdz.mjs +327 -324
  59. package/scripts/client-build-security.cjs +48 -0
  60. package/scripts/component-events.mjs +57 -57
  61. package/scripts/comps-bundle-obfuscation.cjs +266 -262
  62. package/scripts/hel-build-paths.cjs +49 -48
  63. package/scripts/package-artifacts.mjs +206 -0
  64. package/scripts/package-env.cjs +200 -193
  65. package/scripts/publish-stage.mjs +50 -42
  66. package/{src → scripts}/remote-address.cjs +30 -30
  67. package/scripts/vdoc-parser/NOTICE.md +13 -13
  68. package/scripts/vdoc-parser/constants.mjs +3 -3
  69. package/scripts/vdoc-parser/index.d.mts +34 -34
  70. package/scripts/vdoc-parser/index.mjs +2 -2
  71. package/scripts/vdoc-parser/parsers/index.mjs +14 -14
  72. package/scripts/vdoc-parser/parsers/parseCode.mjs +42 -42
  73. package/scripts/vdoc-parser/parsers/parseCommentBlock.mjs +9 -9
  74. package/scripts/vdoc-parser/parsers/parseComponentOptions.mjs +12 -12
  75. package/scripts/vdoc-parser/parsers/parseDefaultValue.mjs +57 -57
  76. package/scripts/vdoc-parser/parsers/parseDefineProps.mjs +33 -33
  77. package/scripts/vdoc-parser/parsers/parseExport.mjs +93 -93
  78. package/scripts/vdoc-parser/parsers/parseFile.mjs +22 -22
  79. package/scripts/vdoc-parser/parsers/parseFileSync.mjs +22 -22
  80. package/scripts/vdoc-parser/parsers/parsePropType.mjs +32 -32
  81. package/scripts/vdoc-parser/parsers/parseProps.mjs +90 -90
  82. package/scripts/vdoc-parser/parsers/parseSetupScript.mjs +14 -14
  83. package/scripts/vdoc-parser/parsers/parseSfc.mjs +21 -21
  84. package/scripts/vdoc-parser/parsers/parseTSTypeLiteral.mjs +48 -48
  85. package/scripts/vdoc-parser/parsers/parseTypes.mjs +53 -53
  86. package/scripts/vdoc-parser/parsers/parseTypesFile.mjs +22 -22
  87. package/scripts/vdoc-parser/parsers/parseTypesFileSync.mjs +22 -22
  88. package/scripts/vdoc-parser/resolvers/index.mjs +2 -2
  89. package/scripts/vdoc-parser/resolvers/resolveSpreadElements.mjs +51 -51
  90. package/scripts/vdoc-parser/utils.mjs +52 -52
  91. package/scripts/webpack-bundle-obfuscation.cjs +123 -121
  92. package/demo/index.js +0 -1
  93. package/dist/hel-deployment.json +0 -8
  94. package/src/browser.d.mts +0 -2
  95. package/src/browser.mjs +0 -3
  96. package/src/demo/docs.mjs +0 -75
  97. package/src/demo/download.mjs +0 -118
  98. package/src/demo/fullscreen.mjs +0 -80
  99. package/src/demo/index.d.mts +0 -4
  100. package/src/demo/index.mjs +0 -4
  101. package/src/demo/model.mjs +0 -203
  102. package/src/remote.mjs +0 -286
  103. package/tsconfig.json +0 -13
@@ -1,262 +1,266 @@
1
- const { createHash } = require('node:crypto')
2
- const fs = require('node:fs')
3
- const path = require('node:path')
4
- const defaults = require('./comps-obfuscator-options.cjs')
5
-
6
- const normalize = value => value.replaceAll('\\', '/')
7
- const RUNTIME_ID = '\0hel:shared-vue-runtime'
8
- let buildSequence = 0
9
- const excludedChunks = /(?:^|\/)(?:vendor|shared-runtime|rolldown-runtime|__vite-browser-external)(?:[-.]|\/)/
10
-
11
- /** Follow installed packages / workspace symlinks, never infer ownership from a .pnpm parent name. */
12
- function createModuleClassifier(root) {
13
- const realRoot = normalize(fs.realpathSync(root)).replace(/\/$/, '')
14
- const rootName = JSON.parse(fs.readFileSync(path.join(realRoot, 'package.json'), 'utf8')).name || ''
15
- const scope = /^(@[^/]+)\//.exec(rootName)?.[1]
16
- const owners = new Map()
17
- const ownerOf = directory => {
18
- if (owners.has(directory)) return owners.get(directory)
19
- const manifest = path.join(directory, 'package.json')
20
- let owner
21
- if (fs.existsSync(manifest)) {
22
- owner = { root: normalize(directory), name: JSON.parse(fs.readFileSync(manifest, 'utf8')).name || '' }
23
- } else {
24
- const parent = path.dirname(directory)
25
- // A nested node_modules must never inherit its containing package's ownership.
26
- owner = parent === directory || path.basename(directory) === 'node_modules' ? null : ownerOf(parent)
27
- }
28
- owners.set(directory, owner)
29
- return owner
30
- }
31
- return id => {
32
- if (id === RUNTIME_ID || id.startsWith('\0hel:shared-runtime:') || /(?:^|\0)plugin-vue:export-helper$/.test(id)) return 'runtime'
33
- const filename = normalize(id.replace(/^\0/, '')).split('?', 1)[0]
34
- if (!path.isAbsolute(filename) || !fs.existsSync(filename)) return 'generated'
35
- const realFile = normalize(fs.realpathSync(filename))
36
- // Embedded upstream source manifests are metadata, not installed dependencies.
37
- if (realFile.startsWith(realRoot + '/') && !realFile.slice(realRoot.length + 1).split('/').includes('node_modules')) return 'own'
38
- const owner = ownerOf(path.dirname(realFile))
39
- if (owner?.root === realRoot) return 'own'
40
- if (scope && owner?.name.startsWith(scope + '/')) return 'related'
41
- return 'thirdParty'
42
- }
43
- }
44
-
45
- /** ESM imports remain hoisted; no in-place import-to-const rewriting and no second Vue runtime. */
46
- function sharedVueRuntimePlugin(exportNames) {
47
- if (!exportNames.length || exportNames.some(name => !/^[$A-Z_a-z][$\w]*$/.test(name))) {
48
- throw new TypeError('Pass the named exports of the consuming package\'s installed vue runtime')
49
- }
50
- return {
51
- name: 'hel:shared-vue-runtime',
52
- enforce: 'pre',
53
- apply: 'build',
54
- resolveId(id) { if (id === 'vue' || id === 'vue-demi') return RUNTIME_ID },
55
- load(id) {
56
- if (id !== RUNTIME_ID) return null
57
- return `const runtime = globalThis.Vue;
58
- if (!runtime) throw new Error('Bind the host Vue runtime before loading remote components');
59
- ${exportNames.map(name => `export const ${name} = runtime[${JSON.stringify(name)}];`).join('\n')}
60
- export default runtime;`
61
- },
62
- }
63
- }
64
-
65
- /**
66
- * Explicit ESM bridges for host-owned runtimes. Each import declares real named
67
- * exports, so both Rollup and Rolldown work without syntheticNamedExports.
68
- * Namespace imports use the host object itself; ESM imports remain hoisted.
69
- * This plugin never changes the consuming package's build/externals/output config.
70
- */
71
- function sharedRuntimePlugin(globals) {
72
- const prefix = '\0hel:shared-runtime:'
73
- const bridges = new Map()
74
- const bridgeId = (source, names = []) => {
75
- const id = prefix + JSON.stringify([source, [...new Set(names)].sort()])
76
- bridges.set(id, { source, names: [...new Set(names)].sort() })
77
- return id
78
- }
79
- return {
80
- name: 'hel:shared-runtime', apply: 'build', enforce: 'post',
81
- buildStart() { bridges.clear() },
82
- resolveId(id) {
83
- if (bridges.has(id)) return id
84
- if (Object.hasOwn(globals, id)) return bridgeId(id)
85
- },
86
- transform(code, id) {
87
- if (id.startsWith(prefix) || !Object.keys(globals).some(source => code.includes(source))) return null
88
- let ast
89
- try { ast = this.parse(code) } catch { return null } // Non-JavaScript assets.
90
- const edits = []
91
- for (const node of ast.body) {
92
- if (!node.source || !Object.hasOwn(globals, node.source.value)) continue
93
- if (node.type === 'ExportAllDeclaration' && node.exported) {
94
- edits.push([node.start, node.end, 'export { default as ' + node.exported.name + ' } from ' + JSON.stringify(bridgeId(node.source.value)) + ';'])
95
- continue
96
- }
97
- if (node.type === 'ExportAllDeclaration') {
98
- this.error('Use explicit named re-exports for shared runtime ' + node.source.value + ' in ' + id)
99
- }
100
- if (!['ImportDeclaration', 'ExportNamedDeclaration'].includes(node.type)) continue
101
- const names = []
102
- for (const specifier of node.specifiers) {
103
- if (specifier.type === 'ImportSpecifier') names.push(specifier.imported.name ?? specifier.imported.value)
104
- if (specifier.type === 'ExportSpecifier') names.push(specifier.local.name ?? specifier.local.value)
105
- if (specifier.type === 'ImportNamespaceSpecifier') {
106
- edits.push([specifier.start, specifier.end, '{ default as ' + specifier.local.name + ' }'])
107
- }
108
- }
109
- edits.push([node.source.start, node.source.end, JSON.stringify(bridgeId(node.source.value, names))])
110
- }
111
- const visit = node => {
112
- if (!node || typeof node !== 'object') return
113
- if (node.type === 'ImportExpression' && Object.hasOwn(globals, node.source?.value)) {
114
- edits.push([node.start, node.end, 'import(' + JSON.stringify(bridgeId(node.source.value)) + ').then(module => module.default)'])
115
- return
116
- }
117
- for (const value of Object.values(node)) {
118
- if (Array.isArray(value)) value.forEach(visit)
119
- else if (value && typeof value === 'object') visit(value)
120
- }
121
- }
122
- visit(ast)
123
- if (!edits.length) return null
124
- for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) {
125
- code = code.slice(0, start) + replacement + code.slice(end)
126
- }
127
- return { code, map: null }
128
- },
129
- load(id) {
130
- const bridge = bridges.get(id)
131
- if (!bridge) return null
132
- const name = globals[bridge.source]
133
- const access = name.split('.').filter(part => !['window', 'globalThis', 'global'].includes(part))
134
- .map(part => '[' + JSON.stringify(part) + ']').join('')
135
- return 'const runtime = globalThis' + access + ';\n'
136
- + 'if (runtime == null) throw new Error(' + JSON.stringify('Bind shared runtime before loading remote package: ' + name) + ');\n'
137
- + 'export default runtime;\n'
138
- + bridge.names.filter(name => name !== 'default').map((name, index) =>
139
- 'const binding' + index + ' = runtime[' + JSON.stringify(name) + ']; export { binding' + index + ' as ' + (/^[$A-Z_a-z][$\w]*$/.test(name) ? name : JSON.stringify(name)) + ' };').join('\n')
140
- },
141
- }
142
- }
143
-
144
- function gzipPlugin() {
145
- return { name: 'hel:final-gzip', apply: 'build', enforce: 'post', generateBundle: { order: 'post', handler(_output, bundle) {
146
- if (process.env.HEL_GZIP === '0') return
147
- const { gzipSync } = require('node:zlib')
148
- for (const item of Object.values(bundle)) {
149
- if (!/\.(?:[cm]?js|css)$/i.test(item.fileName)) continue
150
- const source = item.type === 'chunk' ? item.code : item.source
151
- if (Buffer.byteLength(source) < 10240) continue
152
- this.emitFile({ type: 'asset', fileName: item.fileName + '.gz', source: gzipSync(source) })
153
- }
154
- } } }
155
- }
156
-
157
- /**
158
- * Vite split ESM apps and ES/CJS library outputs.
159
- * Invoke the official app hook after Vite's final dependency/preload rewrites, on minified chunks.
160
- * Its automatic node_modules exclusion is OFF: dependencies in the consumer's scope are protected.
161
- */
162
- function bundleObfuscationPlugins({ root, obfuscatorPlugin, enabled = true, options = {}, library = false, rolldown = false }) {
163
- const classify = createModuleClassifier(root)
164
- const settings = { ...defaults, ...options, seed: options.seed ?? 1, renameProperties: false, sourceMap: false }
165
- const reports = []
166
- let currentReports = []
167
- let runId
168
- const api = { classify, reports }
169
- const guard = {
170
- name: 'hel:bundle-obfuscation-boundaries',
171
- apply: 'build',
172
- api,
173
- buildStart() { reports.length = 0; runId = ++buildSequence },
174
- config() {
175
- return { build: { rollupOptions: { output: {
176
- ...(library ? {} : { format: 'es' }),
177
- ...(rolldown ? {
178
- strictExecutionOrder: true,
179
- codeSplitting: { minSize: 0, includeDependenciesRecursively: false, groups: [
180
- { name: 'shared-runtime', test: id => classify(id) === 'runtime', priority: 100 },
181
- { name: 'vendor', test: id => classify(id) === 'thirdParty' || id.includes('commonjs'), priority: 90 },
182
- { name: 'standalone', test: id => classify(id) === 'own' && normalize(id).includes('/src/standalone/'), priority: 80 },
183
- { name: 'components', test: id => ['own', 'related'].includes(classify(id)), priority: 70 },
184
- ] },
185
- } : {
186
- onlyExplicitManualChunks: true,
187
- manualChunks(id) {
188
- const kind = classify(id)
189
- if (kind === 'runtime') return 'shared-runtime'
190
- if (kind === 'own' && normalize(id).includes('/src/standalone/')) return 'standalone'
191
- if (kind === 'own' || kind === 'related') return 'components'
192
- if (kind === 'thirdParty' || id.includes('commonjs')) return 'vendor'
193
- },
194
- }),
195
- } } } }
196
- },
197
- // The official app plugin runs after Rollup hashes chunks. Include its settings in cache keys.
198
- augmentChunkHash(chunk) {
199
- if (excludedChunks.test(chunk.name + '.js')) return
200
- return createHash('sha256').update(JSON.stringify({ pipeline: 'final-generate-bundle-v2', enabled, settings })).digest('hex')
201
- },
202
- generateBundle(_output, bundle) {
203
- currentReports = []
204
- for (const chunk of Object.values(bundle)) {
205
- if (chunk.type !== 'chunk') continue
206
- const modules = Object.keys(chunk.modules).map(id => ({ id: normalize(id), kind: classify(id) }))
207
- const protectedModules = modules.filter(item => ['own', 'related'].includes(item.kind))
208
- const vendors = modules.filter(item => item.kind === 'thirdParty')
209
- if (protectedModules.length && vendors.length) {
210
- this.error(`Mixed business/vendor chunk cannot be safely obfuscated: ${chunk.fileName}`)
211
- }
212
- const excluded = excludedChunks.test(chunk.fileName)
213
- if (vendors.length && !excluded) this.error(`Third-party chunk is not excluded: ${chunk.fileName}`)
214
- if (protectedModules.length && excluded) this.error(`Protected source leaked into excluded chunk: ${chunk.fileName}`)
215
- const report = { format: _output.format, fileName: chunk.fileName, modules, protectedModules: protectedModules.length,
216
- thirdPartyModules: vendors.length, excluded, beforeHash: createHash('sha256').update(chunk.code).digest('hex') }
217
- reports.push(report)
218
- currentReports.push(report)
219
- }
220
- },
221
- }
222
- const plugin = obfuscatorPlugin({ apply: 'build', enable: enabled, log: true, threadPool: false,
223
- autoExcludeNodeModules: false, excludes: [excludedChunks], options: settings })
224
- const hook = plugin.transformIndexHtml
225
- if (typeof hook?.handler !== 'function' || hook.order !== 'post') {
226
- throw new Error('Expected vite-plugin-bundle-obfuscator post transformIndexHtml hook')
227
- }
228
- // HTML hooks run inside vite:build-html, before Vite finalizes dynamic preload maps.
229
- // Keep the official implementation, but invoke its app hook once at the final output stage.
230
- // Otherwise late Vite rewrites change bytes after our audit and escape obfuscation.
231
- plugin.enforce = 'post'
232
- // The library renderChunk hook otherwise obfuscates before minification.
233
- plugin.renderChunk = undefined
234
- const generateBundle = plugin.generateBundle
235
- plugin.transformIndexHtml = { ...hook, handler: html => html }
236
- plugin.generateBundle = { order: 'post', async handler(output, bundle) {
237
- if (typeof generateBundle === 'function') await generateBundle.call(this, output, bundle)
238
- else if (generateBundle?.handler) await generateBundle.handler.call(this, output, bundle)
239
- const html = Object.values(bundle).find(item => item.type === 'asset' && item.fileName.endsWith('.html'))
240
- for (const report of currentReports) {
241
- report.beforeHash = createHash('sha256').update(bundle[report.fileName].code).digest('hex')
242
- }
243
- // The upstream plugin keeps a process-wide filename registry. Unique lookup keys
244
- // prevent silently skipping a subsequent/watch build without altering output URLs.
245
- const finalBundle = Object.fromEntries(Object.entries(bundle).map(([name, chunk]) => [`__hel_${runId}_${output.format}__/${name}`, chunk]))
246
- await hook.handler.call(this, html ? String(html.source) : '', { bundle: finalBundle })
247
- for (const report of currentReports) {
248
- const code = bundle[report.fileName].code
249
- report.afterHash = createHash('sha256').update(code).digest('hex')
250
- report.identifiers = (code.match(/\b_0x[\da-f]+\b/g) || []).length
251
- report.obfuscated = report.beforeHash !== report.afterHash
252
- if (report.excluded && report.obfuscated) throw new Error(`Excluded chunk changed: ${report.fileName}`)
253
- if (enabled && report.protectedModules && (!report.obfuscated || !report.identifiers)) {
254
- throw new Error(`Final business chunk is not obfuscated: ${report.fileName}`)
255
- }
256
- console.log(`[hel:bundle] ${report.fileName}: ${report.obfuscated ? 'obfuscated' : 'unchanged'}, _0x identifiers=${report.identifiers}, own/related=${report.protectedModules}, third-party=${report.thirdPartyModules}`)
257
- }
258
- } }
259
- return [guard, plugin]
260
- }
261
-
262
- module.exports = { bundleObfuscationPlugins, createModuleClassifier, sharedVueRuntimePlugin, sharedRuntimePlugin, gzipPlugin }
1
+ const { createHash } = require('node:crypto')
2
+ const fs = require('node:fs')
3
+ const path = require('node:path')
4
+ const defaults = require('./comps-obfuscator-options.cjs')
5
+
6
+ const normalize = value => value.replaceAll('\\', '/')
7
+ const RUNTIME_ID = '\0hel:shared-vue-runtime'
8
+ let buildSequence = 0
9
+ const excludedChunks = /(?:^|\/)(?:vendor|shared-runtime|rolldown-runtime|__vite-browser-external)(?:[-.]|\/)/
10
+
11
+ /** Follow installed packages / workspace symlinks, never infer ownership from a .pnpm parent name. */
12
+ function createModuleClassifier(root) {
13
+ const realRoot = normalize(fs.realpathSync(root)).replace(/\/$/, '')
14
+ const rootName = JSON.parse(fs.readFileSync(path.join(realRoot, 'package.json'), 'utf8')).name || ''
15
+ const scope = /^(@[^/]+)\//.exec(rootName)?.[1]
16
+ const owners = new Map()
17
+ const ownerOf = directory => {
18
+ if (owners.has(directory)) return owners.get(directory)
19
+ const manifest = path.join(directory, 'package.json')
20
+ let owner
21
+ if (fs.existsSync(manifest)) {
22
+ owner = { root: normalize(directory), name: JSON.parse(fs.readFileSync(manifest, 'utf8')).name || '' }
23
+ } else {
24
+ const parent = path.dirname(directory)
25
+ // A nested node_modules must never inherit its containing package's ownership.
26
+ owner = parent === directory || path.basename(directory) === 'node_modules' ? null : ownerOf(parent)
27
+ }
28
+ owners.set(directory, owner)
29
+ return owner
30
+ }
31
+ return id => {
32
+ if (id === RUNTIME_ID || id.startsWith('\0hel:shared-runtime:') || /(?:^|\0)plugin-vue:export-helper$/.test(id)) return 'runtime'
33
+ const filename = normalize(id.replace(/^\0/, '')).split('?', 1)[0]
34
+ if (!path.isAbsolute(filename) || !fs.existsSync(filename)) return 'generated'
35
+ const realFile = normalize(fs.realpathSync(filename))
36
+ // Embedded upstream source manifests are metadata, not installed dependencies.
37
+ if (realFile.startsWith(realRoot + '/') && !realFile.slice(realRoot.length + 1).split('/').includes('node_modules')) return 'own'
38
+ const owner = ownerOf(path.dirname(realFile))
39
+ if (owner?.root === realRoot) return 'own'
40
+ if (scope && owner?.name.startsWith(scope + '/')) return 'related'
41
+ return 'thirdParty'
42
+ }
43
+ }
44
+
45
+ /** ESM imports remain hoisted; no in-place import-to-const rewriting and no second Vue runtime. */
46
+ function sharedVueRuntimePlugin(exportNames) {
47
+ if (!exportNames.length || exportNames.some(name => !/^[$A-Z_a-z][$\w]*$/.test(name))) {
48
+ throw new TypeError('Pass the named exports of the consuming package\'s installed vue runtime')
49
+ }
50
+ return {
51
+ name: 'hel:shared-vue-runtime',
52
+ enforce: 'pre',
53
+ apply: 'build',
54
+ resolveId(id) { if (id === 'vue' || id === 'vue-demi') return RUNTIME_ID },
55
+ load(id) {
56
+ if (id !== RUNTIME_ID) return null
57
+ return `const runtime = globalThis.Vue;
58
+ if (!runtime) throw new Error('Bind the host Vue runtime before loading remote components');
59
+ ${exportNames.map(name => `export const ${name} = runtime[${JSON.stringify(name)}];`).join('\n')}
60
+ export default runtime;`
61
+ },
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Explicit ESM bridges for host-owned runtimes. Each import declares real named
67
+ * exports, so both Rollup and Rolldown work without syntheticNamedExports.
68
+ * Namespace imports use the host object itself; ESM imports remain hoisted.
69
+ * This plugin never changes the consuming package's build/externals/output config.
70
+ */
71
+ function sharedRuntimePlugin(globals) {
72
+ const prefix = '\0hel:shared-runtime:'
73
+ const bridges = new Map()
74
+ const bridgeId = (source, names = []) => {
75
+ const id = prefix + JSON.stringify([source, [...new Set(names)].sort()])
76
+ bridges.set(id, { source, names: [...new Set(names)].sort() })
77
+ return id
78
+ }
79
+ return {
80
+ name: 'hel:shared-runtime', apply: 'build', enforce: 'post',
81
+ buildStart() { bridges.clear() },
82
+ resolveId(id) {
83
+ if (bridges.has(id)) return id
84
+ if (Object.hasOwn(globals, id)) return bridgeId(id)
85
+ },
86
+ transform(code, id) {
87
+ if (id.startsWith(prefix) || !Object.keys(globals).some(source => code.includes(source))) return null
88
+ let ast
89
+ try { ast = this.parse(code) } catch { return null } // Non-JavaScript assets.
90
+ const edits = []
91
+ for (const node of ast.body) {
92
+ if (!node.source || !Object.hasOwn(globals, node.source.value)) continue
93
+ if (node.type === 'ExportAllDeclaration' && node.exported) {
94
+ edits.push([node.start, node.end, 'export { default as ' + node.exported.name + ' } from ' + JSON.stringify(bridgeId(node.source.value)) + ';'])
95
+ continue
96
+ }
97
+ if (node.type === 'ExportAllDeclaration') {
98
+ this.error('Use explicit named re-exports for shared runtime ' + node.source.value + ' in ' + id)
99
+ }
100
+ if (!['ImportDeclaration', 'ExportNamedDeclaration'].includes(node.type)) continue
101
+ const names = []
102
+ for (const specifier of node.specifiers) {
103
+ if (specifier.type === 'ImportSpecifier') names.push(specifier.imported.name ?? specifier.imported.value)
104
+ if (specifier.type === 'ExportSpecifier') names.push(specifier.local.name ?? specifier.local.value)
105
+ if (specifier.type === 'ImportNamespaceSpecifier') {
106
+ edits.push([specifier.start, specifier.end, '{ default as ' + specifier.local.name + ' }'])
107
+ }
108
+ }
109
+ edits.push([node.source.start, node.source.end, JSON.stringify(bridgeId(node.source.value, names))])
110
+ }
111
+ const visit = node => {
112
+ if (!node || typeof node !== 'object') return
113
+ if (node.type === 'ImportExpression' && Object.hasOwn(globals, node.source?.value)) {
114
+ edits.push([node.start, node.end, 'import(' + JSON.stringify(bridgeId(node.source.value)) + ').then(module => module.default)'])
115
+ return
116
+ }
117
+ for (const value of Object.values(node)) {
118
+ if (Array.isArray(value)) value.forEach(visit)
119
+ else if (value && typeof value === 'object') visit(value)
120
+ }
121
+ }
122
+ visit(ast)
123
+ if (!edits.length) return null
124
+ for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) {
125
+ code = code.slice(0, start) + replacement + code.slice(end)
126
+ }
127
+ return { code, map: null }
128
+ },
129
+ load(id) {
130
+ const bridge = bridges.get(id)
131
+ if (!bridge) return null
132
+ const name = globals[bridge.source]
133
+ const access = name.split('.').filter(part => !['window', 'globalThis', 'global'].includes(part))
134
+ .map(part => '[' + JSON.stringify(part) + ']').join('')
135
+ return 'const runtime = globalThis' + access + ';\n'
136
+ + 'if (runtime == null) throw new Error(' + JSON.stringify('Bind shared runtime before loading remote package: ' + name) + ');\n'
137
+ + 'export default runtime;\n'
138
+ + bridge.names.filter(name => name !== 'default').map((name, index) =>
139
+ 'const binding' + index + ' = runtime[' + JSON.stringify(name) + ']; export { binding' + index + ' as ' + (/^[$A-Z_a-z][$\w]*$/.test(name) ? name : JSON.stringify(name)) + ' };').join('\n')
140
+ },
141
+ }
142
+ }
143
+
144
+ function gzipPlugin() {
145
+ return { name: 'hel:final-gzip', apply: 'build', enforce: 'post', generateBundle: { order: 'post', handler(_output, bundle) {
146
+ if (process.env.HEL_GZIP === '0') return
147
+ const { gzipSync } = require('node:zlib')
148
+ for (const item of Object.values(bundle)) {
149
+ if (!/\.(?:[cm]?js|css)$/i.test(item.fileName)) continue
150
+ const source = item.type === 'chunk' ? item.code : item.source
151
+ if (Buffer.byteLength(source) < 10240) continue
152
+ this.emitFile({ type: 'asset', fileName: item.fileName + '.gz', source: gzipSync(source) })
153
+ }
154
+ } } }
155
+ }
156
+
157
+ /**
158
+ * Vite split ESM apps and ES/CJS library outputs.
159
+ * Invoke the official app hook after Vite's final dependency/preload rewrites, on minified chunks.
160
+ * Its automatic node_modules exclusion is OFF: dependencies in the consumer's scope are protected.
161
+ */
162
+ function bundleObfuscationPlugins({ root, obfuscatorPlugin, enabled = true, options = {}, library = false, rolldown = false }) {
163
+ const classify = createModuleClassifier(root)
164
+ const settings = { ...defaults, ...options, seed: options.seed ?? 1, renameProperties: false, sourceMap: false }
165
+ const reports = []
166
+ let currentReports = []
167
+ let runId
168
+ const api = { classify, reports }
169
+ const guard = {
170
+ name: 'hel:bundle-obfuscation-boundaries',
171
+ apply: 'build',
172
+ api,
173
+ buildStart() { reports.length = 0; runId = ++buildSequence },
174
+ config() {
175
+ return { build: { rollupOptions: { output: {
176
+ ...(library ? {} : { format: 'es' }),
177
+ ...(rolldown ? {
178
+ strictExecutionOrder: true,
179
+ // Rolldown rejects includeDependenciesRecursively=false with strict library entries.
180
+ codeSplitting: { minSize: 0, ...(library ? {} : { includeDependenciesRecursively: false }), groups: [
181
+ { name: 'shared-runtime', test: id => classify(id) === 'runtime', priority: 100 },
182
+ { name: 'vendor', test: id => classify(id) === 'thirdParty' || id.includes('commonjs'), priority: 90 },
183
+ { name: 'standalone', test: id => classify(id) === 'own' && normalize(id).includes('/src/standalone/'), priority: 80 },
184
+ { name: 'components', test: id => ['own', 'related'].includes(classify(id)), priority: 70 },
185
+ ] },
186
+ } : {
187
+ onlyExplicitManualChunks: true,
188
+ manualChunks(id) {
189
+ const kind = classify(id)
190
+ if (kind === 'runtime') return 'shared-runtime'
191
+ if (kind === 'own' && normalize(id).includes('/src/standalone/')) return 'standalone'
192
+ if (kind === 'own' || kind === 'related') return 'components'
193
+ if (kind === 'thirdParty' || id.includes('commonjs')) return 'vendor'
194
+ },
195
+ }),
196
+ } } } }
197
+ },
198
+ // The official app plugin runs after Rollup hashes chunks. Include its settings in cache keys.
199
+ augmentChunkHash(chunk) {
200
+ if (excludedChunks.test(chunk.name + '.js')) return
201
+ return createHash('sha256').update(JSON.stringify({ pipeline: 'final-generate-bundle-v2', enabled, settings })).digest('hex')
202
+ },
203
+ generateBundle(_output, bundle) {
204
+ currentReports = []
205
+ for (const chunk of Object.values(bundle)) {
206
+ if (chunk.type !== 'chunk') continue
207
+ const modules = Object.keys(chunk.modules).map(id => ({ id: normalize(id), kind: classify(id) }))
208
+ const protectedModules = modules.filter(item => ['own', 'related'].includes(item.kind))
209
+ if (protectedModules.some(item => /\.(?:vue|tsx?|jsx?|mjs|cjs)\?(?:[^#]*&)?raw(?:&|$)/.test(item.id))) {
210
+ this.error(`Raw protected source cannot be distributed: ${chunk.fileName}`)
211
+ }
212
+ const vendors = modules.filter(item => item.kind === 'thirdParty')
213
+ if (protectedModules.length && vendors.length) {
214
+ this.error(`Mixed business/vendor chunk cannot be safely obfuscated: ${chunk.fileName}`)
215
+ }
216
+ const excluded = excludedChunks.test(chunk.fileName)
217
+ if (vendors.length && !excluded) this.error(`Third-party chunk is not excluded: ${chunk.fileName}`)
218
+ if (protectedModules.length && excluded) this.error(`Protected source leaked into excluded chunk: ${chunk.fileName}`)
219
+ const report = { format: _output.format, fileName: chunk.fileName, modules, protectedModules: protectedModules.length,
220
+ thirdPartyModules: vendors.length, excluded, beforeHash: createHash('sha256').update(chunk.code).digest('hex') }
221
+ reports.push(report)
222
+ currentReports.push(report)
223
+ }
224
+ },
225
+ }
226
+ const plugin = obfuscatorPlugin({ apply: 'build', enable: enabled, log: true, threadPool: false,
227
+ autoExcludeNodeModules: false, excludes: [excludedChunks], options: settings })
228
+ const hook = plugin.transformIndexHtml
229
+ if (typeof hook?.handler !== 'function' || hook.order !== 'post') {
230
+ throw new Error('Expected vite-plugin-bundle-obfuscator post transformIndexHtml hook')
231
+ }
232
+ // HTML hooks run inside vite:build-html, before Vite finalizes dynamic preload maps.
233
+ // Keep the official implementation, but invoke its app hook once at the final output stage.
234
+ // Otherwise late Vite rewrites change bytes after our audit and escape obfuscation.
235
+ plugin.enforce = 'post'
236
+ // The library renderChunk hook otherwise obfuscates before minification.
237
+ plugin.renderChunk = undefined
238
+ const generateBundle = plugin.generateBundle
239
+ plugin.transformIndexHtml = { ...hook, handler: html => html }
240
+ plugin.generateBundle = { order: 'post', async handler(output, bundle) {
241
+ if (typeof generateBundle === 'function') await generateBundle.call(this, output, bundle)
242
+ else if (generateBundle?.handler) await generateBundle.handler.call(this, output, bundle)
243
+ const html = Object.values(bundle).find(item => item.type === 'asset' && item.fileName.endsWith('.html'))
244
+ for (const report of currentReports) {
245
+ report.beforeHash = createHash('sha256').update(bundle[report.fileName].code).digest('hex')
246
+ }
247
+ // The upstream plugin keeps a process-wide filename registry. Unique lookup keys
248
+ // prevent silently skipping a subsequent/watch build without altering output URLs.
249
+ const finalBundle = Object.fromEntries(Object.entries(bundle).map(([name, chunk]) => [`__hel_${runId}_${output.format}__/${name}`, chunk]))
250
+ await hook.handler.call(this, html ? String(html.source) : '', { bundle: finalBundle })
251
+ for (const report of currentReports) {
252
+ const code = bundle[report.fileName].code
253
+ report.afterHash = createHash('sha256').update(code).digest('hex')
254
+ report.identifiers = (code.match(/\b_0x[\da-f]+\b/g) || []).length
255
+ report.obfuscated = report.beforeHash !== report.afterHash
256
+ if (report.excluded && report.obfuscated) throw new Error(`Excluded chunk changed: ${report.fileName}`)
257
+ if (enabled && report.protectedModules && (!report.obfuscated || !report.identifiers)) {
258
+ throw new Error(`Final business chunk is not obfuscated: ${report.fileName}`)
259
+ }
260
+ console.log(`[hel:bundle] ${report.fileName}: ${report.obfuscated ? 'obfuscated' : 'unchanged'}, _0x identifiers=${report.identifiers}, own/related=${report.protectedModules}, third-party=${report.thirdPartyModules}`)
261
+ }
262
+ } }
263
+ return [guard, plugin]
264
+ }
265
+
266
+ module.exports = { bundleObfuscationPlugins, createModuleClassifier, sharedVueRuntimePlugin, sharedRuntimePlugin, gzipPlugin }