jiek 2.2.7-alpha.3 → 2.2.7-alpha.5

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 (62) hide show
  1. package/.jiek-production-tag +0 -0
  2. package/dist/.internal/.chunks/{getWD.ZF0avqDB.cjs → filterSupport.4rM7f6jB.cjs} +38 -29
  3. package/dist/.internal/.chunks/{getWD.D6wq8Qc2.js → filterSupport.BXWpLBpT.js} +37 -28
  4. package/dist/.internal/.chunks/index.BHuJRlvZ.js +9059 -0
  5. package/dist/.internal/.chunks/index.Daihq2aI.cjs +9071 -0
  6. package/dist/.internal/.chunks/loadConfig.CFfzkm_p.js +110 -0
  7. package/dist/.internal/.chunks/loadConfig.OOKddvHF.cjs +117 -0
  8. package/dist/.internal/bin/common.cjs +757 -0
  9. package/dist/.internal/bin/common.d.cts +18 -0
  10. package/dist/.internal/bin/common.d.ts +18 -0
  11. package/dist/.internal/bin/common.js +750 -0
  12. package/dist/.internal/bridge.cjs +20 -2
  13. package/dist/.internal/bridge.js +19 -1
  14. package/dist/.internal/utils/filterSupport.cjs +1 -3
  15. package/dist/.internal/utils/filterSupport.js +1 -3
  16. package/dist/.internal/utils/loadConfig.cjs +8 -94
  17. package/dist/.internal/utils/loadConfig.js +7 -92
  18. package/dist/bin/build.cjs +2 -507
  19. package/dist/bin/index.cjs +5 -1
  20. package/package.json +2 -3
  21. package/src/bin/build.cts +2 -8
  22. package/src/bin/common.ts +3 -0
  23. package/src/bin/index.cts +2 -1
  24. package/src/commands/publish.ts +5 -0
  25. package/dist/.internal/.chunks/jiek_create-require.CWFWNQHj.cjs +0 -5
  26. package/dist/.internal/.chunks/jiek_create-require.CxSGbkTB.js +0 -5
  27. package/dist/.internal/commands/build/analyzer.cjs +0 -201
  28. package/dist/.internal/commands/build/analyzer.d.cts +0 -30
  29. package/dist/.internal/commands/build/analyzer.d.ts +0 -30
  30. package/dist/.internal/commands/build/analyzer.js +0 -195
  31. package/dist/.internal/commands/descriptions.cjs +0 -21
  32. package/dist/.internal/commands/descriptions.d.cts +0 -5
  33. package/dist/.internal/commands/descriptions.d.ts +0 -5
  34. package/dist/.internal/commands/descriptions.js +0 -17
  35. package/dist/.internal/commands/meta.cjs +0 -16
  36. package/dist/.internal/commands/meta.d.cts +0 -3
  37. package/dist/.internal/commands/meta.d.ts +0 -3
  38. package/dist/.internal/commands/meta.js +0 -15
  39. package/dist/.internal/commands/utils/optionParser.cjs +0 -8
  40. package/dist/.internal/commands/utils/optionParser.d.cts +0 -3
  41. package/dist/.internal/commands/utils/optionParser.d.ts +0 -3
  42. package/dist/.internal/commands/utils/optionParser.js +0 -6
  43. package/dist/.internal/server.cjs +0 -33
  44. package/dist/.internal/server.d.cts +0 -8
  45. package/dist/.internal/server.d.ts +0 -8
  46. package/dist/.internal/server.js +0 -27
  47. package/dist/.internal/utils/checkDependency.cjs +0 -39
  48. package/dist/.internal/utils/checkDependency.d.cts +0 -3
  49. package/dist/.internal/utils/checkDependency.d.ts +0 -3
  50. package/dist/.internal/utils/checkDependency.js +0 -34
  51. package/dist/.internal/utils/getRoot.cjs +0 -17
  52. package/dist/.internal/utils/getRoot.d.cts +0 -3
  53. package/dist/.internal/utils/getRoot.d.ts +0 -3
  54. package/dist/.internal/utils/getRoot.js +0 -11
  55. package/dist/.internal/utils/getWD.cjs +0 -15
  56. package/dist/.internal/utils/getWD.d.cts +0 -6
  57. package/dist/.internal/utils/getWD.d.ts +0 -6
  58. package/dist/.internal/utils/getWD.js +0 -10
  59. package/dist/.internal/utils/tsRegister.cjs +0 -25
  60. package/dist/.internal/utils/tsRegister.d.cts +0 -3
  61. package/dist/.internal/utils/tsRegister.d.ts +0 -3
  62. package/dist/.internal/utils/tsRegister.js +0 -26
