@cocos/ccbuild 1.0.0-alpha.7 → 1.0.0-alpha.9

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 (101) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +14 -14
  3. package/lib/api-builder.d.ts +1 -0
  4. package/lib/api-builder.d.ts.map +1 -0
  5. package/lib/api-builder.js +1 -1
  6. package/lib/build-engine/engine-js/index.d.ts +3 -0
  7. package/lib/build-engine/engine-js/index.d.ts.map +1 -0
  8. package/lib/build-engine/engine-js/index.js +460 -0
  9. package/lib/build-engine/engine-js/index.js.map +1 -0
  10. package/lib/build-engine/engine-js/rollup-plugins/asset-ref.d.ts +37 -0
  11. package/lib/build-engine/engine-js/rollup-plugins/asset-ref.d.ts.map +1 -0
  12. package/lib/build-engine/engine-js/rollup-plugins/asset-ref.js +88 -0
  13. package/lib/build-engine/engine-js/rollup-plugins/asset-ref.js.map +1 -0
  14. package/lib/build-engine/engine-js/rollup-plugins/asset-url.d.ts +8 -0
  15. package/lib/build-engine/engine-js/rollup-plugins/asset-url.d.ts.map +1 -0
  16. package/lib/build-engine/engine-js/rollup-plugins/asset-url.js +93 -0
  17. package/lib/build-engine/engine-js/rollup-plugins/asset-url.js.map +1 -0
  18. package/lib/build-engine/engine-js/rollup-plugins/code-asset.d.ts +29 -0
  19. package/lib/build-engine/engine-js/rollup-plugins/code-asset.d.ts.map +1 -0
  20. package/lib/build-engine/engine-js/rollup-plugins/code-asset.js +136 -0
  21. package/lib/build-engine/engine-js/rollup-plugins/code-asset.js.map +1 -0
  22. package/lib/build-engine/engine-js/rollup-plugins/remove-deprecated-features.d.ts +3 -0
  23. package/lib/build-engine/engine-js/rollup-plugins/remove-deprecated-features.d.ts.map +1 -0
  24. package/lib/build-engine/engine-js/rollup-plugins/remove-deprecated-features.js +38 -0
  25. package/lib/build-engine/engine-js/rollup-plugins/remove-deprecated-features.js.map +1 -0
  26. package/lib/build-engine/engine-js/rollup-plugins/ts-paths.d.ts +5 -0
  27. package/lib/build-engine/engine-js/rollup-plugins/ts-paths.d.ts.map +1 -0
  28. package/lib/build-engine/engine-js/rollup-plugins/ts-paths.js +43 -0
  29. package/lib/build-engine/engine-js/rollup-plugins/ts-paths.js.map +1 -0
  30. package/lib/build-engine/index.d.ts +119 -0
  31. package/lib/build-engine/index.d.ts.map +1 -0
  32. package/lib/build-engine/index.js +125 -0
  33. package/lib/build-engine/index.js.map +1 -0
  34. package/lib/engine-builder.d.ts +54 -46
  35. package/lib/engine-builder.d.ts.map +1 -0
  36. package/lib/engine-builder.js +549 -545
  37. package/lib/engine-builder.js.map +1 -1
  38. package/lib/index.d.ts +5 -1
  39. package/lib/index.d.ts.map +1 -0
  40. package/lib/index.js +34 -5
  41. package/lib/index.js.map +1 -1
  42. package/lib/module-resolver.d.ts +8 -7
  43. package/lib/module-resolver.d.ts.map +1 -0
  44. package/lib/module-resolver.js +28 -28
  45. package/lib/stats-query/config-interface.d.ts +130 -129
  46. package/lib/stats-query/config-interface.d.ts.map +1 -0
  47. package/lib/stats-query/config-interface.js +3 -3
  48. package/lib/stats-query/constant-manager.d.ts +67 -67
  49. package/lib/stats-query/constant-manager.d.ts.map +1 -0
  50. package/lib/stats-query/constant-manager.js +262 -262
  51. package/lib/stats-query/index.d.ts +162 -91
  52. package/lib/stats-query/index.d.ts.map +1 -0
  53. package/lib/stats-query/index.js +527 -259
  54. package/lib/stats-query/index.js.map +1 -1
  55. package/lib/stats-query/path-utils.d.ts +3 -2
  56. package/lib/stats-query/path-utils.d.ts.map +1 -0
  57. package/lib/stats-query/path-utils.js +35 -31
  58. package/lib/stats-query/path-utils.js.map +1 -1
  59. package/lib/transformer/babel.d.ts +6 -0
  60. package/lib/transformer/babel.d.ts.map +1 -0
  61. package/lib/{config-parser.js → transformer/babel.js} +35 -34
  62. package/lib/transformer/babel.js.map +1 -0
  63. package/lib/transformer/index.d.ts +3 -0
  64. package/lib/transformer/index.d.ts.map +1 -0
  65. package/lib/{config-paerser/config-parser.js → transformer/index.js} +29 -34
  66. package/lib/transformer/index.js.map +1 -0
  67. package/lib/transformer.js +6 -6
  68. package/lib/tsdoc-metadata.json +11 -0
  69. package/lib/utils.d.ts +3 -0
  70. package/lib/utils.d.ts.map +1 -0
  71. package/lib/utils.js +15 -0
  72. package/lib/utils.js.map +1 -0
  73. package/package.json +70 -51
  74. package/static/helper-dynamic-constants.txt +12 -12
  75. package/static/helper-global-exporter.txt +8 -8
  76. package/static/lib.dom.d.ts +20227 -20227
  77. package/lib/babel-plugins/transform-virtual-specifier.js +0 -71
  78. package/lib/babel-plugins/transform-virtual-specifier.js.map +0 -1
  79. package/lib/config-interface.js +0 -3
  80. package/lib/config-interface.js.map +0 -1
  81. package/lib/config-paerser/config-interface.js +0 -3
  82. package/lib/config-paerser/config-interface.js.map +0 -1
  83. package/lib/config-paerser/config-parser.js.map +0 -1
  84. package/lib/config-parser/config-interface.js +0 -4
  85. package/lib/config-parser/config-interface.js.map +0 -1
  86. package/lib/config-parser/config-parser.js +0 -37
  87. package/lib/config-parser/config-parser.js.map +0 -1
  88. package/lib/config-parser/constant-interface.js +0 -3
  89. package/lib/config-parser/constant-interface.js.map +0 -1
  90. package/lib/config-parser/constant-manager.js +0 -263
  91. package/lib/config-parser/constant-manager.js.map +0 -1
  92. package/lib/config-parser/index.js +0 -286
  93. package/lib/config-parser/index.js.map +0 -1
  94. package/lib/config-parser/stats-query.js +0 -248
  95. package/lib/config-parser/stats-query.js.map +0 -1
  96. package/lib/config-parser.js.map +0 -1
  97. package/lib/stats-query/constant-interface.js +0 -3
  98. package/lib/stats-query/constant-interface.js.map +0 -1
  99. package/lib/stats-query/stats-query.js +0 -248
  100. package/lib/stats-query/stats-query.js.map +0 -1
  101. package/lib/transformer.d.ts +0 -2
