@nocobase/build 2.1.0-alpha.13 → 2.1.0-alpha.15

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.
package/lib/build.js CHANGED
@@ -28,12 +28,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
28
28
  var build_exports = {};
29
29
  __export(build_exports, {
30
30
  build: () => build,
31
- buildPackage: () => buildPackage,
32
31
  buildPackages: () => buildPackages
33
32
  });
34
33
  module.exports = __toCommonJS(build_exports);
35
34
  var import_chalk = __toESM(require("chalk"));
36
- var import_execa = __toESM(require("execa"));
37
35
  var import_path = __toESM(require("path"));
38
36
  var import_buildCjs = require("./buildCjs");
39
37
  var import_buildClient = require("./buildClient");
@@ -46,107 +44,288 @@ var import_utils = require("./utils");
46
44
  var import_addlicense = require("./utils/addlicense");
47
45
  var import_getPackages = require("./utils/getPackages");
48
46
  const BUILD_ERROR = "build-error";
47
+ const DEFAULT_LAYER_CONCURRENCY = 2;
48
+ const DEFAULT_PLUGIN_LAYER_CONCURRENCY = 1;
49
+ const ENABLE_BUILD_PROFILE = process.env.BUILD_PROFILE === "true";
49
50
  async function build(pkgs) {
51
+ const profile = ENABLE_BUILD_PROFILE ? (0, import_utils.createBuildProfileCollector)() : null;
52
+ const buildStart = (0, import_utils.nowMs)();
50
53
  const isDev = process.argv.includes("--development");
51
54
  process.env.NODE_ENV = isDev ? "development" : "production";
52
- let packages = (0, import_getPackages.getPackages)(pkgs);
53
- const cachePkg = (0, import_utils.readFromCache)(BUILD_ERROR);
54
- if (process.argv.includes("--retry") && cachePkg?.pkg) {
55
- packages = packages.slice(packages.findIndex((item) => item.name === cachePkg.pkg));
55
+ try {
56
+ let packages = (0, import_getPackages.getPackages)(pkgs);
57
+ const cachePkg = (0, import_utils.readFromCache)(BUILD_ERROR);
58
+ if (process.argv.includes("--retry") && cachePkg?.pkg) {
59
+ packages = packages.slice(packages.findIndex((item) => item.name === cachePkg.pkg));
60
+ }
61
+ if (packages.length === 0) {
62
+ let msg = "";
63
+ if (pkgs.length) {
64
+ msg = `'${pkgs.join(", ")}' did not match any packages`;
65
+ } else {
66
+ msg = "No package matched";
67
+ }
68
+ console.warn(import_chalk.default.yellow(`[@nocobase/build]: ${msg}`));
69
+ return;
70
+ }
71
+ const pluginPackages = (0, import_constant.getPluginPackages)(packages);
72
+ const cjsPackages = (0, import_constant.getCjsPackages)(packages);
73
+ const presetsPackages = (0, import_constant.getPresetsPackages)(packages);
74
+ await buildPackages(cjsPackages, "lib", import_buildCjs.buildCjs, {
75
+ sourceConcurrency: DEFAULT_LAYER_CONCURRENCY,
76
+ declarationConcurrency: 1,
77
+ stageName: "core cjs",
78
+ profile
79
+ });
80
+ const clientCore = packages.find((item) => item.location === import_constant.CORE_CLIENT);
81
+ if (clientCore) {
82
+ await buildSinglePackage(clientCore, "es", import_buildClient.buildClient, {
83
+ stageName: "core client",
84
+ profile
85
+ });
86
+ }
87
+ const esmPackages = packages.filter((pkg) => import_constant.ESM_PACKAGES.includes(pkg.name));
88
+ await buildPackages(esmPackages, "lib", import_buildCjs.buildCjs, {
89
+ sourceConcurrency: DEFAULT_LAYER_CONCURRENCY,
90
+ declarationConcurrency: 1,
91
+ stageName: "esm cjs",
92
+ profile
93
+ });
94
+ await buildPackages(esmPackages, "es", import_buildEsm.buildEsm, {
95
+ sourceConcurrency: DEFAULT_LAYER_CONCURRENCY,
96
+ declarationConcurrency: 1,
97
+ stageName: "esm",
98
+ profile
99
+ });
100
+ await buildPackages(pluginPackages, "dist", import_buildPlugin.buildPlugin, {
101
+ sourceConcurrency: DEFAULT_PLUGIN_LAYER_CONCURRENCY,
102
+ declarationConcurrency: 1,
103
+ stageName: "plugins",
104
+ profile
105
+ });
106
+ await buildPackages(presetsPackages, "lib", import_buildCjs.buildCjs, {
107
+ sourceConcurrency: DEFAULT_LAYER_CONCURRENCY,
108
+ declarationConcurrency: 1,
109
+ stageName: "presets",
110
+ profile
111
+ });
112
+ const appClient = packages.find((item) => item.location === import_constant.CORE_APP);
113
+ if (appClient) {
114
+ await (0, import_utils.runProfiledStage)(profile, "app shell", async () => {
115
+ await (0, import_utils.runScript)(["rsbuild", "build", "--config", import_path.default.join(import_constant.CORE_APP, "client", "rsbuild.config.ts")], import_constant.ROOT_PATH, {
116
+ APP_ROOT: import_path.default.join(import_constant.CORE_APP, "client"),
117
+ ANALYZE: process.env.BUILD_ANALYZE === "true" ? "1" : void 0
118
+ });
119
+ });
120
+ }
121
+ (0, import_utils.writeToCache)(BUILD_ERROR, {});
122
+ } finally {
123
+ if (profile) {
124
+ (0, import_utils.printBuildProfile)(profile, (0, import_utils.nowMs)() - buildStart);
125
+ }
56
126
  }
57
- if (packages.length === 0) {
58
- let msg = "";
59
- if (pkgs.length) {
60
- msg = `'${pkgs.join(", ")}' did not match any packages`;
61
- } else {
62
- msg = "No package matched";
127
+ }
128
+ async function buildPackages(packages, targetDir, doBuildPackage, options = {}) {
129
+ const {
130
+ sourceConcurrency = DEFAULT_LAYER_CONCURRENCY,
131
+ declarationConcurrency = 1,
132
+ stageName = "packages",
133
+ profile = null
134
+ } = options;
135
+ const layers = (0, import_getPackages.groupPackagesByTopoLevel)(packages);
136
+ const shouldRunDeclaration = !process.argv.includes("--no-dts") && !process.argv.includes("--only-tar");
137
+ await (0, import_utils.runProfiledStage)(profile, `${stageName} source`, async () => {
138
+ for (let index = 0; index < layers.length; index++) {
139
+ const layer = layers[index];
140
+ console.log(import_chalk.default.cyan(`[@nocobase/build]: ${stageName} source layer ${index + 1}/${layers.length} (${layer.length} packages)`));
141
+ const layerStart = (0, import_utils.nowMs)();
142
+ await (0, import_utils.runWithConcurrency)(layer, sourceConcurrency, async (pkg) => {
143
+ await buildPackageSourceLifecycle(pkg, targetDir, doBuildPackage, profile);
144
+ });
145
+ const layerDurationMs = (0, import_utils.nowMs)() - layerStart;
146
+ if (profile) {
147
+ profile.layers.push({
148
+ stageName: `${stageName} source`,
149
+ layerIndex: index + 1,
150
+ layerCount: layers.length,
151
+ packageCount: layer.length,
152
+ durationMs: layerDurationMs
153
+ });
154
+ }
155
+ if (ENABLE_BUILD_PROFILE) {
156
+ console.log(import_chalk.default.gray(`[@nocobase/build]: ${stageName} source layer ${index + 1}/${layers.length} finished in ${(0, import_utils.formatDuration)(layerDurationMs)}`));
157
+ }
63
158
  }
64
- console.warn(import_chalk.default.yellow(`[@nocobase/build]: ${msg}`));
159
+ });
160
+ if (!shouldRunDeclaration) {
65
161
  return;
66
162
  }
67
- const pluginPackages = (0, import_constant.getPluginPackages)(packages);
68
- const cjsPackages = (0, import_constant.getCjsPackages)(packages);
69
- const presetsPackages = (0, import_constant.getPresetsPackages)(packages);
70
- await buildPackages(cjsPackages, "lib", import_buildCjs.buildCjs);
71
- const clientCore = packages.find((item) => item.location === import_constant.CORE_CLIENT);
72
- if (clientCore) {
73
- await buildPackage(clientCore, "es", import_buildClient.buildClient);
74
- }
75
- const esmPackages = packages.filter((pkg) => import_constant.ESM_PACKAGES.includes(pkg.name));
76
- await buildPackages(esmPackages, "lib", import_buildCjs.buildCjs);
77
- await buildPackages(esmPackages, "es", import_buildEsm.buildEsm);
78
- await buildPackages(pluginPackages, "dist", import_buildPlugin.buildPlugin);
79
- await buildPackages(presetsPackages, "lib", import_buildCjs.buildCjs);
80
- const appClient = packages.find((item) => item.location === import_constant.CORE_APP);
81
- if (appClient) {
82
- await runScript(["umi", "build"], import_constant.ROOT_PATH, {
83
- APP_ROOT: import_path.default.join(import_constant.CORE_APP, "client"),
84
- ANALYZE: process.env.BUILD_ANALYZE === "true" ? "1" : void 0
85
- });
86
- }
87
- (0, import_utils.writeToCache)(BUILD_ERROR, {});
163
+ await (0, import_utils.runProfiledStage)(profile, `${stageName} declaration`, async () => {
164
+ for (let index = 0; index < layers.length; index++) {
165
+ const layer = layers[index];
166
+ console.log(import_chalk.default.cyan(`[@nocobase/build]: ${stageName} declaration layer ${index + 1}/${layers.length} (${layer.length} packages)`));
167
+ const layerStart = (0, import_utils.nowMs)();
168
+ await (0, import_utils.runWithConcurrency)(layer, declarationConcurrency, async (pkg) => {
169
+ await buildPackageDeclarationLifecycle(pkg, targetDir, profile);
170
+ });
171
+ const layerDurationMs = (0, import_utils.nowMs)() - layerStart;
172
+ if (profile) {
173
+ profile.layers.push({
174
+ stageName: `${stageName} declaration`,
175
+ layerIndex: index + 1,
176
+ layerCount: layers.length,
177
+ packageCount: layer.length,
178
+ durationMs: layerDurationMs
179
+ });
180
+ }
181
+ if (ENABLE_BUILD_PROFILE) {
182
+ console.log(import_chalk.default.gray(`[@nocobase/build]: ${stageName} declaration layer ${index + 1}/${layers.length} finished in ${(0, import_utils.formatDuration)(layerDurationMs)}`));
183
+ }
184
+ }
185
+ });
88
186
  }
89
- async function buildPackages(packages, targetDir, doBuildPackage) {
90
- for await (const pkg of packages) {
91
- (0, import_utils.writeToCache)(BUILD_ERROR, { pkg: pkg.name });
92
- await buildPackage(pkg, targetDir, doBuildPackage);
187
+ async function buildSinglePackage(pkg, targetDir, doBuildPackage, options) {
188
+ const { stageName, profile = null } = options;
189
+ await (0, import_utils.runProfiledStage)(profile, `${stageName} source`, async () => {
190
+ await buildPackageSourceLifecycle(pkg, targetDir, doBuildPackage, profile);
191
+ });
192
+ if (process.argv.includes("--no-dts") || process.argv.includes("--only-tar")) {
193
+ return;
93
194
  }
195
+ await (0, import_utils.runProfiledStage)(profile, `${stageName} declaration`, async () => {
196
+ await buildPackageDeclarationLifecycle(pkg, targetDir, profile);
197
+ });
94
198
  }
95
- async function buildPackage(pkg, targetDir, doBuildPackage) {
199
+ async function buildPackageSourceLifecycle(pkg, targetDir, doBuildPackage, profile = null) {
96
200
  const sourcemap = process.argv.includes("--sourcemap");
97
- const noDeclaration = process.argv.includes("--no-dts");
98
201
  const hasTar = process.argv.includes("--tar");
99
202
  const onlyTar = process.argv.includes("--only-tar");
100
203
  const log = (0, import_utils.getPkgLog)(pkg.name);
101
204
  const packageJson = (0, import_utils.getPackageJson)(pkg.location);
102
205
  if (onlyTar) {
206
+ const packageStart2 = (0, import_utils.nowMs)();
103
207
  await (0, import_tarPlugin.tarPlugin)(pkg.location, log);
208
+ if (profile) {
209
+ profile.packages.push({
210
+ name: pkg.name,
211
+ targetDir,
212
+ kind: "source",
213
+ durationMs: (0, import_utils.nowMs)() - packageStart2,
214
+ status: "success",
215
+ phases: { tar: (0, import_utils.nowMs)() - packageStart2 }
216
+ });
217
+ }
104
218
  return;
105
219
  }
106
220
  log(`${import_chalk.default.bold((0, import_utils.toUnixPath)(pkg.location.replace(import_constant.PACKAGES_PATH, "").slice(1)))} build start`);
107
221
  const userConfig = (0, import_utils.getUserConfig)(pkg.location);
222
+ const packageStart = (0, import_utils.nowMs)();
223
+ const phaseDurations = {};
224
+ let status = "success";
225
+ const runPhase = async (phaseName, task) => {
226
+ const phaseStart = (0, import_utils.nowMs)();
227
+ await task();
228
+ phaseDurations[phaseName] = (phaseDurations[phaseName] || 0) + ((0, import_utils.nowMs)() - phaseStart);
229
+ };
108
230
  if (packageJson?.scripts?.prebuild) {
109
231
  log("prebuild");
110
- await runScript(["prebuild"], pkg.location);
111
- await packageJson.prebuild(pkg.location);
232
+ await runPhase("prebuild", async () => {
233
+ await (0, import_utils.runScript)(["prebuild"], pkg.location);
234
+ await packageJson.prebuild(pkg.location);
235
+ });
112
236
  }
113
237
  if (userConfig.beforeBuild) {
114
238
  log("beforeBuild");
115
- await userConfig.beforeBuild(log);
116
- }
117
- await doBuildPackage(pkg.location, userConfig, sourcemap, log);
118
- if (!noDeclaration) {
119
- log("build declaration");
120
- await (0, import_buildDeclaration.buildDeclaration)(pkg.location, targetDir);
121
- }
122
- if (packageJson?.scripts?.postbuild) {
123
- log("postbuild");
124
- await runScript(["postbuild"], pkg.location);
125
- }
126
- if (userConfig.afterBuild) {
127
- log("afterBuild");
128
- await userConfig.afterBuild(log);
239
+ await runPhase("beforeBuild", async () => {
240
+ await userConfig.beforeBuild(log);
241
+ });
129
242
  }
130
- await (0, import_addlicense.addLicense)(import_path.default.join(pkg.location, targetDir), log);
131
- if (hasTar) {
132
- await (0, import_tarPlugin.tarPlugin)(pkg.location, log);
243
+ try {
244
+ await runPhase("build", async () => {
245
+ await doBuildPackage(pkg.location, userConfig, sourcemap, log);
246
+ });
247
+ if (packageJson?.scripts?.postbuild) {
248
+ log("postbuild");
249
+ await runPhase("postbuild", async () => {
250
+ await (0, import_utils.runScript)(["postbuild"], pkg.location);
251
+ });
252
+ }
253
+ if (userConfig.afterBuild) {
254
+ log("afterBuild");
255
+ await runPhase("afterBuild", async () => {
256
+ await userConfig.afterBuild(log);
257
+ });
258
+ }
259
+ await runPhase("addLicense", async () => {
260
+ await (0, import_addlicense.addLicense)(import_path.default.join(pkg.location, targetDir), log);
261
+ });
262
+ if (hasTar) {
263
+ await runPhase("tar", async () => {
264
+ await (0, import_tarPlugin.tarPlugin)(pkg.location, log);
265
+ });
266
+ }
267
+ } catch (error) {
268
+ status = "failed";
269
+ (0, import_utils.writeToCache)(BUILD_ERROR, { pkg: pkg.name });
270
+ throw error;
271
+ } finally {
272
+ if (profile) {
273
+ profile.packages.push({
274
+ name: pkg.name,
275
+ targetDir,
276
+ kind: "source",
277
+ durationMs: (0, import_utils.nowMs)() - packageStart,
278
+ status,
279
+ phases: phaseDurations
280
+ });
281
+ if (ENABLE_BUILD_PROFILE) {
282
+ const summary = Object.entries(phaseDurations).sort((a, b) => b[1] - a[1]).map(([name, duration]) => `${name}=${(0, import_utils.formatDuration)(duration)}`).join(", ");
283
+ console.log(
284
+ import_chalk.default.gray(
285
+ `[@nocobase/build:profile] ${pkg.name} ${status} in ${(0, import_utils.formatDuration)((0, import_utils.nowMs)() - packageStart)}${summary ? ` (${summary})` : ""}`
286
+ )
287
+ );
288
+ }
289
+ }
133
290
  }
134
291
  }
135
- function runScript(args, cwd, envs = {}) {
136
- return (0, import_execa.default)("yarn", args, {
137
- cwd,
138
- stdio: "inherit",
139
- env: {
140
- ...process.env,
141
- ...envs,
142
- sourcemap: process.argv.includes("--sourcemap") ? "sourcemap" : void 0,
143
- NODE_ENV: process.env.NODE_ENV || "production"
292
+ async function buildPackageDeclarationLifecycle(pkg, targetDir, profile = null) {
293
+ const log = (0, import_utils.getPkgLog)(pkg.name);
294
+ const packageStart = (0, import_utils.nowMs)();
295
+ const phaseDurations = {};
296
+ let status = "success";
297
+ try {
298
+ log("build declaration");
299
+ const phaseStart = (0, import_utils.nowMs)();
300
+ await (0, import_buildDeclaration.buildDeclaration)(pkg.location, targetDir);
301
+ phaseDurations.declaration = (0, import_utils.nowMs)() - phaseStart;
302
+ } catch (error) {
303
+ status = "failed";
304
+ (0, import_utils.writeToCache)(BUILD_ERROR, { pkg: pkg.name });
305
+ throw error;
306
+ } finally {
307
+ if (profile) {
308
+ profile.packages.push({
309
+ name: pkg.name,
310
+ targetDir,
311
+ kind: "declaration",
312
+ durationMs: (0, import_utils.nowMs)() - packageStart,
313
+ status,
314
+ phases: phaseDurations
315
+ });
316
+ if (ENABLE_BUILD_PROFILE) {
317
+ const summary = Object.entries(phaseDurations).sort((a, b) => b[1] - a[1]).map(([name, duration]) => `${name}=${(0, import_utils.formatDuration)(duration)}`).join(", ");
318
+ console.log(
319
+ import_chalk.default.gray(
320
+ `[@nocobase/build:profile] ${pkg.name} declaration ${status} in ${(0, import_utils.formatDuration)((0, import_utils.nowMs)() - packageStart)}${summary ? ` (${summary})` : ""}`
321
+ )
322
+ );
323
+ }
144
324
  }
145
- });
325
+ }
146
326
  }
147
327
  // Annotate the CommonJS export names for ESM import in node:
148
328
  0 && (module.exports = {
149
329
  build,
150
- buildPackage,
151
330
  buildPackages
152
331
  });
@@ -53,7 +53,11 @@ const diagnosticHost = {
53
53
  getCanonicalFileName: (fileName) => import_typescript.default.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(),
54
54
  getNewLine: () => import_typescript.default.sys.newLine
55
55
  };
56
+ let cachedBaseCompilerOptions = null;
56
57
  function loadCompilerOptions() {
58
+ if (cachedBaseCompilerOptions) {
59
+ return { ...cachedBaseCompilerOptions };
60
+ }
57
61
  const configPath = import_path.default.join(import_constant.ROOT_PATH, "tsconfig.json");
58
62
  const configFile = import_typescript.default.readConfigFile(configPath, import_typescript.default.sys.readFile);
59
63
  if (configFile.error) {
@@ -70,7 +74,8 @@ function loadCompilerOptions() {
70
74
  ...parsedConfig.options
71
75
  };
72
76
  delete options.paths;
73
- return options;
77
+ cachedBaseCompilerOptions = Object.freeze({ ...options });
78
+ return { ...cachedBaseCompilerOptions };
74
79
  }
75
80
  const buildDeclaration = async (cwd, targetDir) => {
76
81
  const srcPath = import_path.default.join(cwd, "src");
@@ -22,23 +22,44 @@ __export(injectPublicPathPlugin_exports, {
22
22
  module.exports = __toCommonJS(injectPublicPathPlugin_exports);
23
23
  function createPluginClientPublicPathDataUri(packageName, clientDistDir) {
24
24
  const code = `
25
- var publicPath = window['__nocobase_public_path__'] || '';
26
- if (!publicPath && window.location && window.location.pathname) {
27
- var marker = '/v2/';
28
- var pathname = window.location.pathname || '/';
29
- var index = pathname.indexOf(marker);
30
- publicPath = index >= 0 ? pathname.slice(0, index + 1) : '/';
31
- }
32
- if (publicPath) {
33
- publicPath = publicPath.replace(/\\/v2\\/?$/, '/');
25
+ var publicPath = '';
26
+ var currentScript = typeof document !== 'undefined' ? document.currentScript : null;
27
+ if (currentScript && currentScript.src) {
28
+ publicPath = currentScript.src
29
+ .replace(/^blob:/, '')
30
+ .replace(/#.*$/, '')
31
+ .replace(/\\?.*$/, '')
32
+ .replace(/\\/[^\\/]+$/, '/');
34
33
  }
35
34
  if (!publicPath) {
36
- publicPath = '/';
35
+ var runtimeAssetBase = window['__webpack_public_path__'] || '';
36
+ if (runtimeAssetBase) {
37
+ if (runtimeAssetBase.charAt(runtimeAssetBase.length - 1) !== '/') {
38
+ runtimeAssetBase += '/';
39
+ }
40
+ publicPath = runtimeAssetBase + 'static/plugins/${packageName}/dist/${clientDistDir}/';
41
+ }
37
42
  }
38
- if (publicPath.charAt(publicPath.length - 1) !== '/') {
39
- publicPath += '/';
43
+ if (!publicPath) {
44
+ publicPath = window['__nocobase_public_path__'] || '';
45
+ if (!publicPath && window.location && window.location.pathname) {
46
+ var marker = '/v2/';
47
+ var pathname = window.location.pathname || '/';
48
+ var index = pathname.indexOf(marker);
49
+ publicPath = index >= 0 ? pathname.slice(0, index + 1) : '/';
50
+ }
51
+ if (publicPath) {
52
+ publicPath = publicPath.replace(/\\/v2\\/?$/, '/');
53
+ }
54
+ if (!publicPath) {
55
+ publicPath = '/';
56
+ }
57
+ if (publicPath.charAt(publicPath.length - 1) !== '/') {
58
+ publicPath += '/';
59
+ }
60
+ publicPath += 'static/plugins/${packageName}/dist/${clientDistDir}/';
40
61
  }
41
- __webpack_public_path__ = publicPath + 'static/plugins/${packageName}/dist/${clientDistDir}/';
62
+ __webpack_public_path__ = publicPath;
42
63
  `;
43
64
  return `data:text/javascript,${encodeURIComponent(code)}`;
44
65
  }
@@ -28,6 +28,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
28
28
  var getPackages_exports = {};
29
29
  __export(getPackages_exports, {
30
30
  getPackages: () => getPackages,
31
+ groupPackagesByTopoLevel: () => groupPackagesByTopoLevel,
31
32
  sortPackages: () => sortPackages
32
33
  });
33
34
  module.exports = __toCommonJS(getPackages_exports);
@@ -76,8 +77,55 @@ function sortPackages(packages) {
76
77
  }
77
78
  return sorter.nodes;
78
79
  }
80
+ function groupPackagesByTopoLevel(packages) {
81
+ const filteredPackages = packages.filter((pkg) => pkg.name !== "@nocobase/docs");
82
+ const packageMap = new Map(filteredPackages.map((pkg) => [pkg.name, pkg]));
83
+ const dependencyMap = /* @__PURE__ */ new Map();
84
+ const reverseDependencyMap = /* @__PURE__ */ new Map();
85
+ for (const pkg of filteredPackages) {
86
+ const pkgJson = require(`${pkg.location}/package.json`);
87
+ const internalDeps = Object.keys({
88
+ ...pkgJson.dependencies,
89
+ ...pkgJson.devDependencies,
90
+ ...pkgJson.peerDependencies
91
+ }).filter((dep) => packageMap.has(dep));
92
+ dependencyMap.set(pkg.name, new Set(internalDeps));
93
+ for (const dep of internalDeps) {
94
+ if (!reverseDependencyMap.has(dep)) {
95
+ reverseDependencyMap.set(dep, /* @__PURE__ */ new Set());
96
+ }
97
+ reverseDependencyMap.get(dep).add(pkg.name);
98
+ }
99
+ }
100
+ const remainingDeps = new Map(
101
+ Array.from(dependencyMap.entries()).map(([name, deps]) => [name, new Set(deps)])
102
+ );
103
+ const pending = new Set(filteredPackages.map((pkg) => pkg.name));
104
+ const layers = [];
105
+ while (pending.size > 0) {
106
+ const layer = Array.from(pending).filter((name) => (remainingDeps.get(name)?.size ?? 0) === 0).map((name) => packageMap.get(name)).filter(Boolean);
107
+ if (layer.length === 0) {
108
+ throw new Error(
109
+ `Unable to group packages by topo level, possible circular dependency among: ${Array.from(pending).join(", ")}`
110
+ );
111
+ }
112
+ layers.push(layer);
113
+ for (const pkg of layer) {
114
+ pending.delete(pkg.name);
115
+ const dependents = reverseDependencyMap.get(pkg.name);
116
+ if (!dependents) {
117
+ continue;
118
+ }
119
+ for (const dependent of dependents) {
120
+ remainingDeps.get(dependent)?.delete(pkg.name);
121
+ }
122
+ }
123
+ }
124
+ return layers;
125
+ }
79
126
  // Annotate the CommonJS export names for ESM import in node:
80
127
  0 && (module.exports = {
81
128
  getPackages,
129
+ groupPackagesByTopoLevel,
82
130
  sortPackages
83
131
  });
@@ -27,17 +27,25 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
28
  var utils_exports = {};
29
29
  __export(utils_exports, {
30
+ createBuildProfileCollector: () => createBuildProfileCollector,
30
31
  defineConfig: () => defineConfig,
32
+ formatDuration: () => formatDuration,
31
33
  getEnvDefine: () => getEnvDefine,
32
34
  getPackageJson: () => getPackageJson,
33
35
  getPkgLog: () => getPkgLog,
34
36
  getUserConfig: () => getUserConfig,
37
+ nowMs: () => nowMs,
38
+ printBuildProfile: () => printBuildProfile,
35
39
  readFromCache: () => readFromCache,
40
+ runProfiledStage: () => runProfiledStage,
41
+ runScript: () => runScript,
42
+ runWithConcurrency: () => runWithConcurrency,
36
43
  toUnixPath: () => toUnixPath,
37
44
  writeToCache: () => writeToCache
38
45
  });
39
46
  module.exports = __toCommonJS(utils_exports);
40
47
  var import_chalk = __toESM(require("chalk"));
48
+ var import_execa = __toESM(require("execa"));
41
49
  var import_path = __toESM(require("path"));
42
50
  var import_fast_glob = __toESM(require("fast-glob"));
43
51
  var import_fs_extra = __toESM(require("fs-extra"));
@@ -121,14 +129,128 @@ function getEnvDefine() {
121
129
  "process.env.APP_ENV": process.env.APP_ENV
122
130
  };
123
131
  }
132
+ function createBuildProfileCollector() {
133
+ return {
134
+ stages: [],
135
+ layers: [],
136
+ packages: []
137
+ };
138
+ }
139
+ async function runProfiledStage(profile, stageName, task) {
140
+ const startedAt = nowMs();
141
+ await task();
142
+ if (profile) {
143
+ profile.stages.push({
144
+ name: stageName,
145
+ durationMs: nowMs() - startedAt
146
+ });
147
+ }
148
+ }
149
+ async function runWithConcurrency(items, concurrency, worker) {
150
+ const queue = [...items];
151
+ const workers = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
152
+ while (queue.length > 0) {
153
+ const item = queue.shift();
154
+ if (!item) {
155
+ return;
156
+ }
157
+ await worker(item);
158
+ }
159
+ });
160
+ await Promise.all(workers);
161
+ }
162
+ function printBuildProfile(profile, totalDurationMs) {
163
+ const phaseTotals = /* @__PURE__ */ new Map();
164
+ for (const pkg of profile.packages) {
165
+ for (const [phaseName, duration] of Object.entries(pkg.phases)) {
166
+ phaseTotals.set(phaseName, (phaseTotals.get(phaseName) || 0) + duration);
167
+ }
168
+ }
169
+ console.log(import_chalk.default.cyan(`[@nocobase/build:profile] total build time ${formatDuration(totalDurationMs)}`));
170
+ if (profile.stages.length > 0) {
171
+ console.log(import_chalk.default.cyan("[@nocobase/build:profile] stage totals"));
172
+ for (const stage of [...profile.stages].sort((a, b) => b.durationMs - a.durationMs)) {
173
+ console.log(import_chalk.default.gray(` ${stage.name}: ${formatDuration(stage.durationMs)}`));
174
+ }
175
+ }
176
+ if (profile.layers.length > 0) {
177
+ console.log(import_chalk.default.cyan("[@nocobase/build:profile] slowest layers"));
178
+ for (const layer of [...profile.layers].sort((a, b) => b.durationMs - a.durationMs).slice(0, 12)) {
179
+ console.log(
180
+ import_chalk.default.gray(
181
+ ` ${layer.stageName} layer ${layer.layerIndex}/${layer.layerCount} (${layer.packageCount} packages): ${formatDuration(layer.durationMs)}`
182
+ )
183
+ );
184
+ }
185
+ }
186
+ if (phaseTotals.size > 0) {
187
+ console.log(import_chalk.default.cyan("[@nocobase/build:profile] aggregated package phases"));
188
+ for (const [phaseName, duration] of [...phaseTotals.entries()].sort((a, b) => b[1] - a[1])) {
189
+ console.log(import_chalk.default.gray(` ${phaseName}: ${formatDuration(duration)}`));
190
+ }
191
+ }
192
+ if (profile.packages.length > 0) {
193
+ const sourcePackages = profile.packages.filter((pkg) => pkg.kind === "source");
194
+ const declarationPackages = profile.packages.filter((pkg) => pkg.kind === "declaration");
195
+ console.log(import_chalk.default.cyan("[@nocobase/build:profile] slowest source packages"));
196
+ for (const pkg of [...sourcePackages].sort((a, b) => b.durationMs - a.durationMs).slice(0, 20)) {
197
+ const summary = Object.entries(pkg.phases).sort((a, b) => b[1] - a[1]).slice(0, 4).map(([name, duration]) => `${name}=${formatDuration(duration)}`).join(", ");
198
+ console.log(
199
+ import_chalk.default.gray(
200
+ ` ${pkg.name} [${pkg.status}] ${formatDuration(pkg.durationMs)}${summary ? ` (${summary})` : ""}`
201
+ )
202
+ );
203
+ }
204
+ console.log(import_chalk.default.cyan("[@nocobase/build:profile] slowest declaration packages"));
205
+ for (const pkg of [...declarationPackages].sort((a, b) => b.durationMs - a.durationMs).slice(0, 20)) {
206
+ const summary = Object.entries(pkg.phases).sort((a, b) => b[1] - a[1]).slice(0, 4).map(([name, duration]) => `${name}=${formatDuration(duration)}`).join(", ");
207
+ console.log(
208
+ import_chalk.default.gray(
209
+ ` ${pkg.name} [${pkg.status}] ${formatDuration(pkg.durationMs)}${summary ? ` (${summary})` : ""}`
210
+ )
211
+ );
212
+ }
213
+ }
214
+ }
215
+ function nowMs() {
216
+ return Date.now();
217
+ }
218
+ function formatDuration(durationMs) {
219
+ if (durationMs >= 6e4) {
220
+ return `${(durationMs / 6e4).toFixed(2)}m`;
221
+ }
222
+ if (durationMs >= 1e3) {
223
+ return `${(durationMs / 1e3).toFixed(2)}s`;
224
+ }
225
+ return `${Math.round(durationMs)}ms`;
226
+ }
227
+ function runScript(args, cwd, envs = {}) {
228
+ return (0, import_execa.default)("yarn", args, {
229
+ cwd,
230
+ stdio: "inherit",
231
+ env: {
232
+ ...process.env,
233
+ ...envs,
234
+ sourcemap: process.argv.includes("--sourcemap") ? "sourcemap" : void 0,
235
+ NODE_ENV: process.env.NODE_ENV || "production"
236
+ }
237
+ });
238
+ }
124
239
  // Annotate the CommonJS export names for ESM import in node:
125
240
  0 && (module.exports = {
241
+ createBuildProfileCollector,
126
242
  defineConfig,
243
+ formatDuration,
127
244
  getEnvDefine,
128
245
  getPackageJson,
129
246
  getPkgLog,
130
247
  getUserConfig,
248
+ nowMs,
249
+ printBuildProfile,
131
250
  readFromCache,
251
+ runProfiledStage,
252
+ runScript,
253
+ runWithConcurrency,
132
254
  toUnixPath,
133
255
  writeToCache
134
256
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocobase/build",
3
- "version": "2.1.0-alpha.13",
3
+ "version": "2.1.0-alpha.15",
4
4
  "description": "Library build tool based on rollup.",
5
5
  "main": "lib/index.js",
6
6
  "types": "./lib/index.d.ts",
@@ -53,5 +53,5 @@
53
53
  "build": "tsup",
54
54
  "build:watch": "tsup --watch"
55
55
  },
56
- "gitHead": "2807a8948412d9c235115a31a81a66f7c82dd173"
56
+ "gitHead": "7c86e75b0af4b9f532c8ebf5ef96a7423b0ab60e"
57
57
  }