@cocos/ccbuild 2.1.0 → 2.2.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 (30) hide show
  1. package/modules/build-engine/lib/engine-js/index.js +302 -331
  2. package/modules/build-engine/lib/engine-js/index.js.map +1 -1
  3. package/modules/build-engine/lib/engine-js/rollup-plugins/external-wasm-loader.js +89 -130
  4. package/modules/build-engine/lib/engine-js/rollup-plugins/external-wasm-loader.js.map +1 -1
  5. package/modules/build-engine/lib/engine-js/rollup-plugins/module-query-plugin.js +2 -31
  6. package/modules/build-engine/lib/engine-js/rollup-plugins/module-query-plugin.js.map +1 -1
  7. package/modules/build-engine/lib/engine-ts/engine-builder.js +416 -461
  8. package/modules/build-engine/lib/engine-ts/engine-builder.js.map +1 -1
  9. package/modules/build-engine/lib/engine-ts/index.js +19 -48
  10. package/modules/build-engine/lib/engine-ts/index.js.map +1 -1
  11. package/modules/build-engine/lib/engine-ts/plugins/external-wasm-loader.js +31 -64
  12. package/modules/build-engine/lib/engine-ts/plugins/external-wasm-loader.js.map +1 -1
  13. package/modules/build-engine/lib/engine-ts/plugins/module-query-plugin.js +5 -34
  14. package/modules/build-engine/lib/engine-ts/plugins/module-query-plugin.js.map +1 -1
  15. package/modules/build-engine/lib/engine-ts/plugins/node-module-loader.js +28 -59
  16. package/modules/build-engine/lib/engine-ts/plugins/node-module-loader.js.map +1 -1
  17. package/modules/build-engine/lib/index.d.ts.map +1 -1
  18. package/modules/build-engine/lib/index.js +61 -81
  19. package/modules/build-engine/lib/index.js.map +1 -1
  20. package/modules/dts-bundler/lib/index.js +236 -265
  21. package/modules/dts-bundler/lib/index.js.map +1 -1
  22. package/modules/modularize/lib/module-query.js +153 -198
  23. package/modules/modularize/lib/module-query.js.map +1 -1
  24. package/modules/stats-query/lib/index.d.ts +5 -1
  25. package/modules/stats-query/lib/index.d.ts.map +1 -1
  26. package/modules/stats-query/lib/index.js +48 -81
  27. package/modules/stats-query/lib/index.js.map +1 -1
  28. package/modules/utils/lib/path.js +8 -37
  29. package/modules/utils/lib/path.js.map +1 -1
  30. package/package.json +1 -1
@@ -31,33 +31,6 @@ var __importStar = this && this.__importStar || function (mod) {
31
31
  __setModuleDefault(result, mod);
32
32
  return result;
33
33
  };
