@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
@@ -1,325 +1,328 @@
1
1
  #!/usr/bin/env node
2
- /*
3
- |--------------------------------------------------------------------------
4
- |
5
- | 产物 TDZ 守卫:扫描构建产物,拦住「先引用、后声明」的 let / const / class。
6
- |
7
- | 背景(真实踩过的坑):vite-plugin-externals 在构建期把 import 就地改写成
8
- | `const X = window.X`,而 ESM 的 import 是提升的(写在哪一行都先于模块体执行)。
9
- | 一旦依赖产物把 import 写在模块体后面(tsup 输出常见),改写后就变成:
10
- |
11
- | __reExport(ns, vueNs); const vueNs = window.Vue // ← TDZ
12
- |
13
- | 浏览器加载即抛 `Cannot access 'xxx' before initialization`;混淆后变量名变成
14
- | `_0x2bee8b` 之类,很难看出真因。这个脚本在 build 阶段直接拦下这类产物。
15
- |
16
- | 判定口径:引用位置早于声明位置,且两者之间没有跨函数边界(即加载期就会执行到)。
17
- | 跨了函数的「延后引用」不算——那是正常写法(函数体在模块求值完成后才调用)。
18
- |
19
- | 用法:
20
- | hel-check-tdz # 默认扫当前目录的 hel_dist/assets
21
- | hel-check-tdz dist bundle.js # 也可指定目录 / 文件
22
- | 退出码:发现 immediate TDZ → 1
23
- |
24
- |--------------------------------------------------------------------------
25
- */
26
- import fs from 'node:fs'
27
- import path from 'node:path'
28
- import { parse } from 'acorn'
29
-
30
- const FUNCTION_TYPES = new Set([
31
- 'FunctionDeclaration',
32
- 'FunctionExpression',
33
- 'ArrowFunctionExpression',
34
- ])
35
- const CLASS_TYPES = new Set(['ClassDeclaration', 'ClassExpression'])
36
- const SKIP_KEYS = new Set(['type', 'start', 'end', 'loc', 'range', '__parent'])
37
-
38
- const isNode = v => !!v && typeof v === 'object' && typeof v.type === 'string'
39
-
40
- /** 通用 AST 遍历,顺手挂 __parent,方便判断标识符的语法角色 */
41
- function walk(node, enter) {
42
- enter(node)
43
- for (const key of Object.keys(node)) {
44
- if (SKIP_KEYS.has(key)) continue
45
- const value = node[key]
46
- if (Array.isArray(value)) {
47
- for (const item of value) {
48
- if (isNode(item)) {
49
- item.__parent = node
50
- walk(item, enter)
51
- }
52
- }
53
- } else if (isNode(value)) {
54
- value.__parent = node
55
- walk(value, enter)
56
- }
57
- }
58
- }
59
-
60
- class Scope {
61
- constructor(kind, parent, isFunction) {
62
- this.kind = kind
63
- this.parent = parent
64
- this.isFunction = isFunction
65
- /** name -> { start, kind } */
66
- this.lexical = new Map()
67
- }
68
- }
69
-
70
- function collectPatternNames(node, cb) {
71
- if (!node) return
72
- if (node.type === 'Identifier') return cb(node)
73
- if (node.type === 'AssignmentPattern') return collectPatternNames(node.left, cb)
74
- if (node.type === 'RestElement') return collectPatternNames(node.argument, cb)
75
- if (node.type === 'ArrayPattern') {
76
- for (const el of node.elements) collectPatternNames(el, cb)
77
- return
78
- }
79
- if (node.type === 'ObjectPattern') {
80
- for (const prop of node.properties) {
81
- if (prop.type === 'RestElement') collectPatternNames(prop.argument, cb)
82
- else collectPatternNames(prop.value, cb)
83
- }
84
- }
85
- }
86
-
87
- /** 标识符是否处于「声明位置」(绑定名),是则不算引用 */
88
- function isDeclarationIdentifier(node) {
89
- const p = node.__parent
90
- if (!p) return true
91
- if (p.type === 'VariableDeclarator' && p.id === node) return true
92
- if (FUNCTION_TYPES.has(p.type) && p.id === node) return true
93
- if (CLASS_TYPES.has(p.type) && p.id === node) return true
94
- if (p.type === 'CatchClause' && p.param === node) return true
95
- if (
96
- p.type === 'ImportSpecifier' ||
97
- p.type === 'ImportDefaultSpecifier' ||
98
- p.type === 'ImportNamespaceSpecifier'
99
- )
100
- return true
101
- if (
102
- p.type === 'ArrayPattern' ||
103
- p.type === 'ObjectPattern' ||
104
- p.type === 'RestElement' ||
105
- p.type === 'AssignmentPattern' ||
106
- p.type === 'Property'
107
- ) {
108
- let cur = node
109
- let up = cur.__parent
110
- while (
111
- up &&
112
- (up.type === 'ArrayPattern' ||
113
- up.type === 'ObjectPattern' ||
114
- up.type === 'RestElement' ||
115
- up.type === 'AssignmentPattern' ||
116
- up.type === 'Property')
117
- ) {
118
- if (up.type === 'AssignmentPattern' && up.left === cur && up.right === node) return false
119
- cur = up
120
- up = up.__parent
121
- }
122
- return !!(
123
- up &&
124
- ((up.type === 'VariableDeclarator' && up.id === cur) ||
125
- FUNCTION_TYPES.has(up.type) ||
126
- (up.type === 'CatchClause' && up.param === cur))
127
- )
128
- }
129
- return false
130
- }
131
-
132
- /** 引用是否属于「不是变量引用」的语法位置(属性名、label 等) */
133
- function isNonReferencePosition(node) {
134
- const p = node.__parent
135
- if (!p) return true
136
- if (p.type === 'MemberExpression' && p.property === node && !p.computed) return true
137
- if (p.type === 'Property' && p.key === node && !p.computed) return true
138
- if (p.type === 'MethodDefinition' && p.key === node && !p.computed) return true
139
- if (p.type === 'PropertyDefinition' && p.key === node && !p.computed) return true
140
- if (p.type === 'LabeledStatement' || p.type === 'BreakStatement' || p.type === 'ContinueStatement')
141
- return true
142
- if (p.type === 'ExportSpecifier' || p.type === 'ImportSpecifier') return true
143
- return false
144
- }
145
-
146
- function analyzeCode(code, filename) {
147
- let ast
148
- try {
149
- ast = parse(code, {
150
- ecmaVersion: 'latest',
151
- sourceType: 'script',
152
- allowHashBang: true,
153
- allowReturnOutsideFunction: true,
154
- })
155
- } catch (err) {
156
- // 少数产物是 ESM,按 module 再解析一次
157
- ast = parse(code, {
158
- ecmaVersion: 'latest',
159
- sourceType: 'module',
160
- allowHashBang: true,
161
- })
162
- }
163
-
164
- walk(ast, () => {}) // 只为建立 __parent
165
-
166
- const scopeByNode = new Map()
167
- /** 绑定标识符(函数参数 / catch 参数等)本身,不参与「引用早于声明」判断 */
168
- const bindingByNode = new Map()
169
- const root = new Scope('program', null, false)
170
-
171
- const build = (node, scope) => {
172
- let current = scope
173
- if (FUNCTION_TYPES.has(node.type)) {
174
- current = new Scope('function', scope, true)
175
- } else if (node.type === 'BlockStatement' || node.type === 'StaticBlock') {
176
- current = new Scope('block', scope, false)
177
- } else if (node.type === 'CatchClause') {
178
- current = new Scope('catch', scope, false)
179
- } else if (
180
- // for (let x of/in ...) 的循环变量属于 for 语句自己的作用域,不是外层;
181
- // 压缩产物里 `for(let e in t)` 很常见,不单独建作用域会把它误判成外层 let
182
- node.type === 'ForStatement' ||
183
- node.type === 'ForInStatement' ||
184
- node.type === 'ForOfStatement' ||
185
- // switch 的 case 共用同一个块级作用域
186
- node.type === 'SwitchStatement'
187
- ) {
188
- current = new Scope('block', scope, false)
189
- } else if (CLASS_TYPES.has(node.type)) {
190
- current = new Scope('class', scope, false)
191
- }
192
- scopeByNode.set(node, current)
193
-
194
- const declare = (id, kind) => {
195
- if (!current.lexical.has(id.name)) current.lexical.set(id.name, { start: id.start, kind })
196
- // 参数 / 循环变量 / catch 参数也属于「声明位置」,后续引用不应被当成外层同名变量
197
- if (!bindingByNode.has(id)) bindingByNode.set(id, { scope: current, kind, start: id.start })
198
- }
199
-
200
- // 函数参数与 catch 参数也是绑定:不登记的话,压缩产物里形参名和模块级 let 同名时会大面积误报
201
- if (FUNCTION_TYPES.has(node.type)) {
202
- for (const param of node.params || []) collectPatternNames(param, id => declare(id, 'param'))
203
- }
204
- if (node.type === 'CatchClause' && node.param) {
205
- collectPatternNames(node.param, id => declare(id, 'catch'))
206
- }
207
-
208
- if (node.type === 'VariableDeclaration' && (node.kind === 'let' || node.kind === 'const')) {
209
- for (const decl of node.declarations) {
210
- collectPatternNames(decl.id, id => declare(id, node.kind))
211
- }
212
- }
213
- if (node.type === 'ClassDeclaration' && node.id) {
214
- // 类声明:类名在「类自身作用域」和「外层作用域」都可见
215
- const outer = scopeByNode.get(node.__parent) || scope
216
- if (!outer.lexical.has(node.id.name))
217
- outer.lexical.set(node.id.name, { start: node.id.start, kind: 'class' })
218
- declare(node.id, 'class')
219
- } else if (node.type === 'ClassExpression' && node.id) {
220
- // 类表达式(如压缩产物里的 `var Y = class e extends Error {}`)的类名只在本类内部可见,
221
- // 不能登记到外层作用域,否则会把外层同名引用误判成 TDZ
222
- declare(node.id, 'class')
223
- }
224
- if (node.type === 'ImportDeclaration') {
225
- for (const spec of node.specifiers) declare(spec.local, 'import')
226
- }
227
-
228
- for (const key of Object.keys(node)) {
229
- if (SKIP_KEYS.has(key)) continue
230
- const value = node[key]
231
- if (Array.isArray(value)) {
232
- for (const item of value) if (isNode(item)) build(item, current)
233
- } else if (isNode(value)) build(value, current)
234
- }
235
- }
236
- build(ast, root)
237
-
238
- const problems = []
239
- walk(ast, node => {
240
- if (node.type !== 'Identifier') return
241
- if (bindingByNode.has(node)) return
242
- if (isDeclarationIdentifier(node)) return
243
- if (isNonReferencePosition(node)) return
244
-
245
- let scope = scopeByNode.get(node)
246
- let hit = null
247
- while (scope) {
248
- if (scope.lexical.has(node.name)) {
249
- hit = { scope, info: scope.lexical.get(node.name) }
250
- break
251
- }
252
- scope = scope.parent
253
- }
254
- if (!hit) return
255
- if (node.start > hit.info.start) return // 正常顺序
256
-
257
- // 引用到声明之间是否跨了函数:跨了说明是延后执行(不是加载期 TDZ)
258
- let crossings = 0
259
- let cur = scopeByNode.get(node)
260
- while (cur && cur !== hit.scope) {
261
- if (cur.isFunction) crossings++
262
- cur = cur.parent
263
- }
264
- if (crossings > 0) return
265
-
266
- problems.push({
267
- name: node.name,
268
- start: node.start,
269
- declStart: hit.info.start,
270
- declKind: hit.info.kind,
271
- snippet: code.slice(Math.max(0, node.start - 70), node.start + 90).replace(/\s+/g, ' '),
272
- })
273
- })
274
-
275
- return problems.map(p => ({ ...p, file: filename }))
276
- }
277
-
278
- function collectFiles(target) {
279
- const stat = fs.statSync(target, { throwIfNoEntry: false })
280
- if (!stat) return []
281
- if (stat.isFile()) return [target]
282
- return fs
283
- .readdirSync(target, { withFileTypes: true })
284
- .flatMap(entry => {
285
- const full = path.join(target, entry.name)
286
- if (entry.isDirectory()) return collectFiles(full)
287
- return entry.isFile() && /\.m?js$/.test(entry.name) ? [full] : []
288
- })
289
- }
290
-
291
- const targets = process.argv.slice(2)
292
- const defaultTarget = 'hel_dist/assets'
293
- const files = (targets.length ? targets : [defaultTarget]).flatMap(collectFiles)
294
-
295
- if (!files.length) {
296
- console.warn(`[check-tdz] 没有找到可检查的产物(目标:${targets.join(', ') || defaultTarget})`)
297
- process.exit(0)
298
- }
299
-
300
- let failed = false
301
- for (const file of files) {
302
- const code = fs.readFileSync(file, 'utf8')
303
- const problems = analyzeCode(code, file)
304
- const size = (code.length / 1024).toFixed(0)
305
- if (!problems.length) {
306
- console.log(`[check-tdz] OK ${file} (${size}KB)`)
307
- continue
308
- }
309
- failed = true
310
- console.error(`[check-tdz] FAIL ${file} (${size}KB) —— 发现 ${problems.length} 处加载期 TDZ 风险`)
311
- for (const p of problems.slice(0, 10)) {
312
- console.error(` · ${p.declKind} '${p.name}' 引用@${p.start} 早于声明@${p.declStart}`)
313
- console.error(` ...${p.snippet}...`)
314
- }
315
- }
316
-
317
- if (failed) {
318
- console.error(
319
- '\n[check-tdz] 产物里有「先引用、后声明」的 let/const/class,浏览器加载即抛 ' +
320
- "ReferenceError: Cannot access 'xxx' before initialization。\n" +
321
- '常见原因:构建期用了 vite-plugin-externals(把 import 就地改写成 const,破坏 ESM 提升),' +
322
- '或打包产物把 import 写在了模块体后面。',
323
- )
324
- }
325
- process.exitCode = failed ? 1 : 0
2
+ /*
3
+ |--------------------------------------------------------------------------
4
+ |
5
+ | 产物 TDZ 守卫:扫描构建产物,拦住「先引用、后声明」的 let / const / class。
6
+ |
7
+ | 背景(真实踩过的坑):vite-plugin-externals 在构建期把 import 就地改写成
8
+ | `const X = window.X`,而 ESM 的 import 是提升的(写在哪一行都先于模块体执行)。
9
+ | 一旦依赖产物把 import 写在模块体后面(tsup 输出常见),改写后就变成:
10
+ |
11
+ | __reExport(ns, vueNs); const vueNs = window.Vue // ← TDZ
12
+ |
13
+ | 浏览器加载即抛 `Cannot access 'xxx' before initialization`;混淆后变量名变成
14
+ | `_0x2bee8b` 之类,很难看出真因。这个脚本在 build 阶段直接拦下这类产物。
15
+ |
16
+ | 判定口径:引用位置早于声明位置,且两者之间没有跨函数边界(即加载期就会执行到)。
17
+ | 跨了函数的「延后引用」不算——那是正常写法(函数体在模块求值完成后才调用)。
18
+ |
19
+ | 用法:
20
+ | hel-check-tdz # 默认扫当前目录的 hel_dist/assets
21
+ | hel-check-tdz dist bundle.js # 也可指定目录 / 文件
22
+ | 退出码:发现 immediate TDZ → 1
23
+ |
24
+ |--------------------------------------------------------------------------
25
+ */
26
+ import fs from 'node:fs'
27
+ import path from 'node:path'
28
+ import { parse } from 'acorn'
29
+
30
+ const FUNCTION_TYPES = new Set([
31
+ 'FunctionDeclaration',
32
+ 'FunctionExpression',
33
+ 'ArrowFunctionExpression',
34
+ ])
35
+ const CLASS_TYPES = new Set(['ClassDeclaration', 'ClassExpression'])
36
+ const SKIP_KEYS = new Set(['type', 'start', 'end', 'loc', 'range', '__parent'])
37
+
38
+ const isNode = v => !!v && typeof v === 'object' && typeof v.type === 'string'
39
+
40
+ /** 通用 AST 遍历,顺手挂 __parent,方便判断标识符的语法角色 */
41
+ function walk(node, enter) {
42
+ enter(node)
43
+ for (const key of Object.keys(node)) {
44
+ if (SKIP_KEYS.has(key)) continue
45
+ const value = node[key]
46
+ if (Array.isArray(value)) {
47
+ for (const item of value) {
48
+ if (isNode(item)) {
49
+ item.__parent = node
50
+ walk(item, enter)
51
+ }
52
+ }
53
+ } else if (isNode(value)) {
54
+ value.__parent = node
55
+ walk(value, enter)
56
+ }
57
+ }
58
+ }
59
+
60
+ class Scope {
61
+ constructor(kind, parent, isFunction) {
62
+ this.kind = kind
63
+ this.parent = parent
64
+ this.isFunction = isFunction
65
+ /** name -> { start, kind } */
66
+ this.lexical = new Map()
67
+ }
68
+ }
69
+
70
+ function collectPatternNames(node, cb) {
71
+ if (!node) return
72
+ if (node.type === 'Identifier') return cb(node)
73
+ if (node.type === 'AssignmentPattern') return collectPatternNames(node.left, cb)
74
+ if (node.type === 'RestElement') return collectPatternNames(node.argument, cb)
75
+ if (node.type === 'ArrayPattern') {
76
+ for (const el of node.elements) collectPatternNames(el, cb)
77
+ return
78
+ }
79
+ if (node.type === 'ObjectPattern') {
80
+ for (const prop of node.properties) {
81
+ if (prop.type === 'RestElement') collectPatternNames(prop.argument, cb)
82
+ else collectPatternNames(prop.value, cb)
83
+ }
84
+ }
85
+ }
86
+
87
+ /** 标识符是否处于「声明位置」(绑定名),是则不算引用 */
88
+ function isDeclarationIdentifier(node) {
89
+ const p = node.__parent
90
+ if (!p) return true
91
+ if (p.type === 'VariableDeclarator' && p.id === node) return true
92
+ if (FUNCTION_TYPES.has(p.type) && p.id === node) return true
93
+ if (CLASS_TYPES.has(p.type) && p.id === node) return true
94
+ if (p.type === 'CatchClause' && p.param === node) return true
95
+ if (
96
+ p.type === 'ImportSpecifier' ||
97
+ p.type === 'ImportDefaultSpecifier' ||
98
+ p.type === 'ImportNamespaceSpecifier'
99
+ )
100
+ return true
101
+ if (
102
+ p.type === 'ArrayPattern' ||
103
+ p.type === 'ObjectPattern' ||
104
+ p.type === 'RestElement' ||
105
+ p.type === 'AssignmentPattern' ||
106
+ p.type === 'Property'
107
+ ) {
108
+ let cur = node
109
+ let up = cur.__parent
110
+ while (
111
+ up &&
112
+ (up.type === 'ArrayPattern' ||
113
+ up.type === 'ObjectPattern' ||
114
+ up.type === 'RestElement' ||
115
+ up.type === 'AssignmentPattern' ||
116
+ up.type === 'Property')
117
+ ) {
118
+ if (up.type === 'AssignmentPattern' && up.left === cur && up.right === node) return false
119
+ cur = up
120
+ up = up.__parent
121
+ }
122
+ return !!(
123
+ up &&
124
+ ((up.type === 'VariableDeclarator' && up.id === cur) ||
125
+ FUNCTION_TYPES.has(up.type) ||
126
+ (up.type === 'CatchClause' && up.param === cur))
127
+ )
128
+ }
129
+ return false
130
+ }
131
+
132
+ /** 引用是否属于「不是变量引用」的语法位置(属性名、label 等) */
133
+ function isNonReferencePosition(node) {
134
+ const p = node.__parent
135
+ if (!p) return true
136
+ if (p.type === 'MemberExpression' && p.property === node && !p.computed) return true
137
+ if (p.type === 'Property' && p.key === node && !p.computed) return true
138
+ if (p.type === 'MethodDefinition' && p.key === node && !p.computed) return true
139
+ if (p.type === 'PropertyDefinition' && p.key === node && !p.computed) return true
140
+ if (p.type === 'LabeledStatement' || p.type === 'BreakStatement' || p.type === 'ContinueStatement')
141
+ return true
142
+ if (p.type === 'ExportSpecifier' || p.type === 'ImportSpecifier') return true
143
+ return false
144
+ }
145
+
146
+ function analyzeCode(code, filename) {
147
+ let ast
148
+ try {
149
+ ast = parse(code, {
150
+ ecmaVersion: 'latest',
151
+ sourceType: 'script',
152
+ allowHashBang: true,
153
+ allowReturnOutsideFunction: true,
154
+ })
155
+ } catch (err) {
156
+ // 少数产物是 ESM,按 module 再解析一次
157
+ ast = parse(code, {
158
+ ecmaVersion: 'latest',
159
+ sourceType: 'module',
160
+ allowHashBang: true,
161
+ })
162
+ }
163
+
164
+ walk(ast, () => {}) // 只为建立 __parent
165
+
166
+ const scopeByNode = new Map()
167
+ /** 绑定标识符(函数参数 / catch 参数等)本身,不参与「引用早于声明」判断 */
168
+ const bindingByNode = new Map()
169
+ const root = new Scope('program', null, false)
170
+
171
+ const build = (node, scope) => {
172
+ let current = scope
173
+ if (FUNCTION_TYPES.has(node.type)) {
174
+ current = new Scope('function', scope, true)
175
+ } else if (node.type === 'BlockStatement' || node.type === 'StaticBlock') {
176
+ current = new Scope('block', scope, false)
177
+ } else if (node.type === 'CatchClause') {
178
+ current = new Scope('catch', scope, false)
179
+ } else if (
180
+ // for (let x of/in ...) 的循环变量属于 for 语句自己的作用域,不是外层;
181
+ // 压缩产物里 `for(let e in t)` 很常见,不单独建作用域会把它误判成外层 let
182
+ node.type === 'ForStatement' ||
183
+ node.type === 'ForInStatement' ||
184
+ node.type === 'ForOfStatement' ||
185
+ // switch 的 case 共用同一个块级作用域
186
+ node.type === 'SwitchStatement'
187
+ ) {
188
+ current = new Scope('block', scope, false)
189
+ } else if (CLASS_TYPES.has(node.type)) {
190
+ current = new Scope('class', scope, false)
191
+ }
192
+ scopeByNode.set(node, current)
193
+
194
+ const declare = (id, kind) => {
195
+ if (!current.lexical.has(id.name)) current.lexical.set(id.name, { start: id.start, kind })
196
+ // 参数 / 循环变量 / catch 参数也属于「声明位置」,后续引用不应被当成外层同名变量
197
+ if (!bindingByNode.has(id)) bindingByNode.set(id, { scope: current, kind, start: id.start })
198
+ }
199
+
200
+ // 函数参数与 catch 参数也是绑定:不登记的话,压缩产物里形参名和模块级 let 同名时会大面积误报
201
+ if (FUNCTION_TYPES.has(node.type)) {
202
+ for (const param of node.params || []) collectPatternNames(param, id => declare(id, 'param'))
203
+ }
204
+ if (node.type === 'CatchClause' && node.param) {
205
+ collectPatternNames(node.param, id => declare(id, 'catch'))
206
+ }
207
+
208
+ if (node.type === 'VariableDeclaration' && (node.kind === 'let' || node.kind === 'const')) {
209
+ for (const decl of node.declarations) {
210
+ collectPatternNames(decl.id, id => declare(id, node.kind))
211
+ }
212
+ }
213
+ if (node.type === 'ClassDeclaration' && node.id) {
214
+ // 类声明:类名在「类自身作用域」和「外层作用域」都可见
215
+ const outer = scopeByNode.get(node.__parent) || scope
216
+ if (!outer.lexical.has(node.id.name))
217
+ outer.lexical.set(node.id.name, { start: node.id.start, kind: 'class' })
218
+ declare(node.id, 'class')
219
+ } else if (node.type === 'ClassExpression' && node.id) {
220
+ // 类表达式(如压缩产物里的 `var Y = class e extends Error {}`)的类名只在本类内部可见,
221
+ // 不能登记到外层作用域,否则会把外层同名引用误判成 TDZ
222
+ declare(node.id, 'class')
223
+ }
224
+ if (node.type === 'ImportDeclaration') {
225
+ for (const spec of node.specifiers) declare(spec.local, 'import')
226
+ }
227
+
228
+ for (const key of Object.keys(node)) {
229
+ if (SKIP_KEYS.has(key)) continue
230
+ const value = node[key]
231
+ // The discriminant runs before the case block's lexical environment exists.
232
+ // `switch (x) { case 0: let x }` reads the outer x here.
233
+ const childScope = node.type === 'SwitchStatement' && key === 'discriminant' ? scope : current
234
+ if (Array.isArray(value)) {
235
+ for (const item of value) if (isNode(item)) build(item, childScope)
236
+ } else if (isNode(value)) build(value, childScope)
237
+ }
238
+ }
239
+ build(ast, root)
240
+
241
+ const problems = []
242
+ walk(ast, node => {
243
+ if (node.type !== 'Identifier') return
244
+ if (bindingByNode.has(node)) return
245
+ if (isDeclarationIdentifier(node)) return
246
+ if (isNonReferencePosition(node)) return
247
+
248
+ let scope = scopeByNode.get(node)
249
+ let hit = null
250
+ while (scope) {
251
+ if (scope.lexical.has(node.name)) {
252
+ hit = { scope, info: scope.lexical.get(node.name) }
253
+ break
254
+ }
255
+ scope = scope.parent
256
+ }
257
+ if (!hit) return
258
+ if (node.start > hit.info.start) return // 正常顺序
259
+
260
+ // 引用到声明之间是否跨了函数:跨了说明是延后执行(不是加载期 TDZ)
261
+ let crossings = 0
262
+ let cur = scopeByNode.get(node)
263
+ while (cur && cur !== hit.scope) {
264
+ if (cur.isFunction) crossings++
265
+ cur = cur.parent
266
+ }
267
+ if (crossings > 0) return
268
+
269
+ problems.push({
270
+ name: node.name,
271
+ start: node.start,
272
+ declStart: hit.info.start,
273
+ declKind: hit.info.kind,
274
+ snippet: code.slice(Math.max(0, node.start - 70), node.start + 90).replace(/\s+/g, ' '),
275
+ })
276
+ })
277
+
278
+ return problems.map(p => ({ ...p, file: filename }))
279
+ }
280
+
281
+ function collectFiles(target) {
282
+ const stat = fs.statSync(target, { throwIfNoEntry: false })
283
+ if (!stat) return []
284
+ if (stat.isFile()) return [target]
285
+ return fs
286
+ .readdirSync(target, { withFileTypes: true })
287
+ .flatMap(entry => {
288
+ const full = path.join(target, entry.name)
289
+ if (entry.isDirectory()) return collectFiles(full)
290
+ return entry.isFile() && /\.m?js$/.test(entry.name) ? [full] : []
291
+ })
292
+ }
293
+
294
+ const targets = process.argv.slice(2)
295
+ const defaultTarget = 'hel_dist/assets'
296
+ const files = (targets.length ? targets : [defaultTarget]).flatMap(collectFiles)
297
+
298
+ if (!files.length) {
299
+ console.warn(`[check-tdz] 没有找到可检查的产物(目标:${targets.join(', ') || defaultTarget})`)
300
+ process.exit(0)
301
+ }
302
+
303
+ let failed = false
304
+ for (const file of files) {
305
+ const code = fs.readFileSync(file, 'utf8')
306
+ const problems = analyzeCode(code, file)
307
+ const size = (code.length / 1024).toFixed(0)
308
+ if (!problems.length) {
309
+ console.log(`[check-tdz] OK ${file} (${size}KB)`)
310
+ continue
311
+ }
312
+ failed = true
313
+ console.error(`[check-tdz] FAIL ${file} (${size}KB) —— 发现 ${problems.length} 处加载期 TDZ 风险`)
314
+ for (const p of problems.slice(0, 10)) {
315
+ console.error(` · ${p.declKind} '${p.name}' 引用@${p.start} 早于声明@${p.declStart}`)
316
+ console.error(` ...${p.snippet}...`)
317
+ }
318
+ }
319
+
320
+ if (failed) {
321
+ console.error(
322
+ '\n[check-tdz] 产物里有「先引用、后声明」的 let/const/class,浏览器加载即抛 ' +
323
+ "ReferenceError: Cannot access 'xxx' before initialization。\n" +
324
+ '常见原因:构建期用了 vite-plugin-externals(把 import 就地改写成 const,破坏 ESM 提升),' +
325
+ '或打包产物把 import 写在了模块体后面。',
326
+ )
327
+ }
328
+ process.exitCode = failed ? 1 : 0