xhs-mp-compiler-cli 1.6.0-beta.7 → 1.6.0-beta.8

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.
@@ -30,7 +30,7 @@ const fs_extra_1 = __importDefault(require("fs-extra"));
30
30
  const glob_1 = __importDefault(require("glob"));
31
31
  const path_1 = __importDefault(require("path"));
32
32
  const packs_1 = require("../../../../packs");
33
- const index_1 = __importStar(require("../../../loaders/sjs-loader/index"));
33
+ const xhs_mp_compiler_sjs_loader_1 = __importStar(require("xhs-mp-compiler-sjs-loader"));
34
34
  const common_1 = require("../../../../utils/common");
35
35
  /**
36
36
  * @NOTE 分包中使用 SJS 的规则
@@ -123,7 +123,7 @@ class SjsEntryPlugin {
123
123
  }
124
124
  const sjsAbsPath = formatSJSPath(sjsPath);
125
125
  const content = fs_extra_1.default.readFileSync(sjsAbsPath, 'utf8');
126
- const result = index_1.default.call(compilation, content, requirePath => {
126
+ const result = xhs_mp_compiler_sjs_loader_1.default.call(compilation, content, requirePath => {
127
127
  const realPath = (0, common_1.unixResolve)(path_1.default.dirname(sjsAbsPath), requirePath);
128
128
  const relativePath = (0, common_1.getShortPath)(project.miniprogramDir, realPath);
129
129
  /**
@@ -139,13 +139,20 @@ class SjsEntryPlugin {
139
139
  return relativePath;
140
140
  });
141
141
  if ((_a = result.errors) === null || _a === void 0 ? void 0 : _a.length) {
142
- throw new packs_1.WebpackError(`[SJS 文件编译错误] ${sjsAbsPath}\n${result.errors.map(i => i.message).join("\n")}`);
142
+ throw new packs_1.WebpackError([
143
+ '\n<xhsml!',
144
+ `[error:sjs编译错误]: [file:${sjsAbsPath === null || sjsAbsPath === void 0 ? void 0 : sjsAbsPath.trim()}]`,
145
+ // swc span 信息不准确
146
+ // `${result.errors.map(i => `${i.span.start} ${i.span.end} ${i.message}`).join("\n")}`,
147
+ `${result.errors.map(i => i.message).join("\n")}`,
148
+ '!xhsml>\n'
149
+ ].join('\n'));
143
150
  }
144
151
  const moduleName = (0, common_1.getShortPath)(project.miniprogramDir, sjsAbsPath);
145
152
  // 老版本兼容代码
146
153
  sjsModules.push(`"${moduleName}": ${JSON.stringify(result.legacyCode)}`);
147
154
  // 模块化代码
148
- sjsModules.push(`".sjs#${moduleName}": function(exports,require,module,${index_1.SJS_HELPER}){${(result.code)};return module;}`);
155
+ sjsModules.push(`".sjs#${moduleName}": function(exports,require,module,${xhs_mp_compiler_sjs_loader_1.SJS_HELPER}){${(result.code)};return module;}`);
149
156
  // 处理后的加入缓存
150
157
  sjsPathCache.add(sjsPath);
151
158
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xhs-mp-compiler-cli",
3
- "version": "1.6.0-beta.7",
3
+ "version": "1.6.0-beta.8",
4
4
  "description": "xhs mp command tool.",
5
5
  "preferGlobal": true,
6
6
  "category": "esm",
@@ -82,11 +82,12 @@
82
82
  "webpack-bundle-analyzer": "^4.4.0",
83
83
  "webpack-chain": "^6.5.1",
84
84
  "webpack-sources": "^3.2.2",
85
- "xhs-mp-compiler-ml-loader": "1.6.0-beta.7",
86
- "xhs-mp-compiler-utils": "1.6.0-beta.7",
87
- "xhs-mp-pack": "1.6.0-beta.7",
88
- "xhs-mp-project": "1.6.0-beta.7",
89
- "xhs-mp-utils": "1.6.0-beta.7"
85
+ "xhs-mp-compiler-ml-loader": "1.6.0-beta.8",
86
+ "xhs-mp-compiler-utils": "1.6.0-beta.8",
87
+ "xhs-mp-pack": "1.6.0-beta.8",
88
+ "xhs-mp-project": "1.6.0-beta.8",
89
+ "xhs-mp-utils": "1.6.0-beta.8",
90
+ "xhs-mp-compiler-sjs-loader": "1.6.0-beta.8"
90
91
  },
91
92
  "devDependencies": {
92
93
  "@types/babel__generator": "7.6.3",
@@ -1,12 +0,0 @@
1
- import type { Span } from '@swc/core';
2
- export declare const SJS_HELPER = "_sjs$";
3
- declare function sjsCompiler(code: any, onRequire: (s: string) => string): {
4
- code: string;
5
- map: string | undefined;
6
- legacyCode: string;
7
- errors: {
8
- message: string;
9
- span: Span;
10
- }[];
11
- };
12
- export default sjsCompiler;
@@ -1,605 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SJS_HELPER = void 0;
4
- const lodash_1 = require("lodash");
5
- const tranform_1 = require("./tranform");
6
- const scope_1 = require("./scope");
7
- exports.SJS_HELPER = '_sjs$';
8
- const SETTER = `${exports.SJS_HELPER}.s`;
9
- const GETTER = `${exports.SJS_HELPER}.g`;
10
- const CALLER = `${exports.SJS_HELPER}.c`;
11
- function sjsCompiler(code, onRequire) {
12
- var _a;
13
- const errors = [];
14
- const offset = 1;
15
- // scan 阶段只是对整个树的遍历,会对作用域进行收集,禁止修改语法树
16
- // generate 阶段会生成 helper形式代码
17
- // legacyGenerate 阶段 只生成一份修改 .constructor 访问的代码
18
- let mode = 'scan';
19
- // 普通变量作用域管理
20
- const scopeManager = new scope_1.ScopeManager();
21
- // require语句
22
- const requireCallee = [];
23
- // 找到对应行
24
- function emitCompilerError(msg, span) {
25
- if (mode !== 'scan')
26
- return;
27
- const message = msg.trim().split(/\s+/).length > 1 ? msg : `${msg} is disallowed`;
28
- errors.push({ message, span: Object.assign({}, span) });
29
- }
30
- function handlePattern(pattern) {
31
- switch (pattern.type) {
32
- case "RestElement":
33
- // function f(...a) {}
34
- handlePattern(pattern.argument);
35
- if (pattern.argument.type === "Identifier") {
36
- scopeManager.pushIdentifier(pattern.argument);
37
- }
38
- break;
39
- case "AssignmentPattern":
40
- // 默认值语法 function f(a = 1) {}
41
- handleExpression(pattern.right);
42
- if (pattern.left.type === "Identifier") {
43
- scopeManager.pushIdentifier(pattern.left);
44
- }
45
- break;
46
- case 'Identifier':
47
- // function f(a) {}
48
- scopeManager.pushIdentifier(pattern);
49
- break;
50
- case "MemberExpression":
51
- handleExpression(pattern);
52
- break;
53
- case "ArrayPattern":
54
- emitCompilerError("Destructuring assignment like const [a, b] = array; is disallowed ", pattern.span);
55
- break;
56
- case "ObjectPattern":
57
- emitCompilerError("Destructuring assignment like const {a, b} = obj; is disallowed ", pattern.span);
58
- break;
59
- default:
60
- // @ts-ignore
61
- emitCompilerError(pattern.type, pattern.span);
62
- break;
63
- }
64
- }
65
- function handleParam(p) {
66
- var _a;
67
- // 参数不支持装饰器
68
- if ((_a = p === null || p === void 0 ? void 0 : p.decorators) === null || _a === void 0 ? void 0 : _a.length) {
69
- emitCompilerError(p.type, p.span);
70
- }
71
- if (p.pat) {
72
- handlePattern(p.pat);
73
- }
74
- }
75
- function handleStatement(e) {
76
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
77
- switch (e.type) {
78
- case "BlockStatement":
79
- scopeManager.enterScope();
80
- (_a = e.stmts) === null || _a === void 0 ? void 0 : _a.forEach(handleStatement);
81
- scopeManager.exitScope();
82
- break;
83
- case "TryStatement":
84
- if (e.block) {
85
- handleStatement(e.block);
86
- }
87
- // catch 部分是有参数的
88
- scopeManager.enterScope();
89
- if ((_b = e.handler) === null || _b === void 0 ? void 0 : _b.param) {
90
- handlePattern((_c = e.handler) === null || _c === void 0 ? void 0 : _c.param);
91
- }
92
- if (((_e = (_d = e.handler) === null || _d === void 0 ? void 0 : _d.body) === null || _e === void 0 ? void 0 : _e.type) === "BlockStatement") {
93
- (_g = (_f = e.handler) === null || _f === void 0 ? void 0 : _f.body) === null || _g === void 0 ? void 0 : _g.stmts.forEach(handleStatement);
94
- }
95
- scopeManager.exitScope();
96
- if (e.finalizer) {
97
- handleStatement(e.finalizer);
98
- }
99
- break;
100
- case "ForStatement":
101
- scopeManager.enterScope();
102
- if (e.init) {
103
- switch (e.init.type) {
104
- case "VariableDeclaration":
105
- handleStatement(e.init);
106
- break;
107
- default:
108
- handleExpression(e.init);
109
- break;
110
- }
111
- }
112
- if (e.test) {
113
- handleExpression(e.test);
114
- }
115
- if (e.update) {
116
- handleExpression(e.update);
117
- }
118
- if (e.body.type === "BlockStatement") {
119
- (_h = e.body.stmts) === null || _h === void 0 ? void 0 : _h.forEach(handleStatement);
120
- }
121
- else {
122
- handleStatement(e.body);
123
- }
124
- scopeManager.exitScope();
125
- break;
126
- case "SwitchStatement":
127
- // 处理switch条件
128
- handleExpression(e.discriminant);
129
- // 处理case条件
130
- (_j = e.cases) === null || _j === void 0 ? void 0 : _j.forEach((case_) => {
131
- var _a;
132
- if (case_.test) {
133
- handleExpression(case_.test);
134
- }
135
- (_a = case_.consequent) === null || _a === void 0 ? void 0 : _a.forEach(handleStatement);
136
- });
137
- break;
138
- case "DoWhileStatement":
139
- case "WhileStatement":
140
- handleExpression(e.test);
141
- handleStatement(e.body);
142
- break;
143
- case "IfStatement":
144
- handleExpression(e.test);
145
- handleStatement(e.consequent);
146
- if (e.alternate) {
147
- handleStatement(e.alternate);
148
- }
149
- break;
150
- case "ExpressionStatement":
151
- handleExpression(e.expression);
152
- break;
153
- case "FunctionDeclaration":
154
- checkFunction(e);
155
- scopeManager.pushIdentifier(e.identifier);
156
- scopeManager.enterScope();
157
- e.params.forEach(handleParam);
158
- if (((_k = e === null || e === void 0 ? void 0 : e.body) === null || _k === void 0 ? void 0 : _k.type) === "BlockStatement") {
159
- (_l = e.body.stmts) === null || _l === void 0 ? void 0 : _l.forEach(handleStatement);
160
- }
161
- scopeManager.exitScope();
162
- break;
163
- case "ReturnStatement":
164
- if (e.argument) {
165
- handleExpression(e.argument);
166
- }
167
- break;
168
- case "VariableDeclaration":
169
- for (const declaration of e.declarations) {
170
- switch (declaration.id.type) {
171
- case "Identifier":
172
- scopeManager.pushIdentifier(declaration.id);
173
- break;
174
- default:
175
- // @ts-ignore
176
- emitCompilerError(declaration.id.type, declaration.id.span);
177
- break;
178
- }
179
- if (declaration.init) {
180
- handleExpression(declaration.init);
181
- }
182
- }
183
- break;
184
- case "BreakStatement":
185
- case "DebuggerStatement":
186
- case "ContinueStatement":
187
- case "EmptyStatement":
188
- break;
189
- default:
190
- emitCompilerError(e.type, e.span);
191
- break;
192
- }
193
- }
194
- function handleProperty(p) {
195
- switch (p.type) {
196
- case "Computed":
197
- {
198
- const expression = p.expression;
199
- handleExpression(expression);
200
- }
201
- break;
202
- case "Identifier":
203
- break;
204
- default:
205
- emitCompilerError(p.type, p.span);
206
- break;
207
- }
208
- }
209
- function handleObjectPropertyName(key) {
210
- switch (key.type) {
211
- case "Computed":
212
- {
213
- const expression = key.expression;
214
- handleExpression(expression);
215
- }
216
- break;
217
- default:
218
- break;
219
- }
220
- }
221
- function handleObjectProperty(i) {
222
- var _a, _b, _c;
223
- switch (i.type) {
224
- case "KeyValueProperty":
225
- handleObjectPropertyName(i.key);
226
- handleExpression(i.value);
227
- break;
228
- case "GetterProperty":
229
- handleObjectPropertyName(i.key);
230
- scopeManager.enterScope();
231
- if (((_a = i.body) === null || _a === void 0 ? void 0 : _a.type) === "BlockStatement") {
232
- i.body.stmts.forEach(handleStatement);
233
- }
234
- scopeManager.exitScope();
235
- break;
236
- case "SetterProperty":
237
- handleObjectPropertyName(i.key);
238
- scopeManager.enterScope();
239
- handlePattern(i.param);
240
- if (((_b = i.body) === null || _b === void 0 ? void 0 : _b.type) === "BlockStatement") {
241
- i.body.stmts.forEach(handleStatement);
242
- }
243
- scopeManager.exitScope();
244
- break;
245
- case "Identifier":
246
- scopeManager.pushAccess(i);
247
- fixSpecialVarWhenGenerate(i);
248
- break;
249
- case "MethodProperty":
250
- handleObjectPropertyName(i.key);
251
- checkFunction(i);
252
- scopeManager.enterScope();
253
- i.params.forEach(handleParam);
254
- if (((_c = i.body) === null || _c === void 0 ? void 0 : _c.type) === "BlockStatement") {
255
- i.body.stmts.forEach(handleStatement);
256
- }
257
- scopeManager.exitScope();
258
- break;
259
- case "SpreadElement":
260
- handleExpression(i.arguments);
261
- break;
262
- default:
263
- // @ts-ignore
264
- emitCompilerError(i.type, i.span);
265
- break;
266
- }
267
- }
268
- function modifyProperty(p) {
269
- if (p.type === "Computed") {
270
- handleExpression(p.expression);
271
- return p.expression;
272
- }
273
- if (p.type === "Identifier") {
274
- return {
275
- type: 'StringLiteral',
276
- span: p.span,
277
- value: p.value,
278
- raw: JSON.stringify(p.value)
279
- };
280
- }
281
- if (p.type === "PrivateName") {
282
- return { type: 'NullLiteral' };
283
- }
284
- }
285
- function checkFunction(e) {
286
- // 不允许使用 async 或者 generator 语法
287
- if (e.async || e.generator) {
288
- emitCompilerError(e.type, e.span);
289
- }
290
- }
291
- function collectRequireWhenScan(c) {
292
- if (mode !== 'scan') {
293
- return;
294
- }
295
- requireCallee.push(c);
296
- // 标记作用域
297
- if (c.callee.type === 'Identifier') {
298
- c.callee._xhsScope = scopeManager.getCurrentScope();
299
- }
300
- }
301
- function fixSpecialVarWhenGenerate(id) {
302
- var _a;
303
- if (mode !== 'generate') {
304
- return;
305
- }
306
- // 发现调用全局特殊变量
307
- if (scope_1.SPECIFY_VAR.includes(id.value) && ((_a = id._xhsScope) === null || _a === void 0 ? void 0 : _a.checkGlobal(id.value))) {
308
- // 生成阶段判断是否是调用全局环境
309
- id.value = `${exports.SJS_HELPER}.${id.value}`;
310
- }
311
- }
312
- function handleExpression(e) {
313
- var _a, _b, _c, _d, _e;
314
- switch (e.type) {
315
- case "FunctionExpression":
316
- checkFunction(e);
317
- if (e.identifier) {
318
- scopeManager.pushIdentifier(e.identifier);
319
- }
320
- scopeManager.enterScope();
321
- e.params.forEach(handleParam);
322
- if (((_a = e.body) === null || _a === void 0 ? void 0 : _a.type) === "BlockStatement") {
323
- (_b = e.body.stmts) === null || _b === void 0 ? void 0 : _b.forEach(handleStatement);
324
- }
325
- scopeManager.exitScope();
326
- break;
327
- case "ArrowFunctionExpression":
328
- checkFunction(e);
329
- scopeManager.enterScope();
330
- e.params.forEach(handlePattern);
331
- if (e.body.type === "BlockStatement") {
332
- (_c = e.body.stmts) === null || _c === void 0 ? void 0 : _c.forEach(handleStatement);
333
- }
334
- else {
335
- handleExpression(e.body);
336
- }
337
- scopeManager.exitScope();
338
- break;
339
- case "CallExpression":
340
- switch (e.callee.type) {
341
- case "Import":
342
- case "Super":
343
- emitCompilerError(e.callee.type, e.span);
344
- break;
345
- default:
346
- if (e.callee.type === "MemberExpression" && mode === 'generate') {
347
- const oldCallee = e.callee;
348
- const NewCallExpression = e;
349
- NewCallExpression.type = "CallExpression";
350
- NewCallExpression.callee = {
351
- type: 'Identifier',
352
- span: e.span,
353
- value: CALLER,
354
- optional: false
355
- };
356
- handleExpression(oldCallee.object);
357
- e.arguments.forEach(i => handleExpression(i.expression));
358
- NewCallExpression.arguments = [
359
- { expression: modifyProperty(oldCallee.property) },
360
- { expression: oldCallee.object },
361
- {
362
- expression: {
363
- type: "ArrayExpression",
364
- elements: e.arguments,
365
- span: e.span
366
- }
367
- },
368
- ];
369
- }
370
- else if (e.callee.type === "MemberExpression"
371
- && mode === 'legacyGenerate'
372
- && e.callee.property.type === "Identifier"
373
- && e.callee.property.value === "constructor") {
374
- e.callee.property.value = `${e.callee.property.value}.name`;
375
- handleExpression(e.callee.object);
376
- e.arguments.forEach(i => handleExpression(i.expression));
377
- }
378
- else {
379
- if (e.callee.type === "Identifier") {
380
- if (e.callee.value === "require") {
381
- collectRequireWhenScan(e);
382
- }
383
- // 需要后置处理,否则callee.value会被修改
384
- fixSpecialVarWhenGenerate(e.callee);
385
- }
386
- handleExpression(e.callee);
387
- e.arguments.forEach(i => handleExpression(i.expression));
388
- }
389
- break;
390
- }
391
- break;
392
- case "ArrayExpression":
393
- (_d = e.elements) === null || _d === void 0 ? void 0 : _d.forEach(i => {
394
- if (i) {
395
- handleExpression(i.expression);
396
- }
397
- });
398
- break;
399
- case "ObjectExpression":
400
- e.properties.forEach(handleObjectProperty);
401
- break;
402
- case "TemplateLiteral":
403
- // 当中会有表达式
404
- e.expressions.forEach(handleExpression);
405
- break;
406
- case "UpdateExpression":
407
- if (e.argument.type === "MemberExpression" && mode === 'generate') {
408
- const NewUpdateExpression = e;
409
- NewUpdateExpression.type = "CallExpression";
410
- NewUpdateExpression.callee = {
411
- type: 'Identifier',
412
- span: e.span,
413
- value: SETTER,
414
- optional: false
415
- };
416
- handleExpression(e.argument.object);
417
- NewUpdateExpression.arguments = [
418
- { expression: modifyProperty(e.argument.property) },
419
- { expression: e.argument.object },
420
- {
421
- expression: {
422
- type: 'StringLiteral',
423
- span: e.span,
424
- value: e.operator,
425
- raw: JSON.stringify(e.operator)
426
- }
427
- },
428
- ];
429
- Reflect.deleteProperty(e, 'prefix');
430
- Reflect.deleteProperty(e, 'operator');
431
- Reflect.deleteProperty(e, 'argument');
432
- }
433
- else {
434
- handleExpression(e.argument);
435
- }
436
- break;
437
- case "UnaryExpression":
438
- handleExpression(e.argument);
439
- break;
440
- case "AssignmentExpression":
441
- if (e.left.type === 'MemberExpression' && mode === 'generate') {
442
- const NewAssignmentExpression = e;
443
- NewAssignmentExpression.type = "CallExpression";
444
- NewAssignmentExpression.callee = {
445
- type: 'Identifier',
446
- span: e.span,
447
- value: SETTER,
448
- optional: false
449
- };
450
- handleExpression(e.right);
451
- handleExpression(e.left.object);
452
- NewAssignmentExpression.arguments = [
453
- { expression: modifyProperty(e.left.property) },
454
- { expression: e.left.object },
455
- {
456
- expression: {
457
- type: 'StringLiteral',
458
- span: e.span,
459
- value: e.operator,
460
- raw: JSON.stringify(e.operator)
461
- }
462
- },
463
- { expression: e.right }
464
- ];
465
- Reflect.deleteProperty(e, 'left');
466
- Reflect.deleteProperty(e, 'right');
467
- Reflect.deleteProperty(e, 'operator');
468
- }
469
- else {
470
- handlePattern(e.left);
471
- handleExpression(e.right);
472
- }
473
- break;
474
- case "BinaryExpression":
475
- handleExpression(e.left);
476
- handleExpression(e.right);
477
- break;
478
- case "ConditionalExpression":
479
- handleExpression(e.test);
480
- handleExpression(e.consequent);
481
- handleExpression(e.alternate);
482
- break;
483
- case "MemberExpression":
484
- if (mode === 'generate') {
485
- const NewMemberExpression = e;
486
- NewMemberExpression.type = "CallExpression";
487
- NewMemberExpression.callee = {
488
- type: 'Identifier',
489
- span: e.span,
490
- value: GETTER,
491
- optional: false
492
- };
493
- handleExpression(e.object);
494
- NewMemberExpression.arguments = [
495
- { expression: modifyProperty(e.property) },
496
- { expression: e.object }
497
- ];
498
- // 清除语法树
499
- Reflect.deleteProperty(e, 'object');
500
- Reflect.deleteProperty(e, 'property');
501
- }
502
- else if (mode === 'legacyGenerate' && e.property.type === "Identifier" && e.property.value === "constructor") {
503
- e.property.value = `${e.property.value}.name`;
504
- handleExpression(e.object);
505
- }
506
- else {
507
- // 只遍历
508
- handleExpression(e.object);
509
- handleProperty(e.property);
510
- }
511
- break;
512
- case "ParenthesisExpression":
513
- handleExpression(e.expression);
514
- break;
515
- case "SequenceExpression":
516
- (_e = e.expressions) === null || _e === void 0 ? void 0 : _e.forEach(handleExpression);
517
- break;
518
- case "Identifier":
519
- scopeManager.pushAccess(e);
520
- fixSpecialVarWhenGenerate(e);
521
- break;
522
- // 以下都是字面量无需处理
523
- case "BigIntLiteral":
524
- case "NullLiteral":
525
- case "StringLiteral":
526
- case "BooleanLiteral":
527
- case "NumericLiteral":
528
- case "ThisExpression":
529
- case "RegExpLiteral":
530
- break;
531
- default:
532
- // @ts-ignore
533
- emitCompilerError(e.type, e.span);
534
- break;
535
- }
536
- }
537
- function getSourceCode(span) {
538
- return code.slice(span.start - offset, span.end - offset);
539
- }
540
- let legacyModule;
541
- const result = (0, tranform_1.transform)(code, (module) => {
542
- // 1. 校验基本语法错误,收集变量作用域,构建作用域表
543
- mode = "scan";
544
- scopeManager.enterScope();
545
- module.body.forEach(handleStatement);
546
- scopeManager.exitScope();
547
- scopeManager.stop();
548
- // 2. 分析作用域表 找出不是sjs 标准的模块进行屏蔽
549
- // 2.2 从最小作用域向上分析
550
- const validResult = scopeManager.getDFSScope().map(i => i.anlysis()).filter(Boolean);
551
- validResult.forEach(i => {
552
- if (i) {
553
- emitCompilerError(`identifier(${i.variable}) is undefined`, i.span);
554
- }
555
- });
556
- // 2.1 require语句校验以及处理path
557
- requireCallee.forEach(i => {
558
- var _a, _b, _c;
559
- // 调用全局环境 require
560
- if (i.callee.type === "Identifier" && ((_a = i.callee._xhsScope) === null || _a === void 0 ? void 0 : _a.checkGlobal(i.callee.value))) {
561
- const requirePath = (_c = (_b = i.arguments) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.expression;
562
- if (requirePath && (requirePath === null || requirePath === void 0 ? void 0 : requirePath.type) === 'StringLiteral' && (requirePath === null || requirePath === void 0 ? void 0 : requirePath.value)) {
563
- try {
564
- const formatPath = onRequire === null || onRequire === void 0 ? void 0 : onRequire(requirePath === null || requirePath === void 0 ? void 0 : requirePath.value);
565
- requirePath.value = formatPath;
566
- requirePath.raw = JSON.stringify(formatPath);
567
- }
568
- catch (error) {
569
- // 校验path 地址是否正确不正确进行报错
570
- emitCompilerError(error.message, i.span);
571
- }
572
- }
573
- else {
574
- emitCompilerError('require() must provide static path, dynamic or empty path is disallowed', i.span);
575
- }
576
- }
577
- });
578
- // 3. 抛出前面检查出来的错误
579
- if (errors.length) {
580
- module.body = [];
581
- return module;
582
- }
583
- // 上面的没出错,拷贝一份语法树用于生成兼容代码
584
- legacyModule = (0, lodash_1.cloneDeep)(module);
585
- // 4. 修改语法树生成 set get call 语法
586
- mode = "generate";
587
- module.body.forEach(handleStatement);
588
- return module;
589
- });
590
- mode = 'legacyGenerate';
591
- // 生成老版本的兼容代码
592
- const legacyCode = ((_a = legacyModule === null || legacyModule === void 0 ? void 0 : legacyModule.body) === null || _a === void 0 ? void 0 : _a.length)
593
- ? (0, tranform_1.transform)('var magic;', () => {
594
- legacyModule.body.forEach(handleStatement);
595
- return legacyModule;
596
- }, 'es2015', true).code
597
- : '';
598
- return {
599
- code: result.code,
600
- map: result.map,
601
- legacyCode,
602
- errors,
603
- };
604
- }
605
- exports.default = sjsCompiler;
@@ -1,36 +0,0 @@
1
- import type { Span, Identifier } from '@swc/core';
2
- export declare const SPECIFY_VAR: string[];
3
- declare module "@swc/core" {
4
- interface Identifier {
5
- _xhsScope?: Scope;
6
- }
7
- }
8
- export declare class Scope {
9
- private parentScope;
10
- private defines;
11
- private access;
12
- toString(): string;
13
- /**
14
- * @returns
15
- */
16
- anlysis(): {
17
- variable: string;
18
- span: Span;
19
- } | undefined;
20
- checkGlobal(key: string): boolean;
21
- setAccess(key: string, value: Span): void;
22
- setDefines(key: string, value: Span): void;
23
- setParentScope(scope: Scope | undefined): void;
24
- }
25
- export declare class ScopeManager {
26
- private _scopeStack;
27
- private _scopeTables;
28
- private _stop;
29
- stop(): void;
30
- enterScope(): void;
31
- exitScope(): void;
32
- getCurrentScope(): Scope | undefined;
33
- pushIdentifier(id: Identifier): void;
34
- pushAccess(id: Identifier): void;
35
- getDFSScope(): Scope[];
36
- }
@@ -1,122 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ScopeManager = exports.Scope = exports.SPECIFY_VAR = void 0;
4
- exports.SPECIFY_VAR = ["getDate", "getRegExp", "console"];
5
- const IDENTIFIER_WHITE_LIST = [
6
- "Object", "Boolean", "Array", "String", "Number", "Date", "Map", "Set",
7
- "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "isNaN", "isFinite", "parseFloat", "parseInt",
8
- "Infinity", "NaN", "undefined",
9
- "setTimeout", "clearTimeout", "setInterval", "clearInterval",
10
- "JSON", "Math",
11
- // 模块化
12
- "module", "require", "exports",
13
- ...exports.SPECIFY_VAR
14
- ];
15
- // 变量作用域表
16
- class Scope {
17
- constructor() {
18
- // 当前作用域定义的变量
19
- this.defines = {};
20
- // 当前作用域使用的变量
21
- this.access = {};
22
- }
23
- toString() {
24
- return `defines: ${Object.keys(this.defines)} access: ${Object.keys(this.access)}`;
25
- }
26
- /**
27
- * @returns
28
- */
29
- anlysis() {
30
- // TODO 优化算法复杂度
31
- // 在自身作用域 以及 上级作用域寻找,找到顶层作用域时 则需要看 白名单是否含有
32
- for (const variable in this.access) {
33
- // 白名单也不包含此变量
34
- if (this.checkGlobal(variable) && !IDENTIFIER_WHITE_LIST.includes(variable)) {
35
- return { variable, span: this.access[variable] };
36
- }
37
- }
38
- return undefined;
39
- }
40
- // 检查是否是全局调用
41
- checkGlobal(key) {
42
- let scope = this;
43
- while (scope) {
44
- if (!scope.defines[key]) {
45
- scope = scope.parentScope;
46
- continue;
47
- }
48
- else {
49
- return false;
50
- }
51
- }
52
- return !scope;
53
- }
54
- setAccess(key, value) {
55
- this.access[key] = value;
56
- }
57
- setDefines(key, value) {
58
- this.defines[key] = value;
59
- }
60
- setParentScope(scope) {
61
- this.parentScope = scope;
62
- }
63
- }
64
- exports.Scope = Scope;
65
- class ScopeManager {
66
- constructor() {
67
- // 栈帧
68
- this._scopeStack = [];
69
- // 栈 深度遍历结果
70
- this._scopeTables = [];
71
- // 是否停止收集
72
- this._stop = false;
73
- }
74
- // 停止分析
75
- stop() {
76
- this._stop = true;
77
- }
78
- enterScope() {
79
- if (this._stop)
80
- return;
81
- this._scopeStack.push(new Scope());
82
- }
83
- exitScope() {
84
- if (this._stop)
85
- return;
86
- const scope = this._scopeStack.pop();
87
- if (scope) {
88
- this._scopeTables.push(scope);
89
- scope.setParentScope(this.getCurrentScope());
90
- }
91
- }
92
- getCurrentScope() {
93
- if (this._stop)
94
- return;
95
- return this._scopeStack[this._scopeStack.length - 1];
96
- }
97
- // 记录定义的值
98
- pushIdentifier(id) {
99
- var _a;
100
- if (this._stop)
101
- return;
102
- if (this.getCurrentScope()) {
103
- (_a = this.getCurrentScope()) === null || _a === void 0 ? void 0 : _a.setDefines(id.value, id.span);
104
- }
105
- }
106
- // 记录使用的值
107
- pushAccess(id) {
108
- if (this._stop)
109
- return;
110
- const current = this.getCurrentScope();
111
- if (current) {
112
- current === null || current === void 0 ? void 0 : current.setAccess(id.value, id.span);
113
- if (exports.SPECIFY_VAR.includes(id.value)) {
114
- id._xhsScope = current;
115
- }
116
- }
117
- }
118
- getDFSScope() {
119
- return this._scopeTables;
120
- }
121
- }
122
- exports.ScopeManager = ScopeManager;
@@ -1,2 +0,0 @@
1
- import type { JscTarget, Program } from '@swc/core';
2
- export declare const transform: (code: string, plugin?: ((m: Program) => Program) | undefined, target?: JscTarget, minify?: boolean) => import("@swc/core").Output;
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.transform = void 0;
4
- const core_1 = require("@swc/core");
5
- const transform = (code, plugin, target = 'esnext', minify = false) => (0, core_1.transformSync)(code, {
6
- swcrc: false,
7
- configFile: false,
8
- minify,
9
- sourceMaps: false,
10
- jsc: {
11
- preserveAllComments: true,
12
- target,
13
- // minify: false,
14
- externalHelpers: false,
15
- parser: {
16
- syntax: "ecmascript",
17
- jsx: false,
18
- dynamicImport: false,
19
- privateMethod: false,
20
- functionBind: false,
21
- classPrivateProperty: false,
22
- exportDefaultFrom: false,
23
- exportNamespaceFrom: false,
24
- decorators: false,
25
- decoratorsBeforeExport: false,
26
- importMeta: false,
27
- },
28
- },
29
- plugin,
30
- });
31
- exports.transform = transform;