@@ -0,0 +1,750 @@
1
+ import { g as getWD, t as type$1, r as require, f as filterPackagesGraph, a as getSelectedProjectsGraph } from '../.chunks/filterSupport.BXWpLBpT.js';
2
+ import { program } from 'commander';
3
+ import { existsSync, mkdirSync, writeFileSync, statSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import process from 'node:process';
6
+ import { MultiBar, Presets } from 'cli-progress';
7
+ import { e as execaCommand } from '../.chunks/index.BHuJRlvZ.js';
8
+ import { execSync } from 'node:child_process';
9
+ import { confirm } from '@inquirer/prompts';
10
+ import { BUILDER_TYPE_PACKAGE_NAME_MAP, BUILDER_TYPES } from '../rollup/base.js';
11
+ import Koa from 'koa';
12
+ import { l as loadConfig, t as tsRegisterName } from '../.chunks/loadConfig.CFfzkm_p.js';
13
+ import 'node:module';
14
+ import 'js-yaml';
15
+ import '@jiek/utils/getWorkspaceDir';
16
+ import 'node:url';
17
+ import 'node:string_decoder';
18
+ import 'node:util';
19
+ import 'node:tty';
20
+ import 'child_process';
21
+ import 'path';
22
+ import 'fs';
23
+ import 'node:timers/promises';
24
+ import 'node:os';
25
+ import 'node:events';
26
+ import 'node:v8';
27
+ import 'node:stream';
28
+ import 'node:buffer';
29
+ import 'node:stream/promises';
30
+
31
+ var name = "jiek";
32
+ var type = "module";
33
+ var version = "2.2.7-alpha.4";
34
+ var description$1 = "A lightweight toolkit for compiling and managing libraries based on `package.json` metadata and suitable for `Monorepo`.";
35
+ var author = "YiJie <yijie4188@gmail.com>";
36
+ var homepage = "https://github.com/NWYLZW/jiek/tree/master/packages/jiek#readme";
37
+ var repository = {
38
+ url: "nwylzw/jiek",
39
+ directory: "packages/jiek"
40
+ };
41
+ var bugs = "https://github.com/NWYLZW/jiek/issues?q=is%3Aissue+is%3Aopen+jiek";
42
+ var keywords = [
43
+ "cli",
44
+ "zero-config",
45
+ "bundler",
46
+ "library",
47
+ "monorepo",
48
+ "builder",
49
+ "rollup",
50
+ "workspace"
51
+ ];
52
+ var exports = {
53
+ "./package.json": "./package.json",
54
+ ".": "./src/index.ts",
55
+ "./bin-helper": {
56
+ require: "./bin-helper/index.cjs",
57
+ "default": "./bin-helper/index.js"
58
+ },
59
+ "./rollup": "./src/rollup/index.ts"
60
+ };
61
+ var imports = {
62
+ "#~/*": "./src/*.ts"
63
+ };
64
+ var bin = {
65
+ jiek: "bin/index.cjs",
66
+ jk: "bin/index.cjs",
67
+ "jiek-build": "bin/build.cjs",
68
+ jb: "bin/build.cjs"
69
+ };
70
+ var files = [
71
+ "LICENSE",
72
+ "README.md",
73
+ "bin",
74
+ "bin-helper",
75
+ "dist",
76
+ "src"
77
+ ];
78
+ var scripts = {
79
+ prepublish: "pnpm test && jb -nm && jk",
80
+ postpublish: "jk",
81
+ test: "vitest run"
82
+ };
83
+ var peerDependencies = {
84
+ "@pnpm/filter-workspace-packages": "^7.2.13||^8.0.0||^9.0.0||^10.0.0||>=1000.0.0",
85
+ "@rollup/plugin-terser": "^0.4.4",
86
+ "esbuild-register": "^3.5.0",
87
+ postcss: "^8.4.47",
88
+ "rollup-plugin-esbuild": "^6.1.0",
89
+ "rollup-plugin-postcss": "^4.0.2",
90
+ "rollup-plugin-swc3": "^0.12.1",
91
+ typescript: "^4.0.0||^5.0.0",
92
+ "vite-bundle-analyzer": "0.16.0-beta.3"
93
+ };
94
+ var dependencies = {
95
+ "@inquirer/prompts": "^7.2.0",
96
+ "@jiek/pkger": "workspace:^",
97
+ "@jiek/rollup-plugin-dts": "^6.3.8",
98
+ "@jiek/utils": "workspace:^",
99
+ "@rollup/plugin-commonjs": "^28.0.0",
100
+ "@rollup/plugin-inject": "^5.0.5",
101
+ "@rollup/plugin-json": "^6.0.1",
102
+ "@rollup/plugin-node-resolve": "^15.3.0",
103
+ "cli-progress": "^3.12.0",
104
+ commander: "^12.0.0",
105
+ "detect-indent": "^6.1.0",
106
+ "js-yaml": "^4.1.0",
107
+ "jsonc-parser": "^3.2.1",
108
+ koa: "^2.15.3",
109
+ rollup: "^4.0.0"
110
+ };
111
+ var devDependencies = {
112
+ "@npm/types": "^1.0.2",
113
+ "@pnpm/filter-workspace-packages": "^7.2.13",
114
+ "@pnpm/workspace.pkgs-graph": "^2.0.15",
115
+ "@rollup/plugin-terser": "^0.4.4",
116
+ "@types/cli-progress": "^3.11.5",
117
+ "@types/inquirer": "^9.0.7",
118
+ "@types/js-yaml": "^4.0.9",
119
+ "@types/koa": "^2.15.0",
120
+ "@types/micromatch": "^4.0.6",
121
+ "@types/react": "^18.3.14",
122
+ "esbuild-register": "^3.5.0",
123
+ execa: "~9.3.1",
124
+ micromatch: "^4.0.5",
125
+ "node-sass": "^9.0.0",
126
+ postcss: "^8.4.47",
127
+ "rollup-plugin-esbuild": "^6.1.0",
128
+ "rollup-plugin-postcss": "^4.0.2",
129
+ "rollup-plugin-swc3": "^0.12.1",
130
+ "vite-bundle-analyzer": "0.16.0-beta.3"
131
+ };
132
+ var publishConfig = {
133
+ directory: "./dist/.internal"
134
+ };
135
+ var pkg = {
136
+ name: name,
137
+ type: type,
138
+ version: version,
139
+ description: description$1,
140
+ author: author,
141
+ homepage: homepage,
142
+ repository: repository,
143
+ bugs: bugs,
144
+ keywords: keywords,
145
+ exports: exports,
146
+ imports: imports,
147
+ bin: bin,
148
+ files: files,
149
+ scripts: scripts,
150
+ peerDependencies: peerDependencies,
151
+ dependencies: dependencies,
152
+ devDependencies: devDependencies,
153
+ publishConfig: publishConfig
154
+ };
155
+
156
+ const entriesDescription = `
157
+ Specify the build entry-points of the package.json's 'exports' field.
158
+ Support glob pattern and array.
159
+ .e.g. '.', './*', './sub/*', './a,./b'.
160
+ `.trim();
161
+ const filterDescription = `
162
+ Filter the packages from the workspace.
163
+ Support fuzzy match and array.
164
+ .e.g. 'core,utils'.
165
+ `.trim();
166
+ const outdirDescription = `
167
+ The output directory of the build, which relative to the target subpackage root directory.
168
+ Support with variables: 'PKG_NAME',
169
+ .e.g. 'dist/{{PKG_NAME}}'.
170
+ `.trim();
171
+
172
+ const { notWorkspace } = getWD();
173
+ const IS_WORKSPACE = !notWorkspace;
174
+
175
+ program.name("jk/jiek").version(pkg.version).description(`${pkg.description} - Version ${pkg.version}`).option("-c, --config-path <configPath>", "Custom jiek config path").option("--env.<name>=<value>", "Set the environment variable.");
176
+ if (type$1 !== "" && IS_WORKSPACE) {
177
+ program.option("-f, --filter <filter>", filterDescription);
178
+ }
179
+
180
+ function Main() {
181
+ const { useState, useMemo, useEffect, useCallback } = React;
182
+ const [path, setPath] = useState(() => location.pathname.replace(/^\/ana\/?/, ""));
183
+ const [pkgName, entry] = useMemo(() => {
184
+ const pkgName2 = /^(@[^/]+\/[^/]+|[^/]+)\/?/.exec(path)?.[1];
185
+ return [
186
+ pkgName2,
187
+ pkgName2 != null ? path.replace(`${pkgName2}/`, "") : void 0
188
+ ];
189
+ }, [path]);
190
+ const push = useCallback((newPath) => {
191
+ setPath(newPath);
192
+ document.title = `${document.title.replace(/ - \/.*/, "")} - /${newPath}`;
193
+ history.pushState(null, "", `/ana/${newPath}`);
194
+ }, []);
195
+ const filterModules = useCallback((startWith) => {
196
+ const modules = analyzeModule.filter((m) => m.filename.startsWith(startWith));
197
+ dispatchEvent(new CustomEvent("send:filter", { detail: { analyzeModule: modules } }));
198
+ }, []);
199
+ useEffect(() => {
200
+ if (path !== "") {
201
+ document.title = `${document.title.replace(/ - \/.*/, "")} - /${path}`;
202
+ } else {
203
+ document.title = document.title.replace(/ - \/.*/, "");
204
+ }
205
+ filterModules(path);
206
+ }, [path, filterModules]);
207
+ useEffect(() => {
208
+ const offGraphClick = listen("graph:click", ({ detail }) => {
209
+ if (!detail) return;
210
+ let root = detail.node;
211
+ while (root.parent) {
212
+ root = root.parent;
213
+ }
214
+ if (root.filename === path) return;
215
+ push(root.filename);
216
+ });
217
+ return () => {
218
+ offGraphClick();
219
+ };
220
+ }, [push]);
221
+ function listen(type, listener) {
222
+ window.addEventListener(type, listener);
223
+ return () => {
224
+ window.removeEventListener(type, listener);
225
+ };
226
+ }
227
+ return /* @__PURE__ */ React.createElement(
228
+ "div",
229
+ {
230
+ style: {
231
+ padding: "12px 55px"
232
+ }
233
+ },
234
+ "/",
235
+ /* @__PURE__ */ React.createElement(
236
+ "select",
237
+ {
238
+ style: {
239
+ appearance: "none",
240
+ border: "none",
241
+ background: "none"
242
+ },
243
+ value: pkgName,
244
+ onChange: (e) => push(e.target.value)
245
+ },
246
+ /* @__PURE__ */ React.createElement("option", { value: "" }, "All"),
247
+ analyzeModule.map((m) => /^(@[^/]+\/[^/]+|[^/]+)\/?/.exec(m.filename)?.[1]).filter((v, i, a) => a.indexOf(v) === i).map((v) => /* @__PURE__ */ React.createElement("option", { key: v, value: v }, v))
248
+ ),
249
+ pkgName != null && /* @__PURE__ */ React.createElement(React.Fragment, null, "/", /* @__PURE__ */ React.createElement(
250
+ "select",
251
+ {
252
+ style: {
253
+ appearance: "none",
254
+ border: "none",
255
+ background: "none"
256
+ },
257
+ value: entry,
258
+ onChange: (e) => push(`${pkgName}/${e.target.value}`)
259
+ },
260
+ /* @__PURE__ */ React.createElement("option", { value: "" }, "All"),
261
+ analyzeModule.filter((m) => m.filename.startsWith(`${pkgName}/`)).map((m) => m.filename.replace(`${pkgName}/`, "")).filter((v, i, a) => a.indexOf(v) === i).map((v) => /* @__PURE__ */ React.createElement("option", { key: v, value: v }, v))
262
+ ))
263
+ );
264
+ }
265
+
266
+ function render() {
267
+ CUSTOM_SIDE_BAR = true;
268
+ window.addEventListener("client:ready", () => window.dispatchEvent(
269
+ new CustomEvent("send:ui", {
270
+ detail: { type: "Main", Component: __REPLACE_INJECT__ }
271
+ })
272
+ ));
273
+ }
274
+ const CLIENT_CUSTOM_RENDER_SCRIPT = [
275
+ Main.toString(),
276
+ render.toString().replace("__REPLACE_INJECT__", Main.name),
277
+ `(${render.name})()`
278
+ ].join("\n");
279
+
280
+ function parseBoolean(v) {
281
+ if (v === void 0) return true;
282
+ return Boolean(v);
283
+ }
284
+
285
+ async function checkDependency(dependency) {
286
+ try {
287
+ require.resolve(dependency);
288
+ } catch {
289
+ console.error(`The package '${dependency}' is not installed, please install it first.`);
290
+ const { notWorkspace } = getWD();
291
+ const command = `pnpm add -${notWorkspace ? "" : "w"}D ${dependency}`;
292
+ if (await confirm({ message: `Do you want to add it now? (${command})` })) {
293
+ execSync(command, {
294
+ stdio: "inherit",
295
+ cwd: process.cwd(),
296
+ env: process.env
297
+ });
298
+ } else {
299
+ console.warn(`You can run the command '${command}' to install it manually.`);
300
+ process.exit(1);
301
+ }
302
+ }
303
+ }
304
+
305
+ const registerAnalyzerCommandOptions = (command) => command.option("--ana", "Enable the bundle analyzer.", parseBoolean).option("--ana.dir <DIR>", "The directory of the bundle analyzer.", ".jk-analyses").option(
306
+ "--ana.mode <MODE>",
307
+ 'The mode of the bundle analyzer, support "static", "json" and "server".',
308
+ "server"
309
+ ).option("--ana.open", "Open the bundle analyzer in the browser.", parseBoolean).option(
310
+ "--ana.size <SIZE>",
311
+ 'The default size of the bundle analyzer, support "stat", "parsed" and "gzip".',
312
+ "parsed"
313
+ );
314
+ const useAnalyzer = async (options, server) => {
315
+ const modules = [];
316
+ let bundleAnalyzerModule;
317
+ const analyzer = options.ana ? {
318
+ dir: options["ana.dir"],
319
+ mode: options["ana.mode"],
320
+ open: options["ana.open"],
321
+ size: options["ana.size"]
322
+ } : void 0;
323
+ if (options.ana && ![
324
+ "stat",
325
+ "parsed",
326
+ "gzip"
327
+ ].includes(analyzer?.size ?? "")) {
328
+ throw new Error('The value of `ana.size` must be "stat", "parsed" or "gzip"');
329
+ }
330
+ if (analyzer) {
331
+ await checkDependency("vite-bundle-analyzer");
332
+ bundleAnalyzerModule = await import('vite-bundle-analyzer');
333
+ }
334
+ const refreshAnalyzer = async (cwd, applyModules) => {
335
+ if (!(analyzer && server && bundleAnalyzerModule)) return;
336
+ if (analyzer.mode === "json") {
337
+ const anaDir = path.resolve(cwd, analyzer.dir);
338
+ if (!existsSync(anaDir)) {
339
+ mkdirSync(anaDir, { recursive: true });
340
+ }
341
+ const gitIgnorePath = path.resolve(anaDir, ".gitignore");
342
+ if (!existsSync(gitIgnorePath)) {
343
+ writeFileSync(gitIgnorePath, "*\n!.gitignore\n");
344
+ }
345
+ const npmIgnorePath = path.resolve(anaDir, ".npmignore");
346
+ if (!existsSync(npmIgnorePath)) {
347
+ writeFileSync(npmIgnorePath, "*\n");
348
+ }
349
+ if (!statSync(anaDir).isDirectory()) {
350
+ throw new Error(`The directory '${anaDir}' is not a directory.`);
351
+ }
352
+ }
353
+ const { renderView, injectHTMLTag } = bundleAnalyzerModule;
354
+ applyModules.forEach((m) => {
355
+ const index = modules.findIndex(({ filename }) => filename === m.filename);
356
+ if (index === -1) {
357
+ modules.push(m);
358
+ } else {
359
+ modules[index] = m;
360
+ }
361
+ });
362
+ let html = await renderView(modules, {
363
+ title: `Jiek Analyzer`,
364
+ mode: analyzer.size
365
+ });
366
+ html = injectHTMLTag({
367
+ html,
368
+ injectTo: "body",
369
+ descriptors: [
370
+ { kind: "script", text: CLIENT_CUSTOM_RENDER_SCRIPT }
371
+ ]
372
+ });
373
+ void server.renderTo("/ana", html);
374
+ };
375
+ return {
376
+ modules,
377
+ refreshAnalyzer,
378
+ ANALYZER_ENV: {
379
+ JIEK_ANALYZER: analyzer ? JSON.stringify(analyzer) : void 0
380
+ }
381
+ };
382
+ };
383
+
384
+ const createServer = (port, host) => {
385
+ const app = new Koa();
386
+ app.listen(port, host);
387
+ const streams = /* @__PURE__ */ new Map();
388
+ app.use(async (ctx) => {
389
+ let stream = streams.get(ctx.path);
390
+ if (stream == null) {
391
+ const maybeKey = streams.keys().find((p) => ctx.path.startsWith(p));
392
+ stream = maybeKey != null ? streams.get(maybeKey) : void 0;
393
+ }
394
+ if (stream != null) {
395
+ ctx.body = stream;
396
+ }
397
+ });
398
+ return {
399
+ port,
400
+ host,
401
+ rootUrl: `http://${host}:${port}`,
402
+ renderTo: async (path, stream) => {
403
+ streams.set(path, stream);
404
+ }
405
+ };
406
+ };
407
+
408
+ const FILE_TEMPLATE = (manifest) => `
409
+ module.exports = require('jiek/rollup').template(${JSON.stringify(manifest, null, 2)})
410
+ `.trimStart();
411
+ const ROLLUP_BIN = require.resolve("rollup").replace(/dist\/rollup.js$/, "dist/bin/rollup");
412
+ const isDefault = process.env.JIEK_BIN__FILENAME === "build.cjs";
413
+ const description = `
414
+ Build the package according to the 'exports' field from the package.json.
415
+ If you want to through the options to the \`rollup\` command, you can pass the options after '--'.
416
+ ${isDefault ? "This command is the default command." : ""}
417
+ `.trim();
418
+ let DEFAULT_BUILDER_TYPE;
419
+ Object.entries(BUILDER_TYPE_PACKAGE_NAME_MAP).forEach(([type, packageName]) => {
420
+ try {
421
+ require.resolve(packageName);
422
+ DEFAULT_BUILDER_TYPE = type;
423
+ } catch {
424
+ }
425
+ });
426
+ if (!DEFAULT_BUILDER_TYPE) {
427
+ DEFAULT_BUILDER_TYPE = "esbuild";
428
+ }
429
+ const buildFilterDescription = `
430
+ ${filterDescription}
431
+ If you pass the --filter option, it will merge into the filters of the command.
432
+ `.trim();
433
+ const buildEntriesDescription = `
434
+ ${entriesDescription}
435
+ If you pass the --entries option, it will merge into the entries of the command.
436
+ `.trim();
437
+ let command = isDefault ? (() => {
438
+ const c = program.name("jb/jiek-build").helpCommand(false);
439
+ if (IS_WORKSPACE) {
440
+ c.argument("[filters]", buildFilterDescription);
441
+ } else {
442
+ c.argument("[entries]", buildEntriesDescription);
443
+ }
444
+ return c;
445
+ })() : program.command(`build [${IS_WORKSPACE ? "filters" : "entries"}]`);
446
+ command = command.description(description).option("-t, --type <TYPE>", `The type of build, support ${BUILDER_TYPES.map((s) => `"${s}"`).join(", ")}.`, (v) => {
447
+ if (!BUILDER_TYPES.includes(v)) {
448
+ throw new Error(`The value of 'type' must be ${BUILDER_TYPES.map((s) => `"${s}"`).join(", ")}`);
449
+ }
450
+ return String(v);
451
+ }, "esbuild").option("-o, --outdir <OUTDIR>", outdirDescription, String, "dist").option("-e, --entries <ENTRIES>", entriesDescription).option("--external <EXTERNAL>", "Specify the external dependencies of the package.", String).option("--noConvert", "Specify the `crossModuleConvertor` option to false.", parseBoolean).option("-nj, --noJs", "Do not output js files.", parseBoolean).option("-nd, --noDts", "Do not output dts files.", parseBoolean).option("-nm, --noMin", "Do not output minify files.", parseBoolean).option(
452
+ "--minType <MINTYPE>",
453
+ 'The type of minify, support "builder" and "terser".',
454
+ (v) => {
455
+ if (!["builder", "terser"].includes(v)) {
456
+ throw new Error('The value of `minType` must be "builder" or "terser"');
457
+ }
458
+ return String(v);
459
+ }
460
+ ).option("-nc, --noClean", "Do not clean the output directory before building.", parseBoolean).option(
461
+ "-om, --onlyMin",
462
+ "Only output minify files, but dts files will still be output, it only replaces the js files.",
463
+ parseBoolean
464
+ );
465
+ command = command.option("--features.keepImportAttributes", "Keep the import attributes in the output.");
466
+ command = command.option("--tsconfig <TSCONFIG>", "The path of the tsconfig file which is used to generate js and dts files.", String).option("--dtsconfig <DTSCONFIG>", "The path of the tsconfig file which is used to generate dts files.", String);
467
+ command = command.option("-w, --watch", "Watch the file changes.", parseBoolean).option("-p, --port <PORT>", "The port of the server.", Number.parseInt, 8888);
468
+ command = registerAnalyzerCommandOptions(command);
469
+ command = command.option("-s, --silent", "Don't display logs.", parseBoolean).option("-v, --verbose", "Display debug logs.", parseBoolean);
470
+ command.action(async (commandFiltersOrEntries, options) => {
471
+ let {
472
+ type,
473
+ outdir,
474
+ watch,
475
+ silent,
476
+ verbose,
477
+ entries: optionEntries,
478
+ external,
479
+ noConvert,
480
+ noJs: withoutJs,
481
+ noDts: withoutDts,
482
+ noMin: withoutMin,
483
+ minType: minifyType,
484
+ noClean,
485
+ onlyMin,
486
+ tsconfig,
487
+ dtsconfig
488
+ } = options;
489
+ const resolvedType = type ?? DEFAULT_BUILDER_TYPE;
490
+ if (!withoutJs) {
491
+ await checkDependency(BUILDER_TYPE_PACKAGE_NAME_MAP[resolvedType]);
492
+ if (minifyType === "builder") {
493
+ minifyType = resolvedType;
494
+ }
495
+ }
496
+ if (!withoutMin && minifyType === "terser") {
497
+ await checkDependency("@rollup/plugin-terser");
498
+ }
499
+ let shouldPassThrough = false;
500
+ const passThroughOptions = process.argv.reduce(
501
+ (acc, value) => {
502
+ if (shouldPassThrough) {
503
+ acc.push(value);
504
+ }
505
+ if (value === "--") {
506
+ shouldPassThrough = true;
507
+ }
508
+ return acc;
509
+ },
510
+ []
511
+ );
512
+ const shouldCreateServer = [
513
+ options.ana === true && options["ana.mode"] === "server"
514
+ ].some(Boolean);
515
+ const server = shouldCreateServer ? createServer(options.port, "localhost") : void 0;
516
+ const {
517
+ ANALYZER_ENV,
518
+ refreshAnalyzer
519
+ } = await useAnalyzer(options, server);
520
+ const { build } = loadConfig();
521
+ silent = silent ?? build?.silent ?? false;
522
+ if (withoutMin && onlyMin) {
523
+ throw new Error("Cannot use both --without-minify and --only-minify");
524
+ }
525
+ if (onlyMin && withoutJs) {
526
+ throw new Error("Cannot use --without-js and --only-minify at the same time");
527
+ }
528
+ let entries = [
529
+ optionEntries,
530
+ IS_WORKSPACE ? void 0 : commandFiltersOrEntries
531
+ ].filter(Boolean).join(",");
532
+ if (entries.length === 0) {
533
+ entries = void 0;
534
+ }
535
+ const env = {
536
+ ...ANALYZER_ENV,
537
+ JIEK_BUILDER: type,
538
+ JIEK_OUT_DIR: outdir,
539
+ JIEK_CLEAN: String(!noClean),
540
+ JIEK_ENTRIES: entries,
541
+ JIEK_EXTERNAL: external,
542
+ JIEK_CROSS_MODULE_CONVERTOR: String(!noConvert),
543
+ JIEK_WITHOUT_JS: String(withoutJs),
544
+ JIEK_WITHOUT_DTS: String(withoutDts),
545
+ JIEK_WITHOUT_MINIFY: String(withoutMin),
546
+ JIEK_ONLY_MINIFY: String(onlyMin),
547
+ JIEK_MINIFY_TYPE: minifyType,
548
+ JIEK_TSCONFIG: tsconfig,
549
+ JIEK_DTSCONFIG: dtsconfig,
550
+ JIEK_FEATURES: JSON.stringify({
551
+ keepImportAttributes: options["features.keepImportAttributes"]
552
+ }),
553
+ ...process.env
554
+ };
555
+ const multiBars = new MultiBar({
556
+ clearOnComplete: false,
557
+ hideCursor: true,
558
+ format: "- {bar} | {status} | {pkgName} | {input} | {message}"
559
+ }, Presets.shades_classic);
560
+ const { wd } = getWD();
561
+ const wdNodeModules = path.resolve(wd, "node_modules");
562
+ if (!existsSync(wdNodeModules)) {
563
+ mkdirSync(wdNodeModules);
564
+ }
565
+ const resolveByJiekTemp = (...paths) => path.resolve(wdNodeModules, ".jiek", ...paths);
566
+ const jiekTemp = resolveByJiekTemp();
567
+ if (!existsSync(jiekTemp)) {
568
+ try {
569
+ mkdirSync(jiekTemp);
570
+ } catch (e) {
571
+ if (e.code !== "EEXIST") {
572
+ throw e;
573
+ }
574
+ }
575
+ }
576
+ let i = 0;
577
+ const buildPackage = async ([pkgCWD, manifest], {
578
+ resolveByJiekTemp: resolveByJiekTemp2
579
+ }) => {
580
+ if (manifest.name == null) {
581
+ throw new Error("package.json must have a name field");
582
+ }
583
+ const escapeManifestName = manifest.name.replace(/^@/g, "").replace(/\//g, "+");
584
+ const configFile = resolveByJiekTemp2(
585
+ `${escapeManifestName ?? `anonymous-${i++}`}.rollup.config.js`
586
+ );
587
+ writeFileSync(configFile, FILE_TEMPLATE(manifest));
588
+ const command2 = [ROLLUP_BIN, "--silent", "-c", configFile];
589
+ if (tsRegisterName != null) {
590
+ command2.unshift(`node -r ${tsRegisterName}`);
591
+ }
592
+ if (watch) {
593
+ command2.push("--watch");
594
+ }
595
+ command2.push(...passThroughOptions);
596
+ const child = execaCommand(command2.join(" "), {
597
+ ipc: true,
598
+ cwd: pkgCWD,
599
+ windowsHide: true,
600
+ env: {
601
+ ...env,
602
+ JIEK_NAME: manifest.name,
603
+ JIEK_ROOT: wd
604
+ }
605
+ });
606
+ const bars = {};
607
+ const times = {};
608
+ const locks = {};
609
+ let inputMaxLen = 10;
610
+ child.on("message", (e) => {
611
+ if (silent && [
612
+ "init",
613
+ "progress",
614
+ "watchChange"
615
+ ].includes(e.type)) return;
616
+ switch (e.type) {
617
+ case "init": {
618
+ const { leafMap, targetsLength } = e.data;
619
+ const leafs = Array.from(leafMap.entries()).flatMap(
620
+ ([input, pathAndConditions]) => pathAndConditions.map(([path2, ...conditions]) => ({
621
+ input,
622
+ path: path2,
623
+ conditions
624
+ }))
625
+ );
626
+ let initMessage = `Package '${manifest.name}' has ${targetsLength} targets to build`;
627
+ if (watch) {
628
+ initMessage += " and watching...";
629
+ }
630
+ console.log(initMessage);
631
+ leafs.forEach(({ input }) => {
632
+ inputMaxLen = Math.max(inputMaxLen, input.length);
633
+ });
634
+ leafs.forEach(({ input, path: path2 }) => {
635
+ const key = `${input}:${path2}`;
636
+ if (bars[key]) return;
637
+ bars[key] = multiBars.create(50, 0, {
638
+ pkgName: manifest.name,
639
+ input: input.padEnd(inputMaxLen + 5),
640
+ status: "waiting".padEnd(10)
641
+ }, {
642
+ barsize: 20,
643
+ linewrap: true
644
+ });
645
+ });
646
+ break;
647
+ }
648
+ case "progress": {
649
+ const {
650
+ path: path2,
651
+ tags,
652
+ input,
653
+ event,
654
+ message
655
+ } = e.data;
656
+ const bar = bars[`${input}:${path2}`];
657
+ if (!bar) return;
658
+ const time = times[`${input}:${path2}`];
659
+ bar.update(
660
+ {
661
+ start: 0,
662
+ resolve: 20,
663
+ end: 50
664
+ }[event ?? "start"] ?? 0,
665
+ {
666
+ input: (time ? `${input}(x${time.toString().padStart(2, "0")})` : input).padEnd(inputMaxLen + 5),
667
+ status: event?.padEnd(10),
668
+ message: `${tags?.join(", ")}: ${message}`
669
+ }
670
+ );
671
+ break;
672
+ }
673
+ case "watchChange": {
674
+ const {
675
+ path: path2,
676
+ input
677
+ } = e.data;
678
+ const key = `${input}:${path2}`;
679
+ const bar = bars[key];
680
+ if (!bar) return;
681
+ let time = times[key] ?? 1;
682
+ if (!locks[key]) {
683
+ time += 1;
684
+ times[key] = time;
685
+ setTimeout(() => {
686
+ locks[key] = false;
687
+ }, 100);
688
+ bar.update(0, {
689
+ input: `${input}(x${time.toString().padStart(2, "0")})`.padEnd(inputMaxLen + 5),
690
+ status: "watching".padEnd(10),
691
+ message: "watching..."
692
+ });
693
+ }
694
+ locks[key] = true;
695
+ break;
696
+ }
697
+ case "modulesAnalyze": {
698
+ const {
699
+ data: {
700
+ type: type2,
701
+ modules: pkgModules
702
+ }
703
+ } = e;
704
+ void refreshAnalyzer(
705
+ pkgCWD,
706
+ pkgModules.map((m) => ({
707
+ ...m,
708
+ type: type2,
709
+ filename: `${manifest.name}/${m.filename}`,
710
+ label: `${manifest.name}/${m.label}`
711
+ }))
712
+ );
713
+ break;
714
+ }
715
+ case "debug": {
716
+ console.log(...Array.isArray(e.data) ? e.data : [e.data]);
717
+ break;
718
+ }
719
+ }
720
+ });
721
+ await new Promise((resolve, reject) => {
722
+ let errorStr = `rollup build failed
723
+ package name: ${manifest.name}
724
+ cwd: ${pkgCWD}
725
+
726
+ `;
727
+ child.stderr?.on("data", (data) => {
728
+ errorStr += data;
729
+ });
730
+ child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(errorStr)));
731
+ verbose && child.stdout?.pipe(process.stdout);
732
+ });
733
+ };
734
+ const commandFilters = IS_WORKSPACE ? commandFiltersOrEntries : void 0;
735
+ const filters = [
736
+ .../* @__PURE__ */ new Set([
737
+ ...program.getOptionValue("filter")?.split(",").map((s) => s.trim()).filter((s) => s.length > 0) ?? [],
738
+ ...commandFilters?.split(",").map((s) => s.trim()).filter((s) => s.length > 0) ?? []
739
+ ])
740
+ ];
741
+ try {
742
+ const packages = (filters.length > 0 ? await filterPackagesGraph(filters) : [await getSelectedProjectsGraph()]).flatMap(({ value }) => Object.entries(value ?? {}));
743
+ await Promise.allSettled(
744
+ packages.map(async ([cwd, manifest]) => buildPackage([cwd, manifest], { resolveByJiekTemp }))
745
+ );
746
+ } finally {
747
+ multiBars.stop();
748
+ !silent && console.log("Build complete");
749
+ }
750
+ });