bunup 0.1.9 → 0.1.11

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/build/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun @bun-cjs
3
- (function(exports, require, module, __filename, __dirname) {var ar=require("node:module");var er=Object.create;var{getPrototypeOf:nr,defineProperty:j,getOwnPropertyNames:or}=Object;var ir=Object.prototype.hasOwnProperty;var m=(r,t,s)=>{s=r!=null?er(nr(r)):{};let n=t||!r||!r.__esModule?j(s,"default",{value:r,enumerable:!0}):s;for(let e of or(r))if(!ir.call(n,e))j(n,e,{get:()=>r[e],enumerable:!0});return n};var v=m(require("fs")),Z=m(require("path"));var A=require("node:os"),b=m(require("node:path")),N=require("node:worker_threads");var p=(r)=>{if(r instanceof Error)return r.message;return String(r)},R=(r,t)=>{let s=p(r),n=t?`[${t}] `:"";if(console.error(`\x1B[31m[ERROR]\x1B[0m ${n}${s}`),r instanceof Error&&r.stack)console.error("\x1B[2m"+r.stack.split(`
3
+ (function(exports, require, module, __filename, __dirname) {var Hn=require("node:module");var En=Object.create;var{getPrototypeOf:an,defineProperty:L,getOwnPropertyNames:V,getOwnPropertyDescriptor:ln}=Object,F=Object.prototype.hasOwnProperty;var j=(n,c,r)=>{r=n!=null?En(an(n)):{};let f=c||!n||!n.__esModule?L(r,"default",{value:n,enumerable:!0}):r;for(let s of V(n))if(!F.call(f,s))L(f,s,{get:()=>n[s],enumerable:!0});return f},g=new WeakMap,dn=(n)=>{var c=g.get(n),r;if(c)return c;if(c=L({},"__esModule",{value:!0}),n&&typeof n==="object"||typeof n==="function")V(n).map((f)=>!F.call(c,f)&&L(c,f,{get:()=>n[f],enumerable:!(r=ln(n,f))||r.enumerable}));return g.set(n,c),c};var _n=(n,c)=>{for(var r in c)L(n,r,{get:c[r],enumerable:!0,configurable:!0,set:(f)=>c[r]=()=>f})};var Qn={};_n(Qn,{main:()=>jn});module.exports=dn(Qn);var K=j(require("fs")),wn=j(require("path"));var H=j(require("fs")),N=j(require("path")),cn=j(require("oxc-transform")),fn=require("rollup"),rn=j(require("rollup-plugin-dts")),G=j(require("typescript"));var E=(n)=>{if(n instanceof Error)return n.message;return String(n)},e=(n,c)=>{let r=E(n),f=c?`[${c}] `:"";if(console.error(`\x1B[31m[ERROR]\x1B[0m ${f}${r}`),n instanceof Error&&n.stack)console.error("\x1B[2m"+n.stack.split(`
4
4
  `).slice(1).join(`
5
- `)+"\x1B[0m")};var i={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(r,t,s){let n=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-t.length));return`\x1B[38;5;${r}m[${t}]\x1B[0m ${n}${s}`},cli(r){let t=this.labels.cli;console.log(this.formatMessage(this.colors.cli,t,r))},info(r){let t=this.labels.info;console.log(this.formatMessage(this.colors.info,t,r))},warn(r){let t=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,t,r))},error(r){let t=this.labels.error;console.error(this.formatMessage(this.colors.error,t,r))},progress(r,t){let s=String(r),n=this.colors.default;for(let[e,o]of Object.entries(this.colors.progress))if(s.includes(e)){n=o;break}console.log(this.formatMessage(n,s,t))}};function E(r,t){return`${t?`${t.replace(/-/g,"_")}_`:""}${r}`.toUpperCase()}var __dirname="/home/runner/work/bunup/bunup/src/dts";class W{workers=[];queue=[];maxWorkers;busyWorkers=new Set;isShuttingDown=!1;constructor(r=A.cpus().length||4){this.maxWorkers=r}async process(r){if(this.isShuttingDown)throw new Error("Worker pool is shutting down");return new Promise((t,s)=>{this.queue.push({task:r,resolve:t,reject:s}),this.processQueue()})}processQueue(){if(this.queue.length===0||this.isShuttingDown)return;if(this.workers.length<this.maxWorkers){let r=new N.Worker(b.default.join(__dirname,"./dtsWorker.js"));this.workers.push(r),this.assignTaskToWorker(r)}else{let r=this.workers.find((t)=>!this.busyWorkers.has(t));if(r)this.assignTaskToWorker(r)}}assignTaskToWorker(r){let t=this.queue.shift();if(!t)return;let{task:s,resolve:n,reject:e}=t;this.busyWorkers.add(r);let o=()=>{if(this.busyWorkers.delete(r),this.isShuttingDown&&this.busyWorkers.size===0)this.terminateAllWorkers();else this.processQueue()};r.on("message",(a)=>{if(a.success)i.progress(E("DTS",a.name),a.outputRelativePath),n();else i.error(`DTS generation failed: ${a.error}`),e(new Error(a.error));o()}),r.on("error",(a)=>{let l=p(a);i.error(`Worker error: ${l}`),e(a),o()}),r.postMessage(s)}terminateAllWorkers(){this.workers.forEach((r)=>{try{r.terminate()}catch(t){i.error(`Error terminating worker: ${p(t)}`)}}),this.workers=[],this.busyWorkers.clear()}async cleanup(){if(this.isShuttingDown=!0,this.busyWorkers.size===0){this.terminateAllWorkers();return}return new Promise((r)=>{let t=setInterval(()=>{if(this.busyWorkers.size===0)clearInterval(t),this.terminateAllWorkers(),r()},100);setTimeout(()=>{clearInterval(t),this.terminateAllWorkers(),r()},5000)})}}function k(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function F(r=8){return Math.random().toString(36).substring(2,2+r)}function M(r,t){switch(r){case"esm":return".mjs";case"cjs":return $(t)?".cjs":".js";case"iife":return".global.js"}}function $(r){return r==="module"}function C(r){return r>=1000?`${(r/1000).toFixed(2)}s`:`${Math.round(r)}ms`}function I(r){if(!r)return[];return Array.from(new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.peerDependencies||{})]))}function L(r,t){return r===void 0?t==="esm":r}function cr(r){return r.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function d(r){let t=[],s=new Set;function n(e,o){if(s.has(e)){let a=F();t.push({name:`${e}_${a}`,path:o})}else t.push({name:e,path:o}),s.add(e)}if(Array.isArray(r))for(let e of r){let o=cr(e);n(o,e)}else Object.entries(r).forEach(([e,o])=>{n(e,o)});return t}function P(r,t){return`[dir]/${r}${t}`}function _(r){return r.map((t)=>typeof t==="string"?new RegExp(`^${k(t)}($|\\/|\\\\)`):t)}function H(r,t){return _(r.external||[]).concat(I(t).map((s)=>new RegExp(`^${k(s)}($|\\/|\\\\)`)))}function q(r){return _(r.noExternal||[])}var x=m(require("node:fs")),B=m(require("node:path"));var h={entry:[],format:["esm"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function D(r,t){return{outdir:`${t}/${r.outDir}`,minify:ur(r),target:r.target,splitting:r.splitting}}function ur(r){let{minify:t,minifyWhitespace:s,minifyIdentifiers:n,minifySyntax:e}=r,o=t===!0;return{whitespace:s??o,identifiers:n??o,syntax:e??o}}async function U(r){let t=[];for(let s of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let n=B.default.join(r,`bunup.config${s}`);try{if(!x.default.existsSync(n))continue;let e;if(s===".json"||s===".jsonc"){let o=x.default.readFileSync(n,"utf8");e=JSON.parse(o)}else{let o=await import(`file://${n}`);if(e=o.default||o,!e)i.warn(`No default export found in ${n}`),e={}}if(Array.isArray(e))for(let o of e)t.push({options:{...h,...o},rootDir:r});else t.push({options:{...h,...e},rootDir:r});break}catch(e){i.error(`Failed to load config from ${n}: ${p(e)}`)}if(t.length>0)break}return t}function Q(r){let t=B.default.join(r,"package.json");try{if(!x.default.existsSync(t))return null;let s=x.default.readFileSync(t,"utf8");return JSON.parse(s)}catch(s){return i.error(`Failed to load package.json at ${t}: ${p(s)}`),null}}function G(r,t){return{name:"bunup:external-plugin",setup(s){s.onResolve({filter:/.*/},(n)=>{let e=n.path;if(r.some((a)=>a.test(e))&&!t.some((a)=>a.test(e)))return{path:e,external:!0};return null})}}}async function O(r,t){if(!r.entry||r.entry.length===0||!r.outDir){i.cli("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");return}let s=performance.now();i.cli("Build started");let n=Q(t),e=n?.type,o=H(r,n),a=q(r),l=[G(o,a)],u=d(r.entry),c=r.format.flatMap((f)=>u.map((g)=>fr(r,t,g,f,e,l)));try{await Promise.all(c);let f=performance.now()-s,g=C(f);i.cli(`⚡ Build success in ${g}`)}catch(f){i.error("Build process encountered errors."),process.exit(1)}if(r.dts){let f=performance.now();i.progress("DTS","Bundling types");let g=r.format.filter((w)=>{if(w==="iife"&&!$(e)&&r.format.includes("cjs"))return!1;return!0}),J=r.dts===!0?u:d(r.dts.entry),S=new W;try{let w=g.flatMap((tr)=>J.map((sr)=>lr(r,t,sr,tr,e,S)));await Promise.all(w);let V=performance.now()-f,rr=C(V);i.progress("DTS",`Bundled types in ${rr}`)}catch(w){await S.cleanup()}await S.cleanup()}}async function lr(r,t,s,n,e,o){let a={name:r.name,rootDir:t,outDir:r.outDir,entry:s,format:n,packageType:e,options:r};await o.process(a)}async function fr(r,t,s,n,e,o){let a=M(n,e),l=D(r,t),u=await Bun.build({...l,entrypoints:[`${t}/${s.path}`],format:n,naming:{entry:P(s.name,a)},splitting:L(r.splitting,n),plugins:o,throw:!1});if(!u.success)throw u.logs.forEach((c)=>{if(c.level==="error")i.error(c.message);else if(c.level==="warning")i.warn(c.message);else if(c.level==="info")i.info(c.message)}),new Error(`Build failed for ${s} (${n})`);i.progress(E(n,r.name),`${r.outDir}/${s.name}${a}`)}var mr={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"},pr={name:(r,t)=>{t.name=r},format:(r,t)=>{t.format=r.split(",")},outDir:(r,t)=>{t.outDir=r},minify:(r,t)=>{t.minify=!!r},watch:(r,t)=>{t.watch=!!r},dts:(r,t)=>{t.dts=!!r},external:(r,t)=>{t.external=r.split(",")},minifyWhitespace:(r,t)=>{t.minifyWhitespace=!!r},minifyIdentifiers:(r,t)=>{t.minifyIdentifiers=!!r},minifySyntax:(r,t)=>{t.minifySyntax=!!r},target:(r,t)=>{t.target=r},clean:(r,t)=>{t.clean=!!r},splitting:(r,t)=>{t.splitting=!!r},noExternal:(r,t)=>{t.noExternal=r.split(",")}};function X(r){let t={};for(let s=0;s<r.length;s++){let n=r[s];if(n.startsWith("--")||n.startsWith("-")){let e=n.startsWith("-")&&!n.startsWith("--"),o=e?n.slice(1):n.slice(2),a=e?mr[o]:o,l=pr[a];if(!l){i.error(`Unknown option: ${o}`);continue}let u=r[s+1],c=u&&!u.startsWith("-")?u:!0;if(l(c,t),typeof c==="string")s++}else{if(!t.entry)t.entry=[];if(Array.isArray(t.entry))t.entry.push(n)}}return t}(()=>{if(typeof Bun==="undefined")i.error(`Bunup requires Bun to run.
6
- To install Bun, visit https://bun.sh/docs/installation`),process.exit(1)})();var y=m(require("node:path")),z=m(require("chokidar"));async function K(r,t){let s=new Set;d(r.entry).forEach((u)=>{let c=y.default.resolve(t,u.path),f=y.default.dirname(c);s.add(f)});let e=z.default.watch(Array.from(s),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,r.outDir]}),o=null,a=!1,l=async(u)=>{if(a)return;a=!0;try{await O({...r,entry:[u],clean:!1},t)}catch(c){i.error(`Build failed: ${c}`)}finally{a=!1}};e.on("change",(u)=>{let c=y.default.relative(t,u);if(i.cli(`File changed: ${c}`),o)clearTimeout(o);o=setTimeout(()=>l(c),300)}),e.on("error",(u)=>{i.error(`Watcher error: ${u}`)})}async function hr(r=Bun.argv.slice(2)){let t=X(r),s=await U(process.cwd()),n=process.cwd();if(t.watch)i.cli("Starting watch mode"),i.cli("Watching for file changes");if(s.length===0){let e={...h,...t};if(e.clean)Y(n,e.outDir);await T(e,n)}else{for(let{options:e,rootDir:o}of s)if(e.clean)Y(o,e.outDir);await Promise.all(s.map(async({options:e,rootDir:o})=>{let a={...h,...e,...t};await T(a,o)}))}if(!t.watch)process.exit(0)}async function T(r,t){if(r.watch)await K(r,t);else await O(r,t)}function Y(r,t){let s=Z.default.join(r,t);if(v.default.existsSync(s))try{v.default.rmSync(s,{recursive:!0,force:!0})}catch(n){i.error(`Failed to clean output directory: ${n}`)}v.default.mkdirSync(s,{recursive:!0})}hr().catch((r)=>{R(r),process.exit(1)});})
5
+ `)+"\x1B[0m")};function Z(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function k(n=8){return Math.random().toString(36).substring(2,2+n)}function o(n,c){switch(n){case"esm":return".mjs";case"cjs":return R(c)?".cjs":".js";case"iife":return".global.js"}}function T(n,c){switch(n){case"esm":return".d.mts";case"cjs":return R(c)?".d.cts":".d.ts";case"iife":return".d.ts"}}function R(n){return n==="module"}function y(n){return n>=1000?`${(n/1000).toFixed(2)}s`:`${Math.round(n)}ms`}function b(n){if(!n)return[];return Array.from(new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.peerDependencies||{})]))}function P(n,c){return n===void 0?c==="esm":n}function t(n){return n.map((c)=>typeof c==="string"?new RegExp(`^${Z(c)}($|\\/|\\\\)`):c)}function U(n,c){return t(n.external||[]).concat(b(c).map((r)=>new RegExp(`^${Z(r)}($|\\/|\\\\)`)))}function h(n){return t(n.noExternal||[])}var a=j(require("fs")),I=j(require("path"));var x={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,c,r){let f=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-c.length));return`\x1B[38;5;${n}m[${c}]\x1B[0m ${f}${r}`},cli(n){let c=this.labels.cli;console.log(this.formatMessage(this.colors.cli,c,n))},info(n){let c=this.labels.info;console.log(this.formatMessage(this.colors.info,c,n))},warn(n){let c=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,c,n))},error(n){let c=this.labels.error;console.error(this.formatMessage(this.colors.error,c,n))},progress(n,c){let r=String(n),f=this.colors.default;for(let[s,i]of Object.entries(this.colors.progress))if(r.includes(s)){f=i;break}console.log(this.formatMessage(f,r,c))}};function z(n,c){return`${c?`${c.replace(/-/g,"_")}_`:""}${n}`.toUpperCase()}var _={entry:[],format:["esm"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function p(n,c){return{outdir:`${c}/${n.outDir}`,minify:Ln(n),target:n.target,splitting:n.splitting}}function Ln(n){let{minify:c,minifyWhitespace:r,minifyIdentifiers:f,minifySyntax:s}=n,i=c===!0;return{whitespace:r??i,identifiers:f??i,syntax:s??i}}async function D(n){let c=[];for(let r of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let f=I.default.join(n,`bunup.config${r}`);try{if(!a.default.existsSync(f))continue;let s;if(r===".json"||r===".jsonc"){let i=a.default.readFileSync(f,"utf8");s=JSON.parse(i)}else{let i=await import(`file://${f}`);if(s=i.default||i,!s)x.warn(`No default export found in ${f}`),s={}}if(Array.isArray(s))for(let i of s)c.push({options:{..._,...i},rootDir:n});else c.push({options:{..._,...s},rootDir:n});break}catch(s){x.error(`Failed to load config from ${f}: ${E(s)}`)}if(c.length>0)break}return c}function v(n){let c=I.default.join(n,"package.json");try{if(!a.default.existsSync(c))return null;let r=a.default.readFileSync(c,"utf8");return JSON.parse(r)}catch(r){return x.error(`Failed to load package.json at ${c}: ${E(r)}`),null}}function nn(n){if(!a.default.existsSync(n))return{};try{let c=a.default.readFileSync(n,"utf8");return JSON.parse(c)||{}}catch(c){return x.warn(`Failed to parse tsconfig at ${n}: ${E(c)}`),{}}}async function sn(n,c,r,f){let{absoluteRootDir:s,absoluteEntry:i}=vn(n,c),O=await Wn(i),C=await Un(O);return hn(i,C,r,f,s)}async function Wn(n){let c=new Set,r=[n];while(r.length>0){let f=r.pop();if(!f||c.has(f))continue;c.add(f);try{let s=await H.default.promises.readFile(f,"utf8"),i=Rn(s);for(let O of i){let C=N.default.dirname(f),$=N.default.resolve(C,O),S=[$,`${$}.ts`,`${$}.tsx`,`${$}/index.ts`,`${$}/index.tsx`];for(let B of S)if(H.default.existsSync(B)&&B.endsWith(".ts")&&!c.has(B)){r.push(B);break}}}catch(s){x.warn(`Error processing ${f}: ${s instanceof Error?s.message:String(s)}`)}}return c}function Rn(n){let c=new Set;try{let r=/(?:import|export)(?:(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*)|[\s\n]+)(["'`])([^'"]+)\1/g,f;while((f=r.exec(n))!==null){let O=f[2];if(O.startsWith("."))c.add(O)}let s=/import\s+(["'`])([^'"]+)\1\s*;?/g;while((f=s.exec(n))!==null){let O=f[2];if(O.startsWith("."))c.add(O)}let i=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;while((f=i.exec(n))!==null){let O=f[2];if(O.startsWith("."))c.add(O)}}catch(r){x.warn(`Error extracting imports: ${r instanceof Error?r.message:String(r)}`)}return Array.from(c)}async function Un(n){let c=new Map;return await Promise.all(Array.from(n).map(async(r)=>{try{let f=r.replace(/\.tsx?$/,".d.ts"),s=await H.default.promises.readFile(r,"utf8"),{code:i}=cn.default.isolatedDeclaration(r,s);if(i)c.set(f,i)}catch(f){x.warn(`Failed to generate declaration for ${r}: ${f instanceof Error?f.message:String(f)}`)}})),c}async function hn(n,c,r,f,s){let C=`\x00virtual:${n.replace(/\.tsx?$/,".d.ts")}`,$=typeof f.dts==="object"?f.dts:{},S=$.preferredTsconfigPath?N.default.resolve($.preferredTsconfigPath):N.default.join(s,"tsconfig.json"),m=(await nn(S)).compilerOptions,M={name:"bunup:virtual-dts",resolveId(u,w){if(u.startsWith("\x00virtual:"))return u;if(w?.startsWith("\x00virtual:")){let A=w.slice(9),Nn=N.default.dirname(A);if(u.startsWith(".")){let mn=N.default.resolve(Nn,u);for(let An of["",".d.ts","/index.d.ts"]){let J=`${mn}${An}`;if(c.has(J))return`\x00virtual:${J}`}}}return null},load(u){if(u.startsWith("\x00virtual:")){let w=u.slice(9);return c.get(w)||null}return null}},l=v(s),Q=U(f,l),Y=h(f),d;try{d=await fn.rollup({input:C,onwarn(w,A){if(w.code==="UNRESOLVED_IMPORT"||w.code==="CIRCULAR_DEPENDENCY"||w.code==="EMPTY_BUNDLE")return;A(w)},plugins:[M,rn.default({tsconfig:S,compilerOptions:{...m?G.default.parseJsonConfigFileContent({compilerOptions:m},G.default.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:G.default.ScriptTarget.ESNext}})],external:(w)=>Q.some((A)=>A.test(w))&&!Y.some((A)=>A.test(w))});let{output:u}=await d.generate({format:r});if(!u[0]?.code)throw new Error("Generated bundle is empty");return u[0].code}catch(u){throw new Error(`DTS bundling failed: ${E(u)}`)}finally{if(d)await d.close()}}function vn(n,c){let r=N.default.resolve(n),f=N.default.resolve(r,c);if(!H.default.existsSync(r))throw new Error(`Root directory does not exist: ${r}`);if(!H.default.existsSync(f))throw new Error(`Entry file does not exist: ${f}`);if(!f.endsWith(".ts"))throw new Error(`Entry file must be a TypeScript file (.ts): ${f}`);if(N.default.relative(r,f).startsWith(".."))throw new Error(`Entry file must be within rootDir: ${f}`);return{absoluteRootDir:r,absoluteEntry:f}}function Gn(n){return n.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function W(n){let c=[],r=new Set;function f(s,i){if(r.has(s)){let O=k();c.push({name:`${s}_${O}`,path:i})}else c.push({name:s,path:i}),r.add(s)}if(Array.isArray(n))for(let s of n){let i=Gn(s);f(i,s)}else Object.entries(n).forEach(([s,i])=>{f(s,i)});return c}function On(n,c){return`[dir]/${n}${c}`}function xn(n,c){return{name:"bunup:external-plugin",setup(r){r.onResolve({filter:/.*/},(f)=>{let s=f.path;if(n.some((O)=>O.test(s))&&!c.some((O)=>O.test(s)))return{path:s,external:!0};return null})}}}async function X(n,c){if(!n.entry||n.entry.length===0||!n.outDir){x.cli("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");return}let r=performance.now();x.cli("Build started");let f=v(c),s=f?.type,i=U(n,f),O=h(n),C=[xn(i,O)],$=W(n.entry),S=n.format.flatMap((B)=>$.map((m)=>qn(n,c,m,B,s,C)));try{await Promise.all(S);let B=performance.now()-r,m=y(B);x.cli(`⚡ Build success in ${m}`)}catch(B){x.error("Build process encountered errors."),process.exit(1)}if(n.dts){let B=performance.now();x.progress("DTS","Bundling types");let m=n.format.filter((l)=>{if(l==="iife"&&!R(s)&&n.format.includes("cjs"))return!1;return!0}),M=n.dts===!0?$:W(n.dts.entry);try{let l=m.flatMap((d)=>M.map((u)=>Xn(n,c,u,d,s)));await Promise.all(l);let Q=performance.now()-B,Y=y(Q);x.progress("DTS",`Bundled types in ${Y}`)}catch(l){x.error("DTS build process encountered errors.")}}}async function Xn(n,c,r,f,s){let i=await sn(c,r.path,f,n),O=T(f,s),C=`${n.outDir}/${r.name}${O}`,$=`${c}/${C}`;await Bun.write($,i),x.progress(z("DTS",n.name),C)}async function qn(n,c,r,f,s,i){let O=o(f,s),C=p(n,c),$=await Bun.build({...C,entrypoints:[`${c}/${r.path}`],format:f,naming:{entry:On(r.name,O)},splitting:P(n.splitting,f),plugins:i,throw:!1});if(!$.success)throw $.logs.forEach((S)=>{if(S.level==="error")x.error(S.message);else if(S.level==="warning")x.warn(S.message);else if(S.level==="info")x.info(S.message)}),new Error(`Build failed for ${r} (${f})`);x.progress(z(f,n.name),`${n.outDir}/${r.name}${O}`)}var Kn={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"},Mn={name:(n,c)=>{c.name=n},format:(n,c)=>{c.format=n.split(",")},outDir:(n,c)=>{c.outDir=n},minify:(n,c)=>{c.minify=!!n},watch:(n,c)=>{c.watch=!!n},dts:(n,c)=>{c.dts=!!n},external:(n,c)=>{c.external=n.split(",")},minifyWhitespace:(n,c)=>{c.minifyWhitespace=!!n},minifyIdentifiers:(n,c)=>{c.minifyIdentifiers=!!n},minifySyntax:(n,c)=>{c.minifySyntax=!!n},target:(n,c)=>{c.target=n},clean:(n,c)=>{c.clean=!!n},splitting:(n,c)=>{c.splitting=!!n},noExternal:(n,c)=>{c.noExternal=n.split(",")}};function $n(n){let c={};for(let r=0;r<n.length;r++){let f=n[r];if(f.startsWith("--")||f.startsWith("-")){let s=f.startsWith("-")&&!f.startsWith("--"),i=s?f.slice(1):f.slice(2),O=s?Kn[i]:i,C=Mn[O];if(!C){x.error(`Unknown option: ${i}`);continue}let $=n[r+1],S=$&&!$.startsWith("-")?$:!0;if(C(S,c),typeof S==="string")r++}else{if(!c.entry)c.entry=[];if(Array.isArray(c.entry))c.entry.push(f)}}return c}(()=>{if(typeof Bun==="undefined")x.error(`Bunup requires Bun to run.
6
+ To install Bun, visit https://bun.sh/docs/installation`),process.exit(1)})();var q=j(require("path")),Sn=j(require("chokidar"));async function Cn(n,c){let r=new Set;W(n.entry).forEach(($)=>{let S=q.default.resolve(c,$.path),B=q.default.dirname(S);r.add(B)});let s=Sn.default.watch(Array.from(r),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,n.outDir]}),i=null,O=!1,C=async($)=>{if(O)return;O=!0;try{await X({...n,entry:[$],clean:!1},c)}catch(S){x.error(`Build failed: ${S}`)}finally{O=!1}};s.on("change",($)=>{let S=q.default.relative(c,$);if(x.cli(`File changed: ${S}`),i)clearTimeout(i);i=setTimeout(()=>C(S),300)}),s.on("error",($)=>{x.error(`Watcher error: ${$}`)})}async function jn(n=Bun.argv.slice(2)){let c=$n(n),r=await D(process.cwd()),f=process.cwd();if(c.watch)x.cli("Starting watch mode"),x.cli("Watching for file changes");if(r.length===0){let s={..._,...c};if(s.clean)un(f,s.outDir);await Bn(s,f)}else{for(let{options:s,rootDir:i}of r)if(s.clean)un(i,s.outDir);await Promise.all(r.map(async({options:s,rootDir:i})=>{let O={..._,...s,...c};await Bn(O,i)}))}if(!c.watch)process.exit(0)}async function Bn(n,c){if(n.watch)await Cn(n,c);else await X(n,c)}function un(n,c){let r=wn.default.join(n,c);if(K.default.existsSync(r))try{K.default.rmSync(r,{recursive:!0,force:!0})}catch(f){x.error(`Failed to clean output directory: ${f}`)}K.default.mkdirSync(r,{recursive:!0})}jn().catch((n)=>{e(n),process.exit(1)});})
package/build/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import $ from"fs";import ir from"path";import{cpus as Y}from"node:os";import Z from"node:path";import{Worker as J}from"node:worker_threads";var m=(r)=>{if(r instanceof Error)return r.message;return String(r)},C=(r,t)=>{let s=m(r),n=t?`[${t}] `:"";if(console.error(`\x1B[31m[ERROR]\x1B[0m ${n}${s}`),r instanceof Error&&r.stack)console.error("\x1B[2m"+r.stack.split(`
3
+ import Z from"fs";import _n from"path";import _ from"fs";import j from"path";import $n from"oxc-transform";import{rollup as Sn}from"rollup";import Cn from"rollup-plugin-dts";import Q from"typescript";var A=(n)=>{if(n instanceof Error)return n.message;return String(n)},z=(n,c)=>{let r=A(n),f=c?`[${c}] `:"";if(console.error(`\x1B[31m[ERROR]\x1B[0m ${f}${r}`),n instanceof Error&&n.stack)console.error("\x1B[2m"+n.stack.split(`
4
4
  `).slice(1).join(`
5
- `)+"\x1B[0m")};var i={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(r,t,s){let n=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-t.length));return`\x1B[38;5;${r}m[${t}]\x1B[0m ${n}${s}`},cli(r){let t=this.labels.cli;console.log(this.formatMessage(this.colors.cli,t,r))},info(r){let t=this.labels.info;console.log(this.formatMessage(this.colors.info,t,r))},warn(r){let t=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,t,r))},error(r){let t=this.labels.error;console.error(this.formatMessage(this.colors.error,t,r))},progress(r,t){let s=String(r),n=this.colors.default;for(let[e,o]of Object.entries(this.colors.progress))if(s.includes(e)){n=o;break}console.log(this.formatMessage(n,s,t))}};function x(r,t){return`${t?`${t.replace(/-/g,"_")}_`:""}${r}`.toUpperCase()}var __dirname="/home/runner/work/bunup/bunup/src/dts";class y{workers=[];queue=[];maxWorkers;busyWorkers=new Set;isShuttingDown=!1;constructor(r=Y().length||4){this.maxWorkers=r}async process(r){if(this.isShuttingDown)throw new Error("Worker pool is shutting down");return new Promise((t,s)=>{this.queue.push({task:r,resolve:t,reject:s}),this.processQueue()})}processQueue(){if(this.queue.length===0||this.isShuttingDown)return;if(this.workers.length<this.maxWorkers){let r=new J(Z.join(__dirname,"./dtsWorker.js"));this.workers.push(r),this.assignTaskToWorker(r)}else{let r=this.workers.find((t)=>!this.busyWorkers.has(t));if(r)this.assignTaskToWorker(r)}}assignTaskToWorker(r){let t=this.queue.shift();if(!t)return;let{task:s,resolve:n,reject:e}=t;this.busyWorkers.add(r);let o=()=>{if(this.busyWorkers.delete(r),this.isShuttingDown&&this.busyWorkers.size===0)this.terminateAllWorkers();else this.processQueue()};r.on("message",(a)=>{if(a.success)i.progress(x("DTS",a.name),a.outputRelativePath),n();else i.error(`DTS generation failed: ${a.error}`),e(new Error(a.error));o()}),r.on("error",(a)=>{let l=m(a);i.error(`Worker error: ${l}`),e(a),o()}),r.postMessage(s)}terminateAllWorkers(){this.workers.forEach((r)=>{try{r.terminate()}catch(t){i.error(`Error terminating worker: ${m(t)}`)}}),this.workers=[],this.busyWorkers.clear()}async cleanup(){if(this.isShuttingDown=!0,this.busyWorkers.size===0){this.terminateAllWorkers();return}return new Promise((r)=>{let t=setInterval(()=>{if(this.busyWorkers.size===0)clearInterval(t),this.terminateAllWorkers(),r()},100);setTimeout(()=>{clearInterval(t),this.terminateAllWorkers(),r()},5000)})}}function v(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function B(r=8){return Math.random().toString(36).substring(2,2+r)}function j(r,t){switch(r){case"esm":return".mjs";case"cjs":return S(t)?".cjs":".js";case"iife":return".global.js"}}function S(r){return r==="module"}function W(r){return r>=1000?`${(r/1000).toFixed(2)}s`:`${Math.round(r)}ms`}function R(r){if(!r)return[];return Array.from(new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.peerDependencies||{})]))}function A(r,t){return r===void 0?t==="esm":r}function V(r){return r.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function g(r){let t=[],s=new Set;function n(e,o){if(s.has(e)){let a=B();t.push({name:`${e}_${a}`,path:o})}else t.push({name:e,path:o}),s.add(e)}if(Array.isArray(r))for(let e of r){let o=V(e);n(o,e)}else Object.entries(r).forEach(([e,o])=>{n(e,o)});return t}function b(r,t){return`[dir]/${r}${t}`}function N(r){return r.map((t)=>typeof t==="string"?new RegExp(`^${v(t)}($|\\/|\\\\)`):t)}function F(r,t){return N(r.external||[]).concat(R(t).map((s)=>new RegExp(`^${v(s)}($|\\/|\\\\)`)))}function M(r){return N(r.noExternal||[])}import w from"node:fs";import L from"node:path";var p={entry:[],format:["esm"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function I(r,t){return{outdir:`${t}/${r.outDir}`,minify:rr(r),target:r.target,splitting:r.splitting}}function rr(r){let{minify:t,minifyWhitespace:s,minifyIdentifiers:n,minifySyntax:e}=r,o=t===!0;return{whitespace:s??o,identifiers:n??o,syntax:e??o}}async function P(r){let t=[];for(let s of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let n=L.join(r,`bunup.config${s}`);try{if(!w.existsSync(n))continue;let e;if(s===".json"||s===".jsonc"){let o=w.readFileSync(n,"utf8");e=JSON.parse(o)}else{let o=await import(`file://${n}`);if(e=o.default||o,!e)i.warn(`No default export found in ${n}`),e={}}if(Array.isArray(e))for(let o of e)t.push({options:{...p,...o},rootDir:r});else t.push({options:{...p,...e},rootDir:r});break}catch(e){i.error(`Failed to load config from ${n}: ${m(e)}`)}if(t.length>0)break}return t}function _(r){let t=L.join(r,"package.json");try{if(!w.existsSync(t))return null;let s=w.readFileSync(t,"utf8");return JSON.parse(s)}catch(s){return i.error(`Failed to load package.json at ${t}: ${m(s)}`),null}}function H(r,t){return{name:"bunup:external-plugin",setup(s){s.onResolve({filter:/.*/},(n)=>{let e=n.path;if(r.some((a)=>a.test(e))&&!t.some((a)=>a.test(e)))return{path:e,external:!0};return null})}}}async function E(r,t){if(!r.entry||r.entry.length===0||!r.outDir){i.cli("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");return}let s=performance.now();i.cli("Build started");let n=_(t),e=n?.type,o=F(r,n),a=M(r),l=[H(o,a)],u=g(r.entry),c=r.format.flatMap((f)=>u.map((h)=>sr(r,t,h,f,e,l)));try{await Promise.all(c);let f=performance.now()-s,h=W(f);i.cli(`⚡ Build success in ${h}`)}catch(f){i.error("Build process encountered errors."),process.exit(1)}if(r.dts){let f=performance.now();i.progress("DTS","Bundling types");let h=r.format.filter((d)=>{if(d==="iife"&&!S(e)&&r.format.includes("cjs"))return!1;return!0}),G=r.dts===!0?u:g(r.dts.entry),O=new y;try{let d=h.flatMap((K)=>G.map((T)=>tr(r,t,T,K,e,O)));await Promise.all(d);let X=performance.now()-f,z=W(X);i.progress("DTS",`Bundled types in ${z}`)}catch(d){await O.cleanup()}await O.cleanup()}}async function tr(r,t,s,n,e,o){let a={name:r.name,rootDir:t,outDir:r.outDir,entry:s,format:n,packageType:e,options:r};await o.process(a)}async function sr(r,t,s,n,e,o){let a=j(n,e),l=I(r,t),u=await Bun.build({...l,entrypoints:[`${t}/${s.path}`],format:n,naming:{entry:b(s.name,a)},splitting:A(r.splitting,n),plugins:o,throw:!1});if(!u.success)throw u.logs.forEach((c)=>{if(c.level==="error")i.error(c.message);else if(c.level==="warning")i.warn(c.message);else if(c.level==="info")i.info(c.message)}),new Error(`Build failed for ${s} (${n})`);i.progress(x(n,r.name),`${r.outDir}/${s.name}${a}`)}var er={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"},nr={name:(r,t)=>{t.name=r},format:(r,t)=>{t.format=r.split(",")},outDir:(r,t)=>{t.outDir=r},minify:(r,t)=>{t.minify=!!r},watch:(r,t)=>{t.watch=!!r},dts:(r,t)=>{t.dts=!!r},external:(r,t)=>{t.external=r.split(",")},minifyWhitespace:(r,t)=>{t.minifyWhitespace=!!r},minifyIdentifiers:(r,t)=>{t.minifyIdentifiers=!!r},minifySyntax:(r,t)=>{t.minifySyntax=!!r},target:(r,t)=>{t.target=r},clean:(r,t)=>{t.clean=!!r},splitting:(r,t)=>{t.splitting=!!r},noExternal:(r,t)=>{t.noExternal=r.split(",")}};function q(r){let t={};for(let s=0;s<r.length;s++){let n=r[s];if(n.startsWith("--")||n.startsWith("-")){let e=n.startsWith("-")&&!n.startsWith("--"),o=e?n.slice(1):n.slice(2),a=e?er[o]:o,l=nr[a];if(!l){i.error(`Unknown option: ${o}`);continue}let u=r[s+1],c=u&&!u.startsWith("-")?u:!0;if(l(c,t),typeof c==="string")s++}else{if(!t.entry)t.entry=[];if(Array.isArray(t.entry))t.entry.push(n)}}return t}(()=>{if(typeof Bun==="undefined")i.error(`Bunup requires Bun to run.
6
- To install Bun, visit https://bun.sh/docs/installation`),process.exit(1)})();import k from"node:path";import or from"chokidar";async function D(r,t){let s=new Set;g(r.entry).forEach((u)=>{let c=k.resolve(t,u.path),f=k.dirname(c);s.add(f)});let e=or.watch(Array.from(s),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,r.outDir]}),o=null,a=!1,l=async(u)=>{if(a)return;a=!0;try{await E({...r,entry:[u],clean:!1},t)}catch(c){i.error(`Build failed: ${c}`)}finally{a=!1}};e.on("change",(u)=>{let c=k.relative(t,u);if(i.cli(`File changed: ${c}`),o)clearTimeout(o);o=setTimeout(()=>l(c),300)}),e.on("error",(u)=>{i.error(`Watcher error: ${u}`)})}async function ar(r=Bun.argv.slice(2)){let t=q(r),s=await P(process.cwd()),n=process.cwd();if(t.watch)i.cli("Starting watch mode"),i.cli("Watching for file changes");if(s.length===0){let e={...p,...t};if(e.clean)Q(n,e.outDir);await U(e,n)}else{for(let{options:e,rootDir:o}of s)if(e.clean)Q(o,e.outDir);await Promise.all(s.map(async({options:e,rootDir:o})=>{let a={...p,...e,...t};await U(a,o)}))}if(!t.watch)process.exit(0)}async function U(r,t){if(r.watch)await D(r,t);else await E(r,t)}function Q(r,t){let s=ir.join(r,t);if($.existsSync(s))try{$.rmSync(s,{recursive:!0,force:!0})}catch(n){i.error(`Failed to clean output directory: ${n}`)}$.mkdirSync(s,{recursive:!0})}ar().catch((r)=>{C(r),process.exit(1)});
5
+ `)+"\x1B[0m")};function q(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function I(n=8){return Math.random().toString(36).substring(2,2+n)}function J(n,c){switch(n){case"esm":return".mjs";case"cjs":return L(c)?".cjs":".js";case"iife":return".global.js"}}function g(n,c){switch(n){case"esm":return".d.mts";case"cjs":return L(c)?".d.cts":".d.ts";case"iife":return".d.ts"}}function L(n){return n==="module"}function K(n){return n>=1000?`${(n/1000).toFixed(2)}s`:`${Math.round(n)}ms`}function V(n){if(!n)return[];return Array.from(new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.peerDependencies||{})]))}function F(n,c){return n===void 0?c==="esm":n}function e(n){return n.map((c)=>typeof c==="string"?new RegExp(`^${q(c)}($|\\/|\\\\)`):c)}function W(n,c){return e(n.external||[]).concat(V(c).map((r)=>new RegExp(`^${q(r)}($|\\/|\\\\)`)))}function R(n){return e(n.noExternal||[])}import d from"fs";import o from"path";var x={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,c,r){let f=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-c.length));return`\x1B[38;5;${n}m[${c}]\x1B[0m ${f}${r}`},cli(n){let c=this.labels.cli;console.log(this.formatMessage(this.colors.cli,c,n))},info(n){let c=this.labels.info;console.log(this.formatMessage(this.colors.info,c,n))},warn(n){let c=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,c,n))},error(n){let c=this.labels.error;console.error(this.formatMessage(this.colors.error,c,n))},progress(n,c){let r=String(n),f=this.colors.default;for(let[s,i]of Object.entries(this.colors.progress))if(r.includes(s)){f=i;break}console.log(this.formatMessage(f,r,c))}};function M(n,c){return`${c?`${c.replace(/-/g,"_")}_`:""}${n}`.toUpperCase()}var l={entry:[],format:["esm"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function k(n,c){return{outdir:`${c}/${n.outDir}`,minify:xn(n),target:n.target,splitting:n.splitting}}function xn(n){let{minify:c,minifyWhitespace:r,minifyIdentifiers:f,minifySyntax:s}=n,i=c===!0;return{whitespace:r??i,identifiers:f??i,syntax:s??i}}async function T(n){let c=[];for(let r of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let f=o.join(n,`bunup.config${r}`);try{if(!d.existsSync(f))continue;let s;if(r===".json"||r===".jsonc"){let i=d.readFileSync(f,"utf8");s=JSON.parse(i)}else{let i=await import(`file://${f}`);if(s=i.default||i,!s)x.warn(`No default export found in ${f}`),s={}}if(Array.isArray(s))for(let i of s)c.push({options:{...l,...i},rootDir:n});else c.push({options:{...l,...s},rootDir:n});break}catch(s){x.error(`Failed to load config from ${f}: ${A(s)}`)}if(c.length>0)break}return c}function U(n){let c=o.join(n,"package.json");try{if(!d.existsSync(c))return null;let r=d.readFileSync(c,"utf8");return JSON.parse(r)}catch(r){return x.error(`Failed to load package.json at ${c}: ${A(r)}`),null}}function b(n){if(!d.existsSync(n))return{};try{let c=d.readFileSync(n,"utf8");return JSON.parse(c)||{}}catch(c){return x.warn(`Failed to parse tsconfig at ${n}: ${A(c)}`),{}}}async function P(n,c,r,f){let{absoluteRootDir:s,absoluteEntry:i}=Nn(n,c),O=await Bn(i),C=await wn(O);return jn(i,C,r,f,s)}async function Bn(n){let c=new Set,r=[n];while(r.length>0){let f=r.pop();if(!f||c.has(f))continue;c.add(f);try{let s=await _.promises.readFile(f,"utf8"),i=un(s);for(let O of i){let C=j.dirname(f),$=j.resolve(C,O),S=[$,`${$}.ts`,`${$}.tsx`,`${$}/index.ts`,`${$}/index.tsx`];for(let B of S)if(_.existsSync(B)&&B.endsWith(".ts")&&!c.has(B)){r.push(B);break}}}catch(s){x.warn(`Error processing ${f}: ${s instanceof Error?s.message:String(s)}`)}}return c}function un(n){let c=new Set;try{let r=/(?:import|export)(?:(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*)|[\s\n]+)(["'`])([^'"]+)\1/g,f;while((f=r.exec(n))!==null){let O=f[2];if(O.startsWith("."))c.add(O)}let s=/import\s+(["'`])([^'"]+)\1\s*;?/g;while((f=s.exec(n))!==null){let O=f[2];if(O.startsWith("."))c.add(O)}let i=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;while((f=i.exec(n))!==null){let O=f[2];if(O.startsWith("."))c.add(O)}}catch(r){x.warn(`Error extracting imports: ${r instanceof Error?r.message:String(r)}`)}return Array.from(c)}async function wn(n){let c=new Map;return await Promise.all(Array.from(n).map(async(r)=>{try{let f=r.replace(/\.tsx?$/,".d.ts"),s=await _.promises.readFile(r,"utf8"),{code:i}=$n.isolatedDeclaration(r,s);if(i)c.set(f,i)}catch(f){x.warn(`Failed to generate declaration for ${r}: ${f instanceof Error?f.message:String(f)}`)}})),c}async function jn(n,c,r,f,s){let C=`\x00virtual:${n.replace(/\.tsx?$/,".d.ts")}`,$=typeof f.dts==="object"?f.dts:{},S=$.preferredTsconfigPath?j.resolve($.preferredTsconfigPath):j.join(s,"tsconfig.json"),N=(await b(S)).compilerOptions,v={name:"bunup:virtual-dts",resolveId(u,w){if(u.startsWith("\x00virtual:"))return u;if(w?.startsWith("\x00virtual:")){let m=w.slice(9),rn=j.dirname(m);if(u.startsWith(".")){let sn=j.resolve(rn,u);for(let On of["",".d.ts","/index.d.ts"]){let y=`${sn}${On}`;if(c.has(y))return`\x00virtual:${y}`}}}return null},load(u){if(u.startsWith("\x00virtual:")){let w=u.slice(9);return c.get(w)||null}return null}},E=U(s),G=W(f,E),X=R(f),a;try{a=await Sn({input:C,onwarn(w,m){if(w.code==="UNRESOLVED_IMPORT"||w.code==="CIRCULAR_DEPENDENCY"||w.code==="EMPTY_BUNDLE")return;m(w)},plugins:[v,Cn({tsconfig:S,compilerOptions:{...N?Q.parseJsonConfigFileContent({compilerOptions:N},Q.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:Q.ScriptTarget.ESNext}})],external:(w)=>G.some((m)=>m.test(w))&&!X.some((m)=>m.test(w))});let{output:u}=await a.generate({format:r});if(!u[0]?.code)throw new Error("Generated bundle is empty");return u[0].code}catch(u){throw new Error(`DTS bundling failed: ${A(u)}`)}finally{if(a)await a.close()}}function Nn(n,c){let r=j.resolve(n),f=j.resolve(r,c);if(!_.existsSync(r))throw new Error(`Root directory does not exist: ${r}`);if(!_.existsSync(f))throw new Error(`Entry file does not exist: ${f}`);if(!f.endsWith(".ts"))throw new Error(`Entry file must be a TypeScript file (.ts): ${f}`);if(j.relative(r,f).startsWith(".."))throw new Error(`Entry file must be within rootDir: ${f}`);return{absoluteRootDir:r,absoluteEntry:f}}function mn(n){return n.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function H(n){let c=[],r=new Set;function f(s,i){if(r.has(s)){let O=I();c.push({name:`${s}_${O}`,path:i})}else c.push({name:s,path:i}),r.add(s)}if(Array.isArray(n))for(let s of n){let i=mn(s);f(i,s)}else Object.entries(n).forEach(([s,i])=>{f(s,i)});return c}function t(n,c){return`[dir]/${n}${c}`}function p(n,c){return{name:"bunup:external-plugin",setup(r){r.onResolve({filter:/.*/},(f)=>{let s=f.path;if(n.some((O)=>O.test(s))&&!c.some((O)=>O.test(s)))return{path:s,external:!0};return null})}}}async function h(n,c){if(!n.entry||n.entry.length===0||!n.outDir){x.cli("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");return}let r=performance.now();x.cli("Build started");let f=U(c),s=f?.type,i=W(n,f),O=R(n),C=[p(i,O)],$=H(n.entry),S=n.format.flatMap((B)=>$.map((N)=>En(n,c,N,B,s,C)));try{await Promise.all(S);let B=performance.now()-r,N=K(B);x.cli(`⚡ Build success in ${N}`)}catch(B){x.error("Build process encountered errors."),process.exit(1)}if(n.dts){let B=performance.now();x.progress("DTS","Bundling types");let N=n.format.filter((E)=>{if(E==="iife"&&!L(s)&&n.format.includes("cjs"))return!1;return!0}),v=n.dts===!0?$:H(n.dts.entry);try{let E=N.flatMap((a)=>v.map((u)=>An(n,c,u,a,s)));await Promise.all(E);let G=performance.now()-B,X=K(G);x.progress("DTS",`Bundled types in ${X}`)}catch(E){x.error("DTS build process encountered errors.")}}}async function An(n,c,r,f,s){let i=await P(c,r.path,f,n),O=g(f,s),C=`${n.outDir}/${r.name}${O}`,$=`${c}/${C}`;await Bun.write($,i),x.progress(M("DTS",n.name),C)}async function En(n,c,r,f,s,i){let O=J(f,s),C=k(n,c),$=await Bun.build({...C,entrypoints:[`${c}/${r.path}`],format:f,naming:{entry:t(r.name,O)},splitting:F(n.splitting,f),plugins:i,throw:!1});if(!$.success)throw $.logs.forEach((S)=>{if(S.level==="error")x.error(S.message);else if(S.level==="warning")x.warn(S.message);else if(S.level==="info")x.info(S.message)}),new Error(`Build failed for ${r} (${f})`);x.progress(M(f,n.name),`${n.outDir}/${r.name}${O}`)}var an={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"},ln={name:(n,c)=>{c.name=n},format:(n,c)=>{c.format=n.split(",")},outDir:(n,c)=>{c.outDir=n},minify:(n,c)=>{c.minify=!!n},watch:(n,c)=>{c.watch=!!n},dts:(n,c)=>{c.dts=!!n},external:(n,c)=>{c.external=n.split(",")},minifyWhitespace:(n,c)=>{c.minifyWhitespace=!!n},minifyIdentifiers:(n,c)=>{c.minifyIdentifiers=!!n},minifySyntax:(n,c)=>{c.minifySyntax=!!n},target:(n,c)=>{c.target=n},clean:(n,c)=>{c.clean=!!n},splitting:(n,c)=>{c.splitting=!!n},noExternal:(n,c)=>{c.noExternal=n.split(",")}};function D(n){let c={};for(let r=0;r<n.length;r++){let f=n[r];if(f.startsWith("--")||f.startsWith("-")){let s=f.startsWith("-")&&!f.startsWith("--"),i=s?f.slice(1):f.slice(2),O=s?an[i]:i,C=ln[O];if(!C){x.error(`Unknown option: ${i}`);continue}let $=n[r+1],S=$&&!$.startsWith("-")?$:!0;if(C(S,c),typeof S==="string")r++}else{if(!c.entry)c.entry=[];if(Array.isArray(c.entry))c.entry.push(f)}}return c}(()=>{if(typeof Bun==="undefined")x.error(`Bunup requires Bun to run.
6
+ To install Bun, visit https://bun.sh/docs/installation`),process.exit(1)})();import Y from"path";import dn from"chokidar";async function nn(n,c){let r=new Set;H(n.entry).forEach(($)=>{let S=Y.resolve(c,$.path),B=Y.dirname(S);r.add(B)});let s=dn.watch(Array.from(r),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,n.outDir]}),i=null,O=!1,C=async($)=>{if(O)return;O=!0;try{await h({...n,entry:[$],clean:!1},c)}catch(S){x.error(`Build failed: ${S}`)}finally{O=!1}};s.on("change",($)=>{let S=Y.relative(c,$);if(x.cli(`File changed: ${S}`),i)clearTimeout(i);i=setTimeout(()=>C(S),300)}),s.on("error",($)=>{x.error(`Watcher error: ${$}`)})}async function Hn(n=Bun.argv.slice(2)){let c=D(n),r=await T(process.cwd()),f=process.cwd();if(c.watch)x.cli("Starting watch mode"),x.cli("Watching for file changes");if(r.length===0){let s={...l,...c};if(s.clean)fn(f,s.outDir);await cn(s,f)}else{for(let{options:s,rootDir:i}of r)if(s.clean)fn(i,s.outDir);await Promise.all(r.map(async({options:s,rootDir:i})=>{let O={...l,...s,...c};await cn(O,i)}))}if(!c.watch)process.exit(0)}async function cn(n,c){if(n.watch)await nn(n,c);else await h(n,c)}function fn(n,c){let r=_n.join(n,c);if(Z.existsSync(r))try{Z.rmSync(r,{recursive:!0,force:!0})}catch(f){x.error(`Failed to clean output directory: ${f}`)}Z.mkdirSync(r,{recursive:!0})}Hn().catch((n)=>{z(n),process.exit(1)});export{Hn as main};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunup",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
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",
@@ -18,10 +18,11 @@
18
18
  "@types/bun": "^1.2.5",
19
19
  "@typescript-eslint/eslint-plugin": "^7.3.1",
20
20
  "bumpp": "^10.1.0",
21
- "bunup": "^0.1.6",
21
+ "bunup": "^0.1.9",
22
22
  "eslint": "^8.57.0",
23
23
  "husky": "^9.1.6",
24
24
  "prettier": "^3.2.5",
25
+ "tsup": "^8.4.0",
25
26
  "typescript": "^5.4.3",
26
27
  "vitest": "^2.0.5"
27
28
  },
@@ -1 +0,0 @@
1
- var C=require("node:module");var v=Object.create;var{getPrototypeOf:b,defineProperty:n,getOwnPropertyNames:u,getOwnPropertyDescriptor:E}=Object,h=Object.prototype.hasOwnProperty;var w=(r,e,s)=>{s=r!=null?v(b(r)):{};let o=e||!r||!r.__esModule?n(s,"default",{value:r,enumerable:!0}):s;for(let t of u(r))if(!h.call(o,t))n(o,t,{get:()=>r[t],enumerable:!0});return o},g=new WeakMap,y=(r)=>{var e=g.get(r),s;if(e)return e;if(e=n({},"__esModule",{value:!0}),r&&typeof r==="object"||typeof r==="function")u(r).map((o)=>!h.call(e,o)&&n(e,o,{get:()=>r[o],enumerable:!(s=E(r,o))||s.enumerable}));return g.set(r,e),e};var D=(r,e)=>{for(var s in e)n(r,s,{get:e[s],enumerable:!0,configurable:!0,set:(o)=>e[s]=()=>o})};var M={};D(M,{DtsWorker:()=>d});module.exports=y(M);var m=require("node:os"),f=w(require("node:path")),k=require("node:worker_threads");var c=(r)=>{if(r instanceof Error)return r.message;return String(r)};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(r,e,s){let o=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-e.length));return`\x1B[38;5;${r}m[${e}]\x1B[0m ${o}${s}`},cli(r){let e=this.labels.cli;console.log(this.formatMessage(this.colors.cli,e,r))},info(r){let e=this.labels.info;console.log(this.formatMessage(this.colors.info,e,r))},warn(r){let e=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,e,r))},error(r){let e=this.labels.error;console.error(this.formatMessage(this.colors.error,e,r))},progress(r,e){let s=String(r),o=this.colors.default;for(let[t,l]of Object.entries(this.colors.progress))if(s.includes(t)){o=l;break}console.log(this.formatMessage(o,s,e))}};function p(r,e){return`${e?`${e.replace(/-/g,"_")}_`:""}${r}`.toUpperCase()}var __dirname="/home/runner/work/bunup/bunup/src/dts";class d{workers=[];queue=[];maxWorkers;busyWorkers=new Set;isShuttingDown=!1;constructor(r=m.cpus().length||4){this.maxWorkers=r}async process(r){if(this.isShuttingDown)throw new Error("Worker pool is shutting down");return new Promise((e,s)=>{this.queue.push({task:r,resolve:e,reject:s}),this.processQueue()})}processQueue(){if(this.queue.length===0||this.isShuttingDown)return;if(this.workers.length<this.maxWorkers){let r=new k.Worker(f.default.join(__dirname,"./dtsWorker.js"));this.workers.push(r),this.assignTaskToWorker(r)}else{let r=this.workers.find((e)=>!this.busyWorkers.has(e));if(r)this.assignTaskToWorker(r)}}assignTaskToWorker(r){let e=this.queue.shift();if(!e)return;let{task:s,resolve:o,reject:t}=e;this.busyWorkers.add(r);let l=()=>{if(this.busyWorkers.delete(r),this.isShuttingDown&&this.busyWorkers.size===0)this.terminateAllWorkers();else this.processQueue()};r.on("message",(i)=>{if(i.success)a.progress(p("DTS",i.name),i.outputRelativePath),o();else a.error(`DTS generation failed: ${i.error}`),t(new Error(i.error));l()}),r.on("error",(i)=>{let W=c(i);a.error(`Worker error: ${W}`),t(i),l()}),r.postMessage(s)}terminateAllWorkers(){this.workers.forEach((r)=>{try{r.terminate()}catch(e){a.error(`Error terminating worker: ${c(e)}`)}}),this.workers=[],this.busyWorkers.clear()}async cleanup(){if(this.isShuttingDown=!0,this.busyWorkers.size===0){this.terminateAllWorkers();return}return new Promise((r)=>{let e=setInterval(()=>{if(this.busyWorkers.size===0)clearInterval(e),this.terminateAllWorkers(),r()},100);setTimeout(()=>{clearInterval(e),this.terminateAllWorkers(),r()},5000)})}}
package/build/index.d.mts DELETED
@@ -1,147 +0,0 @@
1
- type WithOptional<
2
- T,
3
- K extends keyof T
4
- > = Omit<T, K> & Partial<Pick<T, K>>;
5
-
6
- type Format = "esm" | "cjs" | "iife";
7
- type Target = "bun" | "node" | "browser";
8
- type External = string[];
9
- type Entry = string[] | Record<string, string>;
10
- type DtsOptions = {
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
45
- };
46
- interface BunupOptions {
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 ['esm'] 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;
141
- }
142
-
143
- type DefineConfigOption = WithOptional<BunupOptions, "outDir" | "format">;
144
- type DefineConfigOptions = DefineConfigOption | DefineConfigOption[];
145
- declare function defineConfig(options: DefineConfigOptions): DefineConfigOptions;
146
-
147
- export { defineConfig };
package/build/index.d.ts DELETED
@@ -1,147 +0,0 @@
1
- type WithOptional<
2
- T,
3
- K extends keyof T
4
- > = Omit<T, K> & Partial<Pick<T, K>>;
5
-
6
- type Format = "esm" | "cjs" | "iife";
7
- type Target = "bun" | "node" | "browser";
8
- type External = string[];
9
- type Entry = string[] | Record<string, string>;
10
- type DtsOptions = {
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
45
- };
46
- interface BunupOptions {
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 ['esm'] 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;
141
- }
142
-
143
- type DefineConfigOption = WithOptional<BunupOptions, "outDir" | "format">;
144
- type DefineConfigOptions = DefineConfigOption | DefineConfigOption[];
145
- declare function defineConfig(options: DefineConfigOptions): DefineConfigOptions;
146
-
147
- export { defineConfig };