@cocos/ccbuild 2.0.0-alpha.2 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +25 -165
  2. package/modules/build-engine/lib/engine-js/index.d.ts.map +1 -1
  3. package/modules/build-engine/lib/engine-js/index.js.map +1 -1
  4. package/modules/build-engine/lib/engine-js/rollup-plugins/external-wasm-loader.d.ts.map +1 -1
  5. package/modules/build-engine/lib/engine-js/rollup-plugins/external-wasm-loader.js +8 -9
  6. package/modules/build-engine/lib/engine-js/rollup-plugins/external-wasm-loader.js.map +1 -1
  7. package/modules/build-engine/lib/engine-ts/engine-builder.d.ts +2 -5
  8. package/modules/build-engine/lib/engine-ts/engine-builder.d.ts.map +1 -1
  9. package/modules/build-engine/lib/engine-ts/engine-builder.js +285 -291
  10. package/modules/build-engine/lib/engine-ts/engine-builder.js.map +1 -1
  11. package/modules/build-engine/lib/engine-ts/field-decorator-helper.d.ts +1 -1
  12. package/modules/build-engine/lib/engine-ts/field-decorator-helper.js +3 -3
  13. package/modules/build-engine/lib/engine-ts/plugins/external-wasm-loader.js +49 -18
  14. package/modules/build-engine/lib/engine-ts/plugins/external-wasm-loader.js.map +1 -1
  15. package/modules/build-engine/lib/engine-ts/plugins/interface.d.ts +7 -5
  16. package/modules/build-engine/lib/engine-ts/plugins/interface.d.ts.map +1 -1
  17. package/modules/build-engine/lib/engine-ts/plugins/node-module-loader.d.ts +2 -0
  18. package/modules/build-engine/lib/engine-ts/plugins/node-module-loader.d.ts.map +1 -0
  19. package/modules/build-engine/lib/engine-ts/plugins/node-module-loader.js +91 -0
  20. package/modules/build-engine/lib/engine-ts/plugins/node-module-loader.js.map +1 -0
  21. package/modules/build-engine/lib/index.d.ts.map +1 -1
  22. package/modules/build-engine/lib/index.js +40 -40
  23. package/modules/build-engine/lib/index.js.map +1 -1
  24. package/modules/bundler/lib/index.d.ts.map +1 -1
  25. package/modules/bundler/lib/index.js.map +1 -1
  26. package/modules/bundler/lib/rollup/index.d.ts.map +1 -1
  27. package/modules/bundler/lib/rollup/plugins.d.ts.map +1 -1
  28. package/modules/stats-query/lib/config-interface.d.ts +1 -1
  29. package/modules/stats-query/lib/index.d.ts.map +1 -1
  30. package/modules/stats-query/lib/index.js +6 -5
  31. package/modules/stats-query/lib/index.js.map +1 -1
  32. package/modules/transformer/lib/babel/plugins.d.ts +2 -1
  33. package/modules/transformer/lib/babel/plugins.d.ts.map +1 -1
  34. package/modules/transformer/lib/babel/plugins.js +8 -5
  35. package/modules/transformer/lib/babel/plugins.js.map +1 -1
  36. package/modules/transformer/lib/babel/presets.d.ts.map +1 -1
  37. package/modules/utils/lib/index.d.ts.map +1 -1
  38. package/modules/utils/lib/path.d.ts.map +1 -1
  39. package/modules/utils/lib/path.js +1 -1
  40. package/modules/utils/lib/path.js.map +1 -1
  41. package/package.json +3 -2
@@ -78,6 +78,7 @@ const dedent_1 = __importDefault(require("dedent"));
78
78
  const glob_1 = require("glob");
79
79
  const field_decorator_helper_1 = require("./field-decorator-helper");
80
80
  const external_wasm_loader_1 = require("./plugins/external-wasm-loader");
81
+ const node_module_loader_1 = require("./plugins/node-module-loader");
81
82
  var babel = transformer_1.babel.core;
82
83
  var t = babel.types;
83
84
  var traverse = babel.traverse;
