@melt-js/libs-core 2026.11.15 → 2026.11.16

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 (76) hide show
  1. package/README.md +35 -2
  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 +3 -0
  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 +38 -33
  28. package/dist/demo/download.mjs +1 -0
  29. package/dist/demo/download.mjs.gz +0 -0
  30. package/dist/demo/fullscreen.mjs +1 -0
  31. package/dist/demo/index.d.mts +9 -0
  32. package/dist/demo/index.mjs +1 -0
  33. package/dist/demo/model.mjs +1 -0
  34. package/dist/demo/remote-debug.d.mts +11 -0
  35. package/dist/demo/remote-debug.mjs +1 -0
  36. package/{src → dist}/demo/runtime.mjs +92 -104
  37. package/dist/demo/split-pane.d.mts +8 -0
  38. package/dist/demo/split-pane.mjs +1 -0
  39. package/dist/demo/standalone.d.mts +9 -0
  40. package/dist/demo/standalone.mjs +1 -0
  41. package/dist/demo/tabs.d.mts +15 -0
  42. package/dist/demo/tabs.mjs +1 -0
  43. package/{src/index.ts → dist/index.d.ts} +1 -1
  44. package/dist/loading.mjs +1 -0
  45. package/dist/remote-address.cjs +2 -0
  46. package/{src → dist}/remote.d.mts +16 -2
  47. package/dist/remote.mjs +1 -0
  48. package/dist/remote.mjs.gz +0 -0
  49. package/dist/vendor/hel-runtime.mjs +50 -0
  50. package/dist/vendor/hel-runtime.mjs.gz +0 -0
  51. package/package.json +41 -25
  52. package/scripts/browser-formats.mjs +355 -0
  53. package/scripts/build-browser.mjs +59 -13
  54. package/scripts/build-protected-esm.mjs +51 -0
  55. package/scripts/cdn-runtime.cjs +30 -0
  56. package/scripts/check-tdz.mjs +327 -324
  57. package/scripts/comps-bundle-obfuscation.cjs +2 -1
  58. package/scripts/package-artifacts.mjs +199 -0
  59. package/scripts/package-env.cjs +193 -193
  60. package/scripts/publish-stage.mjs +50 -42
  61. package/scripts/webpack-bundle-obfuscation.cjs +13 -0
  62. package/demo/index.js +0 -1
  63. package/dist/hel-deployment.json +0 -8
  64. package/src/browser.d.mts +0 -2
  65. package/src/browser.mjs +0 -3
  66. package/src/demo/docs.mjs +0 -75
  67. package/src/demo/download.mjs +0 -118
  68. package/src/demo/fullscreen.mjs +0 -80
  69. package/src/demo/index.d.mts +0 -4
  70. package/src/demo/index.mjs +0 -4
  71. package/src/demo/model.mjs +0 -203
  72. package/src/remote.mjs +0 -286
  73. package/tsconfig.json +0 -13
  74. /package/{src → dist}/demo/fullscreen.d.mts +0 -0
  75. /package/{src → dist}/demo/model.d.mts +0 -0
  76. /package/{src → scripts}/remote-address.cjs +0 -0
