bunup 0.1.13 → 0.1.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/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  A extremely fast, zero-config bundler for TypeScript & JavaScript, powered by Bun.
4
4
 
5
+ ![Demo](/demo.gif)
6
+
5
7
  > Built with speed in mind, Bunup aims to provide the fastest bundling experience possible. This project is currently a work in progress and will be ready for production use soon.
6
8
 
7
9
  ## Benchmarks
@@ -11,35 +13,8 @@ Bunup outperforms other popular bundlers by a significant margin:
11
13
  | Bundler | Format | Build Time | Relative Speed |
12
14
  | ------------- | -------- | ----------- | ---------------- |
13
15
  | bunup | esm, cjs | **3.65ms** | **16.0x faster** |
14
- | bunup (+ dts) | esm, cjs | **42.78ms** | **17.4x faster** |
16
+ | bunup (+ dts) | esm, cjs | **36.44ms** | **20.4x faster** |
15
17
  | tsup | esm, cjs | 58.36ms | baseline |
16
18
  | tsup (+ dts) | esm, cjs | 745.23ms | baseline |
17
19
 
18
20
  _Lower build time is better. Benchmark run on the same code with identical output formats._
19
-
20
- ## Advanced Features
21
-
22
- ### Worker-based DTS Generation
23
-
24
- For large projects, you can enable worker-based DTS generation to improve build performance:
25
-
26
- ```js
27
- // bunup.config.js
28
- import {defineConfig} from 'bunup';
29
-
30
- export default defineConfig({
31
- // ... other options
32
- dts: true,
33
- dtsWorker: true, // Run DTS generation in a worker thread
34
- });
35
- ```
36
-
37
- Or via CLI:
38
-
39
- ```bash
40
- bunup src/index.ts --dts --dts-worker
41
- # or using the short alias
42
- bunup src/index.ts -d -dw
43
- ```
44
-
45
- This runs TypeScript declaration file generation in a separate worker thread, which can significantly improve build times for large projects by parallelizing the work and keeping the main thread responsive.
@@ -0,0 +1,3 @@
1
+ declare function main(args?: string[]);
2
+
3
+ export { main };
package/build/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ declare function main(args?: string[]);
2
+
3
+ export { main };
package/build/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env bun
2
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var _path = require('path'); var _path2 = _interopRequireDefault(_path);var _worker_threads = require('worker_threads');var _oxctransform = require('oxc-transform'); var _oxctransform2 = _interopRequireDefault(_oxctransform);var _rollup = require('rollup');var _rollupplugindts = require('rollup-plugin-dts'); var _rollupplugindts2 = _interopRequireDefault(_rollupplugindts);var _typescript = require('typescript'); var _typescript2 = _interopRequireDefault(_typescript);var d=t=>t instanceof Error?t.message:String(t),j=(t,r)=>{let n=d(t),e=r?`[${r}] `:"";console.error(`\x1B[31m[ERROR]\x1B[0m ${e}${n}`),process.env.NODE_ENV!=="production"&&t instanceof Error&&t.stack&&console.error("\x1B[2m"+t.stack.split(`
2
+ // @bun @bun-cjs
3
+ (function(exports, require, module, __filename, __dirname) {var Nn=require("node:module");var Cn=Object.create;var{getPrototypeOf:En,defineProperty:y,getOwnPropertyNames:q,getOwnPropertyDescriptor:dn}=Object,K=Object.prototype.hasOwnProperty;var g=(n,r,e)=>{e=n!=null?Cn(En(n)):{};let s=r||!n||!n.__esModule?y(e,"default",{value:n,enumerable:!0}):e;for(let t of q(n))if(!K.call(s,t))y(s,t,{get:()=>n[t],enumerable:!0});return s},X=new WeakMap,pn=(n)=>{var r=X.get(n),e;if(r)return r;if(r=y({},"__esModule",{value:!0}),n&&typeof n==="object"||typeof n==="function")q(n).map((s)=>!K.call(r,s)&&y(r,s,{get:()=>n[s],enumerable:!(e=dn(n,s))||e.enumerable}));return X.set(n,r),r};var yn=(n,r)=>{for(var e in r)y(n,e,{get:r[e],enumerable:!0,configurable:!0,set:(s)=>r[e]=()=>s})};var Un={};yn(Un,{main:()=>On});module.exports=pn(Un);var H=g(require("fs")),xn=g(require("path"));var l=require("node:worker_threads");var p=g(require("node:fs")),S=g(require("node:path")),b=g(require("oxc-transform")),nn=require("rollup"),rn=g(require("rollup-plugin-dts")),k=g(require("typescript"));var $=(n)=>{if(n instanceof Error)return n.message;return String(n)},Q=(n,r)=>{let e=$(n),s=r?`[${r}] `:"";if(console.error(`\x1B[31m[ERROR]\x1B[0m ${s}${e}`),n instanceof Error&&n.stack)console.error("\x1B[2m"+n.stack.split(`
3
4
  `).slice(1).join(`
4
- `)+"\x1B[0m")};function v(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N(t=8){return Math.random().toString(36).substring(2,2+t)}function I(t,r){switch(t){case"esm":return".mjs";case"cjs":return $(r)?".cjs":".js";case"iife":return".global.js"}}function A(t,r){switch(t){case"esm":return".d.mts";case"cjs":return $(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function $(t){return t==="module"}function D(t){return t>=1e3?`${(t/1e3).toFixed(2)}s`:`${Math.round(t)}ms`}function L(t){return t?Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})])):[]}function _(t,r){return t===void 0?r==="esm":t}function U(t){return t.map(r=>typeof r=="string"?new RegExp(`^${v(r)}($|\\/|\\\\)`):r)}function B(t,r){return U(t.external||[]).concat(L(r).map(n=>new RegExp(`^${v(n)}($|\\/|\\\\)`)))}function S(t){return U(t.noExternal||[])}var a={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,r,n){let e=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${t}m[${r}]\x1B[0m ${e}${n}`},cli(t){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,t))},info(t){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,t))},warn(t){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,t))},error(t){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,t))},progress(t,r){let n=String(t),e=this.colors.default;for(let[o,s]of Object.entries(this.colors.progress))if(n.includes(o)){e=s;break}console.log(this.formatMessage(e,n,r))}};function J(t,r){return`${r?`${r.replace(/-/g,"_")}_`:""}${t}`.toUpperCase()}var E={entry:[],format:["esm"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function H(t,r){return{outdir:`${r}/${t.outDir}`,minify:ct(t),target:t.target,splitting:t.splitting}}function ct(t){let{minify:r,minifyWhitespace:n,minifyIdentifiers:e,minifySyntax:o}=t,s=r===!0;return{whitespace:_nullishCoalesce(n, () => (s)),identifiers:_nullishCoalesce(e, () => (s)),syntax:_nullishCoalesce(o, () => (s))}}async function V(t){let r=[];for(let n of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let e=_path2.default.join(t,`bunup.config${n}`);try{if(!_fs2.default.existsSync(e))continue;let o;if(n===".json"||n===".jsonc"){let s=_fs2.default.readFileSync(e,"utf8");o=JSON.parse(s)}else{let s=await Promise.resolve().then(() => _interopRequireWildcard(require(`file://${e}`)));o=s.default||s,o||(a.warn(`No default export found in ${e}`),o={})}if(Array.isArray(o))for(let s of o)r.push({options:{...E,...s},rootDir:t});else r.push({options:{...E,...o},rootDir:t});break}catch(o){a.error(`Failed to load config from ${e}: ${d(o)}`)}if(r.length>0)break}return r}function T(t){let r=_path2.default.join(t,"package.json");try{if(!_fs2.default.existsSync(r))return null;let n=_fs2.default.readFileSync(r,"utf8");return JSON.parse(n)}catch(n){return a.error(`Failed to load package.json at ${r}: ${d(n)}`),null}}function G(t){try{if(!_fs2.default.existsSync(t))return{};let r=_fs2.default.readFileSync(t,"utf8");return JSON.parse(r)||{}}catch(r){return a.warn(`Failed to parse tsconfig at ${t}: ${d(r)}`),{}}}async function X(t,r,n,e){let{absoluteRootDir:o,absoluteEntry:s}=yt(t,r),i=await ft(s),p=await gt(i);return dt(s,p,n,e,o)}async function ft(t){let r=new Set,n=[t];for(;n.length>0;){let e=n.pop();if(!(!e||r.has(e))){r.add(e);try{let o=await _fs2.default.promises.readFile(e,"utf8"),s=mt(o);for(let i of s){let p=_path2.default.dirname(e),c=_path2.default.resolve(p,i),l=[c,`${c}.ts`,`${c}.tsx`,`${c}/index.ts`,`${c}/index.tsx`];for(let u of l)if(_fs2.default.existsSync(u)&&u.endsWith(".ts")&&!r.has(u)){n.push(u);break}}}catch(o){a.warn(`Error processing ${e}: ${o instanceof Error?o.message:String(o)}`)}}}return r}function mt(t){let r=new Set;try{let n=/(?:import|export)(?:(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*)|[\s\n]+)(["'`])([^'"]+)\1/g,e;for(;(e=n.exec(t))!==null;){let i=e[2];i.startsWith(".")&&r.add(i)}let o=/import\s+(["'`])([^'"]+)\1\s*;?/g;for(;(e=o.exec(t))!==null;){let i=e[2];i.startsWith(".")&&r.add(i)}let s=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;for(;(e=s.exec(t))!==null;){let i=e[2];i.startsWith(".")&&r.add(i)}}catch(n){a.warn(`Error extracting imports: ${n instanceof Error?n.message:String(n)}`)}return Array.from(r)}async function gt(t){let r=new Map;return await Promise.all(Array.from(t).map(async n=>{try{let e=n.replace(/\.tsx?$/,".d.ts"),o=await _fs2.default.promises.readFile(n,"utf8"),{code:s}=_oxctransform2.default.isolatedDeclaration(n,o);s&&r.set(e,s)}catch(e){a.warn(`Failed to generate declaration for ${n}: ${e instanceof Error?e.message:String(e)}`)}})),r}async function dt(t,r,n,e,o){let s="\0virtual:",i=t.replace(/\.tsx?$/,".d.ts"),p=`${s}${i}`,c=typeof e.dts=="object"?e.dts:{},l=c.preferredTsconfigPath?_path2.default.resolve(c.preferredTsconfigPath):_path2.default.join(o,"tsconfig.json"),g=(await G(l)).compilerOptions,h={name:"bunup:virtual-dts",resolveId(f,m){if(f.startsWith(s))return f;if(_optionalChain([m, 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3(s)])){let x=m.slice(s.length),st=_path2.default.dirname(x);if(f.startsWith(".")){let it=_path2.default.resolve(st,f);for(let at of["",".d.ts","/index.d.ts"]){let W=`${it}${at}`;if(r.has(W))return`${s}${W}`}}}return null},load(f){if(f.startsWith(s)){let m=f.slice(s.length);return r.get(m)||null}return null}},et=T(o),nt=B(e,et),ot=S(e),O;try{O=await _rollup.rollup.call(void 0, {input:p,onwarn(m,x){m.code==="UNRESOLVED_IMPORT"||m.code==="CIRCULAR_DEPENDENCY"||m.code==="EMPTY_BUNDLE"||x(m)},plugins:[h,_rollupplugindts2.default.call(void 0, {tsconfig:l,compilerOptions:{...g?_typescript2.default.parseJsonConfigFileContent({compilerOptions:g},_typescript2.default.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:_typescript2.default.ScriptTarget.ESNext}})],external:m=>nt.some(x=>x.test(m))&&!ot.some(x=>x.test(m))});let{output:f}=await O.generate({format:n});if(!_optionalChain([f, 'access', _4 => _4[0], 'optionalAccess', _5 => _5.code]))throw new Error("Generated bundle is empty");return f[0].code}catch(f){throw new Error(`DTS bundling failed: ${d(f)}`)}finally{O&&await O.close()}}function yt(t,r){let n=_path2.default.resolve(t),e=_path2.default.resolve(n,r);if(!_fs2.default.existsSync(n))throw new Error(`Root directory does not exist: ${n}`);if(!_fs2.default.existsSync(e))throw new Error(`Entry file does not exist: ${e}`);if(!e.endsWith(".ts"))throw new Error(`Entry file must be a TypeScript file (.ts): ${e}`);if(_path2.default.relative(n,e).startsWith(".."))throw new Error(`Entry file must be within rootDir: ${e}`);return{absoluteRootDir:n,absoluteEntry:e}}async function Y(t,r,n,e,o){return new Promise((s,i)=>{let p={rootDir:t,entries:r,formats:n,options:e,packageType:o},c=new (0, _worker_threads.Worker)(new URL("./dtsWorker.js",import.meta.url),{workerData:p});c.on("message",l=>{if(l.success){if(l.timeMs){let u=D(l.timeMs);a.progress("DTS",`Bundled types in ${u}`)}s()}else i(new Error(l.error||"Unknown DTS worker error"))}),c.on("error",i),c.on("exit",l=>{l!==0&&i(new Error(`DTS worker stopped with exit code ${l}`))})})}if(!_worker_threads.isMainThread&&_worker_threads.parentPort){let{rootDir:t,entries:r,formats:n,options:e,packageType:o}=_worker_threads.workerData,s=performance.now();a.progress("DTS","Bundling types in worker thread");try{let i=n.flatMap(p=>r.map(async c=>{let l=await X(t,c.path,p,e),u=A(p,o),g=`${e.outDir}/${c.name}${u}`,h=`${t}/${g}`;await Bun.write(h,l),a.progress("DTS",g)}));Promise.all(i).then(()=>{let p=performance.now()-s;_optionalChain([_worker_threads.parentPort, 'optionalAccess', _6 => _6.postMessage, 'call', _7 => _7({success:!0,timeMs:p})])}).catch(p=>{_optionalChain([_worker_threads.parentPort, 'optionalAccess', _8 => _8.postMessage, 'call', _9 => _9({success:!1,error:p instanceof Error?p.message:String(p)})])})}catch(i){_optionalChain([_worker_threads.parentPort, 'optionalAccess', _10 => _10.postMessage, 'call', _11 => _11({success:!1,error:i instanceof Error?i.message:String(i)})])}}function wt(t){return _optionalChain([t, 'access', _12 => _12.split, 'call', _13 => _13("/"), 'access', _14 => _14.pop, 'call', _15 => _15(), 'optionalAccess', _16 => _16.split, 'call', _17 => _17("."), 'access', _18 => _18.slice, 'call', _19 => _19(0,-1), 'access', _20 => _20.join, 'call', _21 => _21(".")])||""}function b(t){let r=[],n=new Set;function e(o,s){if(n.has(o)){let i=N();r.push({name:`${o}_${i}`,path:s})}else r.push({name:o,path:s}),n.add(o)}if(Array.isArray(t))for(let o of t){let s=wt(o);e(s,o)}else Object.entries(t).forEach(([o,s])=>{e(o,s)});return r}function q(t,r){return`[dir]/${t}${r}`}function K(t,r){return{name:"bunup:external-plugin",setup(n){n.onResolve({filter:/.*/},e=>{let o=e.path;return t.some(i=>i.test(o))&&!r.some(i=>i.test(o))?{path:o,external:!0}:null})}}}async function R(t,r){if(!t.entry||t.entry.length===0||!t.outDir){a.cli("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");return}let n=performance.now();a.cli("Build started");let e=T(r),o=_optionalChain([e, 'optionalAccess', _22 => _22.type]),s=B(t,e),i=S(t),p=[K(s,i)],c=b(t.entry),l=t.format.flatMap(u=>c.map(g=>Pt(t,r,g,u,o,p)));try{await Promise.all(l);let u=performance.now()-n,g=D(u);a.cli(`\u26A1 Build success in ${g}`)}catch (e2){a.error("Build process encountered errors."),process.exit(1)}if(t.dts){a.progress("DTS","Bundling types");let u=t.format.filter(h=>!(h==="iife"&&!$(o)&&t.format.includes("cjs"))),g=t.dts===!0?c:b(t.dts.entry);try{await Y(r,g,u,t,o)}catch(h){a.error(`DTS build process encountered errors: ${d(h)}`)}}}async function Pt(t,r,n,e,o,s){let i=I(e,o),p=H(t,r),c=await Bun.build({...p,entrypoints:[`${r}/${n.path}`],format:e,naming:{entry:q(n.name,i)},splitting:_(t.splitting,e),plugins:s,throw:!1});if(!c.success)throw c.logs.forEach(l=>{l.level==="error"?a.error(l.message):l.level==="warning"?a.warn(l.message):l.level==="info"&&a.info(l.message)}),new Error(`Build failed for ${n} (${e})`);a.progress(J(e,t.name),`${t.outDir}/${n.name}${i}`)}var bt={n:"name",f:"format",o:"outDir",m:"minify",w:"watch",d:"dts",e:"external",t:"target",mw:"minifyWhitespace",mi:"minifyIdentifiers",ms:"minifySyntax",c:"clean",s:"splitting",ne:"noExternal"},Ot={name:(t,r)=>{r.name=t},format:(t,r)=>{r.format=t.split(",")},outDir:(t,r)=>{r.outDir=t},minify:(t,r)=>{r.minify=!!t},watch:(t,r)=>{r.watch=!!t},dts:(t,r)=>{r.dts=!!t},external:(t,r)=>{r.external=t.split(",")},minifyWhitespace:(t,r)=>{r.minifyWhitespace=!!t},minifyIdentifiers:(t,r)=>{r.minifyIdentifiers=!!t},minifySyntax:(t,r)=>{r.minifySyntax=!!t},target:(t,r)=>{r.target=t},clean:(t,r)=>{r.clean=!!t},splitting:(t,r)=>{r.splitting=!!t},noExternal:(t,r)=>{r.noExternal=t.split(",")}};function Q(t){let r={};for(let n=0;n<t.length;n++){let e=t[n];if(e.startsWith("--")||e.startsWith("-")){let o=e.startsWith("-")&&!e.startsWith("--"),s=o?e.slice(1):e.slice(2),i=o?bt[s]:s,p=Ot[i];if(!p){a.error(`Unknown option: ${s}`);continue}let c=t[n+1],l=c&&!c.startsWith("-")?c:!0;p(l,r),typeof l=="string"&&n++}else r.entry||(r.entry=[]),Array.isArray(r.entry)&&r.entry.push(e)}return r}typeof Bun>"u"&&(a.error(`Bunup requires Bun to run.
5
- To install Bun, visit https://bun.sh/docs/installation`),process.exit(1));var _chokidar = require('chokidar'); var _chokidar2 = _interopRequireDefault(_chokidar);async function Z(t,r){let n=new Set;b(t.entry).forEach(c=>{let l=_path2.default.resolve(r,c.path),u=_path2.default.dirname(l);n.add(u)});let o=_chokidar2.default.watch(Array.from(n),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,t.outDir]}),s=null,i=!1,p=async c=>{if(!i){i=!0;try{await R({...t,entry:[c],clean:!1},r)}catch(l){a.error(`Build failed: ${l}`)}finally{i=!1}}};o.on("change",c=>{let l=_path2.default.relative(r,c);a.cli(`File changed: ${l}`),s&&clearTimeout(s),s=setTimeout(()=>p(l),300)}),o.on("error",c=>{a.error(`Watcher error: ${c}`)})}async function Bt(t=Bun.argv.slice(2)){let r=Q(t),n=await V(process.cwd()),e=process.cwd();if(r.watch&&(a.cli("Starting watch mode"),a.cli("Watching for file changes")),n.length===0){let o={...E,...r};o.clean&&rt(e,o.outDir),await tt(o,e)}else{for(let{options:o,rootDir:s}of n)o.clean&&rt(s,o.outDir);await Promise.all(n.map(async({options:o,rootDir:s})=>{let i={...E,...o,...r};await tt(i,s)}))}r.watch||process.exit(0)}async function tt(t,r){t.watch?await Z(t,r):await R(t,r)}function rt(t,r){let n=_path2.default.join(t,r);if(_fs2.default.existsSync(n))try{_fs2.default.rmSync(n,{recursive:!0,force:!0})}catch(e){a.error(`Failed to clean output directory: ${e}`)}_fs2.default.mkdirSync(n,{recursive:!0})}Bt().catch(t=>{j(t),process.exit(1)});exports.main = Bt;
5
+ `)+"\x1B[0m")};function U(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(n=8){return Math.random().toString(36).substring(2,2+n)}function Z(n,r){switch(n){case"esm":return".mjs";case"cjs":return A(r)?".cjs":".js";case"iife":return".global.js"}}function F(n,r){switch(n){case"esm":return".d.mts";case"cjs":return A(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function A(n){return n==="module"}function W(n){return n>=1000?`${(n/1000).toFixed(2)}s`:`${Math.round(n)}ms`}function z(n){if(!n)return[];return Array.from(new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.peerDependencies||{})]))}function I(n,r){return n===void 0?r==="esm":n}function D(n){return n.map((r)=>typeof r==="string"?new RegExp(`^${U(r)}($|\\/|\\\\)`):r)}function h(n,r){return D(n.external||[]).concat(z(r).map((e)=>new RegExp(`^${U(e)}($|\\/|\\\\)`)))}function L(n){return D(n.noExternal||[])}var E=g(require("node:fs")),v=g(require("node:path"));var o={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(n,r,e){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${n}m[${r}]\x1B[0m ${s}${e}`},cli(n){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,n))},info(n){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,n))},warn(n){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,n))},error(n){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,n))},progress(n,r){let e=String(n),s=this.colors.default;for(let[t,c]of Object.entries(this.colors.progress))if(e.includes(t)){s=c;break}console.log(this.formatMessage(s,e,r))}};function J(n,r){return`${r?`${r.replace(/-/g,"_")}_`:""}${n}`.toUpperCase()}var d={entry:[],format:["cjs"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function T(n,r){return{outdir:`${r}/${n.outDir}`,minify:jn(n),target:n.target,splitting:n.splitting}}function jn(n){let{minify:r,minifyWhitespace:e,minifyIdentifiers:s,minifySyntax:t}=n,c=r===!0;return{whitespace:e??c,identifiers:s??c,syntax:t??c}}async function V(n){let r=[];for(let e of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let s=v.default.join(n,`bunup.config${e}`);try{if(!E.default.existsSync(s))continue;let t;if(e===".json"||e===".jsonc"){let c=E.default.readFileSync(s,"utf8");t=JSON.parse(c)}else{let c=await import(`file://${s}`);if(t=c.default||c,!t)o.warn(`No default export found in ${s}`),t={}}if(Array.isArray(t))for(let c of t)r.push({options:{...d,...c},rootDir:n});else r.push({options:{...d,...t},rootDir:n});break}catch(t){o.error(`Failed to load config from ${s}: ${$(t)}`)}if(r.length>0)break}return r}function R(n){let r=v.default.join(n,"package.json");try{if(!E.default.existsSync(r))return null;let e=E.default.readFileSync(r,"utf8");return JSON.parse(e)}catch(e){return o.error(`Failed to load package.json at ${r}: ${$(e)}`),null}}function P(n){try{if(!E.default.existsSync(n))return{};let r=E.default.readFileSync(n,"utf8");return JSON.parse(r)||{}}catch(r){return o.warn(`Failed to parse tsconfig at ${n}: ${$(r)}`),{}}}async function sn(n,r,e,s){let{absoluteRootDir:t,absoluteEntry:c}=Rn(n,r),i=await An(c),m=await hn(i);return Ln(c,m,e,s,t)}async function An(n){let r=new Set,e=[n];while(e.length>0){let s=e.pop();if(!s||r.has(s))continue;r.add(s);try{let t=await p.default.promises.readFile(s,"utf8"),c=Wn(t);for(let i of c){let m=S.default.dirname(s),f=S.default.resolve(m,i),a=[f,`${f}.ts`,`${f}.tsx`,`${f}/index.ts`,`${f}/index.tsx`];for(let u of a)if(p.default.existsSync(u)&&u.endsWith(".ts")&&!r.has(u)){e.push(u);break}}}catch(t){o.warn(`Error processing ${s}: ${t instanceof Error?t.message:String(t)}`)}}return r}function Wn(n){let r=new Set;try{let e=/(?:import|export)(?:(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*)|[\s\n]+)(["'`])([^'"]+)\1/g,s;while((s=e.exec(n))!==null){let i=s[2];if(i.startsWith("."))r.add(i)}let t=/import\s+(["'`])([^'"]+)\1\s*;?/g;while((s=t.exec(n))!==null){let i=s[2];if(i.startsWith("."))r.add(i)}let c=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;while((s=c.exec(n))!==null){let i=s[2];if(i.startsWith("."))r.add(i)}}catch(e){o.warn(`Error extracting imports: ${e instanceof Error?e.message:String(e)}`)}return Array.from(r)}async function hn(n){let r=new Map;return await Promise.all(Array.from(n).map(async(e)=>{try{let s=e.replace(/\.tsx?$/,".d.ts"),t=await p.default.promises.readFile(e,"utf8"),{code:c}=b.default.isolatedDeclaration(e,t);if(c)r.set(s,c)}catch(s){o.warn(`Failed to generate declaration for ${e}: ${s instanceof Error?s.message:String(s)}`)}})),r}async function Ln(n,r,e,s,t){let m=`\x00virtual:${n.replace(/\.tsx?$/,".d.ts")}`,f=typeof s.dts==="object"?s.dts:{},a=f.preferredTsconfigPath?S.default.resolve(f.preferredTsconfigPath):S.default.join(t,"tsconfig.json"),w=(await P(a)).compilerOptions,B={name:"bunup:virtual-dts",resolveId(x,O){if(x.startsWith("\x00virtual:"))return x;if(O?.startsWith("\x00virtual:")){let C=O.slice(9),Sn=S.default.dirname(C);if(x.startsWith(".")){let $n=S.default.resolve(Sn,x);for(let Bn of["",".d.ts","/index.d.ts"]){let G=`${$n}${Bn}`;if(r.has(G))return`\x00virtual:${G}`}}}return null},load(x){if(x.startsWith("\x00virtual:")){let O=x.slice(9);return r.get(O)||null}return null}},wn=R(t),gn=h(s,wn),ln=L(s),j;try{j=await nn.rollup({input:m,onwarn(O,C){if(O.code==="UNRESOLVED_IMPORT"||O.code==="CIRCULAR_DEPENDENCY"||O.code==="EMPTY_BUNDLE")return;C(O)},plugins:[B,rn.default({tsconfig:a,compilerOptions:{...w?k.default.parseJsonConfigFileContent({compilerOptions:w},k.default.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:k.default.ScriptTarget.ESNext}})],external:(O)=>gn.some((C)=>C.test(O))&&!ln.some((C)=>C.test(O))});let{output:x}=await j.generate({format:e});if(!x[0]?.code)throw new Error("Generated bundle is empty");return x[0].code}catch(x){throw new Error(`DTS bundling failed: ${$(x)}`)}finally{if(j)await j.close()}}function Rn(n,r){let e=S.default.resolve(n),s=S.default.resolve(e,r);if(!p.default.existsSync(e))throw new Error(`Root directory does not exist: ${e}`);if(!p.default.existsSync(s))throw new Error(`Entry file does not exist: ${s}`);if(!s.endsWith(".ts"))throw new Error(`Entry file must be a TypeScript file (.ts): ${s}`);if(S.default.relative(e,s).startsWith(".."))throw new Error(`Entry file must be within rootDir: ${s}`);return{absoluteRootDir:e,absoluteEntry:s}}async function en(n,r,e,s,t){return new Promise((c,i)=>{let m={rootDir:n,entries:r,formats:e,options:s,packageType:t},f=new l.Worker(new URL("./dtsWorker.js",import.meta.url),{workerData:m});f.on("message",(a)=>{if(a.success){if(a.timeMs){let u=W(a.timeMs);o.progress("DTS",`Bundled types in ${u}`)}c()}else i(new Error(a.error||"Unknown DTS worker error"))}),f.on("error",i),f.on("exit",(a)=>{if(a!==0)i(new Error(`DTS worker stopped with exit code ${a}`))})})}if(!l.isMainThread&&l.parentPort){let{rootDir:n,entries:r,formats:e,options:s,packageType:t}=l.workerData,c=performance.now();o.progress("DTS","Bundling types");try{let i=e.flatMap((m)=>r.map(async(f)=>{let a=await sn(n,f.path,m,s),u=F(m,t),w=`${s.outDir}/${f.name}${u}`,B=`${n}/${w}`;await Bun.write(B,a),o.progress("DTS",w)}));Promise.all(i).then(()=>{let m=performance.now()-c;l.parentPort?.postMessage({success:!0,timeMs:m})}).catch((m)=>{l.parentPort?.postMessage({success:!1,error:m instanceof Error?m.message:String(m)})})}catch(i){l.parentPort?.postMessage({success:!1,error:i instanceof Error?i.message:String(i)})}}function kn(n){return n.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function N(n){let r=[],e=new Set;function s(t,c){if(e.has(t)){let i=Y();r.push({name:`${t}_${i}`,path:c})}else r.push({name:t,path:c}),e.add(t)}if(Array.isArray(n))for(let t of n){let c=kn(t);s(c,t)}else Object.entries(n).forEach(([t,c])=>{s(t,c)});return r}function tn(n,r){return`[dir]/${n}${r}`}function cn(n,r){return{name:"bunup:external-plugin",setup(e){e.onResolve({filter:/.*/},(s)=>{let t=s.path;if(n.some((i)=>i.test(t))&&!r.some((i)=>i.test(t)))return{path:t,external:!0};return null})}}}async function _(n,r){if(!n.entry||n.entry.length===0||!n.outDir){o.cli("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");return}let e=performance.now();o.cli("Build started");let s=R(r),t=s?.type,c=h(n,s),i=L(n),m=[cn(c,i)],f=N(n.entry),a=n.format.flatMap((u)=>f.map((w)=>_n(n,r,w,u,t,m)));try{await Promise.all(a);let u=performance.now()-e,w=W(u);o.cli(`⚡ Build success in ${w}`)}catch(u){o.error("Build process encountered errors."),process.exit(1)}if(n.dts){o.progress("DTS","Bundling types");let u=n.format.filter((B)=>{if(B==="iife"&&!A(t)&&n.format.includes("cjs"))return!1;return!0}),w=n.dts===!0?f:N(n.dts.entry);try{await en(r,w,u,n,t)}catch(B){o.error(`DTS build process encountered errors: ${$(B)}`)}}}async function _n(n,r,e,s,t,c){let i=Z(s,t),m=T(n,r),f=await Bun.build({...m,entrypoints:[`${r}/${e.path}`],format:s,naming:{entry:tn(e.name,i)},splitting:I(n.splitting,s),plugins:c,throw:!1});if(!f.success)throw f.logs.forEach((a)=>{if(a.level==="error")o.error(a.message);else if(a.level==="warning")o.warn(a.message);else if(a.level==="info")o.info(a.message)}),new Error(`Build failed for ${e} (${s})`);o.progress(J(s,n.name),`${n.outDir}/${e.name}${i}`)}var Mn={n:"name",f:"format",o:"outDir",m:"minify",w:"watch",d:"dts",e:"external",t:"target",mw:"minifyWhitespace",mi:"minifyIdentifiers",ms:"minifySyntax",c:"clean",s:"splitting",ne:"noExternal"},Hn={name:(n,r)=>{r.name=n},format:(n,r)=>{r.format=n.split(",")},outDir:(n,r)=>{r.outDir=n},minify:(n,r)=>{r.minify=!!n},watch:(n,r)=>{r.watch=!!n},dts:(n,r)=>{r.dts=!!n},external:(n,r)=>{r.external=n.split(",")},minifyWhitespace:(n,r)=>{r.minifyWhitespace=!!n},minifyIdentifiers:(n,r)=>{r.minifyIdentifiers=!!n},minifySyntax:(n,r)=>{r.minifySyntax=!!n},target:(n,r)=>{r.target=n},clean:(n,r)=>{r.clean=!!n},splitting:(n,r)=>{r.splitting=!!n},noExternal:(n,r)=>{r.noExternal=n.split(",")}};function on(n){let r={};for(let e=0;e<n.length;e++){let s=n[e];if(s.startsWith("--")||s.startsWith("-")){let t=s.startsWith("-")&&!s.startsWith("--"),c=t?s.slice(1):s.slice(2),i=t?Mn[c]:c,m=Hn[i];if(!m){o.error(`Unknown option: ${c}`);continue}let f=n[e+1],a=f&&!f.startsWith("-")?f:!0;if(m(a,r),typeof a==="string")e++}else{if(!r.entry)r.entry=[];if(Array.isArray(r.entry))r.entry.push(s)}}return r}(()=>{if(typeof Bun==="undefined")o.error(`Bunup requires Bun to run.
6
+ To install Bun, visit https://bun.sh/docs/installation`),process.exit(1)})();var M=g(require("node:path")),fn=g(require("chokidar"));async function an(n,r){let e=new Set;N(n.entry).forEach((f)=>{let a=M.default.resolve(r,f.path),u=M.default.dirname(a);e.add(u)});let t=fn.default.watch(Array.from(e),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,n.outDir]}),c=null,i=!1,m=async(f)=>{if(i)return;i=!0;try{await _({...n,entry:[f],clean:!1},r)}catch(a){o.error(`Build failed: ${a}`)}finally{i=!1}};t.on("change",(f)=>{let a=M.default.relative(r,f);if(o.cli(`File changed: ${a}`),c)clearTimeout(c);c=setTimeout(()=>m(a),300)}),t.on("error",(f)=>{o.error(`Watcher error: ${f}`)})}async function On(n=Bun.argv.slice(2)){let r=on(n),e=await V(process.cwd()),s=process.cwd();if(r.watch)o.cli("Starting watch mode"),o.cli("Watching for file changes");if(e.length===0){let t={...d,...r};if(t.clean)un(s,t.outDir);await mn(t,s)}else{for(let{options:t,rootDir:c}of e)if(t.clean)un(c,t.outDir);await Promise.all(e.map(async({options:t,rootDir:c})=>{let i={...d,...t,...r};await mn(i,c)}))}if(!r.watch)process.exit(0)}async function mn(n,r){if(n.watch)await an(n,r);else await _(n,r)}function un(n,r){let e=xn.default.join(n,r);if(H.default.existsSync(e))try{H.default.rmSync(e,{recursive:!0,force:!0})}catch(s){o.error(`Failed to clean output directory: ${s}`)}H.default.mkdirSync(e,{recursive:!0})}On().catch((n)=>{Q(n),process.exit(1)});})
package/build/cli.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env bun
2
- import C from"fs";import Dt from"path";import{isMainThread as ht,parentPort as k,Worker as xt,workerData as Et}from"worker_threads";import P from"fs";import y from"path";import lt from"oxc-transform";import{rollup as pt}from"rollup";import ut from"rollup-plugin-dts";import F from"typescript";var d=t=>t instanceof Error?t.message:String(t),j=(t,r)=>{let n=d(t),e=r?`[${r}] `:"";console.error(`\x1B[31m[ERROR]\x1B[0m ${e}${n}`),process.env.NODE_ENV!=="production"&&t instanceof Error&&t.stack&&console.error("\x1B[2m"+t.stack.split(`
2
+ // @bun
3
+ import M from"fs";import jn from"path";import{isMainThread as $n,parentPort as h,Worker as Bn,workerData as Cn}from"node:worker_threads";import E from"node:fs";import l from"node:path";import mn from"oxc-transform";import{rollup as un}from"rollup";import xn from"rollup-plugin-dts";import k from"typescript";var g=(n)=>{if(n instanceof Error)return n.message;return String(n)},U=(n,r)=>{let e=g(n),s=r?`[${r}] `:"";if(console.error(`\x1B[31m[ERROR]\x1B[0m ${s}${e}`),n instanceof Error&&n.stack)console.error("\x1B[2m"+n.stack.split(`
3
4
  `).slice(1).join(`
4
- `)+"\x1B[0m")};function v(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N(t=8){return Math.random().toString(36).substring(2,2+t)}function I(t,r){switch(t){case"esm":return".mjs";case"cjs":return $(r)?".cjs":".js";case"iife":return".global.js"}}function A(t,r){switch(t){case"esm":return".d.mts";case"cjs":return $(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function $(t){return t==="module"}function D(t){return t>=1e3?`${(t/1e3).toFixed(2)}s`:`${Math.round(t)}ms`}function L(t){return t?Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})])):[]}function _(t,r){return t===void 0?r==="esm":t}function U(t){return t.map(r=>typeof r=="string"?new RegExp(`^${v(r)}($|\\/|\\\\)`):r)}function B(t,r){return U(t.external||[]).concat(L(r).map(n=>new RegExp(`^${v(n)}($|\\/|\\\\)`)))}function S(t){return U(t.noExternal||[])}import w from"fs";import z from"path";var a={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,r,n){let e=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${t}m[${r}]\x1B[0m ${e}${n}`},cli(t){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,t))},info(t){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,t))},warn(t){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,t))},error(t){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,t))},progress(t,r){let n=String(t),e=this.colors.default;for(let[o,s]of Object.entries(this.colors.progress))if(n.includes(o)){e=s;break}console.log(this.formatMessage(e,n,r))}};function J(t,r){return`${r?`${r.replace(/-/g,"_")}_`:""}${t}`.toUpperCase()}var E={entry:[],format:["esm"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function H(t,r){return{outdir:`${r}/${t.outDir}`,minify:ct(t),target:t.target,splitting:t.splitting}}function ct(t){let{minify:r,minifyWhitespace:n,minifyIdentifiers:e,minifySyntax:o}=t,s=r===!0;return{whitespace:n??s,identifiers:e??s,syntax:o??s}}async function V(t){let r=[];for(let n of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let e=z.join(t,`bunup.config${n}`);try{if(!w.existsSync(e))continue;let o;if(n===".json"||n===".jsonc"){let s=w.readFileSync(e,"utf8");o=JSON.parse(s)}else{let s=await import(`file://${e}`);o=s.default||s,o||(a.warn(`No default export found in ${e}`),o={})}if(Array.isArray(o))for(let s of o)r.push({options:{...E,...s},rootDir:t});else r.push({options:{...E,...o},rootDir:t});break}catch(o){a.error(`Failed to load config from ${e}: ${d(o)}`)}if(r.length>0)break}return r}function T(t){let r=z.join(t,"package.json");try{if(!w.existsSync(r))return null;let n=w.readFileSync(r,"utf8");return JSON.parse(n)}catch(n){return a.error(`Failed to load package.json at ${r}: ${d(n)}`),null}}function G(t){try{if(!w.existsSync(t))return{};let r=w.readFileSync(t,"utf8");return JSON.parse(r)||{}}catch(r){return a.warn(`Failed to parse tsconfig at ${t}: ${d(r)}`),{}}}async function X(t,r,n,e){let{absoluteRootDir:o,absoluteEntry:s}=yt(t,r),i=await ft(s),p=await gt(i);return dt(s,p,n,e,o)}async function ft(t){let r=new Set,n=[t];for(;n.length>0;){let e=n.pop();if(!(!e||r.has(e))){r.add(e);try{let o=await P.promises.readFile(e,"utf8"),s=mt(o);for(let i of s){let p=y.dirname(e),c=y.resolve(p,i),l=[c,`${c}.ts`,`${c}.tsx`,`${c}/index.ts`,`${c}/index.tsx`];for(let u of l)if(P.existsSync(u)&&u.endsWith(".ts")&&!r.has(u)){n.push(u);break}}}catch(o){a.warn(`Error processing ${e}: ${o instanceof Error?o.message:String(o)}`)}}}return r}function mt(t){let r=new Set;try{let n=/(?:import|export)(?:(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*)|[\s\n]+)(["'`])([^'"]+)\1/g,e;for(;(e=n.exec(t))!==null;){let i=e[2];i.startsWith(".")&&r.add(i)}let o=/import\s+(["'`])([^'"]+)\1\s*;?/g;for(;(e=o.exec(t))!==null;){let i=e[2];i.startsWith(".")&&r.add(i)}let s=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;for(;(e=s.exec(t))!==null;){let i=e[2];i.startsWith(".")&&r.add(i)}}catch(n){a.warn(`Error extracting imports: ${n instanceof Error?n.message:String(n)}`)}return Array.from(r)}async function gt(t){let r=new Map;return await Promise.all(Array.from(t).map(async n=>{try{let e=n.replace(/\.tsx?$/,".d.ts"),o=await P.promises.readFile(n,"utf8"),{code:s}=lt.isolatedDeclaration(n,o);s&&r.set(e,s)}catch(e){a.warn(`Failed to generate declaration for ${n}: ${e instanceof Error?e.message:String(e)}`)}})),r}async function dt(t,r,n,e,o){let s="\0virtual:",i=t.replace(/\.tsx?$/,".d.ts"),p=`${s}${i}`,c=typeof e.dts=="object"?e.dts:{},l=c.preferredTsconfigPath?y.resolve(c.preferredTsconfigPath):y.join(o,"tsconfig.json"),g=(await G(l)).compilerOptions,h={name:"bunup:virtual-dts",resolveId(f,m){if(f.startsWith(s))return f;if(m?.startsWith(s)){let x=m.slice(s.length),st=y.dirname(x);if(f.startsWith(".")){let it=y.resolve(st,f);for(let at of["",".d.ts","/index.d.ts"]){let W=`${it}${at}`;if(r.has(W))return`${s}${W}`}}}return null},load(f){if(f.startsWith(s)){let m=f.slice(s.length);return r.get(m)||null}return null}},et=T(o),nt=B(e,et),ot=S(e),O;try{O=await pt({input:p,onwarn(m,x){m.code==="UNRESOLVED_IMPORT"||m.code==="CIRCULAR_DEPENDENCY"||m.code==="EMPTY_BUNDLE"||x(m)},plugins:[h,ut({tsconfig:l,compilerOptions:{...g?F.parseJsonConfigFileContent({compilerOptions:g},F.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:F.ScriptTarget.ESNext}})],external:m=>nt.some(x=>x.test(m))&&!ot.some(x=>x.test(m))});let{output:f}=await O.generate({format:n});if(!f[0]?.code)throw new Error("Generated bundle is empty");return f[0].code}catch(f){throw new Error(`DTS bundling failed: ${d(f)}`)}finally{O&&await O.close()}}function yt(t,r){let n=y.resolve(t),e=y.resolve(n,r);if(!P.existsSync(n))throw new Error(`Root directory does not exist: ${n}`);if(!P.existsSync(e))throw new Error(`Entry file does not exist: ${e}`);if(!e.endsWith(".ts"))throw new Error(`Entry file must be a TypeScript file (.ts): ${e}`);if(y.relative(n,e).startsWith(".."))throw new Error(`Entry file must be within rootDir: ${e}`);return{absoluteRootDir:n,absoluteEntry:e}}async function Y(t,r,n,e,o){return new Promise((s,i)=>{let p={rootDir:t,entries:r,formats:n,options:e,packageType:o},c=new xt(new URL("./dtsWorker.js",import.meta.url),{workerData:p});c.on("message",l=>{if(l.success){if(l.timeMs){let u=D(l.timeMs);a.progress("DTS",`Bundled types in ${u}`)}s()}else i(new Error(l.error||"Unknown DTS worker error"))}),c.on("error",i),c.on("exit",l=>{l!==0&&i(new Error(`DTS worker stopped with exit code ${l}`))})})}if(!ht&&k){let{rootDir:t,entries:r,formats:n,options:e,packageType:o}=Et,s=performance.now();a.progress("DTS","Bundling types in worker thread");try{let i=n.flatMap(p=>r.map(async c=>{let l=await X(t,c.path,p,e),u=A(p,o),g=`${e.outDir}/${c.name}${u}`,h=`${t}/${g}`;await Bun.write(h,l),a.progress("DTS",g)}));Promise.all(i).then(()=>{let p=performance.now()-s;k?.postMessage({success:!0,timeMs:p})}).catch(p=>{k?.postMessage({success:!1,error:p instanceof Error?p.message:String(p)})})}catch(i){k?.postMessage({success:!1,error:i instanceof Error?i.message:String(i)})}}function wt(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function b(t){let r=[],n=new Set;function e(o,s){if(n.has(o)){let i=N();r.push({name:`${o}_${i}`,path:s})}else r.push({name:o,path:s}),n.add(o)}if(Array.isArray(t))for(let o of t){let s=wt(o);e(s,o)}else Object.entries(t).forEach(([o,s])=>{e(o,s)});return r}function q(t,r){return`[dir]/${t}${r}`}function K(t,r){return{name:"bunup:external-plugin",setup(n){n.onResolve({filter:/.*/},e=>{let o=e.path;return t.some(i=>i.test(o))&&!r.some(i=>i.test(o))?{path:o,external:!0}:null})}}}async function R(t,r){if(!t.entry||t.entry.length===0||!t.outDir){a.cli("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");return}let n=performance.now();a.cli("Build started");let e=T(r),o=e?.type,s=B(t,e),i=S(t),p=[K(s,i)],c=b(t.entry),l=t.format.flatMap(u=>c.map(g=>Pt(t,r,g,u,o,p)));try{await Promise.all(l);let u=performance.now()-n,g=D(u);a.cli(`\u26A1 Build success in ${g}`)}catch{a.error("Build process encountered errors."),process.exit(1)}if(t.dts){a.progress("DTS","Bundling types");let u=t.format.filter(h=>!(h==="iife"&&!$(o)&&t.format.includes("cjs"))),g=t.dts===!0?c:b(t.dts.entry);try{await Y(r,g,u,t,o)}catch(h){a.error(`DTS build process encountered errors: ${d(h)}`)}}}async function Pt(t,r,n,e,o,s){let i=I(e,o),p=H(t,r),c=await Bun.build({...p,entrypoints:[`${r}/${n.path}`],format:e,naming:{entry:q(n.name,i)},splitting:_(t.splitting,e),plugins:s,throw:!1});if(!c.success)throw c.logs.forEach(l=>{l.level==="error"?a.error(l.message):l.level==="warning"?a.warn(l.message):l.level==="info"&&a.info(l.message)}),new Error(`Build failed for ${n} (${e})`);a.progress(J(e,t.name),`${t.outDir}/${n.name}${i}`)}var bt={n:"name",f:"format",o:"outDir",m:"minify",w:"watch",d:"dts",e:"external",t:"target",mw:"minifyWhitespace",mi:"minifyIdentifiers",ms:"minifySyntax",c:"clean",s:"splitting",ne:"noExternal"},Ot={name:(t,r)=>{r.name=t},format:(t,r)=>{r.format=t.split(",")},outDir:(t,r)=>{r.outDir=t},minify:(t,r)=>{r.minify=!!t},watch:(t,r)=>{r.watch=!!t},dts:(t,r)=>{r.dts=!!t},external:(t,r)=>{r.external=t.split(",")},minifyWhitespace:(t,r)=>{r.minifyWhitespace=!!t},minifyIdentifiers:(t,r)=>{r.minifyIdentifiers=!!t},minifySyntax:(t,r)=>{r.minifySyntax=!!t},target:(t,r)=>{r.target=t},clean:(t,r)=>{r.clean=!!t},splitting:(t,r)=>{r.splitting=!!t},noExternal:(t,r)=>{r.noExternal=t.split(",")}};function Q(t){let r={};for(let n=0;n<t.length;n++){let e=t[n];if(e.startsWith("--")||e.startsWith("-")){let o=e.startsWith("-")&&!e.startsWith("--"),s=o?e.slice(1):e.slice(2),i=o?bt[s]:s,p=Ot[i];if(!p){a.error(`Unknown option: ${s}`);continue}let c=t[n+1],l=c&&!c.startsWith("-")?c:!0;p(l,r),typeof l=="string"&&n++}else r.entry||(r.entry=[]),Array.isArray(r.entry)&&r.entry.push(e)}return r}typeof Bun>"u"&&(a.error(`Bunup requires Bun to run.
5
- To install Bun, visit https://bun.sh/docs/installation`),process.exit(1));import M from"path";import $t from"chokidar";async function Z(t,r){let n=new Set;b(t.entry).forEach(c=>{let l=M.resolve(r,c.path),u=M.dirname(l);n.add(u)});let o=$t.watch(Array.from(n),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,t.outDir]}),s=null,i=!1,p=async c=>{if(!i){i=!0;try{await R({...t,entry:[c],clean:!1},r)}catch(l){a.error(`Build failed: ${l}`)}finally{i=!1}}};o.on("change",c=>{let l=M.relative(r,c);a.cli(`File changed: ${l}`),s&&clearTimeout(s),s=setTimeout(()=>p(l),300)}),o.on("error",c=>{a.error(`Watcher error: ${c}`)})}async function Bt(t=Bun.argv.slice(2)){let r=Q(t),n=await V(process.cwd()),e=process.cwd();if(r.watch&&(a.cli("Starting watch mode"),a.cli("Watching for file changes")),n.length===0){let o={...E,...r};o.clean&&rt(e,o.outDir),await tt(o,e)}else{for(let{options:o,rootDir:s}of n)o.clean&&rt(s,o.outDir);await Promise.all(n.map(async({options:o,rootDir:s})=>{let i={...E,...o,...r};await tt(i,s)}))}r.watch||process.exit(0)}async function tt(t,r){t.watch?await Z(t,r):await R(t,r)}function rt(t,r){let n=Dt.join(t,r);if(C.existsSync(n))try{C.rmSync(n,{recursive:!0,force:!0})}catch(e){a.error(`Failed to clean output directory: ${e}`)}C.mkdirSync(n,{recursive:!0})}Bt().catch(t=>{j(t),process.exit(1)});export{Bt as main};
5
+ `)+"\x1B[0m")};function R(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v(n=8){return Math.random().toString(36).substring(2,2+n)}function G(n,r){switch(n){case"esm":return".mjs";case"cjs":return y(r)?".cjs":".js";case"iife":return".global.js"}}function X(n,r){switch(n){case"esm":return".d.mts";case"cjs":return y(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function y(n){return n==="module"}function N(n){return n>=1000?`${(n/1000).toFixed(2)}s`:`${Math.round(n)}ms`}function q(n){if(!n)return[];return Array.from(new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.peerDependencies||{})]))}function K(n,r){return n===void 0?r==="esm":n}function Q(n){return n.map((r)=>typeof r==="string"?new RegExp(`^${R(r)}($|\\/|\\\\)`):r)}function j(n,r){return Q(n.external||[]).concat(q(r).map((e)=>new RegExp(`^${R(e)}($|\\/|\\\\)`)))}function A(n){return Q(n.noExternal||[])}import C from"node:fs";import F from"node:path";var o={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(n,r,e){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${n}m[${r}]\x1B[0m ${s}${e}`},cli(n){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,n))},info(n){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,n))},warn(n){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,n))},error(n){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,n))},progress(n,r){let e=String(n),s=this.colors.default;for(let[t,c]of Object.entries(this.colors.progress))if(e.includes(t)){s=c;break}console.log(this.formatMessage(s,e,r))}};function Y(n,r){return`${r?`${r.replace(/-/g,"_")}_`:""}${n}`.toUpperCase()}var B={entry:[],format:["cjs"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function Z(n,r){return{outdir:`${r}/${n.outDir}`,minify:an(n),target:n.target,splitting:n.splitting}}function an(n){let{minify:r,minifyWhitespace:e,minifyIdentifiers:s,minifySyntax:t}=n,c=r===!0;return{whitespace:e??c,identifiers:s??c,syntax:t??c}}async function z(n){let r=[];for(let e of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let s=F.join(n,`bunup.config${e}`);try{if(!C.existsSync(s))continue;let t;if(e===".json"||e===".jsonc"){let c=C.readFileSync(s,"utf8");t=JSON.parse(c)}else{let c=await import(`file://${s}`);if(t=c.default||c,!t)o.warn(`No default export found in ${s}`),t={}}if(Array.isArray(t))for(let c of t)r.push({options:{...B,...c},rootDir:n});else r.push({options:{...B,...t},rootDir:n});break}catch(t){o.error(`Failed to load config from ${s}: ${g(t)}`)}if(r.length>0)break}return r}function W(n){let r=F.join(n,"package.json");try{if(!C.existsSync(r))return null;let e=C.readFileSync(r,"utf8");return JSON.parse(e)}catch(e){return o.error(`Failed to load package.json at ${r}: ${g(e)}`),null}}function I(n){try{if(!C.existsSync(n))return{};let r=C.readFileSync(n,"utf8");return JSON.parse(r)||{}}catch(r){return o.warn(`Failed to parse tsconfig at ${n}: ${g(r)}`),{}}}async function D(n,r,e,s){let{absoluteRootDir:t,absoluteEntry:c}=Sn(n,r),i=await On(c),m=await gn(i);return ln(c,m,e,s,t)}async function On(n){let r=new Set,e=[n];while(e.length>0){let s=e.pop();if(!s||r.has(s))continue;r.add(s);try{let t=await E.promises.readFile(s,"utf8"),c=wn(t);for(let i of c){let m=l.dirname(s),f=l.resolve(m,i),a=[f,`${f}.ts`,`${f}.tsx`,`${f}/index.ts`,`${f}/index.tsx`];for(let u of a)if(E.existsSync(u)&&u.endsWith(".ts")&&!r.has(u)){e.push(u);break}}}catch(t){o.warn(`Error processing ${s}: ${t instanceof Error?t.message:String(t)}`)}}return r}function wn(n){let r=new Set;try{let e=/(?:import|export)(?:(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*)|[\s\n]+)(["'`])([^'"]+)\1/g,s;while((s=e.exec(n))!==null){let i=s[2];if(i.startsWith("."))r.add(i)}let t=/import\s+(["'`])([^'"]+)\1\s*;?/g;while((s=t.exec(n))!==null){let i=s[2];if(i.startsWith("."))r.add(i)}let c=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;while((s=c.exec(n))!==null){let i=s[2];if(i.startsWith("."))r.add(i)}}catch(e){o.warn(`Error extracting imports: ${e instanceof Error?e.message:String(e)}`)}return Array.from(r)}async function gn(n){let r=new Map;return await Promise.all(Array.from(n).map(async(e)=>{try{let s=e.replace(/\.tsx?$/,".d.ts"),t=await E.promises.readFile(e,"utf8"),{code:c}=mn.isolatedDeclaration(e,t);if(c)r.set(s,c)}catch(s){o.warn(`Failed to generate declaration for ${e}: ${s instanceof Error?s.message:String(s)}`)}})),r}async function ln(n,r,e,s,t){let m=`\x00virtual:${n.replace(/\.tsx?$/,".d.ts")}`,f=typeof s.dts==="object"?s.dts:{},a=f.preferredTsconfigPath?l.resolve(f.preferredTsconfigPath):l.join(t,"tsconfig.json"),w=(await I(a)).compilerOptions,S={name:"bunup:virtual-dts",resolveId(x,O){if(x.startsWith("\x00virtual:"))return x;if(O?.startsWith("\x00virtual:")){let $=O.slice(9),cn=l.dirname($);if(x.startsWith(".")){let on=l.resolve(cn,x);for(let fn of["",".d.ts","/index.d.ts"]){let H=`${on}${fn}`;if(r.has(H))return`\x00virtual:${H}`}}}return null},load(x){if(x.startsWith("\x00virtual:")){let O=x.slice(9);return r.get(O)||null}return null}},sn=W(t),en=j(s,sn),tn=A(s),p;try{p=await un({input:m,onwarn(O,$){if(O.code==="UNRESOLVED_IMPORT"||O.code==="CIRCULAR_DEPENDENCY"||O.code==="EMPTY_BUNDLE")return;$(O)},plugins:[S,xn({tsconfig:a,compilerOptions:{...w?k.parseJsonConfigFileContent({compilerOptions:w},k.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:k.ScriptTarget.ESNext}})],external:(O)=>en.some(($)=>$.test(O))&&!tn.some(($)=>$.test(O))});let{output:x}=await p.generate({format:e});if(!x[0]?.code)throw new Error("Generated bundle is empty");return x[0].code}catch(x){throw new Error(`DTS bundling failed: ${g(x)}`)}finally{if(p)await p.close()}}function Sn(n,r){let e=l.resolve(n),s=l.resolve(e,r);if(!E.existsSync(e))throw new Error(`Root directory does not exist: ${e}`);if(!E.existsSync(s))throw new Error(`Entry file does not exist: ${s}`);if(!s.endsWith(".ts"))throw new Error(`Entry file must be a TypeScript file (.ts): ${s}`);if(l.relative(e,s).startsWith(".."))throw new Error(`Entry file must be within rootDir: ${s}`);return{absoluteRootDir:e,absoluteEntry:s}}async function J(n,r,e,s,t){return new Promise((c,i)=>{let m={rootDir:n,entries:r,formats:e,options:s,packageType:t},f=new Bn(new URL("./dtsWorker.js",import.meta.url),{workerData:m});f.on("message",(a)=>{if(a.success){if(a.timeMs){let u=N(a.timeMs);o.progress("DTS",`Bundled types in ${u}`)}c()}else i(new Error(a.error||"Unknown DTS worker error"))}),f.on("error",i),f.on("exit",(a)=>{if(a!==0)i(new Error(`DTS worker stopped with exit code ${a}`))})})}if(!$n&&h){let{rootDir:n,entries:r,formats:e,options:s,packageType:t}=Cn,c=performance.now();o.progress("DTS","Bundling types");try{let i=e.flatMap((m)=>r.map(async(f)=>{let a=await D(n,f.path,m,s),u=X(m,t),w=`${s.outDir}/${f.name}${u}`,S=`${n}/${w}`;await Bun.write(S,a),o.progress("DTS",w)}));Promise.all(i).then(()=>{let m=performance.now()-c;h?.postMessage({success:!0,timeMs:m})}).catch((m)=>{h?.postMessage({success:!1,error:m instanceof Error?m.message:String(m)})})}catch(i){h?.postMessage({success:!1,error:i instanceof Error?i.message:String(i)})}}function En(n){return n.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function d(n){let r=[],e=new Set;function s(t,c){if(e.has(t)){let i=v();r.push({name:`${t}_${i}`,path:c})}else r.push({name:t,path:c}),e.add(t)}if(Array.isArray(n))for(let t of n){let c=En(t);s(c,t)}else Object.entries(n).forEach(([t,c])=>{s(t,c)});return r}function T(n,r){return`[dir]/${n}${r}`}function V(n,r){return{name:"bunup:external-plugin",setup(e){e.onResolve({filter:/.*/},(s)=>{let t=s.path;if(n.some((i)=>i.test(t))&&!r.some((i)=>i.test(t)))return{path:t,external:!0};return null})}}}async function L(n,r){if(!n.entry||n.entry.length===0||!n.outDir){o.cli("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");return}let e=performance.now();o.cli("Build started");let s=W(r),t=s?.type,c=j(n,s),i=A(n),m=[V(c,i)],f=d(n.entry),a=n.format.flatMap((u)=>f.map((w)=>dn(n,r,w,u,t,m)));try{await Promise.all(a);let u=performance.now()-e,w=N(u);o.cli(`⚡ Build success in ${w}`)}catch(u){o.error("Build process encountered errors."),process.exit(1)}if(n.dts){o.progress("DTS","Bundling types");let u=n.format.filter((S)=>{if(S==="iife"&&!y(t)&&n.format.includes("cjs"))return!1;return!0}),w=n.dts===!0?f:d(n.dts.entry);try{await J(r,w,u,n,t)}catch(S){o.error(`DTS build process encountered errors: ${g(S)}`)}}}async function dn(n,r,e,s,t,c){let i=G(s,t),m=Z(n,r),f=await Bun.build({...m,entrypoints:[`${r}/${e.path}`],format:s,naming:{entry:T(e.name,i)},splitting:K(n.splitting,s),plugins:c,throw:!1});if(!f.success)throw f.logs.forEach((a)=>{if(a.level==="error")o.error(a.message);else if(a.level==="warning")o.warn(a.message);else if(a.level==="info")o.info(a.message)}),new Error(`Build failed for ${e} (${s})`);o.progress(Y(s,n.name),`${n.outDir}/${e.name}${i}`)}var pn={n:"name",f:"format",o:"outDir",m:"minify",w:"watch",d:"dts",e:"external",t:"target",mw:"minifyWhitespace",mi:"minifyIdentifiers",ms:"minifySyntax",c:"clean",s:"splitting",ne:"noExternal"},yn={name:(n,r)=>{r.name=n},format:(n,r)=>{r.format=n.split(",")},outDir:(n,r)=>{r.outDir=n},minify:(n,r)=>{r.minify=!!n},watch:(n,r)=>{r.watch=!!n},dts:(n,r)=>{r.dts=!!n},external:(n,r)=>{r.external=n.split(",")},minifyWhitespace:(n,r)=>{r.minifyWhitespace=!!n},minifyIdentifiers:(n,r)=>{r.minifyIdentifiers=!!n},minifySyntax:(n,r)=>{r.minifySyntax=!!n},target:(n,r)=>{r.target=n},clean:(n,r)=>{r.clean=!!n},splitting:(n,r)=>{r.splitting=!!n},noExternal:(n,r)=>{r.noExternal=n.split(",")}};function P(n){let r={};for(let e=0;e<n.length;e++){let s=n[e];if(s.startsWith("--")||s.startsWith("-")){let t=s.startsWith("-")&&!s.startsWith("--"),c=t?s.slice(1):s.slice(2),i=t?pn[c]:c,m=yn[i];if(!m){o.error(`Unknown option: ${c}`);continue}let f=n[e+1],a=f&&!f.startsWith("-")?f:!0;if(m(a,r),typeof a==="string")e++}else{if(!r.entry)r.entry=[];if(Array.isArray(r.entry))r.entry.push(s)}}return r}(()=>{if(typeof Bun==="undefined")o.error(`Bunup requires Bun to run.
6
+ To install Bun, visit https://bun.sh/docs/installation`),process.exit(1)})();import _ from"node:path";import Nn from"chokidar";async function b(n,r){let e=new Set;d(n.entry).forEach((f)=>{let a=_.resolve(r,f.path),u=_.dirname(a);e.add(u)});let t=Nn.watch(Array.from(e),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,n.outDir]}),c=null,i=!1,m=async(f)=>{if(i)return;i=!0;try{await L({...n,entry:[f],clean:!1},r)}catch(a){o.error(`Build failed: ${a}`)}finally{i=!1}};t.on("change",(f)=>{let a=_.relative(r,f);if(o.cli(`File changed: ${a}`),c)clearTimeout(c);c=setTimeout(()=>m(a),300)}),t.on("error",(f)=>{o.error(`Watcher error: ${f}`)})}async function An(n=Bun.argv.slice(2)){let r=P(n),e=await z(process.cwd()),s=process.cwd();if(r.watch)o.cli("Starting watch mode"),o.cli("Watching for file changes");if(e.length===0){let t={...B,...r};if(t.clean)rn(s,t.outDir);await nn(t,s)}else{for(let{options:t,rootDir:c}of e)if(t.clean)rn(c,t.outDir);await Promise.all(e.map(async({options:t,rootDir:c})=>{let i={...B,...t,...r};await nn(i,c)}))}if(!r.watch)process.exit(0)}async function nn(n,r){if(n.watch)await b(n,r);else await L(n,r)}function rn(n,r){let e=jn.join(n,r);if(M.existsSync(e))try{M.rmSync(e,{recursive:!0,force:!0})}catch(s){o.error(`Failed to clean output directory: ${s}`)}M.mkdirSync(e,{recursive:!0})}An().catch((n)=>{U(n),process.exit(1)});export{An as main};
package/build/index.d.mts CHANGED
@@ -1,143 +1,146 @@
1
- type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
1
+ type WithOptional<
2
+ T,
3
+ K extends keyof T
4
+ > = Omit<T, K> & Partial<Pick<T, K>>;
2
5
 
3
- type Format = 'esm' | 'cjs' | 'iife';
4
- type Target = 'bun' | 'node' | 'browser';
6
+ type Format = "esm" | "cjs" | "iife";
7
+ type Target = "bun" | "node" | "browser";
5
8
  type External = string[];
6
9
  type Entry = string[] | Record<string, string>;
7
10
  type DtsOptions = {
8
- /**
9
- * Entry point files for TypeScript declaration file generation
10
- *
11
- * This can be:
12
- * - An array of file paths
13
- * - An object where keys are output names and values are input file paths
14
- *
15
- * The key names are used for the generated declaration files.
16
- * For example, {custom: './src/index.ts'} will generate custom.d.ts
17
- *
18
- * If not specified, the main entry points will be used for declaration file generation.
19
- *
20
- * If a string path is provided in an array, the file name (without extension)
21
- * will be used as the name for the output declaration file.
22
- *
23
- * @example
24
- * // Using string paths in an array
25
- * entry: ['./src/index.ts'] // Generates index.d.ts
26
- *
27
- * // Using named outputs as an object
28
- * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
29
- */
30
- entry: Entry;
31
- /**
32
- * Path to a preferred tsconfig.json file to use for declaration generation
33
- *
34
- * If not specified, the tsconfig.json in the project root will be used.
35
- * This option allows you to use a different TypeScript configuration
36
- * specifically for declaration file generation.
37
- *
38
- * @example
39
- * preferredTsconfigPath: './tsconfig.build.json'
40
- */
41
- preferredTsconfigPath?: string;
11
+ /**
12
+ * Entry point files for TypeScript declaration file generation
13
+ *
14
+ * This can be:
15
+ * - An array of file paths
16
+ * - An object where keys are output names and values are input file paths
17
+ *
18
+ * The key names are used for the generated declaration files.
19
+ * For example, {custom: './src/index.ts'} will generate custom.d.ts
20
+ *
21
+ * If not specified, the main entry points will be used for declaration file generation.
22
+ *
23
+ * If a string path is provided in an array, the file name (without extension)
24
+ * will be used as the name for the output declaration file.
25
+ *
26
+ * @example
27
+ * // Using string paths in an array
28
+ * entry: ['./src/index.ts'] // Generates index.d.ts
29
+ *
30
+ * // Using named outputs as an object
31
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
32
+ */
33
+ entry: Entry
34
+ /**
35
+ * Path to a preferred tsconfig.json file to use for declaration generation
36
+ *
37
+ * If not specified, the tsconfig.json in the project root will be used.
38
+ * This option allows you to use a different TypeScript configuration
39
+ * specifically for declaration file generation.
40
+ *
41
+ * @example
42
+ * preferredTsconfigPath: './tsconfig.build.json'
43
+ */
44
+ preferredTsconfigPath?: string
42
45
  };
43
46
  interface BunupOptions {
44
- /**
45
- * Name of the build configuration
46
- * Used for logging and identification purposes
47
- */
48
- name?: string;
49
- /**
50
- * Entry point files for the build
51
- *
52
- * This can be:
53
- * - An array of file paths
54
- * - An object where keys are output names and values are input file paths
55
- *
56
- * The key names are used for the generated output files.
57
- * For example, {custom: './src/index.ts'} will generate custom.js
58
- *
59
- * If a string path is provided in an array, the file name (without extension)
60
- * will be used as the name for the output file.
61
- *
62
- * @example
63
- * // Using string paths in an array
64
- * entry: ['./src/index.ts'] // Generates index.js
65
- *
66
- * // Using named outputs as an object
67
- * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
68
- */
69
- entry: Entry;
70
- /**
71
- * Output directory for the bundled files
72
- * Defaults to 'dist' if not specified
73
- */
74
- outDir: string;
75
- /**
76
- * Output formats for the bundle
77
- * Can include 'esm', 'cjs', and/or 'iife'
78
- * Defaults to ['esm'] if not specified
79
- */
80
- format: Format[];
81
- /**
82
- * Whether to enable all minification options
83
- * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
84
- */
85
- minify?: boolean;
86
- /**
87
- * Whether to enable code splitting
88
- * Defaults to true for ESM format, false for CJS format
89
- */
90
- splitting?: boolean;
91
- /**
92
- * Whether to minify whitespace in the output
93
- * Removes unnecessary whitespace to reduce file size
94
- */
95
- minifyWhitespace?: boolean;
96
- /**
97
- * Whether to minify identifiers in the output
98
- * Renames variables and functions to shorter names
99
- */
100
- minifyIdentifiers?: boolean;
101
- /**
102
- * Whether to minify syntax in the output
103
- * Optimizes code structure for smaller file size
104
- */
105
- minifySyntax?: boolean;
106
- /**
107
- * Whether to watch for file changes and rebuild automatically
108
- */
109
- watch?: boolean;
110
- /**
111
- * Whether to generate TypeScript declaration files (.d.ts)
112
- * When set to true, generates declaration files for all entry points
113
- * Can also be configured with DtsOptions for more control
114
- */
115
- dts?: boolean | DtsOptions;
116
- /**
117
- * External packages that should not be bundled
118
- * Useful for dependencies that should be kept as external imports
119
- */
120
- external?: External;
121
- /**
122
- * Packages that should be bundled even if they are in external
123
- * Useful for dependencies that should be included in the bundle
124
- */
125
- noExternal?: External;
126
- /**
127
- * The target environment for the bundle
128
- * Can be 'browser', 'bun', 'node', etc.
129
- * Defaults to 'node' if not specified
130
- */
131
- target?: Target;
132
- /**
133
- * Whether to clean the output directory before building
134
- * When true, removes all files in the outDir before starting a new build
135
- * Defaults to true if not specified
136
- */
137
- clean?: boolean;
47
+ /**
48
+ * Name of the build configuration
49
+ * Used for logging and identification purposes
50
+ */
51
+ name?: string;
52
+ /**
53
+ * Entry point files for the build
54
+ *
55
+ * This can be:
56
+ * - An array of file paths
57
+ * - An object where keys are output names and values are input file paths
58
+ *
59
+ * The key names are used for the generated output files.
60
+ * For example, {custom: './src/index.ts'} will generate custom.js
61
+ *
62
+ * If a string path is provided in an array, the file name (without extension)
63
+ * will be used as the name for the output file.
64
+ *
65
+ * @example
66
+ * // Using string paths in an array
67
+ * entry: ['./src/index.ts'] // Generates index.js
68
+ *
69
+ * // Using named outputs as an object
70
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
71
+ */
72
+ entry: Entry;
73
+ /**
74
+ * Output directory for the bundled files
75
+ * Defaults to 'dist' if not specified
76
+ */
77
+ outDir: string;
78
+ /**
79
+ * Output formats for the bundle
80
+ * Can include 'esm', 'cjs', and/or 'iife'
81
+ * Defaults to ['cjs'] if not specified
82
+ */
83
+ format: Format[];
84
+ /**
85
+ * Whether to enable all minification options
86
+ * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
87
+ */
88
+ minify?: boolean;
89
+ /**
90
+ * Whether to enable code splitting
91
+ * Defaults to true for ESM format, false for CJS format
92
+ */
93
+ splitting?: boolean;
94
+ /**
95
+ * Whether to minify whitespace in the output
96
+ * Removes unnecessary whitespace to reduce file size
97
+ */
98
+ minifyWhitespace?: boolean;
99
+ /**
100
+ * Whether to minify identifiers in the output
101
+ * Renames variables and functions to shorter names
102
+ */
103
+ minifyIdentifiers?: boolean;
104
+ /**
105
+ * Whether to minify syntax in the output
106
+ * Optimizes code structure for smaller file size
107
+ */
108
+ minifySyntax?: boolean;
109
+ /**
110
+ * Whether to watch for file changes and rebuild automatically
111
+ */
112
+ watch?: boolean;
113
+ /**
114
+ * Whether to generate TypeScript declaration files (.d.ts)
115
+ * When set to true, generates declaration files for all entry points
116
+ * Can also be configured with DtsOptions for more control
117
+ */
118
+ dts?: boolean | DtsOptions;
119
+ /**
120
+ * External packages that should not be bundled
121
+ * Useful for dependencies that should be kept as external imports
122
+ */
123
+ external?: External;
124
+ /**
125
+ * Packages that should be bundled even if they are in external
126
+ * Useful for dependencies that should be included in the bundle
127
+ */
128
+ noExternal?: External;
129
+ /**
130
+ * The target environment for the bundle
131
+ * Can be 'browser', 'bun', 'node', etc.
132
+ * Defaults to 'node' if not specified
133
+ */
134
+ target?: Target;
135
+ /**
136
+ * Whether to clean the output directory before building
137
+ * When true, removes all files in the outDir before starting a new build
138
+ * Defaults to true if not specified
139
+ */
140
+ clean?: boolean;
138
141
  }
139
142
 
140
- type DefineConfigOption = WithOptional<BunupOptions, 'outDir' | 'format'>;
143
+ type DefineConfigOption = WithOptional<BunupOptions, "outDir" | "format">;
141
144
  type DefineConfigOptions = DefineConfigOption | DefineConfigOption[];
142
145
  declare function defineConfig(options: DefineConfigOptions): DefineConfigOptions;
143
146
 
package/build/index.d.ts CHANGED
@@ -1,143 +1,146 @@
1
- type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
1
+ type WithOptional<
2
+ T,
3
+ K extends keyof T
4
+ > = Omit<T, K> & Partial<Pick<T, K>>;
2
5
 
3
- type Format = 'esm' | 'cjs' | 'iife';
4
- type Target = 'bun' | 'node' | 'browser';
6
+ type Format = "esm" | "cjs" | "iife";
7
+ type Target = "bun" | "node" | "browser";
5
8
  type External = string[];
6
9
  type Entry = string[] | Record<string, string>;
7
10
  type DtsOptions = {
8
- /**
9
- * Entry point files for TypeScript declaration file generation
10
- *
11
- * This can be:
12
- * - An array of file paths
13
- * - An object where keys are output names and values are input file paths
14
- *
15
- * The key names are used for the generated declaration files.
16
- * For example, {custom: './src/index.ts'} will generate custom.d.ts
17
- *
18
- * If not specified, the main entry points will be used for declaration file generation.
19
- *
20
- * If a string path is provided in an array, the file name (without extension)
21
- * will be used as the name for the output declaration file.
22
- *
23
- * @example
24
- * // Using string paths in an array
25
- * entry: ['./src/index.ts'] // Generates index.d.ts
26
- *
27
- * // Using named outputs as an object
28
- * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
29
- */
30
- entry: Entry;
31
- /**
32
- * Path to a preferred tsconfig.json file to use for declaration generation
33
- *
34
- * If not specified, the tsconfig.json in the project root will be used.
35
- * This option allows you to use a different TypeScript configuration
36
- * specifically for declaration file generation.
37
- *
38
- * @example
39
- * preferredTsconfigPath: './tsconfig.build.json'
40
- */
41
- preferredTsconfigPath?: string;
11
+ /**
12
+ * Entry point files for TypeScript declaration file generation
13
+ *
14
+ * This can be:
15
+ * - An array of file paths
16
+ * - An object where keys are output names and values are input file paths
17
+ *
18
+ * The key names are used for the generated declaration files.
19
+ * For example, {custom: './src/index.ts'} will generate custom.d.ts
20
+ *
21
+ * If not specified, the main entry points will be used for declaration file generation.
22
+ *
23
+ * If a string path is provided in an array, the file name (without extension)
24
+ * will be used as the name for the output declaration file.
25
+ *
26
+ * @example
27
+ * // Using string paths in an array
28
+ * entry: ['./src/index.ts'] // Generates index.d.ts
29
+ *
30
+ * // Using named outputs as an object
31
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
32
+ */
33
+ entry: Entry
34
+ /**
35
+ * Path to a preferred tsconfig.json file to use for declaration generation
36
+ *
37
+ * If not specified, the tsconfig.json in the project root will be used.
38
+ * This option allows you to use a different TypeScript configuration
39
+ * specifically for declaration file generation.
40
+ *
41
+ * @example
42
+ * preferredTsconfigPath: './tsconfig.build.json'
43
+ */
44
+ preferredTsconfigPath?: string
42
45
  };
43
46
  interface BunupOptions {
44
- /**
45
- * Name of the build configuration
46
- * Used for logging and identification purposes
47
- */
48
- name?: string;
49
- /**
50
- * Entry point files for the build
51
- *
52
- * This can be:
53
- * - An array of file paths
54
- * - An object where keys are output names and values are input file paths
55
- *
56
- * The key names are used for the generated output files.
57
- * For example, {custom: './src/index.ts'} will generate custom.js
58
- *
59
- * If a string path is provided in an array, the file name (without extension)
60
- * will be used as the name for the output file.
61
- *
62
- * @example
63
- * // Using string paths in an array
64
- * entry: ['./src/index.ts'] // Generates index.js
65
- *
66
- * // Using named outputs as an object
67
- * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
68
- */
69
- entry: Entry;
70
- /**
71
- * Output directory for the bundled files
72
- * Defaults to 'dist' if not specified
73
- */
74
- outDir: string;
75
- /**
76
- * Output formats for the bundle
77
- * Can include 'esm', 'cjs', and/or 'iife'
78
- * Defaults to ['esm'] if not specified
79
- */
80
- format: Format[];
81
- /**
82
- * Whether to enable all minification options
83
- * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
84
- */
85
- minify?: boolean;
86
- /**
87
- * Whether to enable code splitting
88
- * Defaults to true for ESM format, false for CJS format
89
- */
90
- splitting?: boolean;
91
- /**
92
- * Whether to minify whitespace in the output
93
- * Removes unnecessary whitespace to reduce file size
94
- */
95
- minifyWhitespace?: boolean;
96
- /**
97
- * Whether to minify identifiers in the output
98
- * Renames variables and functions to shorter names
99
- */
100
- minifyIdentifiers?: boolean;
101
- /**
102
- * Whether to minify syntax in the output
103
- * Optimizes code structure for smaller file size
104
- */
105
- minifySyntax?: boolean;
106
- /**
107
- * Whether to watch for file changes and rebuild automatically
108
- */
109
- watch?: boolean;
110
- /**
111
- * Whether to generate TypeScript declaration files (.d.ts)
112
- * When set to true, generates declaration files for all entry points
113
- * Can also be configured with DtsOptions for more control
114
- */
115
- dts?: boolean | DtsOptions;
116
- /**
117
- * External packages that should not be bundled
118
- * Useful for dependencies that should be kept as external imports
119
- */
120
- external?: External;
121
- /**
122
- * Packages that should be bundled even if they are in external
123
- * Useful for dependencies that should be included in the bundle
124
- */
125
- noExternal?: External;
126
- /**
127
- * The target environment for the bundle
128
- * Can be 'browser', 'bun', 'node', etc.
129
- * Defaults to 'node' if not specified
130
- */
131
- target?: Target;
132
- /**
133
- * Whether to clean the output directory before building
134
- * When true, removes all files in the outDir before starting a new build
135
- * Defaults to true if not specified
136
- */
137
- clean?: boolean;
47
+ /**
48
+ * Name of the build configuration
49
+ * Used for logging and identification purposes
50
+ */
51
+ name?: string;
52
+ /**
53
+ * Entry point files for the build
54
+ *
55
+ * This can be:
56
+ * - An array of file paths
57
+ * - An object where keys are output names and values are input file paths
58
+ *
59
+ * The key names are used for the generated output files.
60
+ * For example, {custom: './src/index.ts'} will generate custom.js
61
+ *
62
+ * If a string path is provided in an array, the file name (without extension)
63
+ * will be used as the name for the output file.
64
+ *
65
+ * @example
66
+ * // Using string paths in an array
67
+ * entry: ['./src/index.ts'] // Generates index.js
68
+ *
69
+ * // Using named outputs as an object
70
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
71
+ */
72
+ entry: Entry;
73
+ /**
74
+ * Output directory for the bundled files
75
+ * Defaults to 'dist' if not specified
76
+ */
77
+ outDir: string;
78
+ /**
79
+ * Output formats for the bundle
80
+ * Can include 'esm', 'cjs', and/or 'iife'
81
+ * Defaults to ['cjs'] if not specified
82
+ */
83
+ format: Format[];
84
+ /**
85
+ * Whether to enable all minification options
86
+ * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
87
+ */
88
+ minify?: boolean;
89
+ /**
90
+ * Whether to enable code splitting
91
+ * Defaults to true for ESM format, false for CJS format
92
+ */
93
+ splitting?: boolean;
94
+ /**
95
+ * Whether to minify whitespace in the output
96
+ * Removes unnecessary whitespace to reduce file size
97
+ */
98
+ minifyWhitespace?: boolean;
99
+ /**
100
+ * Whether to minify identifiers in the output
101
+ * Renames variables and functions to shorter names
102
+ */
103
+ minifyIdentifiers?: boolean;
104
+ /**
105
+ * Whether to minify syntax in the output
106
+ * Optimizes code structure for smaller file size
107
+ */
108
+ minifySyntax?: boolean;
109
+ /**
110
+ * Whether to watch for file changes and rebuild automatically
111
+ */
112
+ watch?: boolean;
113
+ /**
114
+ * Whether to generate TypeScript declaration files (.d.ts)
115
+ * When set to true, generates declaration files for all entry points
116
+ * Can also be configured with DtsOptions for more control
117
+ */
118
+ dts?: boolean | DtsOptions;
119
+ /**
120
+ * External packages that should not be bundled
121
+ * Useful for dependencies that should be kept as external imports
122
+ */
123
+ external?: External;
124
+ /**
125
+ * Packages that should be bundled even if they are in external
126
+ * Useful for dependencies that should be included in the bundle
127
+ */
128
+ noExternal?: External;
129
+ /**
130
+ * The target environment for the bundle
131
+ * Can be 'browser', 'bun', 'node', etc.
132
+ * Defaults to 'node' if not specified
133
+ */
134
+ target?: Target;
135
+ /**
136
+ * Whether to clean the output directory before building
137
+ * When true, removes all files in the outDir before starting a new build
138
+ * Defaults to true if not specified
139
+ */
140
+ clean?: boolean;
138
141
  }
139
142
 
140
- type DefineConfigOption = WithOptional<BunupOptions, 'outDir' | 'format'>;
143
+ type DefineConfigOption = WithOptional<BunupOptions, "outDir" | "format">;
141
144
  type DefineConfigOptions = DefineConfigOption | DefineConfigOption[];
142
145
  declare function defineConfig(options: DefineConfigOptions): DefineConfigOptions;
143
146
 
package/build/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});function n(i){return i}exports.defineConfig = n;
1
+ var D=require("node:module");var{defineProperty:e,getOwnPropertyNames:r,getOwnPropertyDescriptor:O}=Object,g=Object.prototype.hasOwnProperty;var f=new WeakMap,C=(i)=>{var n=f.get(i),o;if(n)return n;if(n=e({},"__esModule",{value:!0}),i&&typeof i==="object"||typeof i==="function")r(i).map((t)=>!g.call(n,t)&&e(n,t,{get:()=>i[t],enumerable:!(o=O(i,t))||o.enumerable}));return f.set(i,n),n};var u=(i,n)=>{for(var o in n)e(i,o,{get:n[o],enumerable:!0,configurable:!0,set:(t)=>n[o]=()=>t})};var m={};u(m,{defineConfig:()=>p});module.exports=C(m);function p(i){return i}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunup",
3
- "version": "0.1.13",
3
+ "version": "0.1.15",
4
4
  "description": "A extremely fast, zero-config bundler for TypeScript & JavaScript, powered by Bun.",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -59,8 +59,8 @@
