rolldown 1.0.0-beta.1-commit.35fb1f8 → 1.0.0-beta.10

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 (153) hide show
  1. package/bin/cli.mjs +2 -0
  2. package/dist/cli.cjs +1748 -0
  3. package/dist/cli.d.cts +1 -0
  4. package/dist/cli.d.mts +1 -0
  5. package/dist/cli.mjs +1745 -0
  6. package/dist/config.cjs +12 -0
  7. package/dist/config.d.cts +12 -0
  8. package/dist/config.d.mts +12 -0
  9. package/dist/config.mjs +10 -0
  10. package/dist/experimental-index.cjs +132 -0
  11. package/dist/experimental-index.d.cts +96 -0
  12. package/dist/experimental-index.d.mts +96 -0
  13. package/dist/experimental-index.mjs +91 -0
  14. package/dist/filter-index.cjs +105 -0
  15. package/dist/filter-index.d.cts +5 -0
  16. package/dist/filter-index.d.mts +5 -0
  17. package/dist/filter-index.mjs +44 -0
  18. package/dist/index.cjs +9 -0
  19. package/dist/index.d.cts +4 -0
  20. package/dist/index.d.mts +4 -0
  21. package/dist/index.mjs +5 -0
  22. package/dist/{cjs/parallel-plugin-worker.cjs → parallel-plugin-worker.cjs} +7 -14
  23. package/dist/parallel-plugin-worker.d.cts +1 -0
  24. package/dist/parallel-plugin-worker.d.mts +1 -0
  25. package/dist/{esm/parallel-plugin-worker.mjs → parallel-plugin-worker.mjs} +5 -11
  26. package/dist/{cjs/parallel-plugin.cjs → parallel-plugin.cjs} +1 -2
  27. package/dist/parallel-plugin.d.cts +15 -0
  28. package/dist/parallel-plugin.d.mts +15 -0
  29. package/dist/{esm/parallel-plugin.mjs → parallel-plugin.mjs} +0 -1
  30. package/dist/parse-ast-index.cjs +4 -0
  31. package/dist/parse-ast-index.d.cts +9 -0
  32. package/dist/parse-ast-index.d.mts +9 -0
  33. package/dist/parse-ast-index.mjs +3 -0
  34. package/dist/shared/binding.d-Bl5Vi4GH.d.mts +1702 -0
  35. package/dist/shared/binding.d-DcFBMcjI.d.cts +1702 -0
  36. package/dist/shared/{chunk-qZFfknuJ.cjs → chunk-DDkG_k5U.cjs} +0 -1
  37. package/dist/shared/define-config.d-B2xOSmbM.d.cts +1082 -0
  38. package/dist/shared/define-config.d-USfUuKiR.d.mts +1082 -0
  39. package/dist/shared/load-config-D6gW8FDa.cjs +125 -0
  40. package/dist/shared/load-config-eyuttVHY.mjs +119 -0
  41. package/dist/shared/misc-BKp5iIef.cjs +67 -0
  42. package/dist/shared/misc-BN0nse6C.mjs +25 -0
  43. package/dist/shared/{binding-fhgdIkpS.cjs → parse-ast-index-BvK1MT-L.cjs} +347 -309
  44. package/dist/shared/{binding-Bl7VQy7c.mjs → parse-ast-index-PSQWLeSo.mjs} +334 -277
  45. package/dist/shared/prompt-8EeOGx1_.cjs +854 -0
  46. package/dist/shared/prompt-C3zHEaSG.mjs +852 -0
  47. package/dist/shared/src-C2v46mL8.cjs +4654 -0
  48. package/dist/shared/src-D-VRn8rI.mjs +4456 -0
  49. package/package.json +62 -61
  50. package/bin/cli.js +0 -2
  51. package/dist/cjs/cli.cjs +0 -769
  52. package/dist/cjs/experimental-index.cjs +0 -79
  53. package/dist/cjs/index.cjs +0 -8
  54. package/dist/cjs/parse-ast-index.cjs +0 -57
  55. package/dist/esm/cli.mjs +0 -766
  56. package/dist/esm/experimental-index.mjs +0 -56
  57. package/dist/esm/index.mjs +0 -4
  58. package/dist/esm/parse-ast-index.mjs +0 -55
  59. package/dist/shared/consola_36c0034f-Cx52UqEq.mjs +0 -832
  60. package/dist/shared/consola_36c0034f-CynBWXXO.cjs +0 -859
  61. package/dist/shared/prompt-B58MxVuU.cjs +0 -762
  62. package/dist/shared/prompt-DjjlOckE.mjs +0 -758
  63. package/dist/shared/src-Busnx6mE.cjs +0 -2812
  64. package/dist/shared/src-DNOXsZr0.mjs +0 -2631
  65. package/dist/tsconfig.dts.tsbuildinfo +0 -1
  66. package/dist/types/api/build.d.ts +0 -18
  67. package/dist/types/api/experimental.d.ts +0 -7
  68. package/dist/types/api/rolldown/index.d.ts +0 -3
  69. package/dist/types/api/rolldown/rolldown-build.d.ts +0 -12
  70. package/dist/types/api/watch/index.d.ts +0 -3
  71. package/dist/types/api/watch/watch-emitter.d.ts +0 -31
  72. package/dist/types/api/watch/watcher.d.ts +0 -13
  73. package/dist/types/binding.d.ts +0 -1287
  74. package/dist/types/builtin-plugin/alias-plugin.d.ts +0 -10
  75. package/dist/types/builtin-plugin/constructors.d.ts +0 -20
  76. package/dist/types/builtin-plugin/replace-plugin.d.ts +0 -28
  77. package/dist/types/builtin-plugin/transform-plugin.d.ts +0 -9
  78. package/dist/types/builtin-plugin/utils.d.ts +0 -8
  79. package/dist/types/cli/arguments/alias.d.ts +0 -16
  80. package/dist/types/cli/arguments/index.d.ts +0 -15
  81. package/dist/types/cli/arguments/normalize.d.ts +0 -12
  82. package/dist/types/cli/arguments/utils.d.ts +0 -8
  83. package/dist/types/cli/colors.d.ts +0 -11
  84. package/dist/types/cli/commands/bundle.d.ts +0 -3
  85. package/dist/types/cli/commands/help.d.ts +0 -1
  86. package/dist/types/cli/index.d.ts +0 -1
  87. package/dist/types/cli/load-config.d.ts +0 -3
  88. package/dist/types/cli/logger.d.ts +0 -5
  89. package/dist/types/constants/plugin-context.d.ts +0 -7
  90. package/dist/types/constants/plugin.d.ts +0 -45
  91. package/dist/types/experimental-index.d.ts +0 -9
  92. package/dist/types/index.d.ts +0 -28
  93. package/dist/types/log/logHandler.d.ts +0 -4
  94. package/dist/types/log/logger.d.ts +0 -6
  95. package/dist/types/log/logging.d.ts +0 -11
  96. package/dist/types/log/logs.d.ts +0 -18
  97. package/dist/types/options/input-options.d.ts +0 -125
  98. package/dist/types/options/normalized-input-options.d.ts +0 -18
  99. package/dist/types/options/normalized-output-options.d.ts +0 -67
  100. package/dist/types/options/output-options.d.ts +0 -80
  101. package/dist/types/options/watch-options.d.ts +0 -5
  102. package/dist/types/parallel-plugin-worker.d.ts +0 -1
  103. package/dist/types/parallel-plugin.d.ts +0 -1
  104. package/dist/types/parse-ast-index.d.ts +0 -4
  105. package/dist/types/plugin/bindingify-build-hooks.d.ts +0 -10
  106. package/dist/types/plugin/bindingify-hook-filter.d.ts +0 -7
  107. package/dist/types/plugin/bindingify-output-hooks.d.ts +0 -14
  108. package/dist/types/plugin/bindingify-plugin-hook-meta.d.ts +0 -8
  109. package/dist/types/plugin/bindingify-plugin.d.ts +0 -15
  110. package/dist/types/plugin/bindingify-watch-hooks.d.ts +0 -5
  111. package/dist/types/plugin/hook-filter.d.ts +0 -48
  112. package/dist/types/plugin/index.d.ts +0 -126
  113. package/dist/types/plugin/minimal-plugin-context.d.ts +0 -15
  114. package/dist/types/plugin/parallel-plugin-implementation.d.ts +0 -10
  115. package/dist/types/plugin/parallel-plugin.d.ts +0 -9
  116. package/dist/types/plugin/plugin-context-data.d.ts +0 -16
  117. package/dist/types/plugin/plugin-context.d.ts +0 -52
  118. package/dist/types/plugin/plugin-driver.d.ts +0 -8
  119. package/dist/types/plugin/transform-plugin-context.d.ts +0 -17
  120. package/dist/types/types/assert.d.ts +0 -13
  121. package/dist/types/types/config-export.d.ts +0 -5
  122. package/dist/types/types/misc.d.ts +0 -40
  123. package/dist/types/types/module-info.d.ts +0 -15
  124. package/dist/types/types/module-side-effects.d.ts +0 -10
  125. package/dist/types/types/output-bundle.d.ts +0 -4
  126. package/dist/types/types/rolldown-options.d.ts +0 -5
  127. package/dist/types/types/rolldown-output.d.ts +0 -63
  128. package/dist/types/types/schema.d.ts +0 -33
  129. package/dist/types/types/sourcemap.d.ts +0 -13
  130. package/dist/types/types/utils.d.ts +0 -13
  131. package/dist/types/utils/asset-source.d.ts +0 -4
  132. package/dist/types/utils/async-flatten.d.ts +0 -1
  133. package/dist/types/utils/bindingify-input-options.d.ts +0 -7
  134. package/dist/types/utils/bindingify-output-options.d.ts +0 -3
  135. package/dist/types/utils/code-frame.d.ts +0 -1
  136. package/dist/types/utils/compose-js-plugins.d.ts +0 -2
  137. package/dist/types/utils/create-bundler-option.d.ts +0 -11
  138. package/dist/types/utils/create-bundler.d.ts +0 -8
  139. package/dist/types/utils/define-config.d.ts +0 -5
  140. package/dist/types/utils/error.d.ts +0 -2
  141. package/dist/types/utils/initialize-parallel-plugins.d.ts +0 -19
  142. package/dist/types/utils/misc.d.ts +0 -6
  143. package/dist/types/utils/normalize-hook.d.ts +0 -7
  144. package/dist/types/utils/normalize-plugin-option.d.ts +0 -13
  145. package/dist/types/utils/normalize-string-or-regex.d.ts +0 -2
  146. package/dist/types/utils/plugin/index.d.ts +0 -2
  147. package/dist/types/utils/transform-module-info.d.ts +0 -4
  148. package/dist/types/utils/transform-rendered-chunk.d.ts +0 -4
  149. package/dist/types/utils/transform-rendered-module.d.ts +0 -3
  150. package/dist/types/utils/transform-side-effects.d.ts +0 -3
  151. package/dist/types/utils/transform-sourcemap.d.ts +0 -3
  152. package/dist/types/utils/transform-to-rollup-output.d.ts +0 -11
  153. package/dist/types/utils/validator.d.ts +0 -7