@@ -176,7 +176,8 @@ function bundleObfuscationPlugins({ root, obfuscatorPlugin, enabled = true, opti
176
176
  ...(library ? {} : { format: 'es' }),
177
177
  ...(rolldown ? {
178
178
  strictExecutionOrder: true,
179
- codeSplitting: { minSize: 0, includeDependenciesRecursively: false, groups: [
179
+ // Rolldown rejects includeDependenciesRecursively=false with strict library entries.
180
+ codeSplitting: { minSize: 0, ...(library ? {} : { includeDependenciesRecursively: false }), groups: [
180
181
  { name: 'shared-runtime', test: id => classify(id) === 'runtime', priority: 100 },
181
182
  { name: 'vendor', test: id => classify(id) === 'thirdParty' || id.includes('commonjs'), priority: 90 },
182
183
  { name: 'standalone', test: id => classify(id) === 'own' && normalize(id).includes('/src/standalone/'), priority: 80 },
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env node
2
+ // Package-local publication artifacts. Never searches the workspace or builds siblings.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { createRequire } from 'node:module'
6
+ import { pathToFileURL, fileURLToPath } from 'node:url'
7
+ import { spawnSync } from 'node:child_process'
8
+ import { gzipSync } from 'node:zlib'
9
+ import ts from 'typescript'
10
+ import { build } from 'esbuild'
11
+ import { buildBrowserFormats } from './browser-formats.mjs'
12
+ import { buildProtectedEsm } from './build-protected-esm.mjs'
13
+ import bundleObfuscation from './comps-bundle-obfuscation.cjs'
14
+
15
+ const slash = value => value.replaceAll('\\', '/')
16
+ const walk = dir => fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => entry.isDirectory() && entry.name !== 'node_modules' ? walk(path.join(dir, entry.name)) : entry.isFile() ? [path.join(dir, entry.name)] : []) : []
17
+ const write = (file, content) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, content) }
18
+ const copy = (from, to) => { fs.mkdirSync(path.dirname(to), { recursive: true }); fs.copyFileSync(from, to) }
19
+
20
+ export function cleanDeclarationStyles(directory) {
21
+ for (const file of walk(directory).filter(file => /\.d\.(ts|mts)$/.test(file))) {
22
+ const text = fs.readFileSync(file, 'utf8')
23
+ fs.writeFileSync(file, text.replace(/^\s*import\s*['"][^'"\n]+\.(?:css|scss|less)['"];?\s*$/gm, ''))
24
+ }
25
+ }
26
+
27
+ export async function buildPackageArtifacts(root = process.cwd()) {
28
+ root = path.resolve(root)
29
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
30
+ const config = pkg.releaseArtifacts
31
+ if (!config) throw new Error(`${pkg.name}: 缺少 releaseArtifacts 配置`)
32
+ const src = path.join(root, 'src')
33
+ const out = path.resolve(root, config.outDir)
34
+ if (!out.startsWith(root + path.sep)) throw new Error('产物必须位于包目录内')
35
+ const localRequire = createRequire(path.join(root, 'package.json'))
36
+
37
+ if (config.mode === 'declarations') { cleanDeclarationStyles(out); await buildBrowserFormats(root); return }
38
+
39
+ if (config.mode === 'adapter') {
40
+ for (const file of walk(src)) {
41
+ const dest = path.join(out, path.relative(src, file))
42
+ if (/\.mjs$/.test(file)) await buildProtectedEsm({ entryPoints: [file], outfile: dest, minify: true, target: 'es2019', format: 'esm' }, { root })
43
+ else if (/\.d\.(ts|mts)$/.test(file)) copy(file, dest)
44
+ }
45
+ await buildBrowserFormats(root)
46
+ return
47
+ }
48
+
49
+ const typeOut = path.join(out, 'types')
50
+ const previousOutputs = config.mode === 'library' ? [out] : ['types', 'assets', 'subpaths'].map(dir => path.join(out, dir))
51
+ if (previousOutputs.some(dir => walk(dir).length)) {
52
+ const history = path.join(root, '.tmp/release-artifact-history', Date.now() + '-' + process.pid)
53
+ fs.mkdirSync(history, { recursive: true })
54
+ // File-by-file moves also work when a Windows editor holds the directory open.
55
+ for (const file of previousOutputs.flatMap(walk)) {
56
+ const archived = path.join(history, path.relative(out, file))
57
+ fs.mkdirSync(path.dirname(archived), { recursive: true })
58
+ fs.renameSync(file, archived)
59
+ }
60
+ }
61
+ const sourceConfig = path.join(root, 'tsconfig.json')
62
+ const parsed = fs.existsSync(sourceConfig) ? ts.getParsedCommandLineOfConfigFile(sourceConfig, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: diagnostic => { throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')) } }) : { options: {} }
63
+ const compilerOptions = {
64
+ ...parsed.options, rootDir: src, outDir: typeOut, noEmit: false, declaration: true,
65
+ emitDeclarationOnly: true, declarationMap: false, sourceMap: false, noCheck: true,
66
+ composite: false, incremental: false, allowJs: true, skipLibCheck: true, preserveSymlinks: true,
67
+ }
68
+ delete compilerOptions.tsBuildInfoFile
69
+ const allDeclarations = walk(src).filter(file => /\.d\.(ts|mts)$/.test(file))
70
+ const entryTypes = String(pkg.types || '').replace(/^\.?\/?hel_proxy_es\/types\//, 'src/')
71
+ const sourceTypes = path.resolve(root, entryTypes)
72
+ const typeEntry = fs.existsSync(sourceTypes) ? sourceTypes : sourceTypes.replace(/\.d\.ts$/, '.ts')
73
+ const inputs = config.mode === 'library'
74
+ ? [...Object.values(config.entries).map(file => path.resolve(root, file)), ...allDeclarations]
75
+ : config.declarationDir ? [] : [...(pkg.types ? [typeEntry] : []), ...Object.values(config.proxies || {}).map(entry => path.resolve(root, entry.source)), ...allDeclarations]
76
+ if (config.vue && inputs.length) {
77
+ const tempConfig = path.join(root, '.tmp/release-tsconfig.json')
78
+ write(tempConfig, JSON.stringify({ extends: fs.existsSync(sourceConfig) ? sourceConfig : undefined,
79
+ compilerOptions: { rootDir: src, outDir: typeOut, noEmit: false, declaration: true, emitDeclarationOnly: true,
80
+ declarationMap: false, sourceMap: false, noCheck: true, composite: false, incremental: false, allowJs: true, preserveSymlinks: true },
81
+ files: inputs.map(slash), include: [],
82
+ exclude: ['**/node_modules/**'],
83
+ }, null, 2))
84
+ const require = createRequire(import.meta.url)
85
+ const result = spawnSync(process.execPath, [require.resolve('vue-tsc/bin/vue-tsc.js'), '-p', tempConfig], { cwd: root, stdio: 'inherit' })
86
+ if (result.status !== 0) throw new Error(`${pkg.name}: 声明生成失败`)
87
+ } else if (inputs.length) {
88
+ const program = ts.createProgram(inputs, compilerOptions)
89
+ const result = program.emit()
90
+ if (result.emitSkipped || result.diagnostics.length) throw new Error(ts.formatDiagnosticsWithColorAndContext(result.diagnostics, { getCurrentDirectory: () => root, getCanonicalFileName: x => x, getNewLine: () => '\n' }))
91
+ }
92
+ // Declaration inputs are not copied by tsc. Preserve their dependency closure.
93
+ if (!config.declarationDir) for (const file of allDeclarations) copy(file, path.join(typeOut, path.relative(src, file)))
94
+ if (config.declarationDir) {
95
+ for (const file of walk(path.join(root, config.declarationDir))) copy(file, path.join(typeOut, path.relative(path.join(root, config.declarationDir), file)))
96
+ }
97
+ cleanDeclarationStyles(typeOut)
98
+ // Resolve package-local aliases in emitted declarations to the published tree.
99
+ for (const file of walk(typeOut).filter(file => /\.d\.(ts|mts)$/.test(file))) {
100
+ const relative = path.relative(typeOut, file).replace(/\.d\.ts$/, '.ts')
101
+ const source = path.join(src, relative)
102
+ const text = fs.readFileSync(file, 'utf8').replace(/(['"])([^'"\n]+)\1/g, (match, quote, specifier) => {
103
+ if (specifier.startsWith('.') || (!specifier.startsWith('#') && !specifier.startsWith('@/') && !specifier.startsWith(pkg.name + '/'))) return match
104
+ const resolved = ts.resolveModuleName(specifier, source, parsed.options, ts.sys).resolvedModule?.resolvedFileName
105
+ if (!resolved || !resolved.startsWith(src + path.sep)) {
106
+ if (specifier.startsWith(pkg.name + '/')) return match
107
+ throw new Error(`${file}: 无法解析本包类型别名 ${specifier}`)
108
+ }
109
+ let target = slash(path.relative(path.dirname(file), path.join(typeOut, path.relative(src, resolved))))
110
+ target = target.replace(/(?:\.d)?\.tsx?$/, '.js')
111
+ return quote + (target.startsWith('.') ? target : './' + target) + quote
112
+ })
113
+ const portable = text.replace(/(['"])(\.[^'"\n]+)\1/g, (match, quote, specifier) => {
114
+ if (/\.(?:[cm]?js|[cm]?ts|tsx|vue|json)$/.test(specifier)) return match
115
+ const target = path.resolve(path.dirname(file), specifier)
116
+ if (fs.existsSync(target + '.d.ts')) return quote + specifier + '.js' + quote
117
+ if (fs.existsSync(path.join(target, 'index.d.ts'))) return quote + specifier.replace(/\/$/, '') + '/index.js' + quote
118
+ return match
119
+ })
120
+ fs.writeFileSync(file, portable)
121
+ }
122
+ // Schemas and style resources are data, never a reason to ship implementation sources.
123
+ for (const file of walk(src).filter(file => config.mode === 'library' || config.styles
124
+ ? /\.(json|css|scss|less|svg|woff2?|ttf|png|jpe?g|gif)$/.test(file)
125
+ : /propsSchema\.json$/.test(file))) {
126
+ copy(file, path.join(out, 'assets', path.relative(src, file)))
127
+ if (/\.json$/.test(file)) copy(file, path.join(typeOut, path.relative(src, file)))
128
+ }
129
+
130
+ if (config.mode === 'library') {
131
+ const entries = config.entries
132
+ if (config.vite) {
133
+ const { build: viteBuild } = await import(pathToFileURL(localRequire.resolve('vite')).href)
134
+ const { default: vue } = await import(pathToFileURL(localRequire.resolve('@vitejs/plugin-vue')).href)
135
+ const plugins = [vue()]
136
+ if (config.tailwind) {
137
+ const { default: tailwind } = await import(pathToFileURL(localRequire.resolve('@tailwindcss/vite')).href)
138
+ plugins.push(tailwind())
139
+ }
140
+ const pluginModule = await import(pathToFileURL(localRequire.resolve('vite-plugin-bundle-obfuscator')).href)
141
+ const finalObfuscator = pluginModule.default.default || pluginModule.default
142
+ plugins.push(...bundleObfuscation.bundleObfuscationPlugins({ root, obfuscatorPlugin: finalObfuscator,
143
+ enabled: process.env.HEL_OBFUSCATE !== '0', library: true, rolldown: config.rolldown === true }), bundleObfuscation.gzipPlugin())
144
+ await viteBuild({ configFile: false, root, plugins, css: { postcss: { plugins: [] } },
145
+ build: { outDir: out, emptyOutDir: false, minify: true, sourcemap: false, target: 'es2020',
146
+ lib: { entry: Object.fromEntries(Object.entries(entries).map(([key, value]) => [key, path.join(root, value)])), formats: ['es'], fileName: (_format, name) => name + '.js' },
147
+ rollupOptions: { external: id => id !== pkg.name && !id.startsWith(pkg.name + '/') && !id.startsWith('.') && !path.isAbsolute(id) && !id.startsWith('\0') },
148
+ },
149
+ })
150
+ // Native ESM loads extracted CSS through <link>; bundlers keep the CSS side effect.
151
+ if (entries.design) {
152
+ const design = path.join(out, 'design.js')
153
+ const browserDesign = path.join(out, 'design.browser.js')
154
+ copy(design, browserDesign)
155
+ fs.appendFileSync(design, `\nimport './${pkg.name.split('/').at(-1)}.css'\n`)
156
+ for (const file of [design, browserDesign]) {
157
+ const content = fs.readFileSync(file)
158
+ if (process.env.HEL_GZIP !== '0' && (content.length >= 10240 || fs.existsSync(file + '.gz'))) write(file + '.gz', gzipSync(content))
159
+ }
160
+ }
161
+ } else {
162
+ await buildProtectedEsm({ absWorkingDir: root, entryPoints: entries, outdir: out, bundle: true, packages: 'external', define: { 'import.meta.env.DEV': 'false', 'import.meta.env.PROD': 'true' }, format: 'esm', platform: 'neutral', target: 'es2022', minify: true }, { root })
163
+ }
164
+ if (config.bin) {
165
+ await build({ absWorkingDir: root, entryPoints: [config.bin], outfile: path.join(out, 'cli.mjs'), bundle: true, packages: 'external', platform: 'node', format: 'esm', target: 'node22', minify: true, banner: { js: '#!/usr/bin/env node' } })
166
+ }
167
+ }
168
+ if (config.resolver) {
169
+ await build({ absWorkingDir: root, entryPoints: [config.resolver], outfile: path.join(out, 'resolver.js'), bundle: true, packages: 'external', platform: 'node', format: 'esm', minify: true,
170
+ plugins: [{ name: 'package-name', setup(builder) { builder.onLoad({ filter: /resolver\.ts$/ }, args => ({ loader: 'ts', contents: fs.readFileSync(args.path, 'utf8').replace("createRequire(import.meta.url)('./package.json').name", JSON.stringify(pkg.name)) })) } }],
171
+ })
172
+ const program = ts.createProgram([path.join(root, config.resolver)], { ...compilerOptions, rootDir: root, outDir: path.join(typeOut, '__tools') })
173
+ if (program.emit().emitSkipped) throw new Error('resolver 声明生成失败')
174
+ }
175
+ if (config.proxies) {
176
+ const program = ts.createProgram(inputs, { ...parsed.options, noCheck: true })
177
+ const checker = program.getTypeChecker()
178
+ for (const [name, entry] of Object.entries(config.proxies)) {
179
+ const source = program.getSourceFile(path.join(root, entry.source))
180
+ const symbol = source && checker.getSymbolAtLocation(source)
181
+ if (!symbol) throw new Error(`${pkg.name}: 无法读取子路径 ${entry.source}`)
182
+ const names = checker.getExportsOfModule(symbol).filter(symbol => {
183
+ const declarations = symbol.declarations || []
184
+ if (declarations.every(d => ts.isInterfaceDeclaration(d) || ts.isTypeAliasDeclaration(d) || (ts.isExportSpecifier(d) && (d.isTypeOnly || d.parent.parent.isTypeOnly)))) return false
185
+ const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol
186
+ return Boolean(target.flags & ts.SymbolFlags.Value)
187
+ }).map(symbol => symbol.name)
188
+ const body = [`import lib from '../entry.js'`, `const namespace = lib[${JSON.stringify(entry.namespace)}]`]
189
+ for (const key of names) body.push(key === 'default'
190
+ ? `export default namespace["default"]`
191
+ : `export const ${key} = namespace[${JSON.stringify(key)}]`)
192
+ write(path.join(out, 'subpaths', name + '.js'), body.join('\n') + '\n')
193
+ }
194
+ }
195
+ await buildBrowserFormats(root)
196
+ console.log(`[package-artifacts] ${pkg.name}: ${out}`)
197
+ }
198
+
199
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) await buildPackageArtifacts()
@@ -1,193 +1,193 @@
1
- const fs = require('node:fs')
2
- const path = require('node:path')
3
- const { createRequire } = require('node:module')
4
- const dotenv = require('dotenv')
5
- const { expand } = require('dotenv-expand')
6
- const { packageRef, packageUrl } = require('../src/remote-address.cjs')
7
-
8
- const PUBLIC_ENV_KEYS = ['SFTP_PUBLIC_URL', 'GITHUB_PUBLIC_URL', 'UNPKG_PUBLIC_URL']
9
- const WORKSPACE_ENV_KEYS = [...PUBLIC_ENV_KEYS, 'HEL_RELATIVE_PATH']
10
- const TARGETS = ['local', 'sftp', 'github', 'unpkg']
11
- const trim = value => String(value || '').trim().replace(/\/+$/, '')
12
-
13
- function readEnvFile(file) {
14
- return fs.existsSync(file) ? dotenv.parse(fs.readFileSync(file)) : {}
15
- }
16
-
17
- function readPackageFiles(cwd, mode) {
18
- // The root orchestrator copies only public bases here. Never read a parent directory.
19
- return Object.assign({}, ...[
20
- '.env.defaults', '.env.workspace.local', '.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`,
21
- ].map(name => readEnvFile(path.join(cwd, name))))
22
- }
23
-
24
- function remoteSlots(env) {
25
- return Object.keys(env).filter(key => /^[A-Z][A-Z\d_]*_PACKAGE$/.test(key) && !/^(?:DEPLOY_|VITE_|VUE_APP_|REACT_APP_|HEL_)/.test(key))
26
- .map(key => key.slice(0, -8))
27
- }
28
-
29
- function resolveTarget(value, mode) {
30
- const target = String(value || 'auto').toLowerCase()
31
- if (target === 'auto') return ['development', 'mock'].includes(mode) ? 'local' : 'unpkg'
32
- if (!TARGETS.includes(target)) throw new Error(`[hel-env] Unknown remote target: ${target}`)
33
- return target
34
- }
35
-
36
- // Resolve metadata from an installed dependency, never from a sibling/source checkout.
37
- function installedVersion(cwd, packageName) {
38
- const fromPackage = createRequire(path.join(cwd, 'package.json'))
39
- try {
40
- return JSON.parse(fs.readFileSync(fromPackage.resolve(packageName + '/package.json'), 'utf8')).version
41
- } catch (error) {
42
- if (!['ERR_PACKAGE_PATH_NOT_EXPORTED', 'MODULE_NOT_FOUND'].includes(error.code)) throw error
43
- }
44
- let directory = path.dirname(fromPackage.resolve(packageName))
45
- for (;;) {
46
- const manifest = path.join(directory, 'package.json')
47
- if (fs.existsSync(manifest)) {
48
- const pkg = JSON.parse(fs.readFileSync(manifest, 'utf8'))
49
- if (pkg.name === packageName) return pkg.version
50
- }
51
- const parent = path.dirname(directory)
52
- if (parent === directory) throw new Error(`[hel-env] Cannot resolve installed version of ${packageName}; set the dependency's VERSION explicitly`)
53
- directory = parent
54
- }
55
- }
56
-
57
- function resolveRemoteUrl(env, slot, target) {
58
- const packageName = env[`${slot}_PACKAGE`]
59
- if (target === 'local') {
60
- const url = trim(env[`${slot}_LOCAL_URL`])
61
- if (!url) throw new Error(`[hel-env] ${slot}_LOCAL_URL is required for local development`)
62
- return url
63
- }
64
- const base = trim(env[`${target.toUpperCase()}_PUBLIC_URL`])
65
- let version = env[`DEPLOY_${slot}_VERSION`] || env[`${slot}_VERSION`] || 'latest'
66
- if (target === 'unpkg' && version === 'installed') version = installedVersion(env.HEL_ENV_PACKAGE || process.cwd(), packageName)
67
- const output = env[`${slot}_OUTPUT_DIR`] || 'hel_dist'
68
- const entry = env[`${slot}_ENTRY`] || 'hel-meta.json'
69
- try {
70
- const parsed = packageRef(packageName)
71
- parsed.version = version
72
- const url = packageUrl(parsed, {
73
- type: target === 'sftp' ? 'custom' : target, base,
74
- projectName: target === 'unpkg' ? undefined : env[`${slot}_PROJECT`],
75
- // Static deployments update project directories; unpkg versions are npm versions.
76
- versioned: target === 'unpkg',
77
- })
78
- url.pathname += '/' + output + '/' + entry
79
- return url.href
80
- } catch (error) { throw new Error(`[hel-env] ${slot}: ${error.message}`) }
81
- }
82
-
83
- function assertSameOrigin(url, base, slot) {
84
- if (new URL(url).origin !== new URL(base).origin) {
85
- throw new Error(`[hel-env] ${slot} must use the deployment origin ${new URL(base).origin}: ${url}`)
86
- }
87
- }
88
-
89
- // Keep the deployment directory while allowing the same static files on another origin.
90
- function resolveBuildHomePage(env, homePage = env.HEL_APP_HOME_PAGE) {
91
- if (env.HEL_RELATIVE_PATH !== '1') return homePage
92
- if (/^(?:https?:)?\/\//i.test(homePage || '')) return new URL(homePage, 'https://hel.invalid').pathname
93
- return homePage || '/'
94
- }
95
-
96
- function loadPackageEnv({ cwd = process.cwd(), mode = 'development', env = process.env, target, localBuild = false } = {}) {
97
- const inherited = { ...env }
98
- // Recompute our own defaults on reload, but preserve values changed by cross-env.
99
- const generated = JSON.parse(inherited.HEL_ENV_GENERATED || '{}')
100
- for (const [key, value] of Object.entries(generated)) {
101
- if (inherited[key] === value) delete inherited[key]
102
- }
103
- delete inherited.HEL_ENV_GENERATED
104
- delete inherited.HEL_ENV_DERIVED_KEYS
105
- delete inherited.HEL_ENV_PACKAGE
106
- const values = Object.assign({}, readPackageFiles(cwd, mode), inherited)
107
- values.HEL_ENV_PACKAGE = path.resolve(cwd)
108
- expand({ parsed: values, processEnv: { ...values } })
109
- values.UNPKG_PUBLIC_URL ||= 'https://unpkg.com'
110
- const derived = new Set()
111
- const put = (key, value) => {
112
- if (!value) return
113
- if (!values[key]) { values[key] = String(value); derived.add(key) }
114
- }
115
- const deployTarget = values.HEL_DEPLOY_TARGET
116
- const runtimeMode = values.NODE_ENV || mode
117
- const selected = resolveTarget(deployTarget || target || values.REMOTE_TARGET, runtimeMode)
118
- localBuild ||= values.HEL_LOCAL_BUILD === '1'
119
- const port = inherited.PORT || inherited.DEV_PORT || inherited.VITE_PORT || values.PORT || values.DEV_PORT
120
- const previewPort = values.PREVIEW_PORT || port
121
- if (port && (!/^\d+$/.test(String(port)) || +port < 1 || +port > 65535)) throw new Error('[hel-env] DEV_PORT must be between 1 and 65535')
122
- if (port) values.DEV_PORT = String(port)
123
- put('PORT', port)
124
- put('VITE_PORT', port)
125
- put('VUE_APP_PORT', port)
126
- put('REACT_APP_PORT', port)
127
- put('VITE_PREVIEW_PORT', previewPort)
128
- put('VUE_APP_PREVIEW_PORT', previewPort)
129
- put('VITE_DEV_ORIGIN', values.DEV_ORIGIN || (port ? `http://localhost:${port}` : ''))
130
- put('VUE_APP_DEV_ORIGIN', values.VITE_DEV_ORIGIN)
131
- for (const key of PUBLIC_ENV_KEYS) {
132
- // Only these public bases are exposed to browser code, never SFTP credentials.
133
- put(`VITE_${key}`, values[key])
134
- put(`VUE_APP_${key}`, values[key])
135
- }
136
- for (const slot of remoteSlots(values)) {
137
- const slotTarget = resolveTarget(deployTarget || target || values[`${slot}_TARGET`] || selected, runtimeMode)
138
- const keys = [`VITE_${slot}_HOST`, `VUE_APP_${slot}_HOST`, `REACT_APP_${slot}_HOST`, `HEL_${slot}_HOST`]
139
- const overrides = [...keys, `VUE_APP_${slot}_ENTRY`, `VITE_${slot}_ENTRY`, `${slot}_URL`]
140
- .map(key => values[key]).filter(Boolean)
141
- if (new Set(overrides).size > 1) throw new Error(`[hel-env] Conflicting ${slot} address overrides`)
142
- const explicit = overrides[0]
143
- const expected = !explicit || deployTarget
144
- ? localBuild && !deployTarget && values[`${slot}_BUNDLED_PATH`]
145
- ? './' + values[`${slot}_BUNDLED_PATH`]
146
- : resolveRemoteUrl(values, slot, slotTarget)
147
- : explicit
148
- const resolved = explicit || expected
149
- if (deployTarget) {
150
- assertSameOrigin(resolved, values[`${deployTarget.toUpperCase()}_PUBLIC_URL`] || expected, slot)
151
- if (resolved !== expected) throw new Error(`[hel-env] ${slot} must match the deployment package/version URL: ${expected}`)
152
- }
153
- for (const key of keys) put(key, resolved)
154
- if (values[`${slot}_ENTRY`] === 'index.html') {
155
- put(`VUE_APP_${slot}_ENTRY`, resolved)
156
- put(`VITE_${slot}_ENTRY`, resolved)
157
- }
158
- put(`VITE_${slot}_LOCAL_URL`, values[`${slot}_LOCAL_URL`])
159
- put(`VUE_APP_${slot}_LOCAL_URL`, values[`${slot}_LOCAL_URL`])
160
- }
161
- if (localBuild && values.VITE_DEV_ORIGIN) put('HEL_APP_HOME_PAGE', values.VITE_DEV_ORIGIN)
162
- if (runtimeMode === 'production' && !localBuild) {
163
- const homePage = resolveBuildHomePage(values)
164
- if (homePage) values.HEL_APP_HOME_PAGE = homePage
165
- }
166
- if (deployTarget) put('VUE_APP_PUBLISH_MODE', deployTarget)
167
- values.HEL_ENV_PACKAGE = path.resolve(cwd)
168
- const computed = Object.fromEntries(Object.entries(values).filter(([key, value]) =>
169
- !key.startsWith('HEL_ENV_') && inherited[key] !== value && !(key === 'HEL_APP_HOME_PAGE' && inherited[key])))
170
- values.HEL_ENV_DERIVED_KEYS = Object.keys(computed).join(',')
171
- values.HEL_ENV_GENERATED = JSON.stringify(computed)
172
- return values
173
- }
174
-
175
- function inferMode(env = process.env, argv = process.argv) {
176
- const modeIndex = argv.indexOf('--mode')
177
- const inline = argv.find(arg => arg.startsWith('--mode='))
178
- if (modeIndex >= 0 && argv[modeIndex + 1]) return argv[modeIndex + 1]
179
- if (inline) return inline.slice(7)
180
- if (env.HEL_ENV_MODE) return env.HEL_ENV_MODE
181
- if (env.NODE_ENV) return env.NODE_ENV
182
- return /^(?:build|preview|prepublish)/.test(env.npm_lifecycle_event || '') ? 'production' : 'development'
183
- }
184
-
185
- function applyPackageEnv({ cwd = process.cwd(), mode = inferMode() } = {}) {
186
- const values = loadPackageEnv({ cwd, mode })
187
- const preview = /^(?:preview|serve:dist)/.test(process.env.npm_lifecycle_event || '')
188
- if (preview && !process.env.PORT && values.PREVIEW_PORT) values.PORT = values.PREVIEW_PORT
189
- Object.assign(process.env, values)
190
- return values
191
- }
192
-
193
- module.exports = { applyPackageEnv, inferMode, PUBLIC_ENV_KEYS, WORKSPACE_ENV_KEYS, readEnvFile, readPackageFiles, remoteSlots, resolveTarget, resolveRemoteUrl, resolveBuildHomePage, loadPackageEnv }
1
+ const fs = require('node:fs')
2
+ const path = require('node:path')
3
+ const { createRequire } = require('node:module')
4
+ const dotenv = require('dotenv')
5
+ const { expand } = require('dotenv-expand')
6
+ const { packageRef, packageUrl } = require('./remote-address.cjs')
7
+
8
+ const PUBLIC_ENV_KEYS = ['SFTP_PUBLIC_URL', 'GITHUB_PUBLIC_URL', 'UNPKG_PUBLIC_URL']
9
+ const WORKSPACE_ENV_KEYS = [...PUBLIC_ENV_KEYS, 'HEL_RELATIVE_PATH']
10
+ const TARGETS = ['local', 'sftp', 'github', 'unpkg']
11
+ const trim = value => String(value || '').trim().replace(/\/+$/, '')
12
+
13
+ function readEnvFile(file) {
14
+ return fs.existsSync(file) ? dotenv.parse(fs.readFileSync(file)) : {}
15
+ }
16
+
17
+ function readPackageFiles(cwd, mode) {
18
+ // The root orchestrator copies only public bases here. Never read a parent directory.
19
+ return Object.assign({}, ...[
20
+ '.env.defaults', '.env.workspace.local', '.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`,
21
+ ].map(name => readEnvFile(path.join(cwd, name))))
22
+ }
23
+
24
+ function remoteSlots(env) {
25
+ return Object.keys(env).filter(key => /^[A-Z][A-Z\d_]*_PACKAGE$/.test(key) && !/^(?:DEPLOY_|VITE_|VUE_APP_|REACT_APP_|HEL_)/.test(key))
26
+ .map(key => key.slice(0, -8))
27
+ }
28
+
29
+ function resolveTarget(value, mode) {
30
+ const target = String(value || 'auto').toLowerCase()
31
+ if (target === 'auto') return ['development', 'mock'].includes(mode) ? 'local' : 'unpkg'
32
+ if (!TARGETS.includes(target)) throw new Error(`[hel-env] Unknown remote target: ${target}`)
33
+ return target
34
+ }
35
+
36
+ // Resolve metadata from an installed dependency, never from a sibling/source checkout.
37
+ function installedVersion(cwd, packageName) {
38
+ const fromPackage = createRequire(path.join(cwd, 'package.json'))
39
+ try {
40
+ return JSON.parse(fs.readFileSync(fromPackage.resolve(packageName + '/package.json'), 'utf8')).version
41
+ } catch (error) {
42
+ if (!['ERR_PACKAGE_PATH_NOT_EXPORTED', 'MODULE_NOT_FOUND'].includes(error.code)) throw error
43
+ }
44
+ let directory = path.dirname(fromPackage.resolve(packageName))
45
+ for (;;) {
46
+ const manifest = path.join(directory, 'package.json')
47
+ if (fs.existsSync(manifest)) {
48
+ const pkg = JSON.parse(fs.readFileSync(manifest, 'utf8'))
49
+ if (pkg.name === packageName) return pkg.version
50
+ }
51
+ const parent = path.dirname(directory)
52
+ if (parent === directory) throw new Error(`[hel-env] Cannot resolve installed version of ${packageName}; set the dependency's VERSION explicitly`)
53
+ directory = parent
54
+ }
55
+ }
56
+
57
+ function resolveRemoteUrl(env, slot, target) {
58
+ const packageName = env[`${slot}_PACKAGE`]
59
+ if (target === 'local') {
60
+ const url = trim(env[`${slot}_LOCAL_URL`])
61
+ if (!url) throw new Error(`[hel-env] ${slot}_LOCAL_URL is required for local development`)
62
+ return url
63
+ }
64
+ const base = trim(env[`${target.toUpperCase()}_PUBLIC_URL`])
65
+ let version = env[`DEPLOY_${slot}_VERSION`] || env[`${slot}_VERSION`] || 'latest'
66
+ if (target === 'unpkg' && version === 'installed') version = installedVersion(env.HEL_ENV_PACKAGE || process.cwd(), packageName)
67
+ const output = env[`${slot}_OUTPUT_DIR`] || 'hel_dist'
68
+ const entry = env[`${slot}_ENTRY`] || 'hel-meta.json'
69
+ try {
70
+ const parsed = packageRef(packageName)
71
+ parsed.version = version
72
+ const url = packageUrl(parsed, {
73
+ type: target === 'sftp' ? 'custom' : target, base,
74
+ projectName: target === 'unpkg' ? undefined : env[`${slot}_PROJECT`],
75
+ // Static deployments update project directories; unpkg versions are npm versions.
76
+ versioned: target === 'unpkg',
77
+ })
78
+ url.pathname += '/' + output + '/' + entry
79
+ return url.href
80
+ } catch (error) { throw new Error(`[hel-env] ${slot}: ${error.message}`) }
81
+ }
82
+
83
+ function assertSameOrigin(url, base, slot) {
84
+ if (new URL(url).origin !== new URL(base).origin) {
85
+ throw new Error(`[hel-env] ${slot} must use the deployment origin ${new URL(base).origin}: ${url}`)
86
+ }
87
+ }
88
+
89
+ // Keep the deployment directory while allowing the same static files on another origin.
90
+ function resolveBuildHomePage(env, homePage = env.HEL_APP_HOME_PAGE) {
91
+ if (env.HEL_RELATIVE_PATH !== '1') return homePage
92
+ if (/^(?:https?:)?\/\//i.test(homePage || '')) return new URL(homePage, 'https://hel.invalid').pathname
93
+ return homePage || '/'
94
+ }
95
+
96
+ function loadPackageEnv({ cwd = process.cwd(), mode = 'development', env = process.env, target, localBuild = false } = {}) {
97
+ const inherited = { ...env }
98
+ // Recompute our own defaults on reload, but preserve values changed by cross-env.
99
+ const generated = JSON.parse(inherited.HEL_ENV_GENERATED || '{}')
100
+ for (const [key, value] of Object.entries(generated)) {
101
+ if (inherited[key] === value) delete inherited[key]
102
+ }
103
+ delete inherited.HEL_ENV_GENERATED
104
+ delete inherited.HEL_ENV_DERIVED_KEYS
105
+ delete inherited.HEL_ENV_PACKAGE
106
+ const values = Object.assign({}, readPackageFiles(cwd, mode), inherited)
107
+ values.HEL_ENV_PACKAGE = path.resolve(cwd)
108
+ expand({ parsed: values, processEnv: { ...values } })
109
+ values.UNPKG_PUBLIC_URL ||= 'https://unpkg.com'
110
+ const derived = new Set()
111
+ const put = (key, value) => {
112
+ if (!value) return
113
+ if (!values[key]) { values[key] = String(value); derived.add(key) }
114
+ }
115
+ const deployTarget = values.HEL_DEPLOY_TARGET
116
+ const runtimeMode = values.NODE_ENV || mode
117
+ const selected = resolveTarget(deployTarget || target || values.REMOTE_TARGET, runtimeMode)
118
+ localBuild ||= values.HEL_LOCAL_BUILD === '1'
119
+ const port = inherited.PORT || inherited.DEV_PORT || inherited.VITE_PORT || values.PORT || values.DEV_PORT
120
+ const previewPort = values.PREVIEW_PORT || port
121
+ if (port && (!/^\d+$/.test(String(port)) || +port < 1 || +port > 65535)) throw new Error('[hel-env] DEV_PORT must be between 1 and 65535')
122
+ if (port) values.DEV_PORT = String(port)
123
+ put('PORT', port)
124
+ put('VITE_PORT', port)
125
+ put('VUE_APP_PORT', port)
126
+ put('REACT_APP_PORT', port)
127
+ put('VITE_PREVIEW_PORT', previewPort)
128
+ put('VUE_APP_PREVIEW_PORT', previewPort)
129
+ put('VITE_DEV_ORIGIN', values.DEV_ORIGIN || (port ? `http://localhost:${port}` : ''))
130
+ put('VUE_APP_DEV_ORIGIN', values.VITE_DEV_ORIGIN)
131
+ for (const key of PUBLIC_ENV_KEYS) {
132
+ // Only these public bases are exposed to browser code, never SFTP credentials.
133
+ put(`VITE_${key}`, values[key])
134
+ put(`VUE_APP_${key}`, values[key])
135
+ }
136
+ for (const slot of remoteSlots(values)) {
137
+ const slotTarget = resolveTarget(deployTarget || target || values[`${slot}_TARGET`] || selected, runtimeMode)
138
+ const keys = [`VITE_${slot}_HOST`, `VUE_APP_${slot}_HOST`, `REACT_APP_${slot}_HOST`, `HEL_${slot}_HOST`]
139
+ const overrides = [...keys, `VUE_APP_${slot}_ENTRY`, `VITE_${slot}_ENTRY`, `${slot}_URL`]
140
+ .map(key => values[key]).filter(Boolean)
141
+ if (new Set(overrides).size > 1) throw new Error(`[hel-env] Conflicting ${slot} address overrides`)
142
+ const explicit = overrides[0]
143
+ const expected = !explicit || deployTarget
144
+ ? localBuild && !deployTarget && values[`${slot}_BUNDLED_PATH`]
145
+ ? './' + values[`${slot}_BUNDLED_PATH`]
146
+ : resolveRemoteUrl(values, slot, slotTarget)
147
+ : explicit
148
+ const resolved = explicit || expected
149
+ if (deployTarget) {
150
+ assertSameOrigin(resolved, values[`${deployTarget.toUpperCase()}_PUBLIC_URL`] || expected, slot)
151
+ if (resolved !== expected) throw new Error(`[hel-env] ${slot} must match the deployment package/version URL: ${expected}`)
152
+ }
153
+ for (const key of keys) put(key, resolved)
154
+ if (values[`${slot}_ENTRY`] === 'index.html') {
155
+ put(`VUE_APP_${slot}_ENTRY`, resolved)
156
+ put(`VITE_${slot}_ENTRY`, resolved)
157
+ }
158
+ put(`VITE_${slot}_LOCAL_URL`, values[`${slot}_LOCAL_URL`])
159
+ put(`VUE_APP_${slot}_LOCAL_URL`, values[`${slot}_LOCAL_URL`])
160
+ }
161
+ if (localBuild && values.VITE_DEV_ORIGIN) put('HEL_APP_HOME_PAGE', values.VITE_DEV_ORIGIN)
162
+ if (runtimeMode === 'production' && !localBuild) {
163
+ const homePage = resolveBuildHomePage(values)
164
+ if (homePage) values.HEL_APP_HOME_PAGE = homePage
165
+ }
166
+ if (deployTarget) put('VUE_APP_PUBLISH_MODE', deployTarget)
167
+ values.HEL_ENV_PACKAGE = path.resolve(cwd)
168
+ const computed = Object.fromEntries(Object.entries(values).filter(([key, value]) =>
169
+ !key.startsWith('HEL_ENV_') && inherited[key] !== value && !(key === 'HEL_APP_HOME_PAGE' && inherited[key])))
170
+ values.HEL_ENV_DERIVED_KEYS = Object.keys(computed).join(',')
171
+ values.HEL_ENV_GENERATED = JSON.stringify(computed)
172
+ return values
173
+ }
174
+
175
+ function inferMode(env = process.env, argv = process.argv) {
176
+ const modeIndex = argv.indexOf('--mode')
177
+ const inline = argv.find(arg => arg.startsWith('--mode='))
178
+ if (modeIndex >= 0 && argv[modeIndex + 1]) return argv[modeIndex + 1]
179
+ if (inline) return inline.slice(7)
180
+ if (env.HEL_ENV_MODE) return env.HEL_ENV_MODE
181
+ if (env.NODE_ENV) return env.NODE_ENV
182
+ return /^(?:build|preview|prepublish)/.test(env.npm_lifecycle_event || '') ? 'production' : 'development'
183
+ }
184
+
185
+ function applyPackageEnv({ cwd = process.cwd(), mode = inferMode() } = {}) {
186
+ const values = loadPackageEnv({ cwd, mode })
187
+ const preview = /^(?:preview|serve:dist)/.test(process.env.npm_lifecycle_event || '')
188
+ if (preview && !process.env.PORT && values.PREVIEW_PORT) values.PORT = values.PREVIEW_PORT
189
+ Object.assign(process.env, values)
190
+ return values
191
+ }
192
+
193
+ module.exports = { applyPackageEnv, inferMode, PUBLIC_ENV_KEYS, WORKSPACE_ENV_KEYS, readEnvFile, readPackageFiles, remoteSlots, resolveTarget, resolveRemoteUrl, resolveBuildHomePage, loadPackageEnv }