59
59
  "rollup-plugin-dts": "^6.1.1"
60
60
  },
61
61
  "scripts": {
62
- "build": "tsup",
63
- "dev": "tsup --watch",
62
+ "build": "bunup",
63
+ "dev": "bunup --watch",
64
64
  "test-build": "pnpm -C tests build",
65
65
  "test": "vitest run",
66
66
  "tsc": "tsc --noEmit",
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _worker_threads = require('worker_threads');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var _path = require('path'); var _path2 = _interopRequireDefault(_path);var _oxctransform = require('oxc-transform'); var _oxctransform2 = _interopRequireDefault(_oxctransform);var _rollup = require('rollup');var _rollupplugindts = require('rollup-plugin-dts'); var _rollupplugindts2 = _interopRequireDefault(_rollupplugindts);var _typescript = require('typescript'); var _typescript2 = _interopRequireDefault(_typescript);var h=t=>t instanceof Error?t.message:String(t);function b(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function O(t,r){switch(t){case"esm":return".d.mts";case"cjs":return _(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function _(t){return t==="module"}function k(t){return t>=1e3?`${(t/1e3).toFixed(2)}s`:`${Math.round(t)}ms`}function R(t){return t?Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})])):[]}function T(t){return t.map(r=>typeof r=="string"?new RegExp(`^${b(r)}($|\\/|\\\\)`):r)}function B(t,r){return T(t.external||[]).concat(R(r).map(n=>new RegExp(`^${b(n)}($|\\/|\\\\)`)))}function M(t){return T(t.noExternal||[])}var u={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,r,n){let e=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${t}m[${r}]\x1B[0m ${e}${n}`},cli(t){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,t))},info(t){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,t))},warn(t){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,t))},error(t){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,t))},progress(t,r){let n=String(t),e=this.colors.default;for(let[i,s]of Object.entries(this.colors.progress))if(n.includes(i)){e=s;break}console.log(this.formatMessage(e,n,r))}};function F(t){let r=_path2.default.join(t,"package.json");try{if(!_fs2.default.existsSync(r))return null;let n=_fs2.default.readFileSync(r,"utf8");return JSON.parse(n)}catch(n){return u.error(`Failed to load package.json at ${r}: ${h(n)}`),null}}function C(t){try{if(!_fs2.default.existsSync(t))return{};let r=_fs2.default.readFileSync(t,"utf8");return JSON.parse(r)||{}}catch(r){return u.warn(`Failed to parse tsconfig at ${t}: ${h(r)}`),{}}}async function v(t,r,n,e){let{absoluteRootDir:i,absoluteEntry:s}=z(t,r),o=await X(s),a=await Y(o);return q(s,a,n,e,i)}async function X(t){let r=new Set,n=[t];for(;n.length>0;){let e=n.pop();if(!(!e||r.has(e))){r.add(e);try{let i=await _fs2.default.promises.readFile(e,"utf8"),s=H(i);for(let o of s){let a=_path2.default.dirname(e),c=_path2.default.resolve(a,o),l=[c,`${c}.ts`,`${c}.tsx`,`${c}/index.ts`,`${c}/index.tsx`];for(let g of l)if(_fs2.default.existsSync(g)&&g.endsWith(".ts")&&!r.has(g)){n.push(g);break}}}catch(i){u.warn(`Error processing ${e}: ${i instanceof Error?i.message:String(i)}`)}}}return r}function H(t){let r=new Set;try{let n=/(?:import|export)(?:(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*)|[\s\n]+)(["'`])([^'"]+)\1/g,e;for(;(e=n.exec(t))!==null;){let o=e[2];o.startsWith(".")&&r.add(o)}let i=/import\s+(["'`])([^'"]+)\1\s*;?/g;for(;(e=i.exec(t))!==null;){let o=e[2];o.startsWith(".")&&r.add(o)}let s=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;for(;(e=s.exec(t))!==null;){let o=e[2];o.startsWith(".")&&r.add(o)}}catch(n){u.warn(`Error extracting imports: ${n instanceof Error?n.message:String(n)}`)}return Array.from(r)}async function Y(t){let r=new Map;return await Promise.all(Array.from(t).map(async n=>{try{let e=n.replace(/\.tsx?$/,".d.ts"),i=await _fs2.default.promises.readFile(n,"utf8"),{code:s}=_oxctransform2.default.isolatedDeclaration(n,i);s&&r.set(e,s)}catch(e){u.warn(`Failed to generate declaration for ${n}: ${e instanceof Error?e.message:String(e)}`)}})),r}async function q(t,r,n,e,i){let s="\0virtual:",o=t.replace(/\.tsx?$/,".d.ts"),a=`${s}${o}`,c=typeof e.dts=="object"?e.dts:{},l=c.preferredTsconfigPath?_path2.default.resolve(c.preferredTsconfigPath):_path2.default.join(i,"tsconfig.json"),x=(await C(l)).compilerOptions,$={name:"bunup:virtual-dts",resolveId(p,f){if(p.startsWith(s))return p;if(_optionalChain([f, 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3(s)])){let d=f.slice(s.length),N=_path2.default.dirname(d);if(p.startsWith(".")){let L=_path2.default.resolve(N,p);for(let A of["",".d.ts","/index.d.ts"]){let S=`${L}${A}`;if(r.has(S))return`${s}${S}`}}}return null},load(p){if(p.startsWith(s)){let f=p.slice(s.length);return r.get(f)||null}return null}},j=F(i),I=B(e,j),W=M(e),E;try{E=await _rollup.rollup.call(void 0, {input:a,onwarn(f,d){f.code==="UNRESOLVED_IMPORT"||f.code==="CIRCULAR_DEPENDENCY"||f.code==="EMPTY_BUNDLE"||d(f)},plugins:[$,_rollupplugindts2.default.call(void 0, {tsconfig:l,compilerOptions:{...x?_typescript2.default.parseJsonConfigFileContent({compilerOptions:x},_typescript2.default.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:_typescript2.default.ScriptTarget.ESNext}})],external:f=>I.some(d=>d.test(f))&&!W.some(d=>d.test(f))});let{output:p}=await E.generate({format:n});if(!_optionalChain([p, 'access', _4 => _4[0], 'optionalAccess', _5 => _5.code]))throw new Error("Generated bundle is empty");return p[0].code}catch(p){throw new Error(`DTS bundling failed: ${h(p)}`)}finally{E&&await E.close()}}function z(t,r){let n=_path2.default.resolve(t),e=_path2.default.resolve(n,r);if(!_fs2.default.existsSync(n))throw new Error(`Root directory does not exist: ${n}`);if(!_fs2.default.existsSync(e))throw new Error(`Entry file does not exist: ${e}`);if(!e.endsWith(".ts"))throw new Error(`Entry file must be a TypeScript file (.ts): ${e}`);if(_path2.default.relative(n,e).startsWith(".."))throw new Error(`Entry file must be within rootDir: ${e}`);return{absoluteRootDir:n,absoluteEntry:e}}async function Bt(t,r,n,e,i){return new Promise((s,o)=>{let a={rootDir:t,entries:r,formats:n,options:e,packageType:i},c=new (0, _worker_threads.Worker)(new URL("./dtsWorker.js",import.meta.url),{workerData:a});c.on("message",l=>{if(l.success){if(l.timeMs){let g=k(l.timeMs);u.progress("DTS",`Bundled types in ${g}`)}s()}else o(new Error(l.error||"Unknown DTS worker error"))}),c.on("error",o),c.on("exit",l=>{l!==0&&o(new Error(`DTS worker stopped with exit code ${l}`))})})}if(!_worker_threads.isMainThread&&_worker_threads.parentPort){let{rootDir:t,entries:r,formats:n,options:e,packageType:i}=_worker_threads.workerData,s=performance.now();u.progress("DTS","Bundling types in worker thread");try{let o=n.flatMap(a=>r.map(async c=>{let l=await v(t,c.path,a,e),g=O(a,i),x=`${e.outDir}/${c.name}${g}`,$=`${t}/${x}`;await Bun.write($,l),u.progress("DTS",x)}));Promise.all(o).then(()=>{let a=performance.now()-s;_optionalChain([_worker_threads.parentPort, 'optionalAccess', _6 => _6.postMessage, 'call', _7 => _7({success:!0,timeMs:a})])}).catch(a=>{_optionalChain([_worker_threads.parentPort, 'optionalAccess', _8 => _8.postMessage, 'call', _9 => _9({success:!1,error:a instanceof Error?a.message:String(a)})])})}catch(o){_optionalChain([_worker_threads.parentPort, 'optionalAccess', _10 => _10.postMessage, 'call', _11 => _11({success:!1,error:o instanceof Error?o.message:String(o)})])}}exports.runDtsInWorker = Bt;