34
- var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
35
- function adopt(value) {
36
- return value instanceof P ? value : new P(function (resolve) {
37
- resolve(value);
38
- });
39
- }
40
- return new (P || (P = Promise))(function (resolve, reject) {
41
- function fulfilled(value) {
42
- try {
43
- step(generator.next(value));
44
- } catch (e) {
45
- reject(e);
46
- }
47
- }
48
- function rejected(value) {
49
- try {
50
- step(generator["throw"](value));
51
- } catch (e) {
52
- reject(e);
53
- }
54
- }
55
- function step(result) {
56
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
57
- }
58
- step((generator = generator.apply(thisArg, _arguments || [])).next());
59
- });
60
- };
61
34
  var __importDefault = this && this.__importDefault || function (mod) {
62
35
  return mod && mod.__esModule ? mod : {
63
36
  "default": mod
@@ -105,173 +78,165 @@ class EngineBuilder {
105
78
  this._excludeTransform = [/native\/external\//];
106
79
  this._handledCache = {};
107
80
  }
108
- build(options) {
109
- return __awaiter(this, void 0, void 0, function* () {
110
- const {
111
- root
112
- } = options;
113
- this._buildResult = {};
114
- const handleIdList = idList => __awaiter(this, void 0, void 0, function* () {
115
- for (const id of idList) {
116
- const handleResult = yield this._handleId(id);
117
- if (handleResult) {
118
- this._buildResult[handleResult.file] = handleResult;
119
- }
120
- }
121
- });
122
- yield this._initOptions(options);
123
- yield this._initPlugins(options);
124
- for (const plugin of this._plugins) {
125
- if (plugin.buildStart) {
126
- yield plugin.buildStart();
81
+ async build(options) {
82
+ const {
83
+ root
84
+ } = options;
85
+ this._buildResult = {};
86
+ const handleIdList = async idList => {
87
+ for (const id of idList) {
88
+ const handleResult = await this._handleId(id);
89
+ if (handleResult) {
90
+ this._buildResult[handleResult.file] = handleResult;
127
91
  }
128
92
  }
129
- // pass1: build ts for native engine
130
- console.log('[Build Engine]: pass1 - traverse and compile modules');
131
- console.time('pass1');
132
- yield handleIdList(this._entries);
133
- console.timeEnd('pass1');
134
- // pass2: build web version for jsb type declarations
135
- console.log('[Build Engine]: pass2 - apply jsb interface info');
136
- console.time('pass2');
137
- this._handledCache = {}; // clear cache
138
- while (this._entriesForPass2.size !== 0) {
139
- const entries2 = Array.from(this._entriesForPass2);
140
- this._entriesForPass2.clear();
141
- this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
142
- if (!fs.existsSync(k) || !entries2.includes(k)) {
143
- result[k] = v;
144
- }
145
- return result;
146
- }, {});
147
- yield handleIdList(entries2);
148
- }
149
- console.timeEnd('pass2');
150
- if (options.outDir) {
151
- for (const file in this._buildResult) {
152
- const res = this._buildResult[file];
153
- const output = ps.join(options.outDir, ps.relative(root, file));
154
- fs.outputFileSync(output, res.code, 'utf8');
155
- }
156
- this._buildIndex();
157
- yield this._copyTypes();
93
+ };
94
+ await this._initOptions(options);
95
+ await this._initPlugins(options);
96
+ for (const plugin of this._plugins) {
97
+ if (plugin.buildStart) {
98
+ await plugin.buildStart();
158
99
  }
159
- for (const plugin of this._plugins) {
160
- if (plugin.buildEnd) {
161
- yield plugin.buildEnd();
100
+ }
101
+ // pass1: build ts for native engine
102
+ console.log('[Build Engine]: pass1 - traverse and compile modules');
103
+ console.time('pass1');
104
+ await handleIdList(this._entries);
105
+ console.timeEnd('pass1');
106
+ // pass2: build web version for jsb type declarations
107
+ console.log('[Build Engine]: pass2 - apply jsb interface info');
108
+ console.time('pass2');
109
+ this._handledCache = {}; // clear cache
110
+ while (this._entriesForPass2.size !== 0) {
111
+ const entries2 = Array.from(this._entriesForPass2);
112
+ this._entriesForPass2.clear();
113
+ this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
114
+ if (!fs.existsSync(k) || !entries2.includes(k)) {
115
+ result[k] = v;
162
116
  }
117
+ return result;
118
+ }, {});
119
+ await handleIdList(entries2);
120
+ }
121
+ console.timeEnd('pass2');
122
+ if (options.outDir) {
123
+ for (const file in this._buildResult) {
124
+ const res = this._buildResult[file];
125
+ const output = ps.join(options.outDir, ps.relative(root, file));
126
+ fs.outputFileSync(output, res.code, 'utf8');
127
+ }
128
+ this._buildIndex();
129
+ await this._copyTypes();
130
+ }
131
+ for (const plugin of this._plugins) {
132
+ if (plugin.buildEnd) {
133
+ await plugin.buildEnd();
163
134
  }
164
- return this._buildResult;
165
- });
135
+ }
136
+ return this._buildResult;
166
137
  }
167
- _initPlugins(options) {
138
+ async _initPlugins(options) {
168
139
  var _a;
169
- return __awaiter(this, void 0, void 0, function* () {
170
- this._moduleQuery = new modularize_1.ModuleQuery({
171
- engine: options.root,
172
- platform: options.platform
173
- });
174
- this._plugins.push((0, module_query_plugin_1.moduleQueryPlugin)(this._moduleQuery), (0, node_module_loader_1.nodeModuleLoaderFactory)(), (0, external_wasm_loader_1.externalWasmLoaderFactory)({
175
- engineRoot: options.root,
176
- outDir: options.outDir,
177
- cullMeshopt: (_a = options.flagConfig.CULL_MESHOPT) !== null && _a !== void 0 ? _a : false
178
- }));
140
+ this._moduleQuery = new modularize_1.ModuleQuery({
141
+ engine: options.root,
142
+ platform: options.platform
179
143
  });
144
+ this._plugins.push((0, module_query_plugin_1.moduleQueryPlugin)(this._moduleQuery), (0, node_module_loader_1.nodeModuleLoaderFactory)(), (0, external_wasm_loader_1.externalWasmLoaderFactory)({
145
+ engineRoot: options.root,
146
+ outDir: options.outDir,
147
+ cullMeshopt: (_a = options.flagConfig.CULL_MESHOPT) !== null && _a !== void 0 ? _a : false
148
+ }));
180
149
  }
181
- _initOptions(options) {
150
+ async _initOptions(options) {
182
151
  var _a;
183
- return __awaiter(this, void 0, void 0, function* () {
184
- this._options = options;
185
- const {
186
- root,
187
- flagConfig,
188
- platform,
189
- mode
190
- } = options;
191
- const statsQuery = yield stats_query_1.StatsQuery.create(root);
192
- const constantManager = statsQuery.constantManager;
193
- const features = (_a = options.features) !== null && _a !== void 0 ? _a : statsQuery.getFeatures();
194
- const featureUnits = statsQuery.getUnitsOfFeatures(features);
195
- this._entries = featureUnits.map(fu => (0, utils_1.formatPath)(statsQuery.getFeatureUnitFile(fu)));
196
- this._buildTimeConstants = constantManager.genBuildTimeConstants({
197
- platform,
198
- mode,
199
- flags: flagConfig
200
- });
201
- const intrinsicFlags = statsQuery.getIntrinsicFlagsOfFeatures(features);
202
- Object.assign(this._buildTimeConstants, intrinsicFlags);
203
- this._moduleOverrides = statsQuery.evaluateModuleOverrides({
204
- mode: options.mode,
205
- platform: options.platform,
206
- buildTimeConstants: this._buildTimeConstants
207
- });
208
- this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
209
- result[(0, utils_1.formatPath)(k)] = (0, utils_1.formatPath)(v);
210
- return result;
211
- }, {});
212
- // paths in tsconfig.json
213
- const tsconfigFile = ps.join(root, './tsconfig.json');
214
- if (fs.existsSync(tsconfigFile)) {
215
- const tsconfigContent = fs.readFileSync(tsconfigFile, 'utf8');
216
- const tsconfig = json5.parse(tsconfigContent);
217
- const compilerOptions = tsconfig.compilerOptions;
218
- if (compilerOptions && compilerOptions.baseUrl && compilerOptions.paths) {
219
- for (const [key, paths] of Object.entries(compilerOptions.paths)) {
220
- this._moduleOverrides[key] = (0, utils_1.formatPath)(ps.join(ps.dirname(tsconfigFile), compilerOptions.baseUrl, paths[0]));
221
- }
152
+ this._options = options;
153
+ const {
154
+ root,
155
+ flagConfig,
156
+ platform,
157
+ mode
158
+ } = options;
159
+ const statsQuery = await stats_query_1.StatsQuery.create(root);
160
+ const constantManager = statsQuery.constantManager;
161
+ const features = (_a = options.features) !== null && _a !== void 0 ? _a : statsQuery.getFeatures();
162
+ const featureUnits = statsQuery.getUnitsOfFeatures(features);
163
+ this._entries = featureUnits.map(fu => (0, utils_1.formatPath)(statsQuery.getFeatureUnitFile(fu)));
164
+ this._buildTimeConstants = constantManager.genBuildTimeConstants({
165
+ platform,
166
+ mode,
167
+ flags: flagConfig
168
+ });
169
+ const intrinsicFlags = statsQuery.getIntrinsicFlagsOfFeatures(features);
170
+ Object.assign(this._buildTimeConstants, intrinsicFlags);
171
+ this._moduleOverrides = statsQuery.evaluateModuleOverrides({
172
+ mode: options.mode,
173
+ platform: options.platform,
174
+ buildTimeConstants: this._buildTimeConstants
175
+ });
176
+ this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
177
+ result[(0, utils_1.formatPath)(k)] = (0, utils_1.formatPath)(v);
178
+ return result;
179
+ }, {});
180
+ // paths in tsconfig.json
181
+ const tsconfigFile = ps.join(root, './tsconfig.json');
182
+ if (fs.existsSync(tsconfigFile)) {
183
+ const tsconfigContent = fs.readFileSync(tsconfigFile, 'utf8');
184
+ const tsconfig = json5.parse(tsconfigContent);
185
+ const compilerOptions = tsconfig.compilerOptions;
186
+ if (compilerOptions && compilerOptions.baseUrl && compilerOptions.paths) {
187
+ for (const [key, paths] of Object.entries(compilerOptions.paths)) {
188
+ this._moduleOverrides[key] = (0, utils_1.formatPath)(ps.join(ps.dirname(tsconfigFile), compilerOptions.baseUrl, paths[0]));
222
189
  }
223
190
  }
224
- this._virtual2code['internal:constants'] = constantManager.exportStaticConstants({
225
- platform,
226
- mode,
227
- flags: flagConfig
228
- });
229
- this._virtual2code[this._fieldDecoratorHelper.getModuleName()] = this._fieldDecoratorHelper.genModuleSource();
230
- for (const virtualName in this._virtual2code) {
231
- this._virtualOverrides[virtualName] = (0, utils_1.formatPath)(ps.join(root, '__virtual__', virtualName.replace(/:/g, '_'))) + '.ts';
232
- }
191
+ }
192
+ this._virtual2code['internal:constants'] = constantManager.exportStaticConstants({
193
+ platform,
194
+ mode,
195
+ flags: flagConfig
233
196
  });
197
+ this._virtual2code[this._fieldDecoratorHelper.getModuleName()] = this._fieldDecoratorHelper.genModuleSource();
198
+ for (const virtualName in this._virtual2code) {
199
+ this._virtualOverrides[virtualName] = (0, utils_1.formatPath)(ps.join(root, '__virtual__', virtualName.replace(/:/g, '_'))) + '.ts';
200
+ }
234
201
  }
235
- _handleId(idOrSource, importer) {
236
- return __awaiter(this, void 0, void 0, function* () {
237
- const resolvedId = yield this._resolve(idOrSource, importer);
238
- if (typeof resolvedId === 'undefined') {
239
- throw new Error(`Cannot resolve module: ${idOrSource} ${importer ? `in file ${importer}` : ''}`);
240
- }
241
- // In case circular reference
242
- if (this._handledCache[resolvedId]) {
243
- return;
244
- }
245
- this._handledCache[resolvedId] = true;
246
- const code = yield this._load(resolvedId);
247
- if (typeof code === 'undefined') {
248
- throw new Error(`Cannot load module: ${resolvedId} ${importer ? `in file ${importer}` : ''}`);
249
- }
250
- const overrideId = this._getOverrideId(idOrSource, importer);
251
- // handle output file
252
- let file = overrideId || resolvedId;
253
- if (file.endsWith('.json')) {
254
- file = file.slice(0, -5) + '.ts';
255
- }
256
- if (this._buildResult[file]) {
257
- // skip cached file
258
- return this._buildResult[file];
259
- }
260
- const depIdList = this._getDepIdList(file, code);
261
- // we handle the dep module first, because we need to get the resolved dep id to transform the import specifier in current module.
262
- for (const depId of depIdList) {
263
- yield this._handleId(depId, file);
264
- }
265
- const transformResult = yield this._transform(resolvedId, code);
266
- const handleResult = this._buildResult[file] = {
267
- code: transformResult.code,
268
- file,
269
- originalId: idOrSource,
270
- resolvedId,
271
- map: transformResult.map
272
- };
273
- return handleResult;
274
- });
202
+ async _handleId(idOrSource, importer) {
203
+ const resolvedId = await this._resolve(idOrSource, importer);
204
+ if (typeof resolvedId === 'undefined') {
205
+ throw new Error(`Cannot resolve module: ${idOrSource} ${importer ? `in file ${importer}` : ''}`);
206
+ }
207
+ // In case circular reference
208
+ if (this._handledCache[resolvedId]) {
209
+ return;
210
+ }
211
+ this._handledCache[resolvedId] = true;
212
+ const code = await this._load(resolvedId);
213
+ if (typeof code === 'undefined') {
214
+ throw new Error(`Cannot load module: ${resolvedId} ${importer ? `in file ${importer}` : ''}`);
215
+ }
216
+ const overrideId = this._getOverrideId(idOrSource, importer);
217
+ // handle output file
218
+ let file = overrideId || resolvedId;
219
+ if (file.endsWith('.json')) {
220
+ file = file.slice(0, -5) + '.ts';
221
+ }
222
+ if (this._buildResult[file]) {
223
+ // skip cached file
224
+ return this._buildResult[file];
225
+ }
226
+ const depIdList = this._getDepIdList(file, code);
227
+ // we handle the dep module first, because we need to get the resolved dep id to transform the import specifier in current module.
228
+ for (const depId of depIdList) {
229
+ await this._handleId(depId, file);
230
+ }
231
+ const transformResult = await this._transform(resolvedId, code);
232
+ const handleResult = this._buildResult[file] = {
233
+ code: transformResult.code,
234
+ file,
235
+ originalId: idOrSource,
236
+ resolvedId,
237
+ map: transformResult.map
238
+ };
239
+ return handleResult;
275
240
  }
276
241
  _getOverrideId(id, importer) {
277
242
  var _a;
@@ -298,30 +263,28 @@ class EngineBuilder {
298
263
  }
299
264
  return overrideId;
300
265
  }
301
- _resolve(id, importer) {
266
+ async _resolve(id, importer) {
302
267
  var _a, _b;
303
- return __awaiter(this, void 0, void 0, function* () {
304
- for (const p of this._plugins) {
305
- const resolvedId = yield (_a = p.resolve) === null || _a === void 0 ? void 0 : _a.call(p, id, importer);
306
- if (resolvedId) {
307
- return resolvedId;
308
- }
268
+ for (const p of this._plugins) {
269
+ const resolvedId = await ((_a = p.resolve) === null || _a === void 0 ? void 0 : _a.call(p, id, importer));
270
+ if (resolvedId) {
271
+ return resolvedId;
309
272
  }
310
- if (!importer) {
311
- return id; // entry
312
- } else if (id in this._virtualOverrides) {
313
- return id; // virtual module does not have real fs path
314
- } else if (id in this._moduleOverrides) {
315
- return this._moduleOverrides[id];
316
- } else if (ps.isAbsolute(id)) {
317
- return id;
318
- } else {
319
- const resolved = this._resolveRelative(id, importer);
320
- if (resolved) {
321
- return (_b = this._moduleOverrides[resolved]) !== null && _b !== void 0 ? _b : resolved;
322
- }
273
+ }
274
+ if (!importer) {
275
+ return id; // entry
276
+ } else if (id in this._virtualOverrides) {
277
+ return id; // virtual module does not have real fs path
278
+ } else if (id in this._moduleOverrides) {
279
+ return this._moduleOverrides[id];
280
+ } else if (ps.isAbsolute(id)) {
281
+ return id;
282
+ } else {
283
+ const resolved = this._resolveRelative(id, importer);
284
+ if (resolved) {
285
+ return (_b = this._moduleOverrides[resolved]) !== null && _b !== void 0 ? _b : resolved;
323
286
  }
324
- });
287
+ }
325
288
  }
326
289
  _resolveRelative(id, importer) {
327
290
  const file = (0, utils_1.formatPath)(ps.join(ps.dirname(importer), id));
@@ -339,25 +302,23 @@ class EngineBuilder {
339
302
  }
340
303
  }
341
304
  }
342
- _load(id) {
305
+ async _load(id) {
343
306
  var _a;
344
- return __awaiter(this, void 0, void 0, function* () {
345
- for (const p of this._plugins) {
346
- const loadedCode = yield (_a = p.load) === null || _a === void 0 ? void 0 : _a.call(p, id);
347
- if (loadedCode) {
348
- return loadedCode;
349
- }
350
- }
351
- if (fs.existsSync(id)) {
352
- let code = fs.readFileSync(id, 'utf8');
353
- if (id.endsWith('.json')) {
354
- code = `export default ${code};`;
355
- }
356
- return code;
357
- } else if (this._virtualOverrides[id]) {
358
- return this._virtual2code[id];
307
+ for (const p of this._plugins) {
308
+ const loadedCode = await ((_a = p.load) === null || _a === void 0 ? void 0 : _a.call(p, id));
309
+ if (loadedCode) {
310
+ return loadedCode;
359
311
  }
360
- });
312
+ }
313
+ if (fs.existsSync(id)) {
314
+ let code = fs.readFileSync(id, 'utf8');
315
+ if (id.endsWith('.json')) {
316
+ code = `export default ${code};`;
317
+ }
318
+ return code;
319
+ } else if (this._virtualOverrides[id]) {
320
+ return this._virtual2code[id];
321
+ }
361
322
  }
362
323
  _getDepIdList(file, code) {
363
324
  let depIdList = [];
@@ -410,231 +371,229 @@ class EngineBuilder {
410
371
  depIdList = depIdList.filter((id, index) => depIdList.indexOf(id) === index);
411
372
  return depIdList;
412
373
  }
413
- _transform(file, code) {
414
- return __awaiter(this, void 0, void 0, function* () {
415
- file = (0, utils_1.formatPath)(file);
416
- (0, utils_1.asserts)(!file.includes('\\'), 'We should use posix path');
417
- for (const ex of this._excludeTransform) {
418
- if (ex.test(file)) {
419
- return {
420
- code
421
- };
422
- }
374
+ async _transform(file, code) {
375
+ file = (0, utils_1.formatPath)(file);
376
+ (0, utils_1.asserts)(!file.includes('\\'), 'We should use posix path');
377
+ for (const ex of this._excludeTransform) {
378
+ if (ex.test(file)) {
379
+ return {
380
+ code
381
+ };
423
382
  }
424
- let needFieldHelperModule = false;
425
- const importExportVisitor = path => {
426
- // @ts-expect-error TODO: fix type
427
- const source = path.node.source;
428
- if (source) {
429
- const specifier = source.value;
430
- // transform import/export declaration if needed
431
- const overrideId = this._getOverrideId(specifier, file);
432
- if (overrideId) {
433
- let relativePath = (0, utils_1.formatPath)(ps.relative(ps.dirname(file), overrideId));
434
- if (!relativePath.startsWith('.')) {
435
- relativePath = './' + relativePath;
436
- }
437
- if (ps.extname(relativePath) === '.ts') {
438
- relativePath = relativePath.slice(0, -3); // remove '.ts'
439
- }
440
-
441
- traverse(path.node, {
442
- StringLiteral(path) {
443
- path.replaceWith(babel.types.stringLiteral(relativePath));
444
- path.skip();
445
- }
446
- }, path.scope);
383
+ }
384
+ let needFieldHelperModule = false;
385
+ const importExportVisitor = path => {
386
+ // @ts-expect-error TODO: fix type
387
+ const source = path.node.source;
388
+ if (source) {
389
+ const specifier = source.value;
390
+ // transform import/export declaration if needed
391
+ const overrideId = this._getOverrideId(specifier, file);
392
+ if (overrideId) {
393
+ let relativePath = (0, utils_1.formatPath)(ps.relative(ps.dirname(file), overrideId));
394
+ if (!relativePath.startsWith('.')) {
395
+ relativePath = './' + relativePath;
447
396
  }
448
- }
449
- const importExportSpecifier = path => {
450
- const name = path.node.local.name;
451
- const alias = this._renameMap[name];
452
- if (alias) {
453
- path.replaceWith(babel.types.exportSpecifier(babel.types.identifier(alias), babel.types.identifier(alias)));
397
+ if (ps.extname(relativePath) === '.ts') {
398
+ relativePath = relativePath.slice(0, -3); // remove '.ts'
454
399
  }
455
- };
456
- path.traverse({
457
- ExportSpecifier: importExportSpecifier,
458
- ImportSpecifier: importExportSpecifier
459
- });
400
+
401
+ traverse(path.node, {
402
+ StringLiteral(path) {
403
+ path.replaceWith(babel.types.stringLiteral(relativePath));
404
+ path.skip();
405
+ }
406
+ }, path.scope);
407
+ }
408
+ }
409
+ const importExportSpecifier = path => {
410
+ const name = path.node.local.name;
411
+ const alias = this._renameMap[name];
412
+ if (alias) {
413
+ path.replaceWith(babel.types.exportSpecifier(babel.types.identifier(alias), babel.types.identifier(alias)));
414
+ }
460
415
  };
461
- // eslint-disable-next-line @typescript-eslint/no-this-alias
462
- const self = this;
463
- const transformResult = babel.transformSync(code, {
464
- configFile: false,
465
- plugins: [[pluginSyntaxTS], [syntaxDecorators, {
466
- version: '2018-09',
467
- decoratorsBeforeExport: true
468
- }], [() => {
469
- return {
470
- name: 'custom-transform',
471
- pre(file) {
472
- // eslint-disable-next-line @typescript-eslint/no-this-alias
473
- const pluginPass = this;
474
- traverse(file.ast, {
475
- ClassProperty(path) {
476
- const decoratorsPath = path.get('decorators');
477
- if (Array.isArray(decoratorsPath)) {
478
- const propertyValuePath = path.get('value');
479
- const helperIdentifier = self._fieldDecoratorHelper.addHelper(pluginPass.file);
480
- needFieldHelperModule = true;
481
- decoratorsPath.forEach(decPath => {
482
- const expPath = decPath.get('expression');
483
- const type = expPath.node.type;
484
- if (type === 'CallExpression') {
485
- const decName = expPath.node.callee.name;
486
- const args = expPath.node.arguments;
487
- decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [t.identifier(decName), propertyValuePath.node ? t.arrowFunctionExpression([], propertyValuePath.node) : t.nullLiteral(), ...args])));
488
- } else if (type === 'Identifier') {
489
- const decName = expPath.node.name;
490
- decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [t.identifier(decName), propertyValuePath.node ? t.arrowFunctionExpression([], propertyValuePath.node) : t.nullLiteral()])));
416
+ path.traverse({
417
+ ExportSpecifier: importExportSpecifier,
418
+ ImportSpecifier: importExportSpecifier
419
+ });
420
+ };
421
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
422
+ const self = this;
423
+ const transformResult = babel.transformSync(code, {
424
+ configFile: false,
425
+ plugins: [[pluginSyntaxTS], [syntaxDecorators, {
426
+ version: '2018-09',
427
+ decoratorsBeforeExport: true
428
+ }], [() => {
429
+ return {
430
+ name: 'custom-transform',
431
+ pre(file) {
432
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
433
+ const pluginPass = this;
434
+ traverse(file.ast, {
435
+ ClassProperty(path) {
436
+ const decoratorsPath = path.get('decorators');
437
+ if (Array.isArray(decoratorsPath)) {
438
+ const propertyValuePath = path.get('value');
439
+ const helperIdentifier = self._fieldDecoratorHelper.addHelper(pluginPass.file);
440
+ needFieldHelperModule = true;
441
+ decoratorsPath.forEach(decPath => {
442
+ const expPath = decPath.get('expression');
443
+ const type = expPath.node.type;
444
+ if (type === 'CallExpression') {
445
+ const decName = expPath.node.callee.name;
446
+ const args = expPath.node.arguments;
447
+ decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [t.identifier(decName), propertyValuePath.node ? t.arrowFunctionExpression([], propertyValuePath.node) : t.nullLiteral(), ...args])));
448
+ } else if (type === 'Identifier') {
449
+ const decName = expPath.node.name;
450
+ decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [t.identifier(decName), propertyValuePath.node ? t.arrowFunctionExpression([], propertyValuePath.node) : t.nullLiteral()])));
451
+ }
452
+ });
453
+ }
454
+ }
455
+ });
456
+ },
457
+ visitor: {
458
+ ImportDeclaration: importExportVisitor,
459
+ ExportDeclaration: importExportVisitor,
460
+ // TODO: here we rename class Rect and Path
461
+ CallExpression: path => {
462
+ if (path.node.callee.type === 'MemberExpression') {
463
+ const memberExpressionPath = path.get('callee');
464
+ const objectPath = memberExpressionPath.get('object');
465
+ const name = objectPath.node.name;
466
+ const alias = self._renameMap[name];
467
+ if (typeof alias === 'string' && path.node.callee.object.type === 'Identifier') {
468
+ objectPath.replaceWith(t.identifier(alias));
469
+ }
470
+ // TODO: for now, OH doesn't support standard console interface,
471
+ // so we need to ignore the type checking for console call expressions.
472
+ else if (name === 'console') {
473
+ path.node.leadingComments = [{
474
+ type: 'CommentLine',
475
+ value: ' @ts-ignore'
476
+ }];
477
+ }
478
+ } else if (path.node.callee.type === 'Import') {
479
+ // TODO: for now, we transform `import('./xxx/xxx.js')` into `window.__cc_module_context__.import('./xxx/xxx.js')`
480
+ // we need to support import(`project://xxx`) in the future.
481
+ path.replaceWith(t.callExpression(t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('__cc_module_context__')), t.identifier('import')), path.node.arguments));
482
+ const arg0 = path.node.arguments[0];
483
+ if (arg0.type === 'StringLiteral') {
484
+ const specifier = arg0.value;
485
+ // transform import/export declaration if needed
486
+ const overrideId = this._getOverrideId(specifier, file);
487
+ if (overrideId) {
488
+ let relativePath = (0, utils_1.formatPath)(ps.relative(ps.dirname(file), overrideId));
489
+ if (!relativePath.startsWith('.')) {
490
+ relativePath = './' + relativePath;
491
+ }
492
+ if (ps.extname(relativePath) === '.ts') {
493
+ relativePath = relativePath.slice(0, -3); // remove '.ts'
494
+ }
495
+
496
+ traverse(path.node, {
497
+ StringLiteral(path) {
498
+ path.replaceWith(babel.types.stringLiteral(relativePath));
499
+ path.skip();
491
500
  }
492
- });
501
+ }, path.scope);
493
502
  }
494
503
  }
495
- });
504
+ }
496
505
  },
497
- visitor: {
498
- ImportDeclaration: importExportVisitor,
499
- ExportDeclaration: importExportVisitor,
500
- // TODO: here we rename class Rect and Path
501
- CallExpression: path => {
502
- if (path.node.callee.type === 'MemberExpression') {
503
- const memberExpressionPath = path.get('callee');
504
- const objectPath = memberExpressionPath.get('object');
505
- const name = objectPath.node.name;
506
- const alias = self._renameMap[name];
507
- if (typeof alias === 'string' && path.node.callee.object.type === 'Identifier') {
508
- objectPath.replaceWith(t.identifier(alias));
509
- }
510
- // TODO: for now, OH doesn't support standard console interface,
511
- // so we need to ignore the type checking for console call expressions.
512
- else if (name === 'console') {
513
- path.node.leadingComments = [{
514
- type: 'CommentLine',
515
- value: ' @ts-ignore'
516
- }];
517
- }
518
- } else if (path.node.callee.type === 'Import') {
519
- // TODO: for now, we transform `import('./xxx/xxx.js')` into `window.__cc_module_context__.import('./xxx/xxx.js')`
520
- // we need to support import(`project://xxx`) in the future.
521
- path.replaceWith(t.callExpression(t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('__cc_module_context__')), t.identifier('import')), path.node.arguments));
522
- const arg0 = path.node.arguments[0];
523
- if (arg0.type === 'StringLiteral') {
524
- const specifier = arg0.value;
525
- // transform import/export declaration if needed
526
- const overrideId = this._getOverrideId(specifier, file);
527
- if (overrideId) {
528
- let relativePath = (0, utils_1.formatPath)(ps.relative(ps.dirname(file), overrideId));
529
- if (!relativePath.startsWith('.')) {
530
- relativePath = './' + relativePath;
531
- }
532
- if (ps.extname(relativePath) === '.ts') {
533
- relativePath = relativePath.slice(0, -3); // remove '.ts'
534
- }
535
-
536
- traverse(path.node, {
537
- StringLiteral(path) {
538
- path.replaceWith(babel.types.stringLiteral(relativePath));
539
- path.skip();
540
- }
541
- }, path.scope);
542
- }
543
- }
506
+ TSImportType: path => {
507
+ const specifier = path.node.argument.value;
508
+ // transform import/export declaration if needed
509
+ const overrideId = this._getOverrideId(specifier, file);
510
+ if (overrideId) {
511
+ let relativePath = (0, utils_1.formatPath)(ps.relative(ps.dirname(file), overrideId));
512
+ if (!relativePath.startsWith('.')) {
513
+ relativePath = './' + relativePath;
514
+ }
515
+ if (ps.extname(relativePath) === '.ts') {
516
+ relativePath = relativePath.slice(0, -3); // remove '.ts'
544
517
  }
545
- },
546
- TSImportType: path => {
547
- const specifier = path.node.argument.value;
548
- // transform import/export declaration if needed
549
- const overrideId = this._getOverrideId(specifier, file);
550
- if (overrideId) {
551
- let relativePath = (0, utils_1.formatPath)(ps.relative(ps.dirname(file), overrideId));
552
- if (!relativePath.startsWith('.')) {
553
- relativePath = './' + relativePath;
554
- }
555
- if (ps.extname(relativePath) === '.ts') {
556
- relativePath = relativePath.slice(0, -3); // remove '.ts'
557
- }
558
518
 
559
- traverse(path.node, {
560
- StringLiteral(path) {
561
- path.replaceWith(babel.types.stringLiteral(relativePath));
562
- path.skip();
563
- }
564
- }, path.scope);
519
+ traverse(path.node, {
520
+ StringLiteral(path) {
521
+ path.replaceWith(babel.types.stringLiteral(relativePath));
522
+ path.skip();
523
+ }
524
+ }, path.scope);
525
+ }
526
+ },
527
+ ClassDeclaration(path) {
528
+ const idPath = path.get('id');
529
+ const name = idPath.node.name;
530
+ const alias = self._renameMap[name];
531
+ if (typeof alias === 'string') {
532
+ idPath.replaceWith(t.identifier(alias));
533
+ }
534
+ },
535
+ NewExpression(path) {
536
+ const calleePath = path.get('callee');
537
+ // @ts-expect-error TODO: fix type
538
+ const name = calleePath.node.name;
539
+ if (name) {
540
+ const alias = self._renameMap[name];
541
+ if (typeof alias === 'string') {
542
+ calleePath.replaceWith(t.identifier(alias));
565
543
  }
566
- },
567
- ClassDeclaration(path) {
568
- const idPath = path.get('id');
569
- const name = idPath.node.name;
544
+ }
545
+ },
546
+ TSTypeAnnotation(path) {
547
+ // @ts-expect-error TODO: fix type
548
+ const typeName = path.node.typeAnnotation.typeName;
549
+ const childPath = path.get('typeAnnotation');
550
+ if (typeName) {
551
+ const name = typeName.name;
570
552
  const alias = self._renameMap[name];
571
553
  if (typeof alias === 'string') {
572
- idPath.replaceWith(t.identifier(alias));
554
+ path.replaceWith(t.tsTypeAnnotation({
555
+ type: 'TSExpressionWithTypeArguments',
556
+ expression: t.identifier(alias)
557
+ }));
573
558
  }
574
- },
575
- NewExpression(path) {
576
- const calleePath = path.get('callee');
577
- // @ts-expect-error TODO: fix type
578
- const name = calleePath.node.name;
579
- if (name) {
580
- const alias = self._renameMap[name];
581
- if (typeof alias === 'string') {
582
- calleePath.replaceWith(t.identifier(alias));
583
- }
559
+ } else if (childPath.type === 'TSLiteralType') {
560
+ const literalPath = childPath.get('literal');
561
+ if (literalPath.type === 'TemplateLiteral') {
562
+ path.replaceWith(t.tsTypeAnnotation(t.tsStringKeyword()));
584
563
  }
585
- },
586
- TSTypeAnnotation(path) {
587
- // @ts-expect-error TODO: fix type
588
- const typeName = path.node.typeAnnotation.typeName;
589
- const childPath = path.get('typeAnnotation');
590
- if (typeName) {
591
- const name = typeName.name;
592
- const alias = self._renameMap[name];
593
- if (typeof alias === 'string') {
594
- path.replaceWith(t.tsTypeAnnotation({
595
- type: 'TSExpressionWithTypeArguments',
596
- expression: t.identifier(alias)
597
- }));
564
+ }
565
+ },
566
+ Identifier(path) {
567
+ const name = path.node.name;
568
+ const alias = self._renameMap[name];
569
+ if (typeof alias === 'string') {
570
+ if (path.parent.type === 'ObjectProperty' || path.parent.type === 'TSPropertySignature') {
571
+ if (path.parent.key !== path.node) {
572
+ path.replaceWith(t.identifier(alias));
598
573
  }
599
- } else if (childPath.type === 'TSLiteralType') {
600
- const literalPath = childPath.get('literal');
601
- if (literalPath.type === 'TemplateLiteral') {
602
- path.replaceWith(t.tsTypeAnnotation(t.tsStringKeyword()));
574
+ } else if (path.parent.type === 'MemberExpression' || path.parent.type === 'OptionalMemberExpression') {
575
+ if (path.parent.property !== path.node) {
576
+ path.replaceWith(t.identifier(alias));
603
577
  }
604
- }
605
- },
606
- Identifier(path) {
607
- const name = path.node.name;
608
- const alias = self._renameMap[name];
609
- if (typeof alias === 'string') {
610
- if (path.parent.type === 'ObjectProperty' || path.parent.type === 'TSPropertySignature') {
611
- if (path.parent.key !== path.node) {
612
- path.replaceWith(t.identifier(alias));
613
- }
614
- } else if (path.parent.type === 'MemberExpression' || path.parent.type === 'OptionalMemberExpression') {
615
- if (path.parent.property !== path.node) {
616
- path.replaceWith(t.identifier(alias));
617
- }
618
- } else if (!(path.parent.type === 'ClassMethod' && (path.parent.kind === 'get' || path.parent.kind === 'set' || path.parent.key === path.node)) && path.parent.type !== 'ClassProperty') {
619
- const newIdentifier = t.identifier(alias);
620
- if (path.node.typeAnnotation) {
621
- newIdentifier.typeAnnotation = path.node.typeAnnotation;
622
- }
623
- path.replaceWith(newIdentifier);
578
+ } else if (!(path.parent.type === 'ClassMethod' && (path.parent.kind === 'get' || path.parent.kind === 'set' || path.parent.key === path.node)) && path.parent.type !== 'ClassProperty') {
579
+ const newIdentifier = t.identifier(alias);
580
+ if (path.node.typeAnnotation) {
581
+ newIdentifier.typeAnnotation = path.node.typeAnnotation;
624
582
  }
583
+ path.replaceWith(newIdentifier);
625
584
  }
626
585
  }
627
586
  }
628
- };
629
- }]]
630
- });
631
- if (needFieldHelperModule) {
632
- yield this._handleId(this._fieldDecoratorHelper.getModuleName(), file);
633
- }
634
- return {
635
- code: transformResult === null || transformResult === void 0 ? void 0 : transformResult.code
636
- };
587
+ }
588
+ };
589
+ }]]
637
590
  });
591
+ if (needFieldHelperModule) {
592
+ await this._handleId(this._fieldDecoratorHelper.getModuleName(), file);
593
+ }
594
+ return {
595
+ code: transformResult === null || transformResult === void 0 ? void 0 : transformResult.code
596
+ };
638
597
  }
639
598
  _buildIndex() {
640
599
  const {
@@ -668,47 +627,43 @@ class EngineBuilder {
668
627
  fs.outputFileSync(systemCCFile, systemCCContent, 'utf8');
669
628
  }
670
629
  }
671
- _copyTypes() {
672
- return __awaiter(this, void 0, void 0, function* () {
673
- const {
674
- root,
675
- outDir
676
- } = this._options;
677
- if (!outDir) {
678
- return;
679
- }
680
- let dtsFiles;
681
- try {
682
- const ccAmbientTypesQuery = yield this._requireEngineModules('@types/cc-ambient-types/query');
683
- dtsFiles = ccAmbientTypesQuery.getDtsFiles();
684
- } catch (e) {
685
- // NOTE: if failed to resolve '@types/cc-ambient-types', we use the legacy way to copy dts files.
686
- dtsFiles = glob_1.glob.sync((0, utils_1.formatPath)(ps.join(root, './@types/**/*.d.ts')));
687
- const externalDtsFiles = glob_1.glob.sync((0, utils_1.formatPath)(ps.join(root, './native/external/**/*.d.ts')));
688
- dtsFiles = dtsFiles.concat(externalDtsFiles);
689
- }
690
- for (const file of dtsFiles) {
691
- const code = fs.readFileSync(file, 'utf8');
692
- const relativePath = ps.relative(root, file);
693
- const targetPath = (0, utils_1.formatPath)(ps.join(outDir, relativePath));
694
- fs.outputFileSync(targetPath, code, 'utf8');
695
- }
696
- // copy lib.dom.d.ts
697
- // we use 4.2 version of typescript
698
- const originalDomDts = (0, utils_1.formatPath)(ps.join(__dirname, '../../../../static/lib.dom.d.ts'));
699
- const targetDomDts = (0, utils_1.formatPath)(ps.join(outDir, '@types/lib.dom.d.ts'));
700
- const code = fs.readFileSync(originalDomDts, 'utf8');
701
- fs.outputFileSync(targetDomDts, code, 'utf8');
702
- });
630
+ async _copyTypes() {
631
+ const {
632
+ root,
633
+ outDir
634
+ } = this._options;
635
+ if (!outDir) {
636
+ return;
637
+ }
638
+ let dtsFiles;
639
+ try {
640
+ const ccAmbientTypesQuery = await this._requireEngineModules('@types/cc-ambient-types/query');
641
+ dtsFiles = ccAmbientTypesQuery.getDtsFiles();
642
+ } catch (e) {
643
+ // NOTE: if failed to resolve '@types/cc-ambient-types', we use the legacy way to copy dts files.
644
+ dtsFiles = glob_1.glob.sync((0, utils_1.formatPath)(ps.join(root, './@types/**/*.d.ts')));
645
+ const externalDtsFiles = glob_1.glob.sync((0, utils_1.formatPath)(ps.join(root, './native/external/**/*.d.ts')));
646
+ dtsFiles = dtsFiles.concat(externalDtsFiles);
647
+ }
648
+ for (const file of dtsFiles) {
649
+ const code = fs.readFileSync(file, 'utf8');
650
+ const relativePath = ps.relative(root, file);
651
+ const targetPath = (0, utils_1.formatPath)(ps.join(outDir, relativePath));
652
+ fs.outputFileSync(targetPath, code, 'utf8');
653
+ }
654
+ // copy lib.dom.d.ts
655
+ // we use 4.2 version of typescript
656
+ const originalDomDts = (0, utils_1.formatPath)(ps.join(__dirname, '../../../../static/lib.dom.d.ts'));
657
+ const targetDomDts = (0, utils_1.formatPath)(ps.join(outDir, '@types/lib.dom.d.ts'));
658
+ const code = fs.readFileSync(originalDomDts, 'utf8');
659
+ fs.outputFileSync(targetDomDts, code, 'utf8');
703
660
  }
704
- _requireEngineModules(moduleName) {
705
- return __awaiter(this, void 0, void 0, function* () {
706
- const resolvedPath = yield this._moduleQuery.resolveExport(moduleName);
707
- if (!resolvedPath) {
708
- throw new Error(`Can't resolve engine module: ${moduleName}.`);
709
- }
710
- return require(resolvedPath);
711
- });
661
+ async _requireEngineModules(moduleName) {
662
+ const resolvedPath = await this._moduleQuery.resolveExport(moduleName);
663
+ if (!resolvedPath) {
664
+ throw new Error(`Can't resolve engine module: ${moduleName}.`);
665
+ }
666
+ return require(resolvedPath);
712
667
  }
713
668
  }
714
669
  exports.EngineBuilder = EngineBuilder;