package/dist/esm/cli.mjs DELETED
@@ -1,766 +0,0 @@
1
- import { colors } from "../shared/binding-Bl7VQy7c.mjs";
2
- import { arraify, description, getInputCliKeys, getJsonSchema, getOutputCliKeys, rolldown, validateCliOptions, version, watch } from "../shared/src-DNOXsZr0.mjs";
3
- import { createConsola } from "../shared/consola_36c0034f-Cx52UqEq.mjs";
4
- import process$1, { cwd } from "node:process";
5
- import path from "node:path";
6
- import fs from "node:fs";
7
- import { performance } from "node:perf_hooks";
8
- import { parseArgs } from "node:util";
9
- import { readdir } from "node:fs/promises";
10
- import { pathToFileURL } from "node:url";
11
-
12
- //#region ../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/signals.js
13
- const signals = [];
14
- signals.push("SIGHUP", "SIGINT", "SIGTERM");
15
- if (process.platform !== "win32") signals.push(
16
- "SIGALRM",
17
- "SIGABRT",
18
- "SIGVTALRM",
19
- "SIGXCPU",
20
- "SIGXFSZ",
21
- "SIGUSR2",
22
- "SIGTRAP",
23
- "SIGSYS",
24
- "SIGQUIT",
25
- "SIGIOT"
26
- // should detect profiler and enable/disable accordingly.
27
- // see #21
28
- // 'SIGPROF'
29
- );
30
- if (process.platform === "linux") signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT");
31
-
32
- //#endregion
33
- //#region ../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/index.js
34
- const processOk = (process$3) => !!process$3 && typeof process$3 === "object" && typeof process$3.removeListener === "function" && typeof process$3.emit === "function" && typeof process$3.reallyExit === "function" && typeof process$3.listeners === "function" && typeof process$3.kill === "function" && typeof process$3.pid === "number" && typeof process$3.on === "function";
35
- const kExitEmitter = Symbol.for("signal-exit emitter");
36
- const global = globalThis;
37
- const ObjectDefineProperty = Object.defineProperty.bind(Object);
38
- var Emitter = class {
39
- emitted = {
40
- afterExit: false,
41
- exit: false
42
- };
43
- listeners = {
44
- afterExit: [],
45
- exit: []
46
- };
47
- count = 0;
48
- id = Math.random();
49
- constructor() {
50
- if (global[kExitEmitter]) return global[kExitEmitter];
51
- ObjectDefineProperty(global, kExitEmitter, {
52
- value: this,
53
- writable: false,
54
- enumerable: false,
55
- configurable: false
56
- });
57
- }
58
- on(ev, fn) {
59
- this.listeners[ev].push(fn);
60
- }
61
- removeListener(ev, fn) {
62
- const list = this.listeners[ev];
63
- const i = list.indexOf(fn);
64
- if (i === -1) return;
65
- if (i === 0 && list.length === 1) list.length = 0;
66
- else list.splice(i, 1);
67
- }
68
- emit(ev, code, signal) {
69
- if (this.emitted[ev]) return false;
70
- this.emitted[ev] = true;
71
- let ret = false;
72
- for (const fn of this.listeners[ev]) ret = fn(code, signal) === true || ret;
73
- if (ev === "exit") ret = this.emit("afterExit", code, signal) || ret;
74
- return ret;
75
- }
76
- };
77
- var SignalExitBase = class {};
78
- const signalExitWrap = (handler) => {
79
- return {
80
- onExit(cb, opts) {
81
- return handler.onExit(cb, opts);
82
- },
83
- load() {
84
- return handler.load();
85
- },
86
- unload() {
87
- return handler.unload();
88
- }
89
- };
90
- };
91
- var SignalExitFallback = class extends SignalExitBase {
92
- onExit() {
93
- return () => {};
94
- }
95
- load() {}
96
- unload() {}
97
- };
98
- var SignalExit = class extends SignalExitBase {
99
- #hupSig = process$2.platform === "win32" ? "SIGINT" : "SIGHUP";
100
- #emitter = new Emitter();
101
- #process;
102
- #originalProcessEmit;
103
- #originalProcessReallyExit;
104
- #sigListeners = {};
105
- #loaded = false;
106
- constructor(process$3) {
107
- super();
108
- this.#process = process$3;
109
- this.#sigListeners = {};
110
- for (const sig of signals) this.#sigListeners[sig] = () => {
111
- const listeners = this.#process.listeners(sig);
112
- let { count } = this.#emitter;
113
- const p = process$3;
114
- if (typeof p.__signal_exit_emitter__ === "object" && typeof p.__signal_exit_emitter__.count === "number") count += p.__signal_exit_emitter__.count;
115
- if (listeners.length === count) {
116
- this.unload();
117
- const ret = this.#emitter.emit("exit", null, sig);
118
- const s = sig === "SIGHUP" ? this.#hupSig : sig;
119
- if (!ret) process$3.kill(process$3.pid, s);
120
- }
121
- };
122
- this.#originalProcessReallyExit = process$3.reallyExit;
123
- this.#originalProcessEmit = process$3.emit;
124
- }
125
- onExit(cb, opts) {
126
- if (!processOk(this.#process)) return () => {};
127
- if (this.#loaded === false) this.load();
128
- const ev = opts?.alwaysLast ? "afterExit" : "exit";
129
- this.#emitter.on(ev, cb);
130
- return () => {
131
- this.#emitter.removeListener(ev, cb);
132
- if (this.#emitter.listeners["exit"].length === 0 && this.#emitter.listeners["afterExit"].length === 0) this.unload();
133
- };
134
- }
135
- load() {
136
- if (this.#loaded) return;
137
- this.#loaded = true;
138
- this.#emitter.count += 1;
139
- for (const sig of signals) try {
140
- const fn = this.#sigListeners[sig];
141
- if (fn) this.#process.on(sig, fn);
142
- } catch (_) {}
143
- this.#process.emit = (ev, ...a) => {
144
- return this.#processEmit(ev, ...a);
145
- };
146
- this.#process.reallyExit = (code) => {
147
- return this.#processReallyExit(code);
148
- };
149
- }
150
- unload() {
151
- if (!this.#loaded) return;
152
- this.#loaded = false;
153
- signals.forEach((sig) => {
154
- const listener = this.#sigListeners[sig];
155
- if (!listener) throw new Error("Listener not defined for signal: " + sig);
156
- try {
157
- this.#process.removeListener(sig, listener);
158
- } catch (_) {}
159
- });
160
- this.#process.emit = this.#originalProcessEmit;
161
- this.#process.reallyExit = this.#originalProcessReallyExit;
162
- this.#emitter.count -= 1;
163
- }
164
- #processReallyExit(code) {
165
- if (!processOk(this.#process)) return 0;
166
- this.#process.exitCode = code || 0;
167
- this.#emitter.emit("exit", this.#process.exitCode, null);
168
- return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
169
- }
170
- #processEmit(ev, ...args) {
171
- const og = this.#originalProcessEmit;
172
- if (ev === "exit" && processOk(this.#process)) {
173
- if (typeof args[0] === "number") this.#process.exitCode = args[0];
174
- const ret = og.call(this.#process, ev, ...args);
175
- this.#emitter.emit("exit", this.#process.exitCode, null);
176
- return ret;
177
- } else return og.call(this.#process, ev, ...args);
178
- }
179
- };
180
- const process$2 = globalThis.process;
181
- const { onExit, load, unload } = signalExitWrap(processOk(process$2) ? new SignalExit(process$2) : new SignalExitFallback());
182
-
183
- //#endregion
184
- //#region src/cli/logger.ts
185
- const logger = process.env.ROLLDOWN_TEST ? createTestingLogger() : createConsola({ formatOptions: { date: false } });
186
- function createTestingLogger() {
187
- const types = [
188
- "silent",
189
- "fatal",
190
- "error",
191
- "warn",
192
- "log",
193
- "info",
194
- "success",
195
- "fail",
196
- "ready",
197
- "start",
198
- "box",
199
- "debug",
200
- "trace",
201
- "verbose"
202
- ];
203
- const ret = Object.create(null);
204
- for (const type of types) ret[type] = console.log;
205
- return ret;
206
- }
207
-
208
- //#endregion
209
- //#region src/cli/load-config.ts
210
- async function bundleTsConfig(configFile) {
211
- const dirnameVarName = "injected_original_dirname";
212
- const filenameVarName = "injected_original_filename";
213
- const importMetaUrlVarName = "injected_original_import_meta_url";
214
- const bundle = await rolldown({
215
- input: configFile,
216
- platform: "node",
217
- resolve: { mainFields: ["main"] },
218
- define: {
219
- __dirname: dirnameVarName,
220
- __filename: filenameVarName,
221
- "import.meta.url": importMetaUrlVarName,
222
- "import.meta.dirname": dirnameVarName,
223
- "import.meta.filename": filenameVarName
224
- },
225
- treeshake: false,
226
- external: [/^[\w@][^:]/],
227
- plugins: [{
228
- name: "inject-file-scope-variables",
229
- transform: {
230
- filter: { id: /\.[cm]?[jt]s$/ },
231
- async handler(code, id) {
232
- const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path.dirname(id))};` + `const ${filenameVarName} = ${JSON.stringify(id)};` + `const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(id).href)};`;
233
- return {
234
- code: injectValues + code,
235
- map: null
236
- };
237
- }
238
- }
239
- }]
240
- });
241
- const outputDir = path.dirname(configFile);
242
- const result = await bundle.write({
243
- dir: outputDir,
244
- format: "esm",
245
- sourcemap: "inline",
246
- entryFileNames: "rolldown.config.[hash].js"
247
- });
248
- const fileName = result.output.find((chunk) => chunk.type === "chunk" && chunk.isEntry).fileName;
249
- return path.join(outputDir, fileName);
250
- }
251
- const SUPPORTED_JS_CONFIG_FORMATS = [
252
- ".js",
253
- ".mjs",
254
- ".cjs"
255
- ];
256
- const SUPPORTED_TS_CONFIG_FORMATS = [
257
- ".ts",
258
- ".mts",
259
- ".cts"
260
- ];
261
- const SUPPORTED_CONFIG_FORMATS = [...SUPPORTED_JS_CONFIG_FORMATS, ...SUPPORTED_TS_CONFIG_FORMATS];
262
- const DEFAULT_CONFIG_BASE = "rolldown.config";
263
- async function findConfigFileNameInCwd() {
264
- const filesInWorkingDirectory = new Set(await readdir(cwd()));
265
- for (const extension of SUPPORTED_CONFIG_FORMATS) {
266
- const fileName = `${DEFAULT_CONFIG_BASE}${extension}`;
267
- if (filesInWorkingDirectory.has(fileName)) return fileName;
268
- }
269
- throw new Error("No `rolldown.config` configuration file found.");
270
- }
271
- async function loadTsConfig(configFile) {
272
- const file = await bundleTsConfig(configFile);
273
- try {
274
- return (await import(pathToFileURL(file).href)).default;
275
- } finally {
276
- fs.unlink(file, () => {});
277
- }
278
- }
279
- async function loadConfig(configPath) {
280
- const ext = path.extname(configPath = configPath || await findConfigFileNameInCwd());
281
- try {
282
- if (SUPPORTED_JS_CONFIG_FORMATS.includes(ext) || process.env.NODE_OPTIONS?.includes("--import=tsx") && SUPPORTED_TS_CONFIG_FORMATS.includes(ext)) return (await import(pathToFileURL(configPath).href)).default;
283
- else if (SUPPORTED_TS_CONFIG_FORMATS.includes(ext)) {
284
- const rawConfigPath = path.resolve(configPath);
285
- return await loadTsConfig(rawConfigPath);
286
- } else throw new Error(`Unsupported config format. Expected: \`${SUPPORTED_CONFIG_FORMATS.join(",")}\` but got \`${ext}\``);
287
- } catch (err) {
288
- throw new Error("Error happened while loading config.", { cause: err });
289
- }
290
- }
291
-
292
- //#endregion
293
- //#region src/cli/commands/bundle.ts
294
- async function bundleWithConfig(configPath, cliOptions) {
295
- const config = await loadConfig(configPath);
296
- if (!config) {
297
- logger.error(`No configuration found at ${config}`);
298
- process.exit(1);
299
- }
300
- if (cliOptions.watch) await watchInner(config, cliOptions);
301
- else await bundleInner(config, cliOptions);
302
- }
303
- async function bundleWithCliOptions(cliOptions) {
304
- if (cliOptions.output.dir || cliOptions.output.file) {
305
- const operation = cliOptions.watch ? watchInner : bundleInner;
306
- await operation({}, cliOptions);
307
- return;
308
- }
309
- if (cliOptions.watch) {
310
- logger.error("You must specify `output.dir` to use watch mode");
311
- process.exit(1);
312
- }
313
- const build = await rolldown(cliOptions.input);
314
- try {
315
- const { output: outputs } = await build.generate(cliOptions.output);
316
- if (outputs.length === 0) {
317
- logger.error("No output generated");
318
- process.exit(1);
319
- }
320
- for (const file of outputs) {
321
- if (outputs.length > 1) logger.log(`\n${colors.cyan(colors.bold(`|→ ${file.fileName}:`))}\n`);
322
- console.log(file.type === "asset" ? file.source : file.code);
323
- }
324
- } finally {
325
- await build.close();
326
- }
327
- }
328
- async function watchInner(config, cliOptions) {
329
- let normalizedConfig = arraify(config).map((option) => {
330
- return {
331
- ...option,
332
- ...cliOptions.input,
333
- output: arraify(option.output || {}).map((output) => {
334
- return {
335
- ...output,
336
- ...cliOptions.output
337
- };
338
- })
339
- };
340
- });
341
- const watcher = await watch(normalizedConfig);
342
- onExit((code) => {
343
- Promise.resolve(watcher.close()).finally(() => {
344
- process.exit(typeof code === "number" ? code : 0);
345
- });
346
- return true;
347
- });
348
- const changedFile = [];
349
- watcher.on("change", (id, event) => {
350
- if (event.event === "update") changedFile.push(id);
351
- });
352
- watcher.on("event", (event) => {
353
- switch (event.code) {
354
- case "BUNDLE_START":
355
- if (changedFile.length > 0) logger.log(`Found ${colors.bold(changedFile.map(relativeId).join(", "))} changed, rebuilding...`);
356
- changedFile.length = 0;
357
- break;
358
- case "BUNDLE_END":
359
- logger.success(`Rebuilt ${colors.bold(relativeId(event.output[0]))} in ${colors.bold(ms(event.duration))}.`);
360
- break;
361
- case "ERROR":
362
- logger.error(event.error);
363
- break;
364
- default: break;
365
- }
366
- });
367
- logger.log(`Waiting for changes...`);
368
- }
369
- async function bundleInner(config, cliOptions) {
370
- const startTime = performance.now();
371
- const result = [];
372
- const configList = arraify(config);
373
- for (const config$1 of configList) {
374
- const outputList = arraify(config$1.output || {});
375
- const build = await rolldown({
376
- ...config$1,
377
- ...cliOptions.input
378
- });
379
- for (const output of outputList) try {
380
- result.push(await build.write({
381
- ...output,
382
- ...cliOptions.output
383
- }));
384
- } finally {
385
- await build.close();
386
- }
387
- }
388
- result.forEach(printBundleOutputPretty);
389
- logger.log(``);
390
- const endTime = performance.now();
391
- const duration = endTime - startTime;
392
- logger.success(`Finished in ${colors.bold(ms(duration))}`);
393
- }
394
- function printBundleOutputPretty(output) {
395
- const outputEntries = collectOutputEntries(output.output);
396
- const outputLayoutSizes = collectOutputLayoutAdjustmentSizes(outputEntries);
397
- printOutputEntries(outputEntries, outputLayoutSizes, "<DIR>");
398
- }
399
- function collectOutputEntries(output) {
400
- return output.map((chunk) => ({
401
- type: chunk.type,
402
- fileName: chunk.fileName,
403
- size: chunk.type === "chunk" ? chunk.code.length : chunk.source.length
404
- }));
405
- }
406
- function collectOutputLayoutAdjustmentSizes(entries) {
407
- let longest = 0;
408
- let biggestSize = 0;
409
- for (const entry of entries) {
410
- if (entry.fileName.length > longest) longest = entry.fileName.length;
411
- if (entry.size > biggestSize) biggestSize = entry.size;
412
- }
413
- const sizePad = displaySize(biggestSize).length;
414
- return {
415
- longest,
416
- biggestSize,
417
- sizePad
418
- };
419
- }
420
- const numberFormatter = new Intl.NumberFormat("en", {
421
- maximumFractionDigits: 2,
422
- minimumFractionDigits: 2
423
- });
424
- function displaySize(bytes) {
425
- return `${numberFormatter.format(bytes / 1e3)} kB`;
426
- }
427
- const CHUNK_GROUPS = [{
428
- type: "asset",
429
- color: "green"
430
- }, {
431
- type: "chunk",
432
- color: "cyan"
433
- }];
434
- function printOutputEntries(entries, sizeAdjustment, distPath) {
435
- for (const group of CHUNK_GROUPS) {
436
- const filtered = entries.filter((e) => e.type === group.type);
437
- if (!filtered.length) continue;
438
- for (const entry of filtered.sort((a, z) => a.size - z.size)) {
439
- let log = colors.dim(withTrailingSlash(distPath));
440
- log += colors[group.color](entry.fileName.padEnd(sizeAdjustment.longest + 2));
441
- log += colors.dim(entry.type);
442
- log += colors.dim(` │ size: ${displaySize(entry.size).padStart(sizeAdjustment.sizePad)}`);
443
- logger.log(log);
444
- }
445
- }
446
- }
447
- function withTrailingSlash(path$1) {
448
- if (path$1[path$1.length - 1] !== "/") return `${path$1}/`;
449
- return path$1;
450
- }
451
- function ms(duration) {
452
- return duration < 1e3 ? `${duration.toFixed(2)} ms` : `${(duration / 1e3).toFixed(2)} s`;
453
- }
454
- function relativeId(id) {
455
- if (!path.isAbsolute(id)) return id;
456
- return path.relative(path.resolve(), id);
457
- }
458
-
459
- //#endregion
460
- //#region src/cli/arguments/alias.ts
461
- const alias = {
462
- config: {
463
- abbreviation: "c",
464
- hint: "filename"
465
- },
466
- help: { abbreviation: "h" },
467
- version: { abbreviation: "v" },
468
- watch: { abbreviation: "w" },
469
- dir: { abbreviation: "d" },
470
- file: { abbreviation: "o" },
471
- external: { abbreviation: "e" },
472
- format: { abbreviation: "f" },
473
- name: { abbreviation: "n" },
474
- globals: { abbreviation: "g" },
475
- sourcemap: {
476
- abbreviation: "s",
477
- default: true
478
- },
479
- minify: { abbreviation: "m" },
480
- platform: { abbreviation: "p" },
481
- assetFileNames: { hint: "name" },
482
- chunkFileNames: { hint: "name" },
483
- entryFileNames: { hint: "name" },
484
- externalLiveBindings: {
485
- default: true,
486
- reverse: true
487
- },
488
- treeshake: {
489
- default: true,
490
- reverse: true
491
- },
492
- moduleTypes: { hint: "types" }
493
- };
494
-
495
- //#endregion
496
- //#region src/cli/arguments/utils.ts
497
- const priority = [
498
- "object",
499
- "array",
500
- "string",
501
- "number",
502
- "boolean"
503
- ];
504
- function getSchemaType(schema) {
505
- if ("anyOf" in schema) {
506
- const types = schema.anyOf.map(getSchemaType);
507
- let result = priority.find((type) => types.includes(type));
508
- if (result) return result;
509
- }
510
- if ("type" in schema) return schema.type;
511
- if ("const" in schema) return typeof schema.const;
512
- return "object";
513
- }
514
- function flattenSchema(schema, base = {}, parent = "") {
515
- if (schema === undefined) return base;
516
- for (const [k, value] of Object.entries(schema)) {
517
- const key = parent ? `${parent}.${k}` : k;
518
- if (getSchemaType(value) === "object") if ("properties" in value) flattenSchema(value.properties, base, key);
519
- else base[key] = value;
520
- else base[key] = value;
521
- }
522
- return base;
523
- }
524
- function setNestedProperty(obj, path$1, value) {
525
- const keys = path$1.split(".");
526
- let current = obj;
527
- for (let i = 0; i < keys.length - 1; i++) {
528
- if (!current[keys[i]]) current[keys[i]] = {};
529
- current = current[keys[i]];
530
- }
531
- const finalKey = keys[keys.length - 1];
532
- Object.defineProperty(current, finalKey, {
533
- value,
534
- writable: true,
535
- enumerable: true,
536
- configurable: true
537
- });
538
- }
539
- function camelCaseToKebabCase(str) {
540
- return str.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
541
- }
542
- function kebabCaseToCamelCase(str) {
543
- return str.replace(/-./g, (match) => match[1].toUpperCase());
544
- }
545
-
546
- //#endregion
547
- //#region src/cli/arguments/normalize.ts
548
- function normalizeCliOptions(cliOptions, positionals) {
549
- const [data, errors] = validateCliOptions(cliOptions);
550
- if (errors?.length) {
551
- errors.forEach((error) => {
552
- logger.error(`Invalid value for option ${error}. You can use \`rolldown -h\` to see the help.`);
553
- });
554
- process.exit(1);
555
- }
556
- const options$1 = data ?? {};
557
- const result = {
558
- input: {},
559
- output: {},
560
- help: options$1.help ?? false,
561
- version: options$1.version ?? false,
562
- watch: options$1.watch ?? false
563
- };
564
- if (typeof options$1.config === "string") result.config = options$1.config;
565
- const keysOfInput = getInputCliKeys();
566
- const keysOfOutput = getOutputCliKeys();
567
- const reservedKeys = [
568
- "help",
569
- "version",
570
- "config",
571
- "watch"
572
- ];
573
- for (let [key, value] of Object.entries(options$1)) {
574
- const keys = key.split(".");
575
- const [primary] = keys;
576
- if (keysOfInput.includes(primary)) setNestedProperty(result.input, key, value);
577
- else if (keysOfOutput.includes(primary)) setNestedProperty(result.output, key, value);
578
- else if (!reservedKeys.includes(key)) {
579
- logger.error(`Unknown option: ${key}`);
580
- process.exit(1);
581
- }
582
- }
583
- if (!result.config && positionals.length > 0) result.input.input = positionals;
584
- return result;
585
- }
586
-
587
- //#endregion
588
- //#region src/cli/arguments/index.ts
589
- const objectSchema = getJsonSchema();
590
- const flattenedSchema = flattenSchema(objectSchema.properties);
591
- const options = Object.fromEntries(Object.entries(flattenedSchema).map(([key, schema]) => {
592
- const config = Object.getOwnPropertyDescriptor(alias, key)?.value;
593
- const type = getSchemaType(schema);
594
- const result = {
595
- type: type === "boolean" ? "boolean" : "string",
596
- description: schema?.description ?? config?.description ?? "",
597
- hint: config?.hint
598
- };
599
- if (config && config?.abbreviation) result.short = config?.abbreviation;
600
- if (config && config.reverse) if (result.description.startsWith("enable")) result.description = result.description.replace("enable", "disable");
601
- else result.description = `disable ${result.description}`;
602
- key = camelCaseToKebabCase(key);
603
- return [config?.reverse ? `no-${key}` : key, result];
604
- }));
605
- function parseCliArguments() {
606
- const { values, tokens, positionals } = parseArgs({
607
- options,
608
- tokens: true,
609
- allowPositionals: true,
610
- strict: false
611
- });
612
- tokens.filter((token) => token.kind === "option").forEach((option) => {
613
- let negative = false;
614
- if (option.name.startsWith("no-")) {
615
- const name = kebabCaseToCamelCase(option.name.substring(3));
616
- if (name in flattenedSchema) {
617
- delete values[option.name];
618
- option.name = name;
619
- negative = true;
620
- }
621
- }
622
- delete values[option.name];
623
- option.name = kebabCaseToCamelCase(option.name);
624
- let originalType = flattenedSchema[option.name];
625
- if (!originalType) {
626
- logger.error(`Invalid option: ${option.rawName}. We will ignore this option.`);
627
- process.exit(1);
628
- }
629
- let type = getSchemaType(originalType);
630
- if (type === "string" && typeof option.value !== "string") {
631
- let opt = option;
632
- let defaultValue = Object.getOwnPropertyDescriptor(alias, opt.name)?.value;
633
- Object.defineProperty(values, opt.name, {
634
- value: defaultValue.default ?? "",
635
- enumerable: true,
636
- configurable: true,
637
- writable: true
638
- });
639
- } else if (type === "object" && typeof option.value === "string") {
640
- const [key, value] = option.value.split(",").map((x) => x.split("="))[0];
641
- if (!values[option.name]) Object.defineProperty(values, option.name, {
642
- value: {},
643
- enumerable: true,
644
- configurable: true,
645
- writable: true
646
- });
647
- if (key && value) Object.defineProperty(values[option.name], key, {
648
- value,
649
- enumerable: true,
650
- configurable: true,
651
- writable: true
652
- });
653
- } else if (type === "array" && typeof option.value === "string") {
654
- if (!values[option.name]) Object.defineProperty(values, option.name, {
655
- value: [],
656
- enumerable: true,
657
- configurable: true,
658
- writable: true
659
- });
660
- values[option.name].push(option.value);
661
- } else if (type === "boolean") Object.defineProperty(values, option.name, {
662
- value: !negative,
663
- enumerable: true,
664
- configurable: true,
665
- writable: true
666
- });
667
- else Object.defineProperty(values, option.name, {
668
- value: option.value ?? "",
669
- enumerable: true,
670
- configurable: true,
671
- writable: true
672
- });
673
- });
674
- return normalizeCliOptions(values, positionals);
675
- }
676
-
677
- //#endregion
678
- //#region src/cli/commands/help.ts
679
- const introduction = `${colors.gray(`${description} (rolldown v${version})`)}
680
-
681
- ${colors.bold(colors.underline("USAGE"))} ${colors.cyan("rolldown -c <config>")} or ${colors.cyan("rolldown <input> <options>")}`;
682
- const examples = [
683
- {
684
- title: "Bundle with a config file `rolldown.config.mjs`",
685
- command: "rolldown -c rolldown.config.mjs"
686
- },
687
- {
688
- title: "Bundle the `src/main.ts` to `dist` with `cjs` format",
689
- command: "rolldown src/main.ts -d dist -f cjs"
690
- },
691
- {
692
- title: "Bundle the `src/main.ts` and handle the `.png` assets to Data URL",
693
- command: "rolldown src/main.ts -d dist --moduleTypes .png=dataurl"
694
- },
695
- {
696
- title: "Bundle the `src/main.tsx` and minify the output with sourcemap",
697
- command: "rolldown src/main.tsx -d dist -m -s"
698
- },
699
- {
700
- title: "Create self-executing IIFE using external jQuery as `$` and `_`",
701
- command: "rolldown src/main.ts -d dist -n bundle -f iife -e jQuery,window._ -g jQuery=$"
702
- }
703
- ];
704
- const notes = [
705
- "Due to the API limitation, you need to pass `-s` for `.map` sourcemap file as the last argument.",
706
- "If you are using the configuration, please pass the `-c` as the last argument if you ignore the default configuration file.",
707
- "CLI options will override the configuration file.",
708
- "For more information, please visit https://rolldown.rs/."
709
- ];
710
- function showHelp() {
711
- logger.log(introduction);
712
- logger.log("");
713
- logger.log(`${colors.bold(colors.underline("OPTIONS"))}`);
714
- logger.log("");
715
- logger.log(Object.entries(options).sort(([a], [b]) => {
716
- if (options[a].short && !options[b].short) return -1;
717
- if (!options[a].short && options[b].short) return 1;
718
- if (options[a].short && options[b].short) return options[a].short.localeCompare(options[b].short);
719
- return a.localeCompare(b);
720
- }).map(([option, { type, short, hint, description: description$1 }]) => {
721
- let optionStr = ` --${option} `;
722
- option = camelCaseToKebabCase(option);
723
- if (short) optionStr += `-${short}, `;
724
- if (type === "string") optionStr += `<${hint ?? option}>`;
725
- if (description$1 && description$1.length > 0) description$1 = description$1[0].toUpperCase() + description$1.slice(1);
726
- return colors.cyan(optionStr.padEnd(30)) + description$1 + (description$1 && description$1?.endsWith(".") ? "" : ".");
727
- }).join("\n"));
728
- logger.log("");
729
- logger.log(`${colors.bold(colors.underline("EXAMPLES"))}`);
730
- logger.log("");
731
- examples.forEach(({ title, command }, ord) => {
732
- logger.log(` ${ord + 1}. ${title}:`);
733
- logger.log(` ${colors.cyan(command)}`);
734
- logger.log("");
735
- });
736
- logger.log(`${colors.bold(colors.underline("NOTES"))}`);
737
- logger.log("");
738
- notes.forEach((note) => {
739
- logger.log(` * ${colors.gray(note)}`);
740
- });
741
- }
742
-
743
- //#endregion
744
- //#region src/cli/index.ts
745
- async function main() {
746
- const cliOptions = parseCliArguments();
747
- if (cliOptions.config || cliOptions.config === "") {
748
- await bundleWithConfig(cliOptions.config, cliOptions);
749
- return;
750
- }
751
- if ("input" in cliOptions.input) {
752
- await bundleWithCliOptions(cliOptions);
753
- return;
754
- }
755
- if (cliOptions.version) {
756
- logger.log(`rolldown v${version}`);
757
- return;
758
- }
759
- showHelp();
760
- }
761
- main().catch((err) => {
762
- console.error(err);
763
- process$1.exit(1);
764
- });
765
-
766
- //#endregion