@@ -1,546 +1,550 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
- return new (P || (P = Promise))(function (resolve, reject) {
24
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
- step((generator = generator.apply(thisArg, _arguments || [])).next());
28
- });
29
- };
30
- var __importDefault = (this && this.__importDefault) || function (mod) {
31
- return (mod && mod.__esModule) ? mod : { "default": mod };
32
- };
33
- Object.defineProperty(exports, "__esModule", { value: true });
34
- exports.EngineBuilder = void 0;
35
- const fs = __importStar(require("fs-extra"));
36
- const ps = __importStar(require("path"));
37
- const babel = __importStar(require("@babel/core"));
38
- // @ts-ignore
39
- const plugin_syntax_typescript_1 = __importDefault(require("@babel/plugin-syntax-typescript"));
40
- // @ts-ignore
41
- const plugin_syntax_decorators_1 = __importDefault(require("@babel/plugin-syntax-decorators"));
42
- const traverse_1 = __importDefault(require("@babel/traverse"));
43
- const stats_query_1 = require("./stats-query");
44
- const path_utils_1 = require("./stats-query/path-utils");
45
- const json5 = __importStar(require("json5"));
46
- const eslint_1 = require("eslint");
47
- const dedent_1 = __importDefault(require("dedent"));
48
- const glob_1 = require("glob");
49
- var t = babel.types;
50
- class EngineBuilder {
51
- constructor() {
52
- this._entries = [];
53
- this._entriesForPass2 = new Set();
54
- this._virtual2code = {};
55
- this._feature2NodeModule = {
56
- 'dragon-bones': '@cocos/dragonbones-js',
57
- 'physics-2d-box2d': '@cocos/box2d',
58
- 'physics-cannon': '@cocos/cannon',
59
- 'physics-physx': '@cocos/physx',
60
- 'physics-ammo': '@cocos/bullet',
61
- };
62
- this._nodeModules = [];
63
- this._virtualOverrides = {};
64
- this._buildResult = {};
65
- this._resolveExtension = ['.ts', '.js', '.json']; // not an option
66
- // TODO: for now OH global interface conflict with Rect and Path, struct
67
- // so we need to rename them.
68
- this._renameMap = {
69
- Rect: 'RectAlias',
70
- Path: 'PathAlias',
71
- struct: 'structAlias',
72
- };
73
- }
74
- build(options) {
75
- return __awaiter(this, void 0, void 0, function* () {
76
- const { root } = options;
77
- this._buildResult = {};
78
- const handleIdList = (idList) => {
79
- for (let id of idList) {
80
- const handleResult = this._handleId(id);
81
- this._buildResult[handleResult.file] = handleResult;
82
- }
83
- };
84
- // pass1: build ts for native engine
85
- console.log('[Build Engine]: pass1 - traverse and compile modules');
86
- console.time('pass1');
87
- yield this._initOptions(options);
88
- handleIdList(this._entries);
89
- console.timeEnd('pass1');
90
- // pass2: build web version for jsb type declarations
91
- console.log('[Build Engine]: pass2 - apply jsb interface info');
92
- console.time('pass2');
93
- while (this._entriesForPass2.size !== 0) {
94
- const entries2 = Array.from(this._entriesForPass2);
95
- this._entriesForPass2.clear();
96
- this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
97
- if (!fs.existsSync(k) || !entries2.includes(k)) {
98
- result[k] = v;
99
- }
100
- return result;
101
- }, {});
102
- handleIdList(entries2);
103
- }
104
- console.timeEnd('pass2');
105
- if (options.outDir) {
106
- for (let file in this._buildResult) {
107
- const res = this._buildResult[file];
108
- const output = ps.join(options.outDir, ps.relative(root, file));
109
- fs.outputFileSync(output, res.code, 'utf8');
110
- }
111
- // pass3: post handle to lint import
112
- console.log('[Build Engine]: pass3 - linting import statement');
113
- console.time('pass3');
114
- yield this._lintImport([
115
- path_utils_1.normalizePath(ps.join(options.outDir, '**/*.ts'))
116
- ]);
117
- console.timeEnd('pass3');
118
- this._buildIndex();
119
- yield this._copyTypes();
120
- // this._addNodeModulesDeps(); // TODO: support node modules building
121
- }
122
- return this._buildResult;
123
- });
124
- }
125
- _initOptions(options) {
126
- return __awaiter(this, void 0, void 0, function* () {
127
- this._options = options;
128
- const { root, flagConfig, platform, mode } = options;
129
- const statsQuery = yield stats_query_1.StatsQuery.create(root);
130
- const constantManager = statsQuery.constantManager;
131
- if (options.features) {
132
- const featureUnits = statsQuery.getUnitsOfFeatures(options.features);
133
- this._entries = featureUnits.map(fu => path_utils_1.normalizePath(statsQuery.getFeatureUnitFile(fu)));
134
- options.features.forEach(feature => {
135
- const nodeModule = this._feature2NodeModule[feature];
136
- nodeModule && this._nodeModules.push(nodeModule);
137
- });
138
- }
139
- else {
140
- const featureUnits = statsQuery.getFeatureUnits();
141
- this._entries = featureUnits.map(fu => path_utils_1.normalizePath(statsQuery.getFeatureUnitFile(fu)));
142
- this._nodeModules.push(...Object.values(this._feature2NodeModule));
143
- }
144
- this._buildTimeConstants = constantManager.genBuildTimeConstants({
145
- platform,
146
- mode,
147
- flags: flagConfig,
148
- });
149
- this._moduleOverrides = statsQuery.evaluateModuleOverrides({
150
- mode: options.mode,
151
- platform: options.platform,
152
- buildTimeConstants: this._buildTimeConstants,
153
- });
154
- this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
155
- result[path_utils_1.normalizePath(k)] = path_utils_1.normalizePath(v);
156
- return result;
157
- }, {});
158
- // paths in tsconfig.json
159
- const tsconfigFile = ps.join(root, './tsconfig.json');
160
- if (fs.existsSync(tsconfigFile)) {
161
- const tsconfigContent = fs.readFileSync(tsconfigFile, 'utf8');
162
- const tsconfig = json5.parse(tsconfigContent);
163
- const compilerOptions = tsconfig.compilerOptions;
164
- if (compilerOptions && compilerOptions.baseUrl && compilerOptions.paths) {
165
- for (let [key, paths] of Object.entries(compilerOptions.paths)) {
166
- this._moduleOverrides[key] = path_utils_1.normalizePath(ps.join(ps.dirname(tsconfigFile), compilerOptions.baseUrl, paths[0]));
167
- }
168
- }
169
- }
170
- this._virtual2code['internal:constants'] = constantManager.exportStaticConstants({
171
- platform,
172
- mode,
173
- flags: flagConfig,
174
- });
175
- // TODO: resolve node modules
176
- this._virtual2code['@cocos/box2d'] = 'export {}';
177
- this._virtual2code['@cocos/bullet'] = 'export {}';
178
- this._virtual2code['@cocos/cannon'] = 'export {}';
179
- for (let virtualName in this._virtual2code) {
180
- this._virtualOverrides[virtualName] = path_utils_1.normalizePath(ps.join(root, '__virtual__', virtualName.replace(/:/g, '_'))) + '.ts';
181
- }
182
- });
183
- }
184
- _handleId(id, importer) {
185
- const resolvedId = this._resolve(id, importer);
186
- if (typeof resolvedId === 'undefined') {
187
- throw new Error(`Cannot resolve module id: ${id} ${importer ? `in file ${importer}` : ''}`);
188
- }
189
- const code = this._load(resolvedId);
190
- if (typeof code === 'undefined') {
191
- throw new Error(`Cannot load module: ${resolvedId} ${importer ? `in file ${importer}` : ''}`);
192
- }
193
- let overrideId = this._getOverrideId(id, importer);
194
- // handle output file
195
- let file = overrideId || resolvedId;
196
- if (file.endsWith('.json')) {
197
- file = file.slice(0, -5) + '.ts';
198
- }
199
- if (this._buildResult[file]) {
200
- // skip cached file
201
- return this._buildResult[file];
202
- }
203
- const transformResult = this._transform(resolvedId, code);
204
- const handleResult = this._buildResult[file] = {
205
- code: transformResult.code,
206
- file,
207
- originalId: id,
208
- resolvedId,
209
- map: transformResult.map,
210
- };
211
- transformResult.depIdList.forEach(id => {
212
- const handleResult = this._handleId(id, file);
213
- this._buildResult[handleResult.file] = handleResult;
214
- });
215
- return handleResult;
216
- }
217
- _getOverrideId(id, importer) {
218
- let overrideId;
219
- if (id in this._virtualOverrides) {
220
- overrideId = this._virtualOverrides[id];
221
- }
222
- else if (id in this._moduleOverrides) {
223
- overrideId = this._moduleOverrides[id];
224
- }
225
- else if (!ps.isAbsolute(id) && importer) {
226
- const absolutePath = this._resolveRelative(id, importer);
227
- if (absolutePath && this._moduleOverrides[absolutePath] === importer) {
228
- this._entriesForPass2.add(absolutePath); // for next pass
229
- return;
230
- }
231
- if (absolutePath && absolutePath in this._moduleOverrides) {
232
- overrideId = this._moduleOverrides[absolutePath];
233
- }
234
- }
235
- return overrideId;
236
- }
237
- _resolve(id, importer) {
238
- var _a;
239
- if (!importer) {
240
- return id; // entry
241
- }
242
- else if (id in this._virtualOverrides) {
243
- return id; // virtual module does not have real fs path
244
- }
245
- else if (id in this._moduleOverrides) {
246
- return this._moduleOverrides[id];
247
- }
248
- else if (this._nodeModules.includes(id)) {
249
- return id; // node module only use bare specifier as module id
250
- }
251
- else if (ps.isAbsolute(id)) {
252
- return id;
253
- }
254
- else {
255
- const resolved = this._resolveRelative(id, importer);
256
- if (resolved) {
257
- return (_a = this._moduleOverrides[resolved]) !== null && _a !== void 0 ? _a : resolved;
258
- }
259
- }
260
- }
261
- _resolveRelative(id, importer) {
262
- const file = path_utils_1.normalizePath(ps.join(ps.dirname(importer), id));
263
- if (ps.extname(file) && fs.existsSync(file)) {
264
- return file;
265
- }
266
- // resolve extension less
267
- for (const ext of this._resolveExtension) {
268
- const fileExt = file + ext;
269
- const indexExt = path_utils_1.normalizePath(ps.join(file, 'index')) + ext;
270
- if (fs.existsSync(fileExt)) {
271
- return fileExt;
272
- }
273
- else if (fs.existsSync(indexExt)) {
274
- return indexExt;
275
- }
276
- }
277
- }
278
- _load(id) {
279
- if (fs.existsSync(id)) {
280
- let code = fs.readFileSync(id, 'utf8');
281
- if (id.endsWith('.json')) {
282
- code = `export default ${code};`;
283
- }
284
- return code;
285
- }
286
- else if (this._virtualOverrides[id]) {
287
- return this._virtual2code[id];
288
- }
289
- }
290
- _transform(file, code) {
291
- const depIdList = [];
292
- if (ps.extname(file) === '.js') {
293
- const dtsFile = path_utils_1.toExtensionLess(file) + '.d.ts';
294
- if (fs.existsSync(dtsFile)) {
295
- depIdList.push(dtsFile);
296
- }
297
- }
298
- const importExportVisitor = (path) => {
299
- // @ts-ignore
300
- const source = path.node.source;
301
- if (source) {
302
- const specifier = source.value;
303
- // add dependency
304
- if (!this._nodeModules.includes(specifier)) {
305
- // don't load node modules, we post install the modules in OH project
306
- depIdList.push(specifier);
307
- }
308
- // transform import/export declaration if needed
309
- const overrideId = this._getOverrideId(specifier, file);
310
- if (overrideId) {
311
- let relativePath = path_utils_1.normalizePath(ps.relative(ps.dirname(file), overrideId));
312
- if (!relativePath.startsWith('.')) {
313
- relativePath = './' + relativePath;
314
- }
315
- relativePath = relativePath.slice(0, -3); // remove '.ts'
316
- // traverse to transform specifier
317
- traverse_1.default(path.node, {
318
- StringLiteral(path) {
319
- path.replaceWith(babel.types.stringLiteral(relativePath));
320
- path.skip();
321
- },
322
- }, path.scope);
323
- }
324
- }
325
- const importExportSpecifier = (path) => {
326
- const name = path.node.local.name;
327
- const alias = this._renameMap[name];
328
- if (alias) {
329
- path.replaceWith(babel.types.exportSpecifier(babel.types.identifier(alias), babel.types.identifier(alias)));
330
- }
331
- };
332
- path.traverse({
333
- ExportSpecifier: importExportSpecifier,
334
- ImportSpecifier: importExportSpecifier,
335
- });
336
- };
337
- const transformResult = babel.transformSync(code, {
338
- configFile: false,
339
- plugins: [
340
- [plugin_syntax_typescript_1.default],
341
- [plugin_syntax_decorators_1.default, {
342
- version: '2018-09',
343
- decoratorsBeforeExport: true,
344
- }],
345
- [
346
- () => {
347
- return {
348
- name: 'custom-transform',
349
- visitor: {
350
- ImportDeclaration: importExportVisitor,
351
- ExportDeclaration: importExportVisitor,
352
- // TODO: here we rename class Rect and Path
353
- CallExpression: (path) => {
354
- if (path.node.callee.type === 'MemberExpression') {
355
- const memberExpressionPath = path.get('callee');
356
- const objectPath = memberExpressionPath.get('object');
357
- const name = objectPath.node.name;
358
- const alias = this._renameMap[name];
359
- if (typeof alias === 'string' && path.node.callee.object.type === 'Identifier') {
360
- objectPath.replaceWith(t.identifier(alias));
361
- }
362
- // TODO: for now, OH doesn't support standard console interface,
363
- // so we need to ignore the type checking for console call expressions.
364
- else if (name === 'console') {
365
- path.node.leadingComments = [{
366
- type: 'CommentLine',
367
- value: ' @ts-ignore',
368
- }];
369
- }
370
- }
371
- else if (path.node.callee.type === 'Import') {
372
- // TODO: for now, we transform `import('./xxx/xxx.js')` into `window.__cc_module_context__.import('./xxx/xxx.js')`
373
- // we need to support import(`project://xxx`) in the future.
374
- path.replaceWith(t.callExpression(t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('__cc_module_context__')), t.identifier('import')), path.node.arguments));
375
- }
376
- },
377
- ClassDeclaration: (path) => {
378
- const idPath = path.get('id');
379
- const name = idPath.node.name;
380
- const alias = this._renameMap[name];
381
- if (typeof alias === 'string') {
382
- idPath.replaceWith(t.identifier(alias));
383
- }
384
- },
385
- NewExpression: (path) => {
386
- const calleePath = path.get('callee');
387
- // @ts-ignore
388
- const name = calleePath.node.name;
389
- if (name) {
390
- const alias = this._renameMap[name];
391
- if (typeof alias === 'string') {
392
- calleePath.replaceWith(t.identifier(alias));
393
- }
394
- }
395
- },
396
- TSTypeAnnotation: (path) => {
397
- // @ts-ignore
398
- const typeName = path.node.typeAnnotation.typeName;
399
- const childPath = path.get('typeAnnotation');
400
- if (typeName) {
401
- const name = typeName.name;
402
- const alias = this._renameMap[name];
403
- if (typeof alias === 'string') {
404
- path.replaceWith(t.tsTypeAnnotation({
405
- type: 'TSExpressionWithTypeArguments',
406
- expression: t.identifier(alias),
407
- }));
408
- }
409
- }
410
- else if (childPath.type === 'TSLiteralType') {
411
- const literalPath = childPath.get('literal');
412
- if (literalPath.type === 'TemplateLiteral') {
413
- path.replaceWith(t.tsTypeAnnotation(t.tsStringKeyword()));
414
- }
415
- }
416
- },
417
- Identifier: (path) => {
418
- const name = path.node.name;
419
- const alias = this._renameMap[name];
420
- if (typeof alias === 'string') {
421
- if (path.parent.type === 'ObjectProperty' || path.parent.type === 'TSPropertySignature') {
422
- if (path.parent.key !== path.node) {
423
- path.replaceWith(t.identifier(alias));
424
- }
425
- }
426
- else if (path.parent.type === 'MemberExpression' || path.parent.type === 'OptionalMemberExpression') {
427
- if (path.parent.property !== path.node) {
428
- path.replaceWith(t.identifier(alias));
429
- }
430
- }
431
- else if (!(path.parent.type === 'ClassMethod' && (path.parent.kind === 'get' || path.parent.kind === 'set' || path.parent.key === path.node))
432
- && path.parent.type !== 'ClassProperty') {
433
- const newIdentifier = t.identifier(alias);
434
- if (path.node.typeAnnotation) {
435
- newIdentifier.typeAnnotation = path.node.typeAnnotation;
436
- }
437
- path.replaceWith(newIdentifier);
438
- }
439
- }
440
- },
441
- }
442
- };
443
- }
444
- ]
445
- ],
446
- });
447
- return {
448
- code: transformResult === null || transformResult === void 0 ? void 0 : transformResult.code,
449
- depIdList,
450
- };
451
- }
452
- _lintImport(lintFiles, verbose = false) {
453
- return __awaiter(this, void 0, void 0, function* () {
454
- const eslint = new eslint_1.ESLint({ fix: true,
455
- cwd: __dirname,
456
- resolvePluginsRelativeTo: __dirname,
457
- useEslintrc: false,
458
- baseConfig: {
459
- parser: "@typescript-eslint/parser",
460
- plugins: ["@typescript-eslint", "unused-imports"],
461
- rules: {
462
- "@typescript-eslint/consistent-type-imports": "error",
463
- "unused-imports/no-unused-imports": "error",
464
- },
465
- } });
466
- const results = yield eslint.lintFiles(lintFiles);
467
- yield eslint_1.ESLint.outputFixes(results);
468
- if (verbose) {
469
- const formatter = yield eslint.loadFormatter();
470
- const resultText = formatter.format(results);
471
- console.log(resultText);
472
- }
473
- });
474
- }
475
- _buildIndex() {
476
- const { outDir, root } = this._options;
477
- if (outDir) {
478
- const indexFile = path_utils_1.normalizePath(ps.join(outDir, 'index.ts'));
479
- const ccFile = path_utils_1.normalizePath(ps.join(outDir, 'cc.ts'));
480
- const systemCCFile = path_utils_1.normalizePath(ps.join(outDir, 'system-cc.js'));
481
- let indexContent = '';
482
- this._entries.forEach(item => {
483
- const relative = path_utils_1.normalizePath(ps.relative(root, path_utils_1.toExtensionLess(item)));
484
- indexContent += `export * from './${relative}';\n`;
485
- });
486
- const ccContent = dedent_1.default `import * as cc from './index';
487
- // @ts-ignore
488
- window.cc_module = cc;`;
489
- const systemCCContent = dedent_1.default `System.register([], function (exports, module) {
490
- return {
491
- execute: function () {
492
- window.__cc_module_context__ = module;
493
-
494
- exports(window.cc_module);
495
- }
496
- };
497
- });
498
- `;
499
- fs.outputFileSync(indexFile, indexContent, 'utf8');
500
- fs.outputFileSync(ccFile, ccContent, 'utf8');
501
- fs.outputFileSync(systemCCFile, systemCCContent, 'utf8');
502
- }
503
- }
504
- _copyTypes() {
505
- return __awaiter(this, void 0, void 0, function* () {
506
- const { root, outDir } = this._options;
507
- if (!outDir) {
508
- return;
509
- }
510
- const dtsFiles = yield glob_1.glob(path_utils_1.normalizePath(ps.join(root, './@types/**/*.d.ts')));
511
- for (let file of dtsFiles) {
512
- const code = fs.readFileSync(file, 'utf8');
513
- const relativePath = ps.relative(root, file);
514
- const targetPath = path_utils_1.normalizePath(ps.join(outDir, relativePath));
515
- fs.outputFileSync(targetPath, code, 'utf8');
516
- }
517
- // copy lib.dom.d.ts
518
- // we use 4.2 version of typescript
519
- const originalDomDts = path_utils_1.normalizePath(ps.join(__dirname, '../static/lib.dom.d.ts'));
520
- const targetDomDts = path_utils_1.normalizePath(ps.join(outDir, '@types/lib.dom.d.ts'));
521
- const code = fs.readFileSync(originalDomDts, 'utf8');
522
- fs.outputFileSync(targetDomDts, code, 'utf8');
523
- });
524
- }
525
- _addNodeModulesDeps() {
526
- const { outDir } = this._options;
527
- if (!outDir) {
528
- return;
529
- }
530
- const pkgFile = path_utils_1.normalizePath(ps.join(outDir, '..', // src
531
- '..', // cocos
532
- '..', // ets
533
- '..', // main
534
- '..', // src
535
- '..', // entry
536
- 'package.json'));
537
- if (!fs.existsSync(pkgFile)) {
538
- return;
539
- }
540
- const jsonObj = fs.readJSONSync(pkgFile);
541
- console.log(jsonObj);
542
- // TODO
543
- }
544
- }
545
- exports.EngineBuilder = EngineBuilder;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.EngineBuilder = void 0;
39
+ const fs = __importStar(require("fs-extra"));
40
+ const ps = __importStar(require("path"));
41
+ const babel = __importStar(require("@babel/core"));
42
+ // @ts-ignore
43
+ const plugin_syntax_typescript_1 = __importDefault(require("@babel/plugin-syntax-typescript"));
44
+ // @ts-ignore
45
+ const plugin_syntax_decorators_1 = __importDefault(require("@babel/plugin-syntax-decorators"));
46
+ const traverse_1 = __importDefault(require("@babel/traverse"));
47
+ const stats_query_1 = require("./stats-query");
48
+ const path_utils_1 = require("./stats-query/path-utils");
49
+ const json5 = __importStar(require("json5"));
50
+ const eslint_1 = require("eslint");
51
+ const dedent_1 = __importDefault(require("dedent"));
52
+ const glob_1 = require("glob");
53
+ var t = babel.types;
54
+ class EngineBuilder {
55
+ constructor() {
56
+ this._entries = [];
57
+ this._entriesForPass2 = new Set();
58
+ this._virtual2code = {};
59
+ this._feature2NodeModule = {
60
+ 'dragon-bones': '@cocos/dragonbones-js',
61
+ 'physics-2d-box2d': '@cocos/box2d',
62
+ 'physics-cannon': '@cocos/cannon',
63
+ 'physics-physx': '@cocos/physx',
64
+ 'physics-ammo': '@cocos/bullet',
65
+ };
66
+ this._nodeModules = [];
67
+ this._virtualOverrides = {};
68
+ this._buildResult = {};
69
+ this._resolveExtension = ['.ts', '.js', '.json']; // not an option
70
+ // TODO: for now OH global interface conflict with Rect and Path, struct
71
+ // so we need to rename them.
72
+ this._renameMap = {
73
+ Rect: 'RectAlias',
74
+ Path: 'PathAlias',
75
+ struct: 'structAlias',
76
+ };
77
+ }
78
+ build(options) {
79
+ return __awaiter(this, void 0, void 0, function* () {
80
+ const { root } = options;
81
+ this._buildResult = {};
82
+ const handleIdList = (idList) => {
83
+ for (let id of idList) {
84
+ const handleResult = this._handleId(id);
85
+ this._buildResult[handleResult.file] = handleResult;
86
+ }
87
+ };
88
+ // pass1: build ts for native engine
89
+ console.log('[Build Engine]: pass1 - traverse and compile modules');
90
+ console.time('pass1');
91
+ yield this._initOptions(options);
92
+ handleIdList(this._entries);
93
+ console.timeEnd('pass1');
94
+ // pass2: build web version for jsb type declarations
95
+ console.log('[Build Engine]: pass2 - apply jsb interface info');
96
+ console.time('pass2');
97
+ while (this._entriesForPass2.size !== 0) {
98
+ const entries2 = Array.from(this._entriesForPass2);
99
+ this._entriesForPass2.clear();
100
+ this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
101
+ if (!fs.existsSync(k) || !entries2.includes(k)) {
102
+ result[k] = v;
103
+ }
104
+ return result;
105
+ }, {});
106
+ handleIdList(entries2);
107
+ }
108
+ console.timeEnd('pass2');
109
+ if (options.outDir) {
110
+ for (let file in this._buildResult) {
111
+ const res = this._buildResult[file];
112
+ const output = ps.join(options.outDir, ps.relative(root, file));
113
+ fs.outputFileSync(output, res.code, 'utf8');
114
+ }
115
+ // pass3: post handle to lint import
116
+ console.log('[Build Engine]: pass3 - linting import statement');
117
+ console.time('pass3');
118
+ yield this._lintImport([
119
+ (0, path_utils_1.normalizePath)(ps.join(options.outDir, '**/*.ts'))
120
+ ]);
121
+ console.timeEnd('pass3');
122
+ this._buildIndex();
123
+ yield this._copyTypes();
124
+ // this._addNodeModulesDeps(); // TODO: support node modules building
125
+ }
126
+ return this._buildResult;
127
+ });
128
+ }
129
+ _initOptions(options) {
130
+ return __awaiter(this, void 0, void 0, function* () {
131
+ this._options = options;
132
+ const { root, flagConfig, platform, mode } = options;
133
+ const statsQuery = yield stats_query_1.StatsQuery.create(root);
134
+ const constantManager = statsQuery.constantManager;
135
+ if (options.features) {
136
+ const featureUnits = statsQuery.getUnitsOfFeatures(options.features);
137
+ this._entries = featureUnits.map(fu => (0, path_utils_1.normalizePath)(statsQuery.getFeatureUnitFile(fu)));
138
+ options.features.forEach(feature => {
139
+ const nodeModule = this._feature2NodeModule[feature];
140
+ nodeModule && this._nodeModules.push(nodeModule);
141
+ });
142
+ }
143
+ else {
144
+ const featureUnits = statsQuery.getFeatureUnits();
145
+ this._entries = featureUnits.map(fu => (0, path_utils_1.normalizePath)(statsQuery.getFeatureUnitFile(fu)));
146
+ this._nodeModules.push(...Object.values(this._feature2NodeModule));
147
+ }
148
+ this._buildTimeConstants = constantManager.genBuildTimeConstants({
149
+ platform,
150
+ mode,
151
+ flags: flagConfig,
152
+ });
153
+ this._moduleOverrides = statsQuery.evaluateModuleOverrides({
154
+ mode: options.mode,
155
+ platform: options.platform,
156
+ buildTimeConstants: this._buildTimeConstants,
157
+ });
158
+ this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
159
+ result[(0, path_utils_1.normalizePath)(k)] = (0, path_utils_1.normalizePath)(v);
160
+ return result;
161
+ }, {});
162
+ // paths in tsconfig.json
163
+ const tsconfigFile = ps.join(root, './tsconfig.json');
164
+ if (fs.existsSync(tsconfigFile)) {
165
+ const tsconfigContent = fs.readFileSync(tsconfigFile, 'utf8');
166
+ const tsconfig = json5.parse(tsconfigContent);
167
+ const compilerOptions = tsconfig.compilerOptions;
168
+ if (compilerOptions && compilerOptions.baseUrl && compilerOptions.paths) {
169
+ for (let [key, paths] of Object.entries(compilerOptions.paths)) {
170
+ this._moduleOverrides[key] = (0, path_utils_1.normalizePath)(ps.join(ps.dirname(tsconfigFile), compilerOptions.baseUrl, paths[0]));
171
+ }
172
+ }
173
+ }
174
+ this._virtual2code['internal:constants'] = constantManager.exportStaticConstants({
175
+ platform,
176
+ mode,
177
+ flags: flagConfig,
178
+ });
179
+ // TODO: resolve node modules
180
+ this._virtual2code['@cocos/box2d'] = 'export {}';
181
+ this._virtual2code['@cocos/bullet'] = 'export {}';
182
+ this._virtual2code['@cocos/cannon'] = 'export {}';
183
+ for (let virtualName in this._virtual2code) {
184
+ this._virtualOverrides[virtualName] = (0, path_utils_1.normalizePath)(ps.join(root, '__virtual__', virtualName.replace(/:/g, '_'))) + '.ts';
185
+ }
186
+ });
187
+ }
188
+ _handleId(id, importer) {
189
+ const resolvedId = this._resolve(id, importer);
190
+ if (typeof resolvedId === 'undefined') {
191
+ throw new Error(`Cannot resolve module id: ${id} ${importer ? `in file ${importer}` : ''}`);
192
+ }
193
+ const code = this._load(resolvedId);
194
+ if (typeof code === 'undefined') {
195
+ throw new Error(`Cannot load module: ${resolvedId} ${importer ? `in file ${importer}` : ''}`);
196
+ }
197
+ let overrideId = this._getOverrideId(id, importer);
198
+ // handle output file
199
+ let file = overrideId || resolvedId;
200
+ if (file.endsWith('.json')) {
201
+ file = file.slice(0, -5) + '.ts';
202
+ }
203
+ if (this._buildResult[file]) {
204
+ // skip cached file
205
+ return this._buildResult[file];
206
+ }
207
+ const transformResult = this._transform(resolvedId, code);
208
+ const handleResult = this._buildResult[file] = {
209
+ code: transformResult.code,
210
+ file,
211
+ originalId: id,
212
+ resolvedId,
213
+ map: transformResult.map,
214
+ };
215
+ transformResult.depIdList.forEach(id => {
216
+ const handleResult = this._handleId(id, file);
217
+ this._buildResult[handleResult.file] = handleResult;
218
+ });
219
+ return handleResult;
220
+ }
221
+ _getOverrideId(id, importer) {
222
+ let overrideId;
223
+ if (id in this._virtualOverrides) {
224
+ overrideId = this._virtualOverrides[id];
225
+ }
226
+ else if (id in this._moduleOverrides) {
227
+ overrideId = this._moduleOverrides[id];
228
+ }
229
+ else if (!ps.isAbsolute(id) && importer) {
230
+ const absolutePath = this._resolveRelative(id, importer);
231
+ if (absolutePath && this._moduleOverrides[absolutePath] === importer) {
232
+ this._entriesForPass2.add(absolutePath); // for next pass
233
+ return;
234
+ }
235
+ if (absolutePath && absolutePath in this._moduleOverrides) {
236
+ overrideId = this._moduleOverrides[absolutePath];
237
+ }
238
+ }
239
+ return overrideId;
240
+ }
241
+ _resolve(id, importer) {
242
+ var _a;
243
+ if (!importer) {
244
+ return id; // entry
245
+ }
246
+ else if (id in this._virtualOverrides) {
247
+ return id; // virtual module does not have real fs path
248
+ }
249
+ else if (id in this._moduleOverrides) {
250
+ return this._moduleOverrides[id];
251
+ }
252
+ else if (this._nodeModules.includes(id)) {
253
+ return id; // node module only use bare specifier as module id
254
+ }
255
+ else if (ps.isAbsolute(id)) {
256
+ return id;
257
+ }
258
+ else {
259
+ const resolved = this._resolveRelative(id, importer);
260
+ if (resolved) {
261
+ return (_a = this._moduleOverrides[resolved]) !== null && _a !== void 0 ? _a : resolved;
262
+ }
263
+ }
264
+ }
265
+ _resolveRelative(id, importer) {
266
+ const file = (0, path_utils_1.normalizePath)(ps.join(ps.dirname(importer), id));
267
+ if (ps.extname(file) && fs.existsSync(file)) {
268
+ return file;
269
+ }
270
+ // resolve extension less
271
+ for (const ext of this._resolveExtension) {
272
+ const fileExt = file + ext;
273
+ const indexExt = (0, path_utils_1.normalizePath)(ps.join(file, 'index')) + ext;
274
+ if (fs.existsSync(fileExt)) {
275
+ return fileExt;
276
+ }
277
+ else if (fs.existsSync(indexExt)) {
278
+ return indexExt;
279
+ }
280
+ }
281
+ }
282
+ _load(id) {
283
+ if (fs.existsSync(id)) {
284
+ let code = fs.readFileSync(id, 'utf8');
285
+ if (id.endsWith('.json')) {
286
+ code = `export default ${code};`;
287
+ }
288
+ return code;
289
+ }
290
+ else if (this._virtualOverrides[id]) {
291
+ return this._virtual2code[id];
292
+ }
293
+ }
294
+ _transform(file, code) {
295
+ const depIdList = [];
296
+ if (ps.extname(file) === '.js') {
297
+ const dtsFile = (0, path_utils_1.toExtensionLess)(file) + '.d.ts';
298
+ if (fs.existsSync(dtsFile)) {
299
+ depIdList.push(dtsFile);
300
+ }
301
+ }
302
+ const importExportVisitor = (path) => {
303
+ // @ts-ignore
304
+ const source = path.node.source;
305
+ if (source) {
306
+ const specifier = source.value;
307
+ // add dependency
308
+ if (!this._nodeModules.includes(specifier)) {
309
+ // don't load node modules, we post install the modules in OH project
310
+ depIdList.push(specifier);
311
+ }
312
+ // transform import/export declaration if needed
313
+ const overrideId = this._getOverrideId(specifier, file);
314
+ if (overrideId) {
315
+ let relativePath = (0, path_utils_1.normalizePath)(ps.relative(ps.dirname(file), overrideId));
316
+ if (!relativePath.startsWith('.')) {
317
+ relativePath = './' + relativePath;
318
+ }
319
+ relativePath = relativePath.slice(0, -3); // remove '.ts'
320
+ // traverse to transform specifier
321
+ (0, traverse_1.default)(path.node, {
322
+ StringLiteral(path) {
323
+ path.replaceWith(babel.types.stringLiteral(relativePath));
324
+ path.skip();
325
+ },
326
+ }, path.scope);
327
+ }
328
+ }
329
+ const importExportSpecifier = (path) => {
330
+ const name = path.node.local.name;
331
+ const alias = this._renameMap[name];
332
+ if (alias) {
333
+ path.replaceWith(babel.types.exportSpecifier(babel.types.identifier(alias), babel.types.identifier(alias)));
334
+ }
335
+ };
336
+ path.traverse({
337
+ ExportSpecifier: importExportSpecifier,
338
+ ImportSpecifier: importExportSpecifier,
339
+ });
340
+ };
341
+ const transformResult = babel.transformSync(code, {
342
+ configFile: false,
343
+ plugins: [
344
+ [plugin_syntax_typescript_1.default],
345
+ [plugin_syntax_decorators_1.default, {
346
+ version: '2018-09',
347
+ decoratorsBeforeExport: true,
348
+ }],
349
+ [
350
+ () => {
351
+ return {
352
+ name: 'custom-transform',
353
+ visitor: {
354
+ ImportDeclaration: importExportVisitor,
355
+ ExportDeclaration: importExportVisitor,
356
+ // TODO: here we rename class Rect and Path
357
+ CallExpression: (path) => {
358
+ if (path.node.callee.type === 'MemberExpression') {
359
+ const memberExpressionPath = path.get('callee');
360
+ const objectPath = memberExpressionPath.get('object');
361
+ const name = objectPath.node.name;
362
+ const alias = this._renameMap[name];
363
+ if (typeof alias === 'string' && path.node.callee.object.type === 'Identifier') {
364
+ objectPath.replaceWith(t.identifier(alias));
365
+ }
366
+ // TODO: for now, OH doesn't support standard console interface,
367
+ // so we need to ignore the type checking for console call expressions.
368
+ else if (name === 'console') {
369
+ path.node.leadingComments = [{
370
+ type: 'CommentLine',
371
+ value: ' @ts-ignore',
372
+ }];
373
+ }
374
+ }
375
+ else if (path.node.callee.type === 'Import') {
376
+ // TODO: for now, we transform `import('./xxx/xxx.js')` into `window.__cc_module_context__.import('./xxx/xxx.js')`
377
+ // we need to support import(`project://xxx`) in the future.
378
+ path.replaceWith(t.callExpression(t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('__cc_module_context__')), t.identifier('import')), path.node.arguments));
379
+ }
380
+ },
381
+ ClassDeclaration: (path) => {
382
+ const idPath = path.get('id');
383
+ const name = idPath.node.name;
384
+ const alias = this._renameMap[name];
385
+ if (typeof alias === 'string') {
386
+ idPath.replaceWith(t.identifier(alias));
387
+ }
388
+ },
389
+ NewExpression: (path) => {
390
+ const calleePath = path.get('callee');
391
+ // @ts-ignore
392
+ const name = calleePath.node.name;
393
+ if (name) {
394
+ const alias = this._renameMap[name];
395
+ if (typeof alias === 'string') {
396
+ calleePath.replaceWith(t.identifier(alias));
397
+ }
398
+ }
399
+ },
400
+ TSTypeAnnotation: (path) => {
401
+ // @ts-ignore
402
+ const typeName = path.node.typeAnnotation.typeName;
403
+ const childPath = path.get('typeAnnotation');
404
+ if (typeName) {
405
+ const name = typeName.name;
406
+ const alias = this._renameMap[name];
407
+ if (typeof alias === 'string') {
408
+ path.replaceWith(t.tsTypeAnnotation({
409
+ type: 'TSExpressionWithTypeArguments',
410
+ expression: t.identifier(alias),
411
+ }));
412
+ }
413
+ }
414
+ else if (childPath.type === 'TSLiteralType') {
415
+ const literalPath = childPath.get('literal');
416
+ if (literalPath.type === 'TemplateLiteral') {
417
+ path.replaceWith(t.tsTypeAnnotation(t.tsStringKeyword()));
418
+ }
419
+ }
420
+ },
421
+ Identifier: (path) => {
422
+ const name = path.node.name;
423
+ const alias = this._renameMap[name];
424
+ if (typeof alias === 'string') {
425
+ if (path.parent.type === 'ObjectProperty' || path.parent.type === 'TSPropertySignature') {
426
+ if (path.parent.key !== path.node) {
427
+ path.replaceWith(t.identifier(alias));
428
+ }
429
+ }
430
+ else if (path.parent.type === 'MemberExpression' || path.parent.type === 'OptionalMemberExpression') {
431
+ if (path.parent.property !== path.node) {
432
+ path.replaceWith(t.identifier(alias));
433
+ }
434
+ }
435
+ else if (!(path.parent.type === 'ClassMethod' && (path.parent.kind === 'get' || path.parent.kind === 'set' || path.parent.key === path.node))
436
+ && path.parent.type !== 'ClassProperty') {
437
+ const newIdentifier = t.identifier(alias);
438
+ if (path.node.typeAnnotation) {
439
+ newIdentifier.typeAnnotation = path.node.typeAnnotation;
440
+ }
441
+ path.replaceWith(newIdentifier);
442
+ }
443
+ }
444
+ },
445
+ }
446
+ };
447
+ }
448
+ ]
449
+ ],
450
+ });
451
+ return {
452
+ code: transformResult === null || transformResult === void 0 ? void 0 : transformResult.code,
453
+ depIdList,
454
+ };
455
+ }
456
+ _lintImport(lintFiles, verbose = false) {
457
+ return __awaiter(this, void 0, void 0, function* () {
458
+ const eslint = new eslint_1.ESLint({ fix: true,
459
+ cwd: __dirname,
460
+ resolvePluginsRelativeTo: __dirname,
461
+ useEslintrc: false,
462
+ baseConfig: {
463
+ parser: "@typescript-eslint/parser",
464
+ plugins: ["@typescript-eslint", "unused-imports"],
465
+ rules: {
466
+ "@typescript-eslint/consistent-type-imports": "error",
467
+ "unused-imports/no-unused-imports": "error",
468
+ },
469
+ } });
470
+ const results = yield eslint.lintFiles(lintFiles);
471
+ yield eslint_1.ESLint.outputFixes(results);
472
+ if (verbose) {
473
+ const formatter = yield eslint.loadFormatter();
474
+ const resultText = formatter.format(results);
475
+ console.log(resultText);
476
+ }
477
+ });
478
+ }
479
+ _buildIndex() {
480
+ const { outDir, root } = this._options;
481
+ if (outDir) {
482
+ const indexFile = (0, path_utils_1.normalizePath)(ps.join(outDir, 'index.ts'));
483
+ const ccFile = (0, path_utils_1.normalizePath)(ps.join(outDir, 'cc.ts'));
484
+ const systemCCFile = (0, path_utils_1.normalizePath)(ps.join(outDir, 'system-cc.js'));
485
+ let indexContent = '';
486
+ this._entries.forEach(item => {
487
+ const relative = (0, path_utils_1.normalizePath)(ps.relative(root, (0, path_utils_1.toExtensionLess)(item)));
488
+ indexContent += `export * from './${relative}';\n`;
489
+ });
490
+ const ccContent = (0, dedent_1.default) `import * as cc from './index';
491
+ // @ts-ignore
492
+ window.cc_module = cc;`;
493
+ const systemCCContent = (0, dedent_1.default) `System.register([], function (exports, module) {
494
+ return {
495
+ execute: function () {
496
+ window.__cc_module_context__ = module;
497
+
498
+ exports(window.cc_module);
499
+ }
500
+ };
501
+ });
502
+ `;
503
+ fs.outputFileSync(indexFile, indexContent, 'utf8');
504
+ fs.outputFileSync(ccFile, ccContent, 'utf8');
505
+ fs.outputFileSync(systemCCFile, systemCCContent, 'utf8');
506
+ }
507
+ }
508
+ _copyTypes() {
509
+ return __awaiter(this, void 0, void 0, function* () {
510
+ const { root, outDir } = this._options;
511
+ if (!outDir) {
512
+ return;
513
+ }
514
+ const dtsFiles = yield (0, glob_1.glob)((0, path_utils_1.normalizePath)(ps.join(root, './@types/**/*.d.ts')));
515
+ for (let file of dtsFiles) {
516
+ const code = fs.readFileSync(file, 'utf8');
517
+ const relativePath = ps.relative(root, file);
518
+ const targetPath = (0, path_utils_1.normalizePath)(ps.join(outDir, relativePath));
519
+ fs.outputFileSync(targetPath, code, 'utf8');
520
+ }
521
+ // copy lib.dom.d.ts
522
+ // we use 4.2 version of typescript
523
+ const originalDomDts = (0, path_utils_1.normalizePath)(ps.join(__dirname, '../static/lib.dom.d.ts'));
524
+ const targetDomDts = (0, path_utils_1.normalizePath)(ps.join(outDir, '@types/lib.dom.d.ts'));
525
+ const code = fs.readFileSync(originalDomDts, 'utf8');
526
+ fs.outputFileSync(targetDomDts, code, 'utf8');
527
+ });
528
+ }
529
+ _addNodeModulesDeps() {
530
+ const { outDir } = this._options;
531
+ if (!outDir) {
532
+ return;
533
+ }
534
+ const pkgFile = (0, path_utils_1.normalizePath)(ps.join(outDir, '..', // src
535
+ '..', // cocos
536
+ '..', // ets
537
+ '..', // main
538
+ '..', // src
539
+ '..', // entry
540
+ 'package.json'));
541
+ if (!fs.existsSync(pkgFile)) {
542
+ return;
543
+ }
544
+ const jsonObj = fs.readJSONSync(pkgFile);
545
+ console.log(jsonObj);
546
+ // TODO
547
+ }
548
+ }
549
+ exports.EngineBuilder = EngineBuilder;
546
550
  //# sourceMappingURL=engine-builder.js.map