@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,460 +1,459 @@
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.buildJsEngine = void 0;
39
- const fs_extra_1 = __importDefault(require("fs-extra"));
40
- const path_1 = __importDefault(require("path"));
41
- const plugin_babel_1 = __importDefault(require("@rollup/plugin-babel"));
42
- const plugin_json_1 = __importDefault(require("@rollup/plugin-json"));
43
- const plugin_node_resolve_1 = __importDefault(require("@rollup/plugin-node-resolve"));
44
- const plugin_commonjs_1 = __importDefault(require("@rollup/plugin-commonjs"));
45
- const plugin_terser_1 = __importDefault(require("@rollup/plugin-terser"));
46
- const preset_env_1 = __importDefault(require("@babel/preset-env"));
47
- const creator_programming_babel_preset_cc_1 = require("@cocos/creator-programming-babel-preset-cc");
48
- // @ts-expect-error: No typing
49
- const plugin_transform_for_of_1 = __importDefault(require("@babel/plugin-transform-for-of"));
50
- const rollup = __importStar(require("rollup"));
51
- // import rpProgress from 'rollup-plugin-progress';
52
- const plugin_virtual_1 = __importDefault(require("@rollup/plugin-virtual"));
53
- const resolve_1 = __importDefault(require("resolve"));
54
- const babel_plugin_dynamic_import_vars_1 = __importDefault(require("@cocos/babel-plugin-dynamic-import-vars"));
55
- const fs_1 = __importDefault(require("fs"));
56
- const ts_paths_1 = __importDefault(require("./rollup-plugins/ts-paths"));
57
- const remove_deprecated_features_1 = __importDefault(require("./rollup-plugins/remove-deprecated-features"));
58
- const stats_query_1 = require("../../stats-query");
59
- const asset_ref_1 = require("./rollup-plugins/asset-ref");
60
- const code_asset_1 = require("./rollup-plugins/code-asset");
61
- const asset_url_1 = require("./rollup-plugins/asset-url");
62
- const utils_1 = require("../../utils");
63
- // import * as decoratorRecorder from './babel-plugins/decorator-parser';
64
- const realPath = (function () {
65
- const realpath = typeof fs_1.default.realpath.native === 'function' ? fs_1.default.realpath.native : fs_1.default.realpath;
66
- return (file) => new Promise((resolve, reject) => {
67
- realpath(file, (err, path) => {
68
- if (err && err.code !== 'ENOENT') {
69
- reject(err);
70
- }
71
- else {
72
- resolve(err ? file : path);
73
- }
74
- });
75
- });
76
- })();
77
- function makePathEqualityKey(path) {
78
- return process.platform === 'win32' ? path.toLocaleLowerCase() : path;
79
- }
80
- function buildJsEngine(options) {
81
- var _a, _b, _c, _d, _e, _f;
82
- return __awaiter(this, void 0, void 0, function* () {
83
- const doUglify = !!options.compress;
84
- const engineRoot = path_1.default.resolve(options.engine);
85
- const rollupFormat = (_a = options.moduleFormat) !== null && _a !== void 0 ? _a : 'iife';
86
- let { ammoJsWasm } = options;
87
- if (ammoJsWasm === 'fallback'
88
- && rollupFormat !== 'system') {
89
- console.warn('--ammojs-wasm=fallback is only available under SystemJS target.');
90
- ammoJsWasm = false;
91
- }
92
- const statsQuery = yield stats_query_1.StatsQuery.create(engineRoot);
93
- if (options.features) {
94
- for (const feature of options.features) {
95
- if (!statsQuery.hasFeature(feature)) {
96
- console.warn(`'${feature}' is not a valid feature.`);
97
- }
98
- }
99
- }
100
- let features;
101
- let split = (_b = options.split) !== null && _b !== void 0 ? _b : false;
102
- if (options.features && options.features.length !== 0) {
103
- features = options.features;
104
- }
105
- else {
106
- features = statsQuery.getFeatures();
107
- if (split !== true) {
108
- split = true;
109
- console.warn(`You did not specify features which implies 'split: true'. `
110
- + `Explicitly set 'split: true' to suppress this warning.`);
111
- }
112
- }
113
- (0, utils_1.asserts)(options.mode === 'BUILD', `the mode should be 'BUILD' when building js engine!`);
114
- const flags = (_c = options.flags) !== null && _c !== void 0 ? _c : {};
115
- const intrinsicFlags = statsQuery.getIntrinsicFlagsOfFeatures(features);
116
- let buildTimeConstants = statsQuery.constantManager.genBuildTimeConstants({
117
- mode: options.mode,
118
- platform: options.platform,
119
- flags,
120
- });
121
- buildTimeConstants = Object.assign(Object.assign({}, intrinsicFlags), buildTimeConstants);
122
- // if (typeof options.forceJitValue !== undefined) {
123
- // buildTimeConstants['SUPPORT_JIT'] = options.forceJitValue as boolean;
124
- // }
125
- const moduleOverrides = Object.entries(statsQuery.evaluateModuleOverrides({
126
- mode: options.mode,
127
- platform: options.platform,
128
- buildTimeConstants,
129
- })).reduce((result, [k, v]) => {
130
- result[makePathEqualityKey(k)] = v;
131
- return result;
132
- }, {});
133
- const featureUnits = statsQuery.getUnitsOfFeatures(features);
134
- // Wether use webgpu
135
- const useWebGPU = !!((_d = options.flags) === null || _d === void 0 ? void 0 : _d.WEBGPU);
136
- const rpVirtualOptions = {};
137
- const vmInternalConstants = statsQuery.constantManager.exportStaticConstants({
138
- platform: options.platform,
139
- mode: options.mode,
140
- flags,
141
- });
142
- console.debug(`Module source "internal-constants":\n${vmInternalConstants}`);
143
- rpVirtualOptions['internal:constants'] = vmInternalConstants;
144
- rpVirtualOptions[creator_programming_babel_preset_cc_1.helpers.CC_HELPER_MODULE] = creator_programming_babel_preset_cc_1.helpers.generateHelperModuleSource();
145
- const forceStandaloneModules = ['wait-for-ammo-instantiation', 'decorator'];
146
- let rollupEntries;
147
- if (split) {
148
- rollupEntries = featureUnits.reduce((result, featureUnit) => {
149
- result[featureUnit] = statsQuery.getFeatureUnitFile(featureUnit);
150
- return result;
151
- }, {});
152
- }
153
- else {
154
- rollupEntries = {
155
- cc: 'cc',
156
- };
157
- const selectedFeatureUnits = [];
158
- for (const featureUnit of featureUnits) {
159
- if (forceStandaloneModules.includes(featureUnit)) {
160
- rollupEntries[featureUnit] = statsQuery.getFeatureUnitFile(featureUnit);
161
- }
162
- else {
163
- selectedFeatureUnits.push(featureUnit);
164
- }
165
- }
166
- rpVirtualOptions.cc = statsQuery.evaluateIndexModuleSource(selectedFeatureUnits, (featureUnit) => (0, utils_1.filePathToModuleRequest)(statsQuery.getFeatureUnitFile(featureUnit)));
167
- rollupEntries.cc = 'cc';
168
- console.debug(`Module source "cc":\n${rpVirtualOptions.cc}`);
169
- }
170
- const presetEnvOptions = {
171
- loose: (_e = options.loose) !== null && _e !== void 0 ? _e : true,
172
- // We need explicitly specified targets.
173
- // Ignore it to avoid the engine's parent dirs contain unexpected config.
174
- ignoreBrowserslistConfig: true,
175
- };
176
- if (options.targets !== undefined) {
177
- presetEnvOptions.targets = options.targets;
178
- }
179
- const babelPlugins = [];
180
- if (options.targets === undefined) {
181
- babelPlugins.push([plugin_transform_for_of_1.default, {
182
- loose: true,
183
- }]);
184
- }
185
- babelPlugins.push([babel_plugin_dynamic_import_vars_1.default, {
186
- resolve: {
187
- forwardExt: 'resolved',
188
- },
189
- }]);
190
- const { fieldDecorators, editorDecorators } = statsQuery.getOptimizeDecorators();
191
- const babelOptions = {
192
- babelHelpers: 'bundled',
193
- extensions: ['.js', '.ts'],
194
- exclude: [
195
- /node_modules[/\\]@cocos[/\\]ammo/,
196
- /node_modules[/\\]@cocos[/\\]cannon/,
197
- /node_modules[/\\]@cocos[/\\]physx/,
198
- ],
199
- comments: false,
200
- overrides: [{
201
- // Eliminates the babel compact warning:
202
- // 'The code generator has deoptimised the styling of ...'
203
- // that came from node_modules/@cocos
204
- test: /node_modules[/\\]@cocos[/\\]/,
205
- compact: true,
206
- }],
207
- plugins: babelPlugins,
208
- presets: [
209
- [preset_env_1.default, presetEnvOptions],
210
- [creator_programming_babel_preset_cc_1.babelPresetCC, {
211
- allowDeclareFields: true,
212
- ccDecoratorHelpers: 'external',
213
- fieldDecorators,
214
- editorDecorators,
215
- }],
216
- ],
217
- };
218
- // if (options.generateDecoratorsForJSB) {
219
- // if (!process.env.ENGINE_PATH) {
220
- // throw new Error('ENGINE_PATH environment variable not set');
221
- // }
222
- // babelOptions.presets?.push([() => ({ plugins: [[decoratorRecorder]] })]);
223
- // }
224
- const rollupPlugins = [];
225
- const codeAssetMapping = {};
226
- if (rollupFormat === 'system') {
227
- // `@cocos/physx` is too big(~6Mb) and cause memory crash.
228
- // Our temporary solution: exclude @cocos/physx from bundling and connect it with source map.
229
- rollupPlugins.push((0, code_asset_1.codeAsset)({
230
- resultMapping: codeAssetMapping,
231
- include: [
232
- /node_modules[/\\]@cocos[/\\]physx/,
233
- ],
234
- }));
235
- }
236
- if (options.noDeprecatedFeatures) {
237
- rollupPlugins.push((0, remove_deprecated_features_1.default)(typeof options.noDeprecatedFeatures === 'string' ? options.noDeprecatedFeatures : undefined));
238
- }
239
- rollupPlugins.push((0, asset_ref_1.assetRef)({
240
- format: options.assetURLFormat,
241
- }), {
242
- name: '@cocos/build-engine|module-overrides',
243
- resolveId(source, importer) {
244
- if (moduleOverrides[source]) {
245
- return source;
246
- }
247
- else {
248
- return null;
249
- }
250
- },
251
- load(id) {
252
- const key = makePathEqualityKey(id);
253
- if (!(key in moduleOverrides)) {
254
- return null;
255
- }
256
- const replacement = moduleOverrides[key];
257
- console.debug(`Redirect module ${id} to ${replacement}`);
258
- return `export * from '${(0, utils_1.filePathToModuleRequest)(replacement)}';`;
259
- },
260
- }, (0, plugin_virtual_1.default)(rpVirtualOptions), (0, ts_paths_1.default)({
261
- configFileName: path_1.default.resolve(options.engine, 'tsconfig.json'),
262
- }), (0, plugin_node_resolve_1.default)({
263
- extensions: ['.js', '.ts', '.json'],
264
- jail: yield realPath(engineRoot),
265
- rootDir: engineRoot,
266
- }), (0, plugin_json_1.default)({
267
- preferConst: true,
268
- }), (0, plugin_commonjs_1.default)({
269
- include: [
270
- /node_modules[/\\]/,
271
- ],
272
- sourceMap: false,
273
- }), (0, plugin_babel_1.default)(Object.assign({ skipPreflightCheck: true }, babelOptions)));
274
- // if (options.progress) {
275
- // rollupPlugins.unshift(rpProgress());
276
- // }
277
- if (doUglify) { // TODO: tree-shaking not clear!
278
- rollupPlugins.push((0, plugin_terser_1.default)({
279
- // see https://github.com/terser/terser#compress-options
280
- compress: {
281
- reduce_funcs: false,
282
- keep_fargs: false,
283
- unsafe_Function: true,
284
- unsafe_math: true,
285
- unsafe_methods: true,
286
- passes: 2, // first: remove deadcodes and const objects, second: drop variables
287
- },
288
- mangle: doUglify,
289
- keep_fnames: !doUglify,
290
- output: {
291
- beautify: !doUglify,
292
- },
293
- // https://github.com/rollup/rollup/issues/3315
294
- // We only do this for CommonJS.
295
- // Especially, we cannot do this for IIFE.
296
- toplevel: rollupFormat === 'cjs',
297
- }));
298
- }
299
- // const visualizeOptions = typeof options.visualize === 'object'
300
- // ? options.visualize
301
- // : (options.visualize ? {} : undefined);
302
- // if (visualizeOptions) {
303
- // let rpVisualizer;
304
- // try {
305
- // // @ts-expect-error: No typing
306
- // rpVisualizer = await import('rollup-plugin-visualizer');
307
- // } catch {
308
- // console.warn('Visualizing needs \'rollup-plugin-visualizer\' to be installed. It\'s installed as dev-dependency.');
309
- // }
310
- // if (rpVisualizer) {
311
- // const visualizeFile = visualizeOptions.file ?? ps.join(options.out, 'visualize.html');
312
- // rollupPlugins.push(rpVisualizer({
313
- // filename: visualizeFile,
314
- // title: 'Cocos Creator build visualizer',
315
- // template: 'treemap',
316
- // }));
317
- // }
318
- // }
319
- let hasCriticalWarns = false;
320
- const rollupWarningHandler = (warning, defaultHandler) => {
321
- var _a;
322
- if (typeof warning !== 'string') {
323
- if (warning.code === 'CIRCULAR_DEPENDENCY') {
324
- hasCriticalWarns = true;
325
- }
326
- else if (warning.code === 'THIS_IS_UNDEFINED') {
327
- // TODO: It's really inappropriate to do this...
328
- // Let's fix these files instead of suppressing rollup.
329
- if ((_a = warning.id) === null || _a === void 0 ? void 0 : _a.match(/(?:spine-core\.js$)|(?:dragonBones\.js$)/)) {
330
- console.debug(`Rollup warning 'THIS_IS_UNDEFINED' is omitted for ${warning.id}`);
331
- return;
332
- }
333
- }
334
- }
335
- defaultHandler(warning);
336
- };
337
- rollupPlugins.unshift((0, asset_url_1.assetUrl)({
338
- engineRoot,
339
- useWebGPU,
340
- }));
341
- const rollupOptions = {
342
- input: rollupEntries,
343
- plugins: rollupPlugins,
344
- cache: false,
345
- onwarn: rollupWarningHandler,
346
- };
347
- const perf = true;
348
- if (perf) {
349
- rollupOptions.perf = true;
350
- }
351
- const bulletAsmJsModule = yield nodeResolveAsync('@cocos/bullet/bullet.cocos.js');
352
- const wasmBinaryPath = path_1.default.join(bulletAsmJsModule, '..', 'bullet.wasm.wasm');
353
- if (ammoJsWasm === true) {
354
- rpVirtualOptions['@cocos/bullet'] = `
355
- import wasmBinaryURL from '${(0, asset_ref_1.pathToAssetRefURL)(wasmBinaryPath)}';
356
- export const bulletType = 'wasm';
357
- export default wasmBinaryURL;
358
- `;
359
- }
360
- else if (ammoJsWasm === 'fallback') {
361
- rpVirtualOptions['@cocos/bullet'] = `
362
- export async function initialize(isWasm) {
363
- let ammo;
364
- if (isWasm) {
365
- ammo = await import('${(0, asset_ref_1.pathToAssetRefURL)(wasmBinaryPath)}');
366
- } else {
367
- ammo = await import('${(0, utils_1.filePathToModuleRequest)(bulletAsmJsModule)}');
368
- }
369
- return ammo.default;
370
- }
371
- export const bulletType = 'fallback';
372
- export default initialize;
373
- `;
374
- }
375
- else {
376
- rpVirtualOptions['@cocos/bullet'] = `
377
- import Bullet from '${(0, utils_1.filePathToModuleRequest)(bulletAsmJsModule)}';
378
- export const bulletType = 'asmjs';
379
- export default Bullet;
380
- `;
381
- }
382
- const rollupBuild = yield rollup.rollup(rollupOptions);
383
- const timing = (_f = rollupBuild.getTimings) === null || _f === void 0 ? void 0 : _f.call(rollupBuild);
384
- if (timing) {
385
- console.debug(`==== Performance ====`);
386
- console.debug(JSON.stringify(timing));
387
- console.debug(`==== ====`);
388
- }
389
- const { incremental: incrementalFile } = options;
390
- if (incrementalFile) {
391
- const watchFiles = {};
392
- const files = rollupBuild.watchFiles;
393
- yield Promise.all(files.map((watchFile) => __awaiter(this, void 0, void 0, function* () {
394
- try {
395
- const stat = yield fs_extra_1.default.stat(watchFile);
396
- watchFiles[watchFile] = stat.mtimeMs;
397
- }
398
- catch (_g) {
399
- // the `watchFiles` may contain non-fs modules.
400
- }
401
- })));
402
- yield fs_extra_1.default.ensureDir(path_1.default.dirname(incrementalFile));
403
- yield fs_extra_1.default.writeFile(incrementalFile, JSON.stringify(watchFiles, undefined, 2));
404
- }
405
- const result = {
406
- chunkAliases: {},
407
- exports: {},
408
- hasCriticalWarns: false,
409
- };
410
- const rollupOutputOptions = {
411
- format: rollupFormat,
412
- sourcemap: options.sourceMap,
413
- sourcemapFile: options.sourceMapFile,
414
- name: (rollupFormat === 'iife' ? 'ccm' : undefined),
415
- dir: options.out,
416
- // minifyInternalExports: false,
417
- // preserveEntrySignatures: "allow-extension",
418
- };
419
- const rollupOutput = yield rollupBuild.write(rollupOutputOptions);
420
- const validEntryChunks = {};
421
- for (const output of rollupOutput.output) {
422
- if (output.type === 'chunk') {
423
- if (output.isEntry) {
424
- const chunkName = output.name;
425
- if (chunkName in rollupEntries || chunkName === 'cc') {
426
- validEntryChunks[chunkName] = output.fileName;
427
- }
428
- }
429
- }
430
- }
431
- Object.assign(result.exports, validEntryChunks);
432
- Object.assign(result.chunkAliases, codeAssetMapping);
433
- result.dependencyGraph = {};
434
- for (const output of rollupOutput.output) {
435
- if (output.type === 'chunk') {
436
- result.dependencyGraph[output.fileName] = output.imports.concat(output.dynamicImports);
437
- }
438
- }
439
- result.hasCriticalWarns = hasCriticalWarns;
440
- return result;
441
- function nodeResolveAsync(specifier) {
442
- return __awaiter(this, void 0, void 0, function* () {
443
- return new Promise((r, reject) => {
444
- (0, resolve_1.default)(specifier, {
445
- basedir: engineRoot,
446
- }, (err, resolved, pkg) => {
447
- if (err) {
448
- reject(err);
449
- }
450
- else {
451
- r(resolved);
452
- }
453
- });
454
- });
455
- });
456
- }
457
- });
458
- }
459
- exports.buildJsEngine = buildJsEngine;
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.buildJsEngine = void 0;
39
+ const fs_extra_1 = __importDefault(require("fs-extra"));
40
+ const path_1 = __importDefault(require("path"));
41
+ const plugin_babel_1 = __importDefault(require("@rollup/plugin-babel"));
42
+ const plugin_json_1 = __importDefault(require("@rollup/plugin-json"));
43
+ const plugin_node_resolve_1 = __importDefault(require("@rollup/plugin-node-resolve"));
44
+ const plugin_commonjs_1 = __importDefault(require("@rollup/plugin-commonjs"));
45
+ const rollup_plugin_terser_1 = require("rollup-plugin-terser");
46
+ const preset_env_1 = __importDefault(require("@babel/preset-env"));
47
+ const creator_programming_babel_preset_cc_1 = require("@cocos/creator-programming-babel-preset-cc");
48
+ // @ts-expect-error: No typing
49
+ const plugin_transform_for_of_1 = __importDefault(require("@babel/plugin-transform-for-of"));
50
+ const rollup = __importStar(require("rollup"));
51
+ // import rpProgress from 'rollup-plugin-progress';
52
+ const plugin_virtual_1 = __importDefault(require("@rollup/plugin-virtual"));
53
+ const resolve_1 = __importDefault(require("resolve"));
54
+ const babel_plugin_dynamic_import_vars_1 = __importDefault(require("@cocos/babel-plugin-dynamic-import-vars"));
55
+ const fs_1 = __importDefault(require("fs"));
56
+ const ts_paths_1 = __importDefault(require("./rollup-plugins/ts-paths"));
57
+ const remove_deprecated_features_1 = __importDefault(require("./rollup-plugins/remove-deprecated-features"));
58
+ const stats_query_1 = require("../../stats-query");
59
+ const asset_ref_1 = require("./rollup-plugins/asset-ref");
60
+ const code_asset_1 = require("./rollup-plugins/code-asset");
61
+ const asset_url_1 = require("./rollup-plugins/asset-url");
62
+ const utils_1 = require("../../utils");
63
+ // import * as decoratorRecorder from './babel-plugins/decorator-parser';
64
+ const realPath = (function () {
65
+ const realpath = typeof fs_1.default.realpath.native === 'function' ? fs_1.default.realpath.native : fs_1.default.realpath;
66
+ return (file) => new Promise((resolve, reject) => {
67
+ realpath(file, (err, path) => {
68
+ if (err && err.code !== 'ENOENT') {
69
+ reject(err);
70
+ }
71
+ else {
72
+ resolve(err ? file : path);
73
+ }
74
+ });
75
+ });
76
+ })();
77
+ function makePathEqualityKey(path) {
78
+ return process.platform === 'win32' ? path.toLocaleLowerCase() : path;
79
+ }
80
+ function buildJsEngine(options) {
81
+ var _a, _b, _c, _d, _e, _f;
82
+ return __awaiter(this, void 0, void 0, function* () {
83
+ const doUglify = !!options.compress;
84
+ const engineRoot = path_1.default.resolve(options.engine);
85
+ const rollupFormat = (_a = options.moduleFormat) !== null && _a !== void 0 ? _a : 'iife';
86
+ let { ammoJsWasm } = options;
87
+ if (ammoJsWasm === 'fallback'
88
+ && rollupFormat !== 'system') {
89
+ console.warn('--ammojs-wasm=fallback is only available under SystemJS target.');
90
+ ammoJsWasm = false;
91
+ }
92
+ const statsQuery = yield stats_query_1.StatsQuery.create(engineRoot);
93
+ if (options.features) {
94
+ for (const feature of options.features) {
95
+ if (!statsQuery.hasFeature(feature)) {
96
+ console.warn(`'${feature}' is not a valid feature.`);
97
+ }
98
+ }
99
+ }
100
+ let features;
101
+ let split = (_b = options.split) !== null && _b !== void 0 ? _b : false;
102
+ if (options.features && options.features.length !== 0) {
103
+ features = options.features;
104
+ }
105
+ else {
106
+ features = statsQuery.getFeatures();
107
+ if (split !== true) {
108
+ split = true;
109
+ console.warn(`You did not specify features which implies 'split: true'. `
110
+ + `Explicitly set 'split: true' to suppress this warning.`);
111
+ }
112
+ }
113
+ const flags = (_c = options.flags) !== null && _c !== void 0 ? _c : {};
114
+ const intrinsicFlags = statsQuery.getIntrinsicFlagsOfFeatures(features);
115
+ let buildTimeConstants = statsQuery.constantManager.genBuildTimeConstants({
116
+ mode: options.mode,
117
+ platform: options.platform,
118
+ flags,
119
+ });
120
+ buildTimeConstants = Object.assign(Object.assign({}, intrinsicFlags), buildTimeConstants);
121
+ // if (typeof options.forceJitValue !== undefined) {
122
+ // buildTimeConstants['SUPPORT_JIT'] = options.forceJitValue as boolean;
123
+ // }
124
+ const moduleOverrides = Object.entries(statsQuery.evaluateModuleOverrides({
125
+ mode: options.mode,
126
+ platform: options.platform,
127
+ buildTimeConstants,
128
+ })).reduce((result, [k, v]) => {
129
+ result[makePathEqualityKey(k)] = v;
130
+ return result;
131
+ }, {});
132
+ const featureUnits = statsQuery.getUnitsOfFeatures(features);
133
+ // Wether use webgpu
134
+ const useWebGPU = !!((_d = options.flags) === null || _d === void 0 ? void 0 : _d.WEBGPU);
135
+ const rpVirtualOptions = {};
136
+ const vmInternalConstants = statsQuery.constantManager.exportStaticConstants({
137
+ platform: options.platform,
138
+ mode: options.mode,
139
+ flags,
140
+ });
141
+ console.debug(`Module source "internal-constants":\n${vmInternalConstants}`);
142
+ rpVirtualOptions['internal:constants'] = vmInternalConstants;
143
+ rpVirtualOptions[creator_programming_babel_preset_cc_1.helpers.CC_HELPER_MODULE] = creator_programming_babel_preset_cc_1.helpers.generateHelperModuleSource();
144
+ const forceStandaloneModules = ['wait-for-ammo-instantiation', 'decorator'];
145
+ let rollupEntries;
146
+ if (split) {
147
+ rollupEntries = featureUnits.reduce((result, featureUnit) => {
148
+ result[featureUnit] = statsQuery.getFeatureUnitFile(featureUnit);
149
+ return result;
150
+ }, {});
151
+ }
152
+ else {
153
+ rollupEntries = {
154
+ cc: 'cc',
155
+ };
156
+ const selectedFeatureUnits = [];
157
+ for (const featureUnit of featureUnits) {
158
+ if (forceStandaloneModules.includes(featureUnit)) {
159
+ rollupEntries[featureUnit] = statsQuery.getFeatureUnitFile(featureUnit);
160
+ }
161
+ else {
162
+ selectedFeatureUnits.push(featureUnit);
163
+ }
164
+ }
165
+ rpVirtualOptions.cc = statsQuery.evaluateIndexModuleSource(selectedFeatureUnits, (featureUnit) => (0, utils_1.filePathToModuleRequest)(statsQuery.getFeatureUnitFile(featureUnit)));
166
+ rollupEntries.cc = 'cc';
167
+ console.debug(`Module source "cc":\n${rpVirtualOptions.cc}`);
168
+ }
169
+ const presetEnvOptions = {
170
+ loose: (_e = options.loose) !== null && _e !== void 0 ? _e : true,
171
+ // We need explicitly specified targets.
172
+ // Ignore it to avoid the engine's parent dirs contain unexpected config.
173
+ ignoreBrowserslistConfig: true,
174
+ };
175
+ if (options.targets !== undefined) {
176
+ presetEnvOptions.targets = options.targets;
177
+ }
178
+ const babelPlugins = [];
179
+ if (options.targets === undefined) {
180
+ babelPlugins.push([plugin_transform_for_of_1.default, {
181
+ loose: true,
182
+ }]);
183
+ }
184
+ babelPlugins.push([babel_plugin_dynamic_import_vars_1.default, {
185
+ resolve: {
186
+ forwardExt: 'resolved',
187
+ },
188
+ }]);
189
+ const { fieldDecorators, editorDecorators } = statsQuery.getOptimizeDecorators();
190
+ const babelOptions = {
191
+ babelHelpers: 'bundled',
192
+ extensions: ['.js', '.ts'],
193
+ exclude: [
194
+ /node_modules[/\\]@cocos[/\\]ammo/,
195
+ /node_modules[/\\]@cocos[/\\]cannon/,
196
+ /node_modules[/\\]@cocos[/\\]physx/,
197
+ ],
198
+ comments: false,
199
+ overrides: [{
200
+ // Eliminates the babel compact warning:
201
+ // 'The code generator has deoptimised the styling of ...'
202
+ // that came from node_modules/@cocos
203
+ test: /node_modules[/\\]@cocos[/\\]/,
204
+ compact: true,
205
+ }],
206
+ plugins: babelPlugins,
207
+ presets: [
208
+ [preset_env_1.default, presetEnvOptions],
209
+ [creator_programming_babel_preset_cc_1.babelPresetCC, {
210
+ allowDeclareFields: true,
211
+ ccDecoratorHelpers: 'external',
212
+ fieldDecorators,
213
+ editorDecorators,
214
+ }],
215
+ ],
216
+ };
217
+ // if (options.generateDecoratorsForJSB) {
218
+ // if (!process.env.ENGINE_PATH) {
219
+ // throw new Error('ENGINE_PATH environment variable not set');
220
+ // }
221
+ // babelOptions.presets?.push([() => ({ plugins: [[decoratorRecorder]] })]);
222
+ // }
223
+ const rollupPlugins = [];
224
+ const codeAssetMapping = {};
225
+ if (rollupFormat === 'system') {
226
+ // `@cocos/physx` is too big(~6Mb) and cause memory crash.
227
+ // Our temporary solution: exclude @cocos/physx from bundling and connect it with source map.
228
+ rollupPlugins.push((0, code_asset_1.codeAsset)({
229
+ resultMapping: codeAssetMapping,
230
+ include: [
231
+ /node_modules[/\\]@cocos[/\\]physx/,
232
+ ],
233
+ }));
234
+ }
235
+ if (options.noDeprecatedFeatures) {
236
+ rollupPlugins.push((0, remove_deprecated_features_1.default)(typeof options.noDeprecatedFeatures === 'string' ? options.noDeprecatedFeatures : undefined));
237
+ }
238
+ rollupPlugins.push((0, asset_ref_1.assetRef)({
239
+ format: options.assetURLFormat,
240
+ }), {
241
+ name: '@cocos/ccbuild|module-overrides',
242
+ resolveId(source, importer) {
243
+ if (moduleOverrides[source]) {
244
+ return source;
245
+ }
246
+ else {
247
+ return null;
248
+ }
249
+ },
250
+ load(id) {
251
+ const key = makePathEqualityKey(id);
252
+ if (!(key in moduleOverrides)) {
253
+ return null;
254
+ }
255
+ const replacement = moduleOverrides[key];
256
+ console.debug(`Redirect module ${id} to ${replacement}`);
257
+ return `export * from '${(0, utils_1.filePathToModuleRequest)(replacement)}';`;
258
+ },
259
+ }, (0, plugin_virtual_1.default)(rpVirtualOptions), (0, ts_paths_1.default)({
260
+ configFileName: path_1.default.resolve(options.engine, 'tsconfig.json'),
261
+ }), (0, plugin_node_resolve_1.default)({
262
+ extensions: ['.js', '.ts', '.json'],
263
+ jail: yield realPath(engineRoot),
264
+ rootDir: engineRoot,
265
+ }), (0, plugin_json_1.default)({
266
+ preferConst: true,
267
+ }), (0, plugin_commonjs_1.default)({
268
+ include: [
269
+ /node_modules[/\\]/,
270
+ ],
271
+ sourceMap: false,
272
+ }), (0, plugin_babel_1.default)(Object.assign({ skipPreflightCheck: true }, babelOptions)));
273
+ // if (options.progress) {
274
+ // rollupPlugins.unshift(rpProgress());
275
+ // }
276
+ if (doUglify) { // TODO: tree-shaking not clear!
277
+ rollupPlugins.push((0, rollup_plugin_terser_1.terser)({
278
+ // see https://github.com/terser/terser#compress-options
279
+ compress: {
280
+ reduce_funcs: false,
281
+ keep_fargs: false,
282
+ unsafe_Function: true,
283
+ unsafe_math: true,
284
+ unsafe_methods: true,
285
+ passes: 2, // first: remove deadcodes and const objects, second: drop variables
286
+ },
287
+ mangle: doUglify,
288
+ keep_fnames: !doUglify,
289
+ output: {
290
+ beautify: !doUglify,
291
+ },
292
+ // https://github.com/rollup/rollup/issues/3315
293
+ // We only do this for CommonJS.
294
+ // Especially, we cannot do this for IIFE.
295
+ toplevel: rollupFormat === 'cjs',
296
+ }));
297
+ }
298
+ // const visualizeOptions = typeof options.visualize === 'object'
299
+ // ? options.visualize
300
+ // : (options.visualize ? {} : undefined);
301
+ // if (visualizeOptions) {
302
+ // let rpVisualizer;
303
+ // try {
304
+ // // @ts-expect-error: No typing
305
+ // rpVisualizer = await import('rollup-plugin-visualizer');
306
+ // } catch {
307
+ // console.warn('Visualizing needs \'rollup-plugin-visualizer\' to be installed. It\'s installed as dev-dependency.');
308
+ // }
309
+ // if (rpVisualizer) {
310
+ // const visualizeFile = visualizeOptions.file ?? ps.join(options.out, 'visualize.html');
311
+ // rollupPlugins.push(rpVisualizer({
312
+ // filename: visualizeFile,
313
+ // title: 'Cocos Creator build visualizer',
314
+ // template: 'treemap',
315
+ // }));
316
+ // }
317
+ // }
318
+ let hasCriticalWarns = false;
319
+ const rollupWarningHandler = (warning, defaultHandler) => {
320
+ var _a;
321
+ if (typeof warning !== 'string') {
322
+ if (warning.code === 'CIRCULAR_DEPENDENCY') {
323
+ hasCriticalWarns = true;
324
+ }
325
+ else if (warning.code === 'THIS_IS_UNDEFINED') {
326
+ // TODO: It's really inappropriate to do this...
327
+ // Let's fix these files instead of suppressing rollup.
328
+ if ((_a = warning.id) === null || _a === void 0 ? void 0 : _a.match(/(?:spine-core\.js$)|(?:dragonBones\.js$)/)) {
329
+ console.debug(`Rollup warning 'THIS_IS_UNDEFINED' is omitted for ${warning.id}`);
330
+ return;
331
+ }
332
+ }
333
+ }
334
+ defaultHandler(warning);
335
+ };
336
+ rollupPlugins.unshift((0, asset_url_1.assetUrl)({
337
+ engineRoot,
338
+ useWebGPU,
339
+ }));
340
+ const rollupOptions = {
341
+ input: rollupEntries,
342
+ plugins: rollupPlugins,
343
+ cache: false,
344
+ onwarn: rollupWarningHandler,
345
+ };
346
+ const perf = true;
347
+ if (perf) {
348
+ rollupOptions.perf = true;
349
+ }
350
+ const bulletAsmJsModule = yield nodeResolveAsync('@cocos/bullet/bullet.cocos.js');
351
+ const wasmBinaryPath = path_1.default.join(bulletAsmJsModule, '..', 'bullet.wasm.wasm');
352
+ if (ammoJsWasm === true) {
353
+ rpVirtualOptions['@cocos/bullet'] = `
354
+ import wasmBinaryURL from '${(0, asset_ref_1.pathToAssetRefURL)(wasmBinaryPath)}';
355
+ export const bulletType = 'wasm';
356
+ export default wasmBinaryURL;
357
+ `;
358
+ }
359
+ else if (ammoJsWasm === 'fallback') {
360
+ rpVirtualOptions['@cocos/bullet'] = `
361
+ export async function initialize(isWasm) {
362
+ let ammo;
363
+ if (isWasm) {
364
+ ammo = await import('${(0, asset_ref_1.pathToAssetRefURL)(wasmBinaryPath)}');
365
+ } else {
366
+ ammo = await import('${(0, utils_1.filePathToModuleRequest)(bulletAsmJsModule)}');
367
+ }
368
+ return ammo.default;
369
+ }
370
+ export const bulletType = 'fallback';
371
+ export default initialize;
372
+ `;
373
+ }
374
+ else {
375
+ rpVirtualOptions['@cocos/bullet'] = `
376
+ import Bullet from '${(0, utils_1.filePathToModuleRequest)(bulletAsmJsModule)}';
377
+ export const bulletType = 'asmjs';
378
+ export default Bullet;
379
+ `;
380
+ }
381
+ const rollupBuild = yield rollup.rollup(rollupOptions);
382
+ const timing = (_f = rollupBuild.getTimings) === null || _f === void 0 ? void 0 : _f.call(rollupBuild);
383
+ if (timing) {
384
+ console.debug(`==== Performance ====`);
385
+ console.debug(JSON.stringify(timing));
386
+ console.debug(`==== ====`);
387
+ }
388
+ const { incremental: incrementalFile } = options;
389
+ if (incrementalFile) {
390
+ const watchFiles = {};
391
+ const files = rollupBuild.watchFiles;
392
+ yield Promise.all(files.map((watchFile) => __awaiter(this, void 0, void 0, function* () {
393
+ try {
394
+ const stat = yield fs_extra_1.default.stat(watchFile);
395
+ watchFiles[watchFile] = stat.mtimeMs;
396
+ }
397
+ catch (_g) {
398
+ // the `watchFiles` may contain non-fs modules.
399
+ }
400
+ })));
401
+ yield fs_extra_1.default.ensureDir(path_1.default.dirname(incrementalFile));
402
+ yield fs_extra_1.default.writeFile(incrementalFile, JSON.stringify(watchFiles, undefined, 2));
403
+ }
404
+ const result = {
405
+ chunkAliases: {},
406
+ exports: {},
407
+ hasCriticalWarns: false,
408
+ };
409
+ const rollupOutputOptions = {
410
+ format: rollupFormat,
411
+ sourcemap: options.sourceMap,
412
+ sourcemapFile: options.sourceMapFile,
413
+ name: (rollupFormat === 'iife' ? 'ccm' : undefined),
414
+ dir: options.out,
415
+ // minifyInternalExports: false,
416
+ // preserveEntrySignatures: "allow-extension",
417
+ };
418
+ const rollupOutput = yield rollupBuild.write(rollupOutputOptions);
419
+ const validEntryChunks = {};
420
+ for (const output of rollupOutput.output) {
421
+ if (output.type === 'chunk') {
422
+ if (output.isEntry) {
423
+ const chunkName = output.name;
424
+ if (chunkName in rollupEntries || chunkName === 'cc') {
425
+ validEntryChunks[chunkName] = output.fileName;
426
+ }
427
+ }
428
+ }
429
+ }
430
+ Object.assign(result.exports, validEntryChunks);
431
+ Object.assign(result.chunkAliases, codeAssetMapping);
432
+ result.dependencyGraph = {};
433
+ for (const output of rollupOutput.output) {
434
+ if (output.type === 'chunk') {
435
+ result.dependencyGraph[output.fileName] = output.imports.concat(output.dynamicImports);
436
+ }
437
+ }
438
+ result.hasCriticalWarns = hasCriticalWarns;
439
+ return result;
440
+ function nodeResolveAsync(specifier) {
441
+ return __awaiter(this, void 0, void 0, function* () {
442
+ return new Promise((r, reject) => {
443
+ (0, resolve_1.default)(specifier, {
444
+ basedir: engineRoot,
445
+ }, (err, resolved, pkg) => {
446
+ if (err) {
447
+ reject(err);
448
+ }
449
+ else {
450
+ r(resolved);
451
+ }
452
+ });
453
+ });
454
+ });
455
+ }
456
+ });
457
+ }
458
+ exports.buildJsEngine = buildJsEngine;
460
459
  //# sourceMappingURL=index.js.map