experimental-index.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import { n as __toESM, t as require_binding } from "./shared/binding-s-V_wTpj.mjs";
  2. import { n as BuiltinPlugin, t as normalizedStringOrRegex } from "./shared/normalize-string-or-regex-CVvpepxa.mjs";
  3. import { o as transformToRollupOutput } from "./shared/bindingify-input-options-DYpBf1OG.mjs";
  4. import { c as validateOption, n as createBundlerOptions, t as RolldownBuild, u as PluginDriver } from "./shared/rolldown-build-DtGk-m96.mjs";
  5. import { i as unwrapBindingResult, r as normalizeBindingResult } from "./shared/error-w0u7biK-.mjs";
  6. import { n as parseSync$1, t as parse$1 } from "./shared/parse-BywQARUG.mjs";
  7. import { a as viteDynamicImportVarsPlugin, c as viteLoadFallbackPlugin, d as viteReporterPlugin, f as viteResolvePlugin, i as viteBuildImportAnalysisPlugin, l as viteModulePreloadPolyfillPlugin, m as viteWebWorkerPostPlugin, n as isolatedDeclarationPlugin, o as viteImportGlobPlugin, p as viteWasmFallbackPlugin, r as oxcRuntimePlugin, s as viteJsonPlugin, u as viteReactRefreshWrapperPlugin } from "./shared/constructors-BaEBnHl3.mjs";
  8. import { a as minify$1, i as transformSync$1, n as resolveTsconfig, o as minifySync$1, r as transform$1, t as TsconfigCache$1 } from "./shared/resolve-tsconfig-CNjJwuKB.mjs";
  9. import { pathToFileURL } from "node:url";
  10. //#region src/api/dev/dev-engine.ts
  11. var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
  12. var DevEngine = class DevEngine {
  13. #inner;
  14. #cachedBuildFinishPromise = null;
  15. static async create(inputOptions, outputOptions = {}, devOptions = {}) {
  16. inputOptions = await PluginDriver.callOptionsHook(inputOptions);
  17. const options = await createBundlerOptions(inputOptions, outputOptions, false);
  18. const userOnHmrUpdates = devOptions.onHmrUpdates;
  19. const bindingOnHmrUpdates = userOnHmrUpdates ? function(rawResult) {
  20. const result = normalizeBindingResult(rawResult);
  21. if (result instanceof Error) {
  22. userOnHmrUpdates(result);
  23. return;
  24. }
  25. const [updates, changedFiles] = result;
  26. userOnHmrUpdates({
  27. updates,
  28. changedFiles
  29. });
  30. } : void 0;
  31. const userOnOutput = devOptions.onOutput;
  32. const bindingDevOptions = {
  33. onHmrUpdates: bindingOnHmrUpdates,
  34. onOutput: userOnOutput ? function(rawResult) {
  35. const result = normalizeBindingResult(rawResult);
  36. if (result instanceof Error) {
  37. userOnOutput(result);
  38. return;
  39. }
  40. userOnOutput(transformToRollupOutput(result));
  41. } : void 0,
  42. rebuildStrategy: devOptions.rebuildStrategy ? devOptions.rebuildStrategy === "always" ? import_binding.BindingRebuildStrategy.Always : devOptions.rebuildStrategy === "auto" ? import_binding.BindingRebuildStrategy.Auto : import_binding.BindingRebuildStrategy.Never : void 0,
  43. watch: devOptions.watch && {
  44. skipWrite: devOptions.watch.skipWrite,
  45. usePolling: devOptions.watch.usePolling,
  46. pollInterval: devOptions.watch.pollInterval,
  47. useDebounce: devOptions.watch.useDebounce,
  48. debounceDuration: devOptions.watch.debounceDuration,
  49. compareContentsForPolling: devOptions.watch.compareContentsForPolling,
  50. debounceTickRate: devOptions.watch.debounceTickRate
  51. }
  52. };
  53. return new DevEngine(new import_binding.BindingDevEngine(options.bundlerOptions, bindingDevOptions));
  54. }
  55. constructor(inner) {
  56. this.#inner = inner;
  57. }
  58. async run() {
  59. await this.#inner.run();
  60. }
  61. async ensureCurrentBuildFinish() {
  62. if (this.#cachedBuildFinishPromise) return this.#cachedBuildFinishPromise;
  63. const promise = this.#inner.ensureCurrentBuildFinish().then(() => {
  64. this.#cachedBuildFinishPromise = null;
  65. });
  66. this.#cachedBuildFinishPromise = promise;
  67. return promise;
  68. }
  69. async getBundleState() {
  70. return this.#inner.getBundleState();
  71. }
  72. async ensureLatestBuildOutput() {
  73. await this.#inner.ensureLatestBuildOutput();
  74. }
  75. async invalidate(file, firstInvalidatedBy) {
  76. return this.#inner.invalidate(file, firstInvalidatedBy);
  77. }
  78. async registerModules(clientId, modules) {
  79. await this.#inner.registerModules(clientId, modules);
  80. }
  81. async removeClient(clientId) {
  82. await this.#inner.removeClient(clientId);
  83. }
  84. async close() {
  85. await this.#inner.close();
  86. }
  87. /**
  88. * Compile a lazy entry module and return HMR-style patch code.
  89. *
  90. * This is called when a dynamically imported module is first requested at runtime.
  91. * The module was previously stubbed with a proxy, and now we need to compile the
  92. * actual module and its dependencies.
  93. *
  94. * @param moduleId - The absolute file path of the module to compile
  95. * @param clientId - The client ID requesting this compilation
  96. * @returns The compiled JavaScript code as a string (HMR patch format)
  97. */
  98. async compileEntry(moduleId, clientId) {
  99. return this.#inner.compileEntry(moduleId, clientId);
  100. }
  101. };
  102. //#endregion
  103. //#region src/api/dev/index.ts
  104. const dev = (...args) => DevEngine.create(...args);
  105. //#endregion
  106. //#region src/types/external-memory-handle.ts
  107. const symbolForExternalMemoryHandle = "__rolldown_external_memory_handle__";
  108. /**
  109. * Frees the external memory held by the given handle.
  110. *
  111. * This is useful when you want to manually release memory held by Rust objects
  112. * (like `OutputChunk` or `OutputAsset`) before they are garbage collected.
  113. *
  114. * @param handle - The object with external memory to free
  115. * @param keepDataAlive - If true, evaluates all lazy fields before freeing memory (default: false).
  116. * This will take time to copy data from Rust to JavaScript, but prevents errors
  117. * when accessing properties after the memory is freed.
  118. * @returns Status object with `freed` boolean and optional `reason` string.
  119. * - `{ freed: true }` if memory was successfully freed
  120. * - `{ freed: false, reason: "..." }` if memory couldn't be freed (e.g., already freed or other references exist)
  121. *
  122. * @example
  123. * ```typescript
  124. * import { freeExternalMemory } from 'rolldown/experimental';
  125. *
  126. * const output = await bundle.generate();
  127. * const chunk = output.output[0];
  128. *
  129. * // Use the chunk...
  130. *
  131. * // Manually free the memory (fast, but accessing properties after will throw)
  132. * const status = freeExternalMemory(chunk); // { freed: true }
  133. * const statusAgain = freeExternalMemory(chunk); // { freed: false, reason: "Memory has already been freed" }
  134. *
  135. * // Keep data alive before freeing (slower, but data remains accessible)
  136. * freeExternalMemory(chunk, true); // Evaluates all lazy fields first
  137. * console.log(chunk.code); // OK - data was copied to JavaScript before freeing
  138. *
  139. * // Without keepDataAlive, accessing chunk properties after freeing will throw an error
  140. * ```
  141. */
  142. function freeExternalMemory(handle, keepDataAlive = false) {
  143. return handle[symbolForExternalMemoryHandle](keepDataAlive);
  144. }
  145. //#endregion
  146. //#region src/api/experimental.ts
  147. /**
  148. * This is an experimental API. Its behavior may change in the future.
  149. *
  150. * - Calling this API will only execute the `scan/build` stage of rolldown.
  151. * - `scan` will clean up all resources automatically, but if you want to ensure timely cleanup, you need to wait for the returned promise to resolve.
  152. *
  153. * @example To ensure cleanup of resources, use the returned promise to wait for the scan to complete.
  154. * ```ts
  155. * import { scan } from 'rolldown/api/experimental';
  156. *
  157. * const cleanupPromise = await scan(...);
  158. * await cleanupPromise;
  159. * // Now all resources have been cleaned up.
  160. * ```
  161. */
  162. const scan = async (rawInputOptions, rawOutputOptions = {}) => {
  163. validateOption("input", rawInputOptions);
  164. validateOption("output", rawOutputOptions);
  165. const ret = await createBundlerOptions(await PluginDriver.callOptionsHook(rawInputOptions), rawOutputOptions, false);
  166. const bundler = new import_binding.BindingBundler();
  167. if (RolldownBuild.asyncRuntimeShutdown) (0, import_binding.startAsyncRuntime)();
  168. async function cleanup() {
  169. await bundler.close();
  170. await ret.stopWorkers?.();
  171. (0, import_binding.shutdownAsyncRuntime)();
  172. RolldownBuild.asyncRuntimeShutdown = true;
  173. }
  174. let cleanupPromise = Promise.resolve();
  175. try {
  176. unwrapBindingResult(await bundler.scan(ret.bundlerOptions));
  177. } catch (err) {
  178. await cleanup();
  179. throw err;
  180. } finally {
  181. cleanupPromise = cleanup();
  182. }
  183. return cleanupPromise;
  184. };
  185. //#endregion
  186. //#region src/plugin/parallel-plugin.ts
  187. function defineParallelPlugin(pluginPath) {
  188. return (options) => {
  189. return { _parallel: {
  190. fileUrl: pathToFileURL(pluginPath).href,
  191. options
  192. } };
  193. };
  194. }
  195. //#endregion
  196. //#region src/builtin-plugin/alias-plugin.ts
  197. function viteAliasPlugin(config) {
  198. return new BuiltinPlugin("builtin:vite-alias", config);
  199. }
  200. //#endregion
  201. //#region src/builtin-plugin/bundle-analyzer-plugin.ts
  202. /**
  203. * A plugin that analyzes bundle composition and generates detailed reports.
  204. *
  205. * The plugin outputs a file containing detailed information about:
  206. * - All chunks and their relationships
  207. * - Modules bundled in each chunk
  208. * - Import dependencies between chunks
  209. * - Reachable modules from each entry point
  210. *
  211. * @example
  212. * ```js
  213. * import { bundleAnalyzerPlugin } from 'rolldown/experimental';
  214. *
  215. * export default {
  216. * plugins: [
  217. * bundleAnalyzerPlugin()
  218. * ]
  219. * }
  220. * ```
  221. *
  222. * @example
  223. * **Custom filename**
  224. * ```js
  225. * import { bundleAnalyzerPlugin } from 'rolldown/experimental';
  226. *
  227. * export default {
  228. * plugins: [
  229. * bundleAnalyzerPlugin({
  230. * fileName: 'bundle-analysis.json'
  231. * })
  232. * ]
  233. * }
  234. * ```
  235. *
  236. * @example
  237. * **LLM-friendly markdown output**
  238. * ```js
  239. * import { bundleAnalyzerPlugin } from 'rolldown/experimental';
  240. *
  241. * export default {
  242. * plugins: [
  243. * bundleAnalyzerPlugin({
  244. * format: 'md'
  245. * })
  246. * ]
  247. * }
  248. * ```
  249. */
  250. function bundleAnalyzerPlugin(config) {
  251. return new BuiltinPlugin("builtin:bundle-analyzer", config);
  252. }
  253. //#endregion
  254. //#region src/builtin-plugin/transform-plugin.ts
  255. function viteTransformPlugin(config) {
  256. return new BuiltinPlugin("builtin:vite-transform", {
  257. ...config,
  258. include: normalizedStringOrRegex(config.include),
  259. exclude: normalizedStringOrRegex(config.exclude),
  260. jsxRefreshInclude: normalizedStringOrRegex(config.jsxRefreshInclude),
  261. jsxRefreshExclude: normalizedStringOrRegex(config.jsxRefreshExclude),
  262. yarnPnp: typeof process === "object" && !!process.versions?.pnp
  263. });
  264. }
  265. //#endregion
  266. //#region src/builtin-plugin/vite-manifest-plugin.ts
  267. function viteManifestPlugin(config) {
  268. return new BuiltinPlugin("builtin:vite-manifest", config);
  269. }
  270. //#endregion
  271. //#region src/experimental-index.ts
  272. /**
  273. * In-memory file system for browser builds.
  274. *
  275. * This is a re-export of the {@link https://github.com/streamich/memfs | memfs} package used by the WASI runtime.
  276. * It allows you to read and write files to a virtual filesystem when using rolldown in browser environments.
  277. *
  278. * - `fs`: A Node.js-compatible filesystem API (`IFs` from memfs)
  279. * - `volume`: The underlying `Volume` instance that stores the filesystem state
  280. *
  281. * Returns `undefined` in Node.js builds (only available in browser builds via `@rolldown/browser`).
  282. *
  283. * @example
  284. * ```typescript
  285. * import { memfs } from 'rolldown/experimental';
  286. *
  287. * // Write files to virtual filesystem before bundling
  288. * memfs?.volume.fromJSON({
  289. * '/src/index.js': 'export const foo = 42;',
  290. * '/package.json': '{"name": "my-app"}'
  291. * });
  292. *
  293. * // Read files from the virtual filesystem
  294. * const content = memfs?.fs.readFileSync('/src/index.js', 'utf8');
  295. * ```
  296. *
  297. * @see {@link https://github.com/streamich/memfs} for more information on the memfs API.
  298. */
  299. const memfs = void 0;
  300. /** @deprecated Use from `rolldown/utils` instead. */
  301. const parse = parse$1;
  302. /** @deprecated Use from `rolldown/utils` instead. */
  303. const parseSync = parseSync$1;
  304. /** @deprecated Use from `rolldown/utils` instead. */
  305. const minify = minify$1;
  306. /** @deprecated Use from `rolldown/utils` instead. */
  307. const minifySync = minifySync$1;
  308. /** @deprecated Use from `rolldown/utils` instead. */
  309. const transform = transform$1;
  310. /** @deprecated Use from `rolldown/utils` instead. */
  311. const transformSync = transformSync$1;
  312. /** @deprecated Use from `rolldown/utils` instead. */
  313. const TsconfigCache = TsconfigCache$1;
  314. //#endregion
  315. var BindingRebuildStrategy = import_binding.BindingRebuildStrategy;
  316. var ResolverFactory = import_binding.ResolverFactory;
  317. var isolatedDeclaration = import_binding.isolatedDeclaration;
  318. var isolatedDeclarationSync = import_binding.isolatedDeclarationSync;
  319. var moduleRunnerTransform = import_binding.moduleRunnerTransform;
  320. export { BindingRebuildStrategy, DevEngine, ResolverFactory, TsconfigCache, bundleAnalyzerPlugin, defineParallelPlugin, dev, viteDynamicImportVarsPlugin as dynamicImportVarsPlugin, viteDynamicImportVarsPlugin, freeExternalMemory, viteImportGlobPlugin as importGlobPlugin, viteImportGlobPlugin, isolatedDeclaration, isolatedDeclarationPlugin, isolatedDeclarationSync, memfs, minify, minifySync, moduleRunnerTransform, oxcRuntimePlugin, parse, parseSync, resolveTsconfig, scan, transform, transformSync, viteAliasPlugin, viteBuildImportAnalysisPlugin, viteJsonPlugin, viteLoadFallbackPlugin, viteManifestPlugin, viteModulePreloadPolyfillPlugin, viteReactRefreshWrapperPlugin, viteReporterPlugin, viteResolvePlugin, viteTransformPlugin, viteWasmFallbackPlugin, viteWebWorkerPostPlugin };