@cocos/ccbuild 1.0.0-alpha.8 → 1.0.0

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 (65) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +14 -14
  3. package/lib/api-builder.js +1 -1
  4. package/lib/build-engine/engine-js/index.d.ts +2 -2
  5. package/lib/build-engine/engine-js/index.d.ts.map +1 -1
  6. package/lib/build-engine/engine-js/index.js +458 -459
  7. package/lib/build-engine/engine-js/index.js.map +1 -1
  8. package/lib/build-engine/engine-js/rollup-plugins/asset-ref.d.ts +36 -36
  9. package/lib/build-engine/engine-js/rollup-plugins/asset-ref.js +87 -87
  10. package/lib/build-engine/engine-js/rollup-plugins/asset-ref.js.map +1 -1
  11. package/lib/build-engine/engine-js/rollup-plugins/asset-url.d.ts +7 -7
  12. package/lib/build-engine/engine-js/rollup-plugins/asset-url.js +92 -92
  13. package/lib/build-engine/engine-js/rollup-plugins/asset-url.js.map +1 -1
  14. package/lib/build-engine/engine-js/rollup-plugins/code-asset.d.ts +28 -28
  15. package/lib/build-engine/engine-js/rollup-plugins/code-asset.js +135 -135
  16. package/lib/build-engine/engine-js/rollup-plugins/code-asset.js.map +1 -1
  17. package/lib/build-engine/engine-js/rollup-plugins/remove-deprecated-features.d.ts +2 -2
  18. package/lib/build-engine/engine-js/rollup-plugins/remove-deprecated-features.js +37 -37
  19. package/lib/build-engine/engine-js/rollup-plugins/remove-deprecated-features.js.map +1 -1
  20. package/lib/build-engine/engine-js/rollup-plugins/ts-paths.d.ts +4 -4
  21. package/lib/build-engine/engine-js/rollup-plugins/ts-paths.js +42 -42
  22. package/lib/{engine-builder.d.ts → build-engine/engine-ts/engine-builder.d.ts} +53 -53
  23. package/lib/build-engine/engine-ts/engine-builder.d.ts.map +1 -0
  24. package/lib/{engine-builder.js → build-engine/engine-ts/engine-builder.js} +549 -549
  25. package/lib/build-engine/engine-ts/engine-builder.js.map +1 -0
  26. package/lib/build-engine/engine-ts/index.d.ts +3 -0
  27. package/lib/build-engine/engine-ts/index.d.ts.map +1 -0
  28. package/lib/build-engine/engine-ts/index.js +35 -0
  29. package/lib/build-engine/engine-ts/index.js.map +1 -0
  30. package/lib/build-engine/index.d.ts +125 -118
  31. package/lib/build-engine/index.d.ts.map +1 -1
  32. package/lib/build-engine/index.js +138 -124
  33. package/lib/build-engine/index.js.map +1 -1
  34. package/lib/index.d.ts +4 -4
  35. package/lib/index.d.ts.map +1 -1
  36. package/lib/index.js +33 -34
  37. package/lib/index.js.map +1 -1
  38. package/lib/module-resolver.d.ts +7 -7
  39. package/lib/module-resolver.js +28 -28
  40. package/lib/stats-query/config-interface.d.ts +129 -129
  41. package/lib/stats-query/config-interface.js +3 -3
  42. package/lib/stats-query/index.d.ts +161 -161
  43. package/lib/stats-query/index.d.ts.map +1 -1
  44. package/lib/stats-query/index.js +527 -527
  45. package/lib/stats-query/path-utils.d.ts +2 -2
  46. package/lib/stats-query/path-utils.js +35 -35
  47. package/lib/transformer/babel.d.ts +5 -5
  48. package/lib/transformer/babel.js +34 -34
  49. package/lib/transformer/index.d.ts +2 -2
  50. package/lib/transformer/index.js +28 -28
  51. package/lib/utils.d.ts +2 -2
  52. package/lib/utils.js +14 -14
  53. package/package.json +6 -3
  54. package/static/helper-dynamic-constants.txt +12 -12
  55. package/static/helper-global-exporter.txt +8 -8
  56. package/static/lib.dom.d.ts +20227 -20227
  57. package/lib/engine-builder.d.ts.map +0 -1
  58. package/lib/engine-builder.js.map +0 -1
  59. package/lib/stats-query/constant-manager.d.ts +0 -67
  60. package/lib/stats-query/constant-manager.d.ts.map +0 -1
  61. package/lib/stats-query/constant-manager.js +0 -263
  62. package/lib/stats-query/constant-manager.js.map +0 -1
  63. package/lib/transformer.js +0 -7
  64. package/lib/transformer.js.map +0 -1
  65. package/lib/tsdoc-metadata.json +0 -11
@@ -1,550 +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
- 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;
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;
550
550
  //# sourceMappingURL=engine-builder.js.map