@@ -88,14 +89,6 @@ class EngineBuilder {
88
89
  this._entries = [];
89
90
  this._entriesForPass2 = new Set();
90
91
  this._virtual2code = {};
91
- this._feature2NodeModule = {
92
- 'dragon-bones': '@cocos/dragonbones-js',
93
- 'physics-2d-box2d': '@cocos/box2d',
94
- 'physics-cannon': '@cocos/cannon',
95
- 'physics-physx': '@cocos/physx',
96
- 'physics-ammo': '@cocos/bullet'
97
- };
98
- this._nodeModules = [];
99
92
  this._virtualOverrides = {};
100
93
  this._buildResult = {};
101
94
  this._resolveExtension = ['.ts', '.js', '.json']; // not an option
@@ -106,9 +99,9 @@ class EngineBuilder {
106
99
  Path: 'PathAlias',
107
100
  struct: 'structAlias'
108
101
  };
109
- this._filedDecoratorHelper = new field_decorator_helper_1.FiledDecoratorHelper();
102
+ this._fieldDecoratorHelper = new field_decorator_helper_1.FieldDecoratorHelper();
110
103
  this._plugins = [];
111
- this._excludeTransform = [/external\:/];
104
+ this._excludeTransform = [/external:/];
112
105
  }
113
106
  build(options) {
114
107
  return __awaiter(this, void 0, void 0, function* () {
@@ -116,18 +109,23 @@ class EngineBuilder {
116
109
  root
117
110
  } = options;
118
111
  this._buildResult = {};
119
- const handleIdList = idList => {
120
- for (let id of idList) {
121
- const handleResult = this._handleId(id);
112
+ const handleIdList = idList => __awaiter(this, void 0, void 0, function* () {
113
+ for (const id of idList) {
114
+ const handleResult = yield this._handleId(id);
122
115
  this._buildResult[handleResult.file] = handleResult;
123
116
  }
124
- };
117
+ });
118
+ this._initPlugins(options);
119
+ yield this._initOptions(options);
120
+ for (const plugin of this._plugins) {
121
+ if (plugin.buildStart) {
122
+ yield plugin.buildStart();
123
+ }
124
+ }
125
125
  // pass1: build ts for native engine
126
126
  console.log('[Build Engine]: pass1 - traverse and compile modules');
127
127
  console.time('pass1');
128
- this._initPlugins(options);
129
- yield this._initOptions(options);
130
- handleIdList(this._entries);
128
+ yield handleIdList(this._entries);
131
129
  console.timeEnd('pass1');
132
130
  // pass2: build web version for jsb type declarations
133
131
  console.log('[Build Engine]: pass2 - apply jsb interface info');
@@ -145,7 +143,7 @@ class EngineBuilder {
145
143
  }
146
144
  console.timeEnd('pass2');
147
145
  if (options.outDir) {
148
- for (let file in this._buildResult) {
146
+ for (const file in this._buildResult) {
149
147
  const res = this._buildResult[file];
150
148
  const output = ps.join(options.outDir, ps.relative(root, file));
151
149
  fs.outputFileSync(output, res.code, 'utf8');
@@ -157,18 +155,22 @@ class EngineBuilder {
157
155
  console.timeEnd('pass3');
158
156
  this._buildIndex();
159
157
  yield this._copyTypes();
160
- // this._addNodeModulesDeps(); // TODO: support node modules building
161
158
  }
162
-
159
+ for (const plugin of this._plugins) {
160
+ if (plugin.buildEnd) {
161
+ yield plugin.buildEnd();
162
+ }
163
+ }
163
164
  return this._buildResult;
164
165
  });
165
166
  }
166
167
  _initPlugins(options) {
167
- this._plugins.push((0, external_wasm_loader_1.externalWasmLoaderFactory)({
168
+ this._plugins.push((0, node_module_loader_1.nodeModuleLoaderFactory)(), (0, external_wasm_loader_1.externalWasmLoaderFactory)({
168
169
  engineRoot: options.root
169
170
  }));
170
171
  }
171
172
  _initOptions(options) {
173
+ var _a;
172
174
  return __awaiter(this, void 0, void 0, function* () {
173
175
  this._options = options;
174
176
  const {
@@ -179,23 +181,16 @@ class EngineBuilder {
179
181
  } = options;
180
182
  const statsQuery = yield stats_query_1.StatsQuery.create(root);
181
183
  const constantManager = statsQuery.constantManager;
182
- if (options.features) {
183
- const featureUnits = statsQuery.getUnitsOfFeatures(options.features);
184
- this._entries = featureUnits.map(fu => (0, utils_1.formatPath)(statsQuery.getFeatureUnitFile(fu)));
185
- options.features.forEach(feature => {
186
- const nodeModule = this._feature2NodeModule[feature];
187
- nodeModule && this._nodeModules.push(nodeModule);
188
- });
189
- } else {
190
- const featureUnits = statsQuery.getFeatureUnits();
191
- this._entries = featureUnits.map(fu => (0, utils_1.formatPath)(statsQuery.getFeatureUnitFile(fu)));
192
- this._nodeModules.push(...Object.values(this._feature2NodeModule));
193
- }
184
+ const features = (_a = options.features) !== null && _a !== void 0 ? _a : statsQuery.getFeatures();
185
+ const featureUnits = statsQuery.getUnitsOfFeatures(features);
186
+ this._entries = featureUnits.map(fu => (0, utils_1.formatPath)(statsQuery.getFeatureUnitFile(fu)));
194
187
  this._buildTimeConstants = constantManager.genBuildTimeConstants({
195
188
  platform,
196
189
  mode,
197
190
  flags: flagConfig
198
191
  });
192
+ const intrinsicFlags = statsQuery.getIntrinsicFlagsOfFeatures(features);
193
+ Object.assign(this._buildTimeConstants, intrinsicFlags);
199
194
  this._moduleOverrides = statsQuery.evaluateModuleOverrides({
200
195
  mode: options.mode,
201
196
  platform: options.platform,
@@ -212,7 +207,7 @@ class EngineBuilder {
212
207
  const tsconfig = json5.parse(tsconfigContent);
213
208
  const compilerOptions = tsconfig.compilerOptions;
214
209
  if (compilerOptions && compilerOptions.baseUrl && compilerOptions.paths) {
215
- for (let [key, paths] of Object.entries(compilerOptions.paths)) {
210
+ for (const [key, paths] of Object.entries(compilerOptions.paths)) {
216
211
  this._moduleOverrides[key] = (0, utils_1.formatPath)(ps.join(ps.dirname(tsconfigFile), compilerOptions.baseUrl, paths[0]));
217
212
  }
218
213
  }
@@ -222,53 +217,52 @@ class EngineBuilder {
222
217
  mode,
223
218
  flags: flagConfig
224
219
  });
225
- this._virtual2code[this._filedDecoratorHelper.getModuleName()] = this._filedDecoratorHelper.genModuleSource();
226
- // TODO: resolve node modules
227
- this._virtual2code['@cocos/box2d'] = 'export {}';
228
- this._virtual2code['@cocos/bullet'] = 'export {}';
229
- this._virtual2code['@cocos/cannon'] = 'export {}';
230
- for (let virtualName in this._virtual2code) {
220
+ this._virtual2code[this._fieldDecoratorHelper.getModuleName()] = this._fieldDecoratorHelper.genModuleSource();
221
+ for (const virtualName in this._virtual2code) {
231
222
  this._virtualOverrides[virtualName] = (0, utils_1.formatPath)(ps.join(root, '__virtual__', virtualName.replace(/:/g, '_'))) + '.ts';
232
223
  }
233
224
  });
234
225
  }
235
226
  _handleId(id, importer) {
236
- const resolvedId = this._resolve(id, importer);
237
- if (typeof resolvedId === 'undefined') {
238
- throw new Error(`Cannot resolve module id: ${id} ${importer ? `in file ${importer}` : ''}`);
239
- }
240
- const code = this._load(resolvedId);
241
- if (typeof code === 'undefined') {
242
- throw new Error(`Cannot load module: ${resolvedId} ${importer ? `in file ${importer}` : ''}`);
243
- }
244
- let overrideId = this._getOverrideId(id, importer);
245
- // handle output file
246
- let file = overrideId || resolvedId;
247
- if (file.endsWith('.json')) {
248
- file = file.slice(0, -5) + '.ts';
249
- }
250
- if (this._buildResult[file]) {
251
- // skip cached file
252
- return this._buildResult[file];
253
- }
254
- const transformResult = this._transform(resolvedId, code);
255
- const handleResult = this._buildResult[file] = {
256
- code: transformResult.code,
257
- file,
258
- originalId: id,
259
- resolvedId,
260
- map: transformResult.map
261
- };
262
- transformResult.depIdList.forEach(id => {
263
- const handleResult = this._handleId(id, file);
264
- this._buildResult[handleResult.file] = handleResult;
227
+ return __awaiter(this, void 0, void 0, function* () {
228
+ const resolvedId = yield this._resolve(id, importer);
229
+ if (typeof resolvedId === 'undefined') {
230
+ throw new Error(`Cannot resolve module id: ${id} ${importer ? `in file ${importer}` : ''}`);
231
+ }
232
+ const code = yield this._load(resolvedId);
233
+ if (typeof code === 'undefined') {
234
+ throw new Error(`Cannot load module: ${resolvedId} ${importer ? `in file ${importer}` : ''}`);
235
+ }
236
+ const overrideId = this._getOverrideId(id, importer);
237
+ // handle output file
238
+ let file = overrideId || resolvedId;
239
+ if (file.endsWith('.json')) {
240
+ file = file.slice(0, -5) + '.ts';
241
+ }
242
+ if (this._buildResult[file]) {
243
+ // skip cached file
244
+ return this._buildResult[file];
245
+ }
246
+ const depIdList = this._getDepIdList(file, code);
247
+ // we handle the dep module first, because we need to get the resolved dep id to transform the import specifier in current module.
248
+ for (const depId of depIdList) {
249
+ yield this._handleId(depId, file);
250
+ }
251
+ const transformResult = yield this._transform(resolvedId, code);
252
+ const handleResult = this._buildResult[file] = {
253
+ code: transformResult.code,
254
+ file,
255
+ originalId: id,
256
+ resolvedId,
257
+ map: transformResult.map
258
+ };
259
+ return handleResult;
265
260
  });
266
- return handleResult;
267
261
  }
268
262
  _getOverrideId(id, importer) {
269
263
  var _a;
270
264
  let overrideId;
271
- for (let p of this._plugins) {
265
+ for (const p of this._plugins) {
272
266
  overrideId = (_a = p.transformId) === null || _a === void 0 ? void 0 : _a.call(p, id, importer);
273
267
  if (overrideId) {
274
268
  return overrideId;
@@ -292,28 +286,28 @@ class EngineBuilder {
292
286
  }
293
287
  _resolve(id, importer) {
294
288
  var _a, _b;
295
- for (let p of this._plugins) {
296
- const resolvedId = (_a = p.resolve) === null || _a === void 0 ? void 0 : _a.call(p, id, importer);
297
- if (resolvedId) {
298
- return resolvedId;
289
+ return __awaiter(this, void 0, void 0, function* () {
290
+ for (const p of this._plugins) {
291
+ const resolvedId = yield (_a = p.resolve) === null || _a === void 0 ? void 0 : _a.call(p, id, importer);
292
+ if (resolvedId) {
293
+ return resolvedId;
294
+ }
299
295
  }
300
- }
301
- if (!importer) {
302
- return id; // entry
303
- } else if (id in this._virtualOverrides) {
304
- return id; // virtual module does not have real fs path
305
- } else if (id in this._moduleOverrides) {
306
- return this._moduleOverrides[id];
307
- } else if (this._nodeModules.includes(id)) {
308
- return id; // node module only use bare specifier as module id
309
- } else if (ps.isAbsolute(id)) {
310
- return id;
311
- } else {
312
- const resolved = this._resolveRelative(id, importer);
313
- if (resolved) {
314
- return (_b = this._moduleOverrides[resolved]) !== null && _b !== void 0 ? _b : resolved;
296
+ if (!importer) {
297
+ return id; // entry
298
+ } else if (id in this._virtualOverrides) {
299
+ return id; // virtual module does not have real fs path
300
+ } else if (id in this._moduleOverrides) {
301
+ return this._moduleOverrides[id];
302
+ } else if (ps.isAbsolute(id)) {
303
+ return id;
304
+ } else {
305
+ const resolved = this._resolveRelative(id, importer);
306
+ if (resolved) {
307
+ return (_b = this._moduleOverrides[resolved]) !== null && _b !== void 0 ? _b : resolved;
308
+ }
315
309
  }
316
- }
310
+ });
317
311
  }
318
312
  _resolveRelative(id, importer) {
319
313
  const file = (0, utils_1.formatPath)(ps.join(ps.dirname(importer), id));
@@ -333,33 +327,27 @@ class EngineBuilder {
333
327
  }
334
328
  _load(id) {
335
329
  var _a;
336
- for (let p of this._plugins) {
337
- const loadedCode = (_a = p.load) === null || _a === void 0 ? void 0 : _a.call(p, id);
338
- if (loadedCode) {
339
- return loadedCode;
330
+ return __awaiter(this, void 0, void 0, function* () {
331
+ for (const p of this._plugins) {
332
+ const loadedCode = yield (_a = p.load) === null || _a === void 0 ? void 0 : _a.call(p, id);
333
+ if (loadedCode) {
334
+ return loadedCode;
335
+ }
340
336
  }
341
- }
342
- if (fs.existsSync(id)) {
343
- let code = fs.readFileSync(id, 'utf8');
344
- if (id.endsWith('.json')) {
345
- code = `export default ${code};`;
337
+ if (fs.existsSync(id)) {
338
+ let code = fs.readFileSync(id, 'utf8');
339
+ if (id.endsWith('.json')) {
340
+ code = `export default ${code};`;
341
+ }
342
+ return code;
343
+ } else if (this._virtualOverrides[id]) {
344
+ return this._virtual2code[id];
346
345
  }
347
- return code;
348
- } else if (this._virtualOverrides[id]) {
349
- return this._virtual2code[id];
350
- }
346
+ });
351
347
  }
352
- _transform(file, code) {
353
- file = (0, utils_1.formatPath)(file);
354
- for (let ex of this._excludeTransform) {
355
- if (ex.test(file)) {
356
- return {
357
- code,
358
- depIdList: []
359
- };
360
- }
361
- }
348
+ _getDepIdList(file, code) {
362
349
  const depIdList = [];
350
+ // eg. zlib.js dependent on zlib.d.ts
363
351
  if (ps.extname(file) === '.js') {
364
352
  const dtsFile = (0, utils_1.toExtensionLess)(file) + '.d.ts';
365
353
  if (fs.existsSync(dtsFile)) {
@@ -368,174 +356,208 @@ class EngineBuilder {
368
356
  }
369
357
 
370
358
  const importExportVisitor = path => {
371
- // @ts-ignore
359
+ // @ts-expect-error TODO: fix type
372
360
  const source = path.node.source;
373
361
  if (source) {
374
362
  const specifier = source.value;
375
363
  // add dependency
376
- if (!this._nodeModules.includes(specifier)) {
377
- // don't load node modules, we post install the modules in OH project
378
- depIdList.push(specifier);
379
- }
380
- // transform import/export declaration if needed
381
- const overrideId = this._getOverrideId(specifier, file);
382
- if (overrideId) {
383
- let relativePath = (0, utils_1.formatPath)(ps.relative(ps.dirname(file), overrideId));
384
- if (!relativePath.startsWith('.')) {
385
- relativePath = './' + relativePath;
386
- }
387
- if (ps.extname(relativePath) === '.ts') {
388
- relativePath = relativePath.slice(0, -3); // remove '.ts'
389
- }
390
- // traverse to transform specifier
391
- traverse(path.node, {
392
- StringLiteral(path) {
393
- path.replaceWith(babel.types.stringLiteral(relativePath));
394
- path.skip();
395
- }
396
- }, path.scope);
397
- }
364
+ depIdList.push(specifier);
398
365
  }
399
- const importExportSpecifier = path => {
400
- const name = path.node.local.name;
401
- const alias = this._renameMap[name];
402
- if (alias) {
403
- path.replaceWith(babel.types.exportSpecifier(babel.types.identifier(alias), babel.types.identifier(alias)));
404
- }
405
- };
406
- path.traverse({
407
- ExportSpecifier: importExportSpecifier,
408
- ImportSpecifier: importExportSpecifier
409
- });
410
366
  };
411
- const self = this;
412
- const transformResult = babel.transformSync(code, {
367
+ const res = babel.parseSync(code, {
413
368
  configFile: false,
414
369
  plugins: [[pluginSyntaxTS], [syntaxDecorators, {
415
370
  version: '2018-09',
416
371
  decoratorsBeforeExport: true
417
- }], [() => {
418
- return {
419
- name: 'custom-transform',
420
- pre(file) {
421
- const pluginPass = this;
422
- traverse(file.ast, {
423
- ClassProperty(path) {
424
- const decoratorsPath = path.get('decorators');
425
- if (Array.isArray(decoratorsPath)) {
426
- const propertyValuePath = path.get('value');
427
- const helperIdentifier = self._filedDecoratorHelper.addHelper(pluginPass.file);
428
- decoratorsPath.forEach(decPath => {
429
- const expPath = decPath.get('expression');
430
- const type = expPath.node.type;
431
- if (type === 'CallExpression') {
432
- const decName = expPath.node.callee.name;
433
- const args = expPath.node.arguments;
434
- decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [t.identifier(decName), propertyValuePath.node ? t.arrowFunctionExpression([], propertyValuePath.node) : t.nullLiteral(), ...args])));
435
- } else if (type === 'Identifier') {
436
- const decName = expPath.node.name;
437
- decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [t.identifier(decName), propertyValuePath.node ? t.arrowFunctionExpression([], propertyValuePath.node) : t.nullLiteral()])));
438
- }
439
- });
440
- }
372
+ }]]
373
+ });
374
+ babel.traverse(res, {
375
+ ImportDeclaration: importExportVisitor,
376
+ ExportDeclaration: importExportVisitor
377
+ });
378
+ return depIdList;
379
+ }
380
+ _transform(file, code) {
381
+ return __awaiter(this, void 0, void 0, function* () {
382
+ file = (0, utils_1.formatPath)(file);
383
+ for (const ex of this._excludeTransform) {
384
+ if (ex.test(file)) {
385
+ return {
386
+ code
387
+ };
388
+ }
389
+ }
390
+ let needFieldHelperModule = false;
391
+ const importExportVisitor = path => {
392
+ // @ts-expect-error TODO: fix type
393
+ const source = path.node.source;
394
+ if (source) {
395
+ const specifier = source.value;
396
+ // transform import/export declaration if needed
397
+ const overrideId = this._getOverrideId(specifier, file);
398
+ if (overrideId) {
399
+ let relativePath = (0, utils_1.formatPath)(ps.relative(ps.dirname(file), overrideId));
400
+ if (!relativePath.startsWith('.')) {
401
+ relativePath = './' + relativePath;
402
+ }
403
+ if (ps.extname(relativePath) === '.ts') {
404
+ relativePath = relativePath.slice(0, -3); // remove '.ts'
405
+ }
406
+
407
+ traverse(path.node, {
408
+ StringLiteral(path) {
409
+ path.replaceWith(babel.types.stringLiteral(relativePath));
410
+ path.skip();
441
411
  }
442
- });
443
- },
444
- visitor: {
445
- ImportDeclaration: importExportVisitor,
446
- ExportDeclaration: importExportVisitor,
447
- // TODO: here we rename class Rect and Path
448
- CallExpression(path) {
449
- if (path.node.callee.type === 'MemberExpression') {
450
- const memberExpressionPath = path.get('callee');
451
- const objectPath = memberExpressionPath.get('object');
452
- const name = objectPath.node.name;
453
- const alias = self._renameMap[name];
454
- if (typeof alias === 'string' && path.node.callee.object.type === 'Identifier') {
455
- objectPath.replaceWith(t.identifier(alias));
456
- }
457
- // TODO: for now, OH doesn't support standard console interface,
458
- // so we need to ignore the type checking for console call expressions.
459
- else if (name === 'console') {
460
- path.node.leadingComments = [{
461
- type: 'CommentLine',
462
- value: ' @ts-ignore'
463
- }];
412
+ }, path.scope);
413
+ }
414
+ }
415
+ const importExportSpecifier = path => {
416
+ const name = path.node.local.name;
417
+ const alias = this._renameMap[name];
418
+ if (alias) {
419
+ path.replaceWith(babel.types.exportSpecifier(babel.types.identifier(alias), babel.types.identifier(alias)));
420
+ }
421
+ };
422
+ path.traverse({
423
+ ExportSpecifier: importExportSpecifier,
424
+ ImportSpecifier: importExportSpecifier
425
+ });
426
+ };
427
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
428
+ const self = this;
429
+ const transformResult = babel.transformSync(code, {
430
+ configFile: false,
431
+ plugins: [[pluginSyntaxTS], [syntaxDecorators, {
432
+ version: '2018-09',
433
+ decoratorsBeforeExport: true
434
+ }], [() => {
435
+ return {
436
+ name: 'custom-transform',
437
+ pre(file) {
438
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
439
+ const pluginPass = this;
440
+ traverse(file.ast, {
441
+ ClassProperty(path) {
442
+ const decoratorsPath = path.get('decorators');
443
+ if (Array.isArray(decoratorsPath)) {
444
+ const propertyValuePath = path.get('value');
445
+ const helperIdentifier = self._fieldDecoratorHelper.addHelper(pluginPass.file);
446
+ needFieldHelperModule = true;
447
+ decoratorsPath.forEach(decPath => {
448
+ const expPath = decPath.get('expression');
449
+ const type = expPath.node.type;
450
+ if (type === 'CallExpression') {
451
+ const decName = expPath.node.callee.name;
452
+ const args = expPath.node.arguments;
453
+ decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [t.identifier(decName), propertyValuePath.node ? t.arrowFunctionExpression([], propertyValuePath.node) : t.nullLiteral(), ...args])));
454
+ } else if (type === 'Identifier') {
455
+ const decName = expPath.node.name;
456
+ decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [t.identifier(decName), propertyValuePath.node ? t.arrowFunctionExpression([], propertyValuePath.node) : t.nullLiteral()])));
457
+ }
458
+ });
459
+ }
464
460
  }
465
- } else if (path.node.callee.type === 'Import') {
466
- // TODO: for now, we transform `import('./xxx/xxx.js')` into `window.__cc_module_context__.import('./xxx/xxx.js')`
467
- // we need to support import(`project://xxx`) in the future.
468
- path.replaceWith(t.callExpression(t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('__cc_module_context__')), t.identifier('import')), path.node.arguments));
469
- }
461
+ });
470
462
  },
471
- ClassDeclaration(path) {
472
- const idPath = path.get('id');
473
- const name = idPath.node.name;
474
- const alias = self._renameMap[name];
475
- if (typeof alias === 'string') {
476
- idPath.replaceWith(t.identifier(alias));
477
- }
478
- },
479
- NewExpression(path) {
480
- const calleePath = path.get('callee');
481
- // @ts-ignore
482
- const name = calleePath.node.name;
483
- if (name) {
484
- const alias = self._renameMap[name];
485
- if (typeof alias === 'string') {
486
- calleePath.replaceWith(t.identifier(alias));
463
+ visitor: {
464
+ ImportDeclaration: importExportVisitor,
465
+ ExportDeclaration: importExportVisitor,
466
+ // TODO: here we rename class Rect and Path
467
+ CallExpression(path) {
468
+ if (path.node.callee.type === 'MemberExpression') {
469
+ const memberExpressionPath = path.get('callee');
470
+ const objectPath = memberExpressionPath.get('object');
471
+ const name = objectPath.node.name;
472
+ const alias = self._renameMap[name];
473
+ if (typeof alias === 'string' && path.node.callee.object.type === 'Identifier') {
474
+ objectPath.replaceWith(t.identifier(alias));
475
+ }
476
+ // TODO: for now, OH doesn't support standard console interface,
477
+ // so we need to ignore the type checking for console call expressions.
478
+ else if (name === 'console') {
479
+ path.node.leadingComments = [{
480
+ type: 'CommentLine',
481
+ value: ' @ts-ignore'
482
+ }];
483
+ }
484
+ } else if (path.node.callee.type === 'Import') {
485
+ // TODO: for now, we transform `import('./xxx/xxx.js')` into `window.__cc_module_context__.import('./xxx/xxx.js')`
486
+ // we need to support import(`project://xxx`) in the future.
487
+ path.replaceWith(t.callExpression(t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('__cc_module_context__')), t.identifier('import')), path.node.arguments));
487
488
  }
488
- }
489
- },
490
- TSTypeAnnotation(path) {
491
- // @ts-ignore
492
- const typeName = path.node.typeAnnotation.typeName;
493
- const childPath = path.get('typeAnnotation');
494
- if (typeName) {
495
- const name = typeName.name;
489
+ },
490
+ ClassDeclaration(path) {
491
+ const idPath = path.get('id');
492
+ const name = idPath.node.name;
496
493
  const alias = self._renameMap[name];
497
494
  if (typeof alias === 'string') {
498
- path.replaceWith(t.tsTypeAnnotation({
499
- type: 'TSExpressionWithTypeArguments',
500
- expression: t.identifier(alias)
501
- }));
495
+ idPath.replaceWith(t.identifier(alias));
502
496
  }
503
- } else if (childPath.type === 'TSLiteralType') {
504
- const literalPath = childPath.get('literal');
505
- if (literalPath.type === 'TemplateLiteral') {
506
- path.replaceWith(t.tsTypeAnnotation(t.tsStringKeyword()));
497
+ },
498
+ NewExpression(path) {
499
+ const calleePath = path.get('callee');
500
+ // @ts-expect-error TODO: fix type
501
+ const name = calleePath.node.name;
502
+ if (name) {
503
+ const alias = self._renameMap[name];
504
+ if (typeof alias === 'string') {
505
+ calleePath.replaceWith(t.identifier(alias));
506
+ }
507
507
  }
508
- }
509
- },
510
- Identifier(path) {
511
- const name = path.node.name;
512
- const alias = self._renameMap[name];
513
- if (typeof alias === 'string') {
514
- if (path.parent.type === 'ObjectProperty' || path.parent.type === 'TSPropertySignature') {
515
- if (path.parent.key !== path.node) {
516
- path.replaceWith(t.identifier(alias));
508
+ },
509
+ TSTypeAnnotation(path) {
510
+ // @ts-expect-error TODO: fix type
511
+ const typeName = path.node.typeAnnotation.typeName;
512
+ const childPath = path.get('typeAnnotation');
513
+ if (typeName) {
514
+ const name = typeName.name;
515
+ const alias = self._renameMap[name];
516
+ if (typeof alias === 'string') {
517
+ path.replaceWith(t.tsTypeAnnotation({
518
+ type: 'TSExpressionWithTypeArguments',
519
+ expression: t.identifier(alias)
520
+ }));
517
521
  }
518
- } else if (path.parent.type === 'MemberExpression' || path.parent.type === 'OptionalMemberExpression') {
519
- if (path.parent.property !== path.node) {
520
- path.replaceWith(t.identifier(alias));
522
+ } else if (childPath.type === 'TSLiteralType') {
523
+ const literalPath = childPath.get('literal');
524
+ if (literalPath.type === 'TemplateLiteral') {
525
+ path.replaceWith(t.tsTypeAnnotation(t.tsStringKeyword()));
521
526
  }
522
- } else if (!(path.parent.type === 'ClassMethod' && (path.parent.kind === 'get' || path.parent.kind === 'set' || path.parent.key === path.node)) && path.parent.type !== 'ClassProperty') {
523
- const newIdentifier = t.identifier(alias);
524
- if (path.node.typeAnnotation) {
525
- newIdentifier.typeAnnotation = path.node.typeAnnotation;
527
+ }
528
+ },
529
+ Identifier(path) {
530
+ const name = path.node.name;
531
+ const alias = self._renameMap[name];
532
+ if (typeof alias === 'string') {
533
+ if (path.parent.type === 'ObjectProperty' || path.parent.type === 'TSPropertySignature') {
534
+ if (path.parent.key !== path.node) {
535
+ path.replaceWith(t.identifier(alias));
536
+ }
537
+ } else if (path.parent.type === 'MemberExpression' || path.parent.type === 'OptionalMemberExpression') {
538
+ if (path.parent.property !== path.node) {
539
+ path.replaceWith(t.identifier(alias));
540
+ }
541
+ } else if (!(path.parent.type === 'ClassMethod' && (path.parent.kind === 'get' || path.parent.kind === 'set' || path.parent.key === path.node)) && path.parent.type !== 'ClassProperty') {
542
+ const newIdentifier = t.identifier(alias);
543
+ if (path.node.typeAnnotation) {
544
+ newIdentifier.typeAnnotation = path.node.typeAnnotation;
545
+ }
546
+ path.replaceWith(newIdentifier);
526
547
  }
527
- path.replaceWith(newIdentifier);
528
548
  }
529
549
  }
530
550
  }
531
- }
532
- };
533
- }]]
551
+ };
552
+ }]]
553
+ });
554
+ if (needFieldHelperModule) {
555
+ yield this._handleId(this._fieldDecoratorHelper.getModuleName(), file);
556
+ }
557
+ return {
558
+ code: transformResult === null || transformResult === void 0 ? void 0 : transformResult.code
559
+ };
534
560
  });
535
- return {
536
- code: transformResult === null || transformResult === void 0 ? void 0 : transformResult.code,
537
- depIdList
538
- };
539
561
  }
540
562
  _lintImport(lintFiles, verbose = false) {
541
563
  return __awaiter(this, void 0, void 0, function* () {
@@ -545,11 +567,11 @@ class EngineBuilder {
545
567
  resolvePluginsRelativeTo: __dirname,
546
568
  useEslintrc: false,
547
569
  baseConfig: {
548
- parser: "@typescript-eslint/parser",
549
- plugins: ["@typescript-eslint", "unused-imports"],
570
+ parser: '@typescript-eslint/parser',
571
+ plugins: ['@typescript-eslint', 'unused-imports'],
550
572
  rules: {
551
- "@typescript-eslint/consistent-type-imports": "error",
552
- "unused-imports/no-unused-imports": "error"
573
+ '@typescript-eslint/consistent-type-imports': 'error',
574
+ 'unused-imports/no-unused-imports': 'error'
553
575
  }
554
576
  }
555
577
  });
@@ -603,8 +625,8 @@ class EngineBuilder {
603
625
  if (!outDir) {
604
626
  return;
605
627
  }
606
- const dtsFiles = yield (0, glob_1.glob)((0, utils_1.formatPath)(ps.join(root, './@types/**/*.d.ts')));
607
- for (let file of dtsFiles) {
628
+ const dtsFiles = glob_1.glob.sync((0, utils_1.formatPath)(ps.join(root, './@types/**/*.d.ts')));
629
+ for (const file of dtsFiles) {
608
630
  const code = fs.readFileSync(file, 'utf8');
609
631
  const relativePath = ps.relative(root, file);
610
632
  const targetPath = (0, utils_1.formatPath)(ps.join(outDir, relativePath));
@@ -618,33 +640,5 @@ class EngineBuilder {
618
640
  fs.outputFileSync(targetDomDts, code, 'utf8');
619
641
  });
620
642
  }
621
- _addNodeModulesDeps() {
622
- const {
623
- outDir
624
- } = this._options;
625
- if (!outDir) {
626
- return;
627
- }
628
- const pkgFile = (0, utils_1.formatPath)(ps.join(outDir, '..',
629
- // src
630
- '..',
631
- // cocos
632
- '..',
633
- // ets
634
- '..',
635
- // main
636
- '..',
637
- // src
638
- '..',
639
- // entry
640
- 'package.json'));
641
- if (!fs.existsSync(pkgFile)) {
642
- return;
643
- }
644
- const jsonObj = fs.readJSONSync(pkgFile);
645
- console.log(jsonObj);
646
- // TODO
647
- }
648
643
  }
649
-
650
644
  exports.EngineBuilder = EngineBuilder;