bunup 0.4.65 → 0.4.67

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
@@ -3,28 +3,22 @@
3
3
  [![npm version](https://img.shields.io/npm/v/bunup.svg?style=flat-square)](https://www.npmjs.com/package/bunup)
4
4
  [![npm downloads](https://img.shields.io/npm/dm/bunup.svg?style=flat-square)](https://www.npmjs.com/package/bunup)
5
5
 
6
- Bunup is the **high-performance build tool** for TypeScript and JavaScript libraries, designed for beautiful developer experience and speed. It provides **first-class support** for libraries built with [Bun](https://bun.sh/) and delivers **lightning-fast builds** — up to **~50× faster than Tsup**.
6
+ Bunup is the **blazing-fast build tool** for TypeScript and JavaScript libraries, designed for beautiful developer experience and speed, **powered by Bun's native bundler** — up to **~50× faster than Tsup**.
7
7
 
8
- | Bundler | Format | Build Time | Build Time (with dts) |
9
- | ------- | -------- | -------------- | --------------------- |
10
- | bunup | esm, cjs | **3.52ms ⚡️** | **20.84ms ⚡️** |
11
- | tsdown | esm, cjs | 5.81ms | 35.84ms |
12
- | unbuild | esm, cjs | 42.47ms | 314.54ms |
13
- | tsup | esm, cjs | 63.59ms | 943.61ms |
14
-
15
- _Lower is better. Benchmarks run on identical code and output formats._
8
+ | Bundler | Format | Build Time | Build Time (with dts) |
9
+ | --------- | ------------ | -------------- | --------------------- |
10
+ | **bunup** | **esm, cjs** | **3.52ms ⚡️** | **20.84ms ⚡️** |
11
+ | tsdown | esm, cjs | 5.81ms | 35.84ms |
12
+ | unbuild | esm, cjs | 42.47ms | 314.54ms |
13
+ | tsup | esm, cjs | 63.59ms | 943.61ms |
16
14
 
17
15
  ## Key Features
18
16
 
19
- - ⚡️ **Ultra Fast Builds**: Lightning-fast performance powered by [Bun](https://bun.sh/)'s native bundler and [Oxc](https://oxc.rs).
20
-
17
+ - 🚀 **Easy to Use**: Bunup preconfigures everything you need out-of-the-box. Just focus on your code.
21
18
  - 🔥 **Bytecode Generation**: Faster startups by compiling to Bun bytecode—perfect for CLIs.
22
-
23
- - 📦 **Workspace Support**: Build multiple packages with [defineWorkspace()](https://bunup.dev/documentation/#workspaces) in one config file and command.
24
-
19
+ - 📦 **[Workspace](https://bunup.dev/workspaces) Support**: Build multiple packages within one config file and command.
25
20
  - 🔄 **Tsup Familiarity**: Familiar tsup-like CLI and config.
26
-
27
- - 🎯 **Bun Targeting**: Optimize for Bun runtime with `--target bun` for native features.
21
+ - 🎯 **Bun Target**: First-class bundling support for libraries built with Bun.
28
22
 
29
23
  ## 📚 Documentation
30
24
 
@@ -35,3 +29,4 @@ To get started, visit the [documentation](https://bunup.dev/documentation).
35
29
  For guidelines on contributing, please read the [contributing guide](https://github.com/arshad-yaseen/bunup/blob/main/CONTRIBUTING.md).
36
30
 
37
31
  We welcome contributions from the community to enhance Bunup's capabilities and make it even more powerful.
32
+ 1
package/dist/cli.mjs CHANGED
@@ -1,35 +1,21 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{createRequire as en}from"node:module";var Xe=Object.create;var{getPrototypeOf:Ve,defineProperty:se,getOwnPropertyNames:Je}=Object;var Pe=Object.prototype.hasOwnProperty;var ie=(e,n,t)=>{t=e!=null?Xe(Ve(e)):{};let r=n||!e||!e.__esModule?se(t,"default",{value:e,enumerable:!0}):t;for(let s of Je(e))if(!Pe.call(r,s))se(r,s,{get:()=>e[s],enumerable:!0});return r};var oe=en(import.meta.url);import{exec as kn}from"tinyexec";var ae=!1;function M(e){ae=e??!1}class B{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",muted:"245",info:"117",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(e){if(!e?.once)return!0;if(this.loggedOnceMessages.has(e.once))return!1;return this.loggedOnceMessages.add(e.once),!0}formatMessage({colorCode:e,label:n,message:t,size:r,identifier:s,muted:o}){let i=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-n.length)),a=o?`\x1B[38;5;${this.colors.muted}m${t}\x1B[0m`:t;if(r){let[u,...m]=a.split(" "),p=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-u.length)),f=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${n}\x1B[0m ${i}${u}${p} \x1B[38;5;${this.colors.size}m${r}\x1B[0m ${m.join(" ")}${f}`}let c=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${n}\x1B[0m ${i}${a}${c}`}output(e,n={},t=console.log){if(ae)return;if(!this.shouldLog(n))return;if(n.verticalSpace)console.log("");if(t(e),n.verticalSpace)console.log("")}cli(e,n={}){let t=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:n.identifier,muted:n.muted});this.output(t,n)}info(e,n={}){let t=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:n.identifier,muted:n.muted});this.output(t,n)}warn(e,n={}){let t=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:n.identifier,muted:n.muted});this.output(t,n,console.warn)}error(e,n={}){let t=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:n.identifier,muted:n.muted});this.output(t,n,console.error)}progress(e,n,t,r){let s=String(e),o=this.colors.default,i,a,c={};if(typeof t==="string")i=t,a=r;else if(t)i=t.size,a=t.identifier,c=t;for(let[m,p]of Object.entries(this.colors.progress))if(s.includes(m)){o=p;break}let u=this.formatMessage({colorCode:o,label:s,message:n,size:i,identifier:a,muted:c.muted});this.output(u,c)}}var l=B.getInstance();class S extends Error{constructor(e){super(e);this.name="BunupError"}}class O extends S{constructor(e){super(e);this.name="BunupBuildError"}}class g extends S{constructor(e){super(e);this.name="BunupDTSBuildError"}}class h extends S{constructor(e){super(e);this.name="BunupCLIError"}}class j extends S{constructor(e){super(e);this.name="BunupWatchError"}}var b=(e)=>{if(e instanceof Error)return e.message;return String(e)},nn=[{pattern:/Could not resolve: "bun"/i,errorType:"BUILD ERROR",logSolution:()=>{l.error("\x1B[0mYou're trying to build a project that uses Bun. Please set the target option to \x1B[36m`bun`\x1B[0m.\nExample: \x1B[32m`bunup --target bun`\x1B[0m or in config: \x1B[32m{ target: 'bun' }\x1B[0m")}}],Y=(e,n)=>{let t=b(e),r=n?`[${n}] `:"",s="ERROR";if(e instanceof O)s="BUILD ERROR";else if(e instanceof g)s="DTS ERROR";else if(e instanceof h)s="CLI ERROR";else if(e instanceof j)s="WATCH ERROR";else if(e instanceof S)s="BUNUP ERROR";let o=nn.find((i)=>i.pattern.test(t)&&(i.errorType===s||!i.errorType));if(!o)console.error(`\x1B[31m${s}\x1B[0m ${r}${t}`);if(o)console.log(`
4
- `),o.logSolution(t),console.log(`
5
- `);else console.error("\x1B[90mIf you think this is a bug, please open an issue at: \x1B[36mhttps://github.com/arshad-yaseen/bunup/issues/new\x1B[0m")},ce=(e,n)=>{Y(e,n),process.exit(1)};import ue from"node:fs/promises";import tn from"node:path";function z(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function le(e=8){let n="";while(n.length<e)n+=Math.random().toString(36).substring(2);return n.substring(0,e)}function me(e,n,t){return Array.isArray(e)?e.map((r)=>({...r,[n]:t})):{...e,[n]:t}}function fe(e){return Array.isArray(e)?e:[e]}function pe(e,n){switch(e){case"esm":return T(n)?".js":".mjs";case"cjs":return T(n)?".cjs":".js";case"iife":return".global.js"}}function de(e,n){switch(e){case"esm":return T(n)?".d.ts":".d.mts";case"cjs":return T(n)?".d.cts":".d.ts";case"iife":return".d.ts"}}function Q(e){return e==="node"||e==="bun"}function T(e){return e==="module"}function k(e){return e>=1000?`${(e/1000).toFixed(2)}s`:`${Math.round(e)}ms`}function ge(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function Z(e){if(e===0)return"0 B";let n=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(1024));if(t===0)return`${e} ${n[t]}`;return`${(e/1024**t).toFixed(2)} ${n[t]}`}function y(e,n=3){return e.split("/").slice(-n).join("/")}async function be(e,n){let t=tn.join(e,n);try{await ue.rm(t,{recursive:!0,force:!0})}catch(r){throw new O(`Failed to clean output directory: ${r}`)}await ue.mkdir(t,{recursive:!0})}function I(e){return[".ts",".mts",".cts",".tsx"].some((n)=>e.endsWith(n))}function he(e){return e.map((n)=>typeof n==="string"?new RegExp(`^${z(n)}($|\\/|\\\\)`):n)}function _(e,n){return he(e.external||[]).concat(ge(n).map((t)=>new RegExp(`^${z(t)}($|\\/|\\\\)`)))}function N(e){return he(e.noExternal||[])}import $e from"node:path";import{ResolverFactory as sn}from"oxc-resolver";import{resolveTsImportPath as rn}from"ts-import-resolver";var A="\x00dts:",xe=(e,n,t)=>{return{name:"bunup:virtual-dts",async resolveId(r,s){if(X(r))return r;if(!s||!X(s))return null;let o=n.tsconfig?rn({path:r,importer:L(s),tsconfig:n.tsconfig,rootDir:t}):null;if(!o)return null;let i=C(o);if(e.has(i))return U(i);return null},load(r){if(r.startsWith(A)){let s=L(r),o=e.get(s);if(o)return E.add(s),o}return null}}};var V=/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/;function ye(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}function J(e){return V.test(e)&&!ye(e)}function C(e){if(ye(e))return e;if(e.endsWith(".mts"))return`${e.slice(0,-4)}.d.mts`;if(e.endsWith(".cts"))return`${e.slice(0,-4)}.d.cts`;if(V.test(e))return e.replace(V,".d.ts");return`${e}.d.ts`}function we(e){if(J(e))return e;if(e.endsWith(".d.mts"))return`${e.slice(0,-6)}.mts`;if(e.endsWith(".d.cts"))return`${e.slice(0,-6)}.cts`;if(e.endsWith(".d.ts"))return`${e.slice(0,-5)}.ts`;return e}function X(e){return e.startsWith(A)}function L(e){return e.replace(A,"")}function U(e){return`${A}${e}`}function Ce(e,n,t,r){if(typeof r==="boolean"&&r)return!1;if(Array.isArray(r)){for(let s of r)if(typeof s==="string"&&e===s)return!1;else if(s instanceof RegExp&&s.test(e))return!1}return n.some((s)=>s.test(e))&&!t.some((s)=>s.test(e))}var P;function Oe(e,n){return{name:"bunup:types-resolve",buildStart(){P||=new sn({mainFields:["types","typings","module","main"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".d.mts",".d.cts",".ts",".mts",".cts"],...e.path&&{tsconfig:{configFile:e.path}},modules:["node_modules","node_modules/@types"]})},async resolveId(t,r){if(n===!1)return;if(t==="bun")return;let s=r?L(r):void 0;if(/\0/.test(t))return;if(Array.isArray(n)){if(!n.some((c)=>typeof c==="string"?c===t:c.test(t)))return}let o=s?$e.dirname(s):process.cwd(),{path:i}=await P.async(o,t);if(!i)return;if(J(i)){let a=C(i);try{let{path:c}=await P.async($e.dirname(i),a);if(c)return c}catch(c){}return}return i}}}var on=import("rolldown"),an=import("rolldown-plugin-dts");async function Be(e,n,t,r,s,o){let i=(await on).build,a=(await an).dts,c=C(e),u=U(c),m=_(t,r),p=N(t),f=typeof t.dts==="object"&&"resolve"in t.dts?t.dts.resolve:void 0;try{let{output:w}=await i({input:u,output:{dir:t.outDir},write:!1,...s.path&&{resolve:{tsconfigFilename:s.path}},onwarn($,G){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes($.code??""))return;G($)},plugins:[xe(n,s,o),f&&Oe(s,f),a({dtsInput:!0,emitDtsOnly:!0})],external:($)=>Ce($,m,p,f)});if(!w[0]?.code)return l.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return w[0].code}catch(w){throw new g(`DTS bundling failed for entry "${e}": ${b(w)}`)}}import{resolveTsImportPath as cn}from"ts-import-resolver";var un=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,ln=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,mn=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,fn=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,pn=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,dn=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,gn=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function bn(e){let n=new Set,t=[un,ln,mn,fn,pn,dn,gn];for(let r of t){let s=e.matchAll(r);for(let o of s)if(o[1])n.add(o[1])}return n}async function Se(e,n,t){let r=new Set([e]),s=[e];while(s.length){let o=s.pop();if(!o)continue;try{let i=await Bun.file(o).text(),a=bn(i);for(let c of a){let u=n.tsconfig?cn({path:c,importer:o,tsconfig:n.tsconfig,rootDir:t}):null;if(!u)continue;if(!r.has(u))r.add(u),s.push(u)}}catch(i){l.warn(`Error processing ${o}: ${b(i)}`)}}return r}import{isolatedDeclaration as hn}from"oxc-transform";async function Te(e){let n=new Map;return await Promise.all([...e].map(async(t)=>{try{let r=C(t);if(!await Bun.file(t).exists())return;let o=await Bun.file(t).text(),{code:i}=hn(t,o);if(i)n.set(r,i)}catch(r){l.warn(`Failed to generate declaration for ${t}: ${b(r)}`)}})),n}import Ee from"node:fs/promises";import ee from"node:path";import{isolatedDeclaration as xn}from"oxc-transform";async function Le(e,n){let t=ee.resolve(e),r=ee.resolve(t,n);if(!await Ee.exists(t))throw new g(`Root directory does not exist: ${t}`);if(!await Bun.file(r).exists())throw new g(`Entry file does not exist: ${r}`);if(!I(r))throw new g(`Entry file must be a TypeScript file: ${r}`);if(ee.relative(t,r).startsWith(".."))throw new g(`Entry file must be within rootDir: ${r}`);return{absoluteRootDir:t,absoluteEntry:r}}async function Ae(e){let n=!1;if(await Promise.all([...e].map(async(t)=>{try{let r=we(t),s=await Bun.file(r).text(),{errors:o}=xn(r,s);for(let i of o){if(!n)console.log(`
6
- `);let a=i.labels[0],c=a?yn(s,a.start):"",m=`${y(r)}${c}: ${wn(i.message)}`;l.warn(m),n=!0}}catch{}})),n)l.info(`You may have noticed some TypeScript warnings above related to missing type annotations. This is because Bunup uses TypeScript's "isolatedDeclarations" approach for generating declaration files. This modern approach requires explicit type annotations on exports for better, more accurate type declarations. Adding the suggested type annotations will not only silence these warnings but also improve the quality of your published type definitions, making your library more reliable for consumers.`,{muted:!0,verticalSpace:!0})}function yn(e,n){if(n===void 0)return"";let t=e.slice(0,n).split(`
7
- `),r=t.length,s=t[t.length-1].length+1;return` (${r}:${s})`}function wn(e){return e.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}async function Re(e,n,t,r,s){let{absoluteEntry:o}=await Le(e,n),i=await Se(o,r,e),a=await Te(i);return Be(o,a,t,s,r,e)}import{basename as Cn,extname as $n}from"node:path";function v(e){let n=Cn(e),t=$n(n);return t?n.slice(0,-t.length):n}function R(e,{warnOnConflict:n=!0}={}){let t=[],r=new Set,s={};function o(i,a){if(r.has(i)){let c=le(),u=`${i}_${c}`;if(n)l.warn(`Output name conflict: "${i}" is used by multiple files.
8
- Bunup uses filenames without extensions as output names by default.
9
-
10
- ${s[i]} -> ${i}.js
11
- ${a} -> ${u}.js (auto-renamed to avoid conflict)
12
-
13
- To fix this, use named entries in your configuration:
14
- {
15
- entry: {
16
- custom_name: "${s[i]}",
17
- another_name: "${a}"
18
- }
19
- }
20
-
21
- See: https://bunup.dev/documentation/#named-entries`,{muted:!0,verticalSpace:!0});t.push({name:u,path:a})}else t.push({name:i,path:a}),r.add(i),s[i]=a}if(Array.isArray(e))for(let i of e){let a=v(i);o(a,i)}else if(typeof e==="object")for(let[i,a]of Object.entries(e))o(i,a);else{let i=v(e);o(i,e)}return t}function Me(e){return e.filter((n)=>I(n.path))}function je(e,n){return`[dir]/${e}${n}`}import{loadConfig as ke}from"coffi";async function Ie(e,n){return Array.isArray(e)&&"root"in e[0]?e.map((t)=>({rootDir:t.root,options:me(t.config,"name",t.name)})):[{rootDir:n,options:e}]}async function _e(e){let{config:n,filepath:t}=await ke({name:"package",cwd:e,extensions:[".json"],maxDepth:3});return{packageJson:n,path:t}}async function Ne(e,n){let{config:t,filepath:r}=await ke({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:n,maxDepth:3});return{tsconfig:t,path:r}}var On={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function H(e){return{...On,...e}}function Ue(e){let{minify:n,minifyWhitespace:t,minifyIdentifiers:r,minifySyntax:s}=e,o=n===!0;return{whitespace:t??o,identifiers:r??o,syntax:s??o}}function ve(e,n){return n==="cjs"?e:void 0}function He(e,n,t,r){return{...typeof t==="object"&&Object.keys(t).reduce((s,o)=>{let i=JSON.stringify(t[o]);return s[`process.env.${o}`]=i,s[`import.meta.env.${o}`]=i,s},{}),...e,...r==="cjs"&&(n===!0||typeof n==="object"&&n.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function We(e,n){return e===void 0?n==="esm":e}function De(e){return typeof e==="string"?e:void 0}function qe(e,n){return{name:"bunup:external-plugin",setup(t){t.onResolve({filter:/.*/},(r)=>{let s=r.path;if(e.some((i)=>i.test(s))&&!n.some((i)=>i.test(s)))return{path:s,external:!0};return null})}}}var Bn=/\.(js|ts|jsx|tsx|mts|cts)$/,ne={dirnameFilename:{appliesTo:(e,n)=>e==="esm"&&Q(n),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
3
+ import{createRequire as Vn}from"node:module";var Qn=Object.create;var{getPrototypeOf:Zn,defineProperty:en,getOwnPropertyNames:Xn}=Object;var zn=Object.prototype.hasOwnProperty;var rn=(n,e,r)=>{r=n!=null?Qn(Zn(n)):{};let t=e||!n||!n.__esModule?en(r,"default",{value:n,enumerable:!0}):r;for(let s of Xn(n))if(!zn.call(t,s))en(t,s,{get:()=>n[s],enumerable:!0});return t};var tn=Vn(import.meta.url);import{exec as Ee}from"tinyexec";var sn=!1;function M(n){sn=n??!1}class B{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",muted:"245",info:"117",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(n){if(!n?.once)return!0;if(this.loggedOnceMessages.has(n.once))return!1;return this.loggedOnceMessages.add(n.once),!0}formatMessage({colorCode:n,label:e,message:r,size:t,identifier:s,muted:o}){let i=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-e.length)),c=o?`\x1B[38;5;${this.colors.muted}m${r}\x1B[0m`:r;if(t){let[l,...u]=c.split(" "),f=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-l.length)),d=s?` \x1B[48;5;${n};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${n}m${e}\x1B[0m ${i}${l}${f} \x1B[38;5;${this.colors.size}m${t}\x1B[0m ${u.join(" ")}${d}`}let a=s?` \x1B[48;5;${n};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${n}m${e}\x1B[0m ${i}${c}${a}`}output(n,e={},r=console.log){if(sn)return;if(!this.shouldLog(e))return;if(e.verticalSpace)console.log("");if(r(n),e.verticalSpace)console.log("")}cli(n,e={}){let r=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:n,identifier:e.identifier,muted:e.muted});this.output(r,e)}info(n,e={}){let r=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:n,identifier:e.identifier,muted:e.muted});this.output(r,e)}warn(n,e={}){let r=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:n,identifier:e.identifier,muted:e.muted});this.output(r,e,console.warn)}error(n,e={}){let r=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:n,identifier:e.identifier,muted:e.muted});this.output(r,e,console.error)}progress(n,e,r,t){let s=String(n),o=this.colors.default,i,c,a={};if(typeof r==="string")i=r,c=t;else if(r)i=r.size,c=r.identifier,a=r;for(let[u,f]of Object.entries(this.colors.progress))if(s.includes(u)){o=f;break}let l=this.formatMessage({colorCode:o,label:s,message:e,size:i,identifier:c,muted:a.muted});this.output(l,a)}}var m=B.getInstance();class $ extends Error{constructor(n){super(n);this.name="BunupError"}}class y extends ${constructor(n){super(n);this.name="BunupBuildError"}}class g extends ${constructor(n){super(n);this.name="BunupDTSBuildError"}}class h extends ${constructor(n){super(n);this.name="BunupCLIError"}}class E extends ${constructor(n){super(n);this.name="BunupWatchError"}}var b=(n)=>{if(n instanceof Error)return n.message;return String(n)},Jn=[{pattern:/Could not resolve: "bun"/i,errorType:"BUILD ERROR",logSolution:()=>{m.error("\x1B[0mYou're trying to build a project that uses Bun. Please set the target option to \x1B[36m`bun`\x1B[0m.\nExample: \x1B[32m`bunup --target bun`\x1B[0m or in config: \x1B[32m{ target: 'bun' }\x1B[0m")}}],F=(n,e)=>{let r=b(n),t=e?`[${e}] `:"",s="ERROR";if(n instanceof y)s="BUILD ERROR";else if(n instanceof g)s="DTS ERROR";else if(n instanceof h)s="CLI ERROR";else if(n instanceof E)s="WATCH ERROR";else if(n instanceof $)s="BUNUP ERROR";let o=Jn.find((i)=>i.pattern.test(r)&&(i.errorType===s||!i.errorType));if(!o)console.error(`\x1B[31m${s}\x1B[0m ${t}${r}`);if(o)console.log(`
4
+ `),o.logSolution(r),console.log(`
5
+ `);else console.error("\x1B[90mIf you think this is a bug, please open an issue at: \x1B[36mhttps://github.com/arshad-yaseen/bunup/issues/new\x1B[0m")},on=(n,e)=>{F(n,e),process.exit(1)};import wn from"node:path";import{ResolverFactory as re}from"oxc-resolver";import an from"node:fs/promises";import Pn from"node:path";function cn(n,e,r){return Array.isArray(n)?n.map((t)=>({...t,[e]:r})):{...n,[e]:r}}function ln(n){return Array.isArray(n)?n:[n]}function un(n,e){switch(n){case"esm":return O(e)?".js":".mjs";case"cjs":return O(e)?".cjs":".js";case"iife":return".global.js"}}function mn(n,e){switch(n){case"esm":return O(e)?".d.ts":".d.mts";case"cjs":return O(e)?".d.cts":".d.ts";case"iife":return".d.ts"}}function G(n){return n==="node"||n==="bun"}function O(n){return n==="module"}function I(n){return n>=1000?`${(n/1000).toFixed(2)}s`:`${Math.round(n)}ms`}function fn(n){if(!n)return[];return Array.from(new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.peerDependencies||{})]))}function K(n){if(n===0)return"0 B";let e=["B","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(1024));if(r===0)return`${n} ${e[r]}`;return`${(n/1024**r).toFixed(2)} ${e[r]}`}function C(n,e=3){return n.split("/").slice(-e).join("/")}async function dn(n,e){let r=Pn.join(n,e);try{await an.rm(r,{recursive:!0,force:!0})}catch(t){throw new y(`Failed to clean output directory: ${t}`)}await an.mkdir(r,{recursive:!0})}function R(n){return[".ts",".mts",".cts",".tsx"].some((e)=>n.endsWith(e))}function ne(n){return fn(n).map((e)=>new RegExp(`^${e}($|\\/|\\\\)`))}function pn(n,e){return typeof e==="string"?e===n:e.test(n)}function j(n,e,r){let s=ne(r).some((i)=>i.test(n))||e.external?.some((i)=>pn(n,i)),o=e.noExternal?.some((i)=>pn(n,i));return s&&!o}import{resolveTsImportPath as ee}from"ts-import-resolver";var A="\x00dts:",gn=(n,e,r)=>{return{name:"bunup:virtual-dts",async resolveId(t,s){if(Y(t))return t;if(!s||!Y(s))return null;let o=e.tsconfig?ee({path:t,importer:L(s),tsconfig:e.tsconfig,rootDir:r}):null;if(!o)return null;let i=w(o);if(n.has(i))return U(i);return null},load(t){if(t.startsWith(A)){let s=L(t),o=n.get(s);if(o)return S.add(s),o}return null}}};var N=/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/;function bn(n){return n.endsWith(".d.ts")||n.endsWith(".d.mts")||n.endsWith(".d.cts")}function Q(n){return N.test(n)&&!bn(n)}function w(n){if(bn(n))return n;if(n.endsWith(".mts"))return`${n.slice(0,-4)}.d.mts`;if(n.endsWith(".cts"))return`${n.slice(0,-4)}.d.cts`;if(N.test(n))return n.replace(N,".d.ts");return`${n}.d.ts`}function hn(n){if(Q(n))return n;if(n.endsWith(".d.mts"))return`${n.slice(0,-6)}.mts`;if(n.endsWith(".d.cts"))return`${n.slice(0,-6)}.cts`;if(n.endsWith(".d.ts"))return`${n.slice(0,-5)}.ts`;return n}function Y(n){return n.startsWith(A)}function L(n){return n.replace(A,"")}function U(n){return`${A}${n}`}function xn(n,e,r,t){if(typeof t==="boolean"&&t)return!1;if(Array.isArray(t)){for(let s of t)if(typeof s==="string"&&n===s)return!1;else if(s instanceof RegExp&&s.test(n))return!1}return j(n,e,r)}var Z;function yn(n,e){return{name:"bunup:types-resolve",buildStart(){Z||=new re({mainFields:["types","typings","module","main"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".d.mts",".d.cts",".ts",".mts",".cts"],...n.path&&{tsconfig:{configFile:n.path}},modules:["node_modules","node_modules/@types"]})},async resolveId(r,t){if(e===!1)return;if(r==="bun")return;let s=t?L(t):void 0;if(/\0/.test(r))return;if(Array.isArray(e)){if(!e.some((a)=>typeof a==="string"?a===r:a.test(r)))return}let o=s?wn.dirname(s):process.cwd(),{path:i}=await Z.async(o,r);if(!i)return;if(Q(i)){let c=w(i);try{let{path:a}=await Z.async(wn.dirname(i),c);if(a)return a}catch(a){}return}return i}}}var te=import("rolldown"),se=import("rolldown-plugin-dts");async function Cn(n,e,r,t,s,o){let i=(await te).build,c=(await se).dts,a=w(n),l=U(a),u=typeof r.dts==="object"&&"resolve"in r.dts?r.dts.resolve:void 0;try{let{output:f}=await i({input:l,output:{dir:r.outDir},write:!1,...s.path&&{resolve:{tsconfigFilename:s.path}},onwarn(d,T){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(d.code??""))return;T(d)},plugins:[gn(e,s,o),u&&yn(s,u),c({dtsInput:!0,emitDtsOnly:!0})],external:(d)=>xn(d,r,t,u)});if(!f[0]?.code)return m.warn(`Generated empty declaration file for entry "${n}"`,{muted:!0}),"";return f[0].code}catch(f){throw new g(`DTS bundling failed for entry "${n}": ${b(f)}`)}}import{resolveTsImportPath as ie}from"ts-import-resolver";var oe=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,ae=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,ce=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,le=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,ue=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,me=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,fe=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function de(n){let e=new Set,r=[oe,ae,ce,le,ue,me,fe];for(let t of r){let s=n.matchAll(t);for(let o of s)if(o[1])e.add(o[1])}return e}async function Bn(n,e,r){let t=new Set([n]),s=[n];while(s.length){let o=s.pop();if(!o)continue;try{let i=await Bun.file(o).text(),c=de(i);for(let a of c){let l=e.tsconfig?ie({path:a,importer:o,tsconfig:e.tsconfig,rootDir:r}):null;if(!l)continue;if(!t.has(l))t.add(l),s.push(l)}}catch(i){m.warn(`Error processing ${o}: ${b(i)}`)}}return t}import{isolatedDeclaration as pe}from"oxc-transform";async function $n(n){let e=new Map;return await Promise.all([...n].map(async(r)=>{try{let t=w(r);if(!await Bun.file(r).exists())return;let o=await Bun.file(r).text(),{code:i}=pe(r,o);if(i)e.set(t,i)}catch(t){m.warn(`Failed to generate declaration for ${r}: ${b(t)}`)}})),e}import On from"node:fs/promises";import X from"node:path";import{isolatedDeclaration as ge}from"oxc-transform";async function Sn(n,e){let r=X.resolve(n),t=X.resolve(r,e);if(!await On.exists(r))throw new g(`Root directory does not exist: ${r}`);if(!await Bun.file(t).exists())throw new g(`Entry file does not exist: ${t}`);if(!R(t))throw new g(`Entry file must be a TypeScript file: ${t}`);if(X.relative(r,t).startsWith(".."))throw new g(`Entry file must be within rootDir: ${t}`);return{absoluteRootDir:r,absoluteEntry:t}}async function Tn(n){let e=!1;if(await Promise.all([...n].map(async(r)=>{try{let t=hn(r),s=await Bun.file(t).text(),{errors:o}=ge(t,s);for(let i of o){if(!e)console.log(`
6
+ `);let c=i.labels[0],a=c?be(s,c.start):"",u=`${C(t)}${a}: ${he(i.message)}`;m.warn(u),e=!0}}catch{}})),e)m.info(`You may have noticed some TypeScript warnings above related to missing type annotations. This is because Bunup uses TypeScript's "isolatedDeclarations" approach for generating declaration files. This modern approach requires explicit type annotations on exports for better, more accurate type declarations. Adding the suggested type annotations will not only silence these warnings but also improve the quality of your published type definitions, making your library more reliable for consumers.`,{muted:!0,verticalSpace:!0})}function be(n,e){if(e===void 0)return"";let r=n.slice(0,e).split(`
7
+ `),t=r.length,s=r[r.length-1].length+1;return` (${t}:${s})`}function he(n){return n.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}async function Ln(n,e,r,t,s){let{absoluteEntry:o}=await Sn(n,e),i=await Bn(o,t,n),c=await $n(i);return Cn(o,c,r,s,t,n)}import{basename as xe,dirname as we,extname as ye}from"node:path";function _(n){let e=xe(n),r=ye(e);return r?e.slice(0,-r.length):e}function k(n){if(typeof n==="string")return[{fullEntryPath:n,name:_(n)}];if(typeof n==="object"&&!Array.isArray(n))return Object.entries(n).map(([t,s])=>({fullEntryPath:s,name:t}));let e=[],r=new Set;for(let t of n){let s=_(t);if(!r.has(s)){e.push({fullEntryPath:t,name:s}),r.add(s);continue}let i=we(t).split("/").filter((a)=>a!=="."&&a!=="");if(i.length===0){let a=1,l;do l=`${s}_${a++}`;while(r.has(l));e.push({fullEntryPath:t,name:l}),r.add(l);continue}let c=!1;for(let a=1;a<=i.length&&!c;a++){let u=`${i.slice(-a).join("/")}/${s}`;if(!r.has(u))e.push({fullEntryPath:t,name:u}),r.add(u),c=!0}if(!c){let a=1,l;do l=`${i.join("/")}/${s}_${a++}`;while(r.has(l));e.push({fullEntryPath:t,name:l}),r.add(l)}}return e}function An(n){return n.filter((e)=>R(e.fullEntryPath))}function kn(n,e){return`[dir]/${n}${e}`}import{loadConfig as Mn}from"coffi";async function En(n,e){return Array.isArray(n)&&"root"in n[0]?n.map((r)=>({rootDir:r.root,options:cn(r.config,"name",r.name)})):[{rootDir:e,options:n}]}async function In(n){let{config:e,filepath:r}=await Mn({name:"package",cwd:n,extensions:[".json"],maxDepth:3});return{packageJson:e,path:r}}async function Rn(n,e){let{config:r,filepath:t}=await Mn({name:"tsconfig",cwd:n,extensions:[".json"],preferredPath:e,maxDepth:3});return{tsconfig:r,path:t}}var Ce={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function D(n){return{...Ce,...n}}function jn(n){let{minify:e,minifyWhitespace:r,minifyIdentifiers:t,minifySyntax:s}=n,o=e===!0;return{whitespace:r??o,identifiers:t??o,syntax:s??o}}function Un(n,e){return e==="cjs"?n:void 0}function _n(n,e,r,t){return{...typeof r==="object"&&Object.keys(r).reduce((s,o)=>{let i=JSON.stringify(r[o]);return s[`process.env.${o}`]=i,s[`import.meta.env.${o}`]=i,s},{}),...n,...t==="cjs"&&(e===!0||typeof e==="object"&&e.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Dn(n,e){return n===void 0?e==="esm":n}function Wn(n){return typeof n==="string"?n:void 0}function Hn(n,e){return{name:"bunup:external-plugin",setup(r){r.onResolve({filter:/.*/},(t)=>{let s=t.path;if(j(s,n,e))return{path:s,external:!0};return null})}}}var Be=/\.(js|ts|jsx|tsx|mts|cts)$/,z={dirnameFilename:{appliesTo:(n,e)=>n==="esm"&&G(e),isNeededInFile:(n)=>/\b__dirname\b/.test(n)||/\b__filename\b/.test(n),generateCode:()=>`import { fileURLToPath } from 'url';
22
8
  import { dirname } from 'path';
23
9
 
24
10
  const __filename = fileURLToPath(import.meta.url);
25
11
  const __dirname = dirname(__filename);
26
12
 
27
- `},importMetaUrl:{appliesTo:(e,n)=>e==="cjs"&&Q(n),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
13
+ `},importMetaUrl:{appliesTo:(n,e)=>n==="cjs"&&G(e),isNeededInFile:(n)=>/\bimport\.meta\.url\b/.test(n),generateCode:()=>`import { pathToFileURL } from 'url';
28
14
 
29
15
  const importMetaUrl = pathToFileURL(__filename).href;
30
16
 
31
- `}};function Fe({format:e,target:n,shims:t}){let s=Sn(t).map((o)=>ne[o]).filter((o)=>o.appliesTo(e,n));if(s.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:Bn},async({path:i})=>{let a=await Bun.file(i).text(),c=s.filter((f)=>f.isNeededInFile(a));if(c.length===0)return;let{shebangLine:u,codeContent:m}=Tn(a),p=c.map((f)=>f.generateCode()).join("");return{contents:u+p+m}})}}}function Sn(e){if(e===!0)return Object.keys(ne);if(!e)return[];return Object.entries(e).filter(([n,t])=>t&&(n in ne)).map(([n])=>n)}function Tn(e){if(!e.startsWith("#!"))return{shebangLine:"",codeContent:e};let n=e.indexOf(`
32
- `);return n===-1?{shebangLine:"",codeContent:e}:{shebangLine:e.slice(0,n+1),codeContent:e.slice(n+1)}}function Ge(e){return e.filter((n)=>n.type==="bun").map((n)=>n.plugin)}var E=new Set;async function W(e,n=process.cwd()){let t=H(e);if(!t.entry||t.entry.length===0||!t.outDir)throw new O("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)be(n,t.outDir);M(t.silent);let{packageJson:r,path:s}=await _e(n);if(r&&s)l.cli(`Using package.json: ${y(s,2)}`,{muted:!0,identifier:t.name,once:`${s}:${t.name}`});let o=R(t.entry),i=r?.type,a=_(t,r),c=N(t);if(!t.dtsOnly){let u=[qe(a,c),...Ge(t.plugins??[])],m=t.format.flatMap((p)=>o.map((f)=>{return En(t,n,f,p,i,u)}));await Promise.all(m)}if(t.dts||t.dtsOnly){let u=await Ne(n,t.preferredTsconfigPath);if(u.path)l.cli(`Using tsconfig: ${y(u.path,2)}`,{muted:!0,identifier:t.name,once:`${u.path}:${t.name}`});let m=t.format.filter((f)=>{if(f==="iife"&&!T(i)&&t.format.includes("cjs"))return!1;return!0}),p=typeof t.dts==="object"&&t.dts.entry?R(t.dts.entry):Me(o);try{await Promise.all(p.map(async(f)=>{let w=await Re(n,f.path,t,u,r);await Promise.all(m.map(async($)=>{let G=t.outputExtension?.({format:$,packageType:i,options:t,entry:f}).dts??de($,i),K=`${n}/${t.outDir}/${f.name}${G}`;await Bun.write(K,w);let Ze=Bun.file(K).size||0;l.progress("DTS",y(K),Z(Ze),t.name)}))}))}catch(f){throw new g(b(f))}}if(t.onBuildSuccess)await t.onBuildSuccess(t)}async function En(e,n,t,r,s,o){let i=e.outputExtension?.({format:r,packageType:s,options:e,entry:t}).js??pe(r,s),a=await Bun.build({entrypoints:[`${n}/${t.path}`],format:r,naming:{entry:je(t.name,i)},splitting:We(e.splitting,r),bytecode:ve(e.bytecode,r),define:He(e.define,e.shims,e.env,r),minify:Ue(e),outdir:`${n}/${e.outDir}`,target:e.target,sourcemap:e.sourcemap,loader:e.loader,drop:e.drop,banner:e.banner,footer:e.footer,publicPath:e.publicPath,env:De(e.env),plugins:[...o,Fe({format:r,target:e.target,shims:e.shims})],throw:!1});if(!a.success)for(let m of a.logs){if(m.level==="error")throw new O(m.message);if(m.level==="warning")l.warn(m.message);else if(m.level==="info")l.info(m.message)}let c=`${n}/${e.outDir}/${t.name}${i}`,u=Bun.file(c).size||0;l.progress(r.toUpperCase(),y(c),Z(u),e.name)}var D="0.4.65";var Ke="https://bunup.dev/cli-options";function d(e){return(n,t)=>{t[e]=n===!0||n==="true"}}function x(e){return(n,t)=>{if(typeof n==="string")t[e]=n;else throw new h(`Option --${e} requires a string value`)}}function te(e){return(n,t)=>{if(typeof n==="string")t[e]=n.split(",");else throw new h(`Option --${e} requires a string value`)}}function An(e){return(n,t)=>{if(typeof n==="boolean")t[e]=n;else if(typeof n==="string")if(n.toLowerCase()==="true"||n.toLowerCase()==="false")t[e]=n.toLowerCase()==="true";else t[e]=n;else throw new h(`Option --${e} requires a boolean or string value`)}}function Rn(){console.log(`
17
+ `}};function vn({format:n,target:e,shims:r}){let s=$e(r).map((o)=>z[o]).filter((o)=>o.appliesTo(n,e));if(s.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:Be},async({path:i})=>{let c=await Bun.file(i).text(),a=s.filter((d)=>d.isNeededInFile(c));if(a.length===0)return;let{shebangLine:l,codeContent:u}=Oe(c),f=a.map((d)=>d.generateCode()).join("");return{contents:l+f+u}})}}}function $e(n){if(n===!0)return Object.keys(z);if(!n)return[];return Object.entries(n).filter(([e,r])=>r&&(e in z)).map(([e])=>e)}function Oe(n){if(!n.startsWith("#!"))return{shebangLine:"",codeContent:n};let e=n.indexOf(`
18
+ `);return e===-1?{shebangLine:"",codeContent:n}:{shebangLine:n.slice(0,e+1),codeContent:n.slice(e+1)}}function qn(n){return n.filter((e)=>e.type==="bun").map((e)=>e.plugin)}var S=new Set;async function W(n,e=process.cwd()){let r=D(n);if(!r.entry||r.entry.length===0||!r.outDir)throw new y("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(r.clean)dn(e,r.outDir);M(r.silent);let{packageJson:t,path:s}=await In(e);if(t&&s)m.cli(`Using package.json: ${C(s,2)}`,{muted:!0,identifier:r.name,once:`${s}:${r.name}`});let o=k(r.entry),i=t?.type;if(!r.dtsOnly){let c=[Hn(r,t),...qn(r.plugins??[])],a=r.format.flatMap((l)=>o.map((u)=>{return Se(r,e,u,l,i,c)}));await Promise.all(a)}if(r.dts||r.dtsOnly){let c=await Rn(e,r.preferredTsconfigPath);if(c.path)m.cli(`Using tsconfig: ${C(c.path,2)}`,{muted:!0,identifier:r.name,once:`${c.path}:${r.name}`});let a=r.format.filter((u)=>{if(u==="iife"&&!O(i)&&r.format.includes("cjs"))return!1;return!0}),l=typeof r.dts==="object"&&r.dts.entry?k(r.dts.entry):An(o);try{await Promise.all(l.map(async(u)=>{let f=await Ln(e,u.fullEntryPath,r,c,t);await Promise.all(a.map(async(d)=>{let T=r.outputExtension?.({format:d,packageType:i,options:r,entry:u}).dts??mn(d,i),P=`${r.outDir}/${u.name}${T}`,nn=`${e}/${P}`;await Bun.write(nn,f);let Nn=Bun.file(nn).size||0;m.progress("DTS",P,K(Nn),r.name)}))}))}catch(u){throw new g(b(u))}}if(r.onBuildSuccess)await r.onBuildSuccess(r)}async function Se(n,e,r,t,s,o){let i=n.outputExtension?.({format:t,packageType:s,options:n,entry:r}).js??un(t,s),c=await Bun.build({entrypoints:[`${e}/${r.fullEntryPath}`],format:t,naming:{entry:kn(r.name,i)},splitting:Dn(n.splitting,t),bytecode:Un(n.bytecode,t),define:_n(n.define,n.shims,n.env,t),minify:jn(n),outdir:`${e}/${n.outDir}`,target:n.target,sourcemap:n.sourcemap,loader:n.loader,drop:n.drop,banner:n.banner,footer:n.footer,publicPath:n.publicPath,env:Wn(n.env),plugins:[...o,vn({format:t,target:n.target,shims:n.shims})],throw:!1});if(!c.success)for(let f of c.logs){if(f.level==="error")throw new y(f.message);if(f.level==="warning")m.warn(f.message);else if(f.level==="info")m.info(f.message)}let a=`${n.outDir}/${r.name}${i}`,l=`${e}/${a}`,u=Bun.file(l).size||0;m.progress(t.toUpperCase(),a,K(u),n.name)}var H="0.4.67";var Fn="https://bunup.dev/cli-options";function p(n){return(e,r)=>{r[n]=e===!0||e==="true"}}function x(n){return(e,r)=>{if(typeof e==="string")r[n]=e;else throw new h(`Option --${n} requires a string value`)}}function V(n){return(e,r)=>{if(typeof e==="string")r[n]=e.split(",");else throw new h(`Option --${n} requires a string value`)}}function Le(n){return(e,r)=>{if(typeof e==="boolean")r[n]=e;else if(typeof e==="string")if(e.toLowerCase()==="true"||e.toLowerCase()==="false")r[n]=e.toLowerCase()==="true";else r[n]=e;else throw new h(`Option --${n} requires a boolean or string value`)}}function Ae(){console.log(`
33
19
  Bunup - A blazing-fast build tool for your libraries built with Bun.
34
- `),console.log("For more information on available options, visit:"),console.log(`\x1B[36m\x1B[4m${Ke}\x1B[0m
35
- `),process.exit(0)}function Mn(){console.log(D),process.exit(0)}var Ye={name:{flags:["n","name"],handler:x("name")},format:{flags:["f","format"],handler:te("format")},outDir:{flags:["o","out-dir"],handler:x("outDir")},minify:{flags:["m","minify"],handler:d("minify")},watch:{flags:["w","watch"],handler:d("watch")},dts:{flags:["d","dts"],handler:d("dts")},banner:{flags:["bn","banner"],handler:x("banner")},footer:{flags:["ft","footer"],handler:x("footer")},external:{flags:["e","external"],handler:te("external")},sourcemap:{flags:["sm","sourcemap"],handler:An("sourcemap")},target:{flags:["t","target"],handler:x("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:d("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:d("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:d("minifySyntax")},clean:{flags:["c","clean"],handler:d("clean")},splitting:{flags:["s","splitting"],handler:d("splitting")},noExternal:{flags:["ne","no-external"],handler:te("noExternal")},preferredTsconfigPath:{flags:["tsconfig","preferred-tsconfig-path"],handler:x("preferredTsconfigPath")},bytecode:{flags:["bc","bytecode"],handler:d("bytecode")},dtsOnly:{flags:["do","dts-only"],handler:d("dtsOnly")},silent:{flags:["silent"],handler:d("silent")},config:{flags:["config"],handler:x("config")},publicPath:{flags:["pp","public-path"],handler:x("publicPath")},env:{flags:["env"],handler:x("env")},shims:{flags:["shims"],handler:d("shims")},onSuccess:{flags:["onSuccess"],handler:x("onSuccess")},entry:{flags:["entry"],handler:(e,n,t)=>{if(typeof e!=="string")throw new h(`Entry${t?` --entry.${t}`:""} requires a string value`);let r=n.entry||{};if(t){if(r[t])l.warn(`Duplicate entry name '${t}' provided via --entry.${t}. Overwriting previous entry.`);r[t]=e}else{let s=v(e);if(r[s])l.warn(`Duplicate entry name '${s}' derived from '${e}'. Overwriting previous entry.`);r[s]=e}n.entry=r}},resolveDts:{flags:["rd","resolve-dts"],handler:(e,n)=>{if(!n.dts)n.dts={};if(typeof n.dts==="boolean")n.dts={};if(typeof e==="string")if(e==="true"||e==="false")n.dts.resolve=e==="true";else n.dts.resolve=e.split(",");else n.dts.resolve=!0}},help:{flags:["h","help"],handler:()=>Rn()},version:{flags:["v","version"],handler:()=>Mn()}},q={};for(let e of Object.values(Ye))for(let n of e.flags)q[n]=e.handler;function ze(e){let n={};for(let t=0;t<e.length;t++){let r=e[t];if(r.startsWith("--")){let s,o;if(r.includes("=")){let[i,a]=r.slice(2).split("=",2);s=i,o=a}else{s=r.slice(2);let i=e[t+1];if(o=i&&!i.startsWith("-")?i:!0,typeof o==="string")t++}if(s.includes(".")){let[i,a]=s.split(".",2),c=q[i];if(c)c(o,n,a);else throw new h(`Unknown option: --${s}`)}else{let i=q[s];if(i)i(o,n);else throw new h(`Unknown option: --${s}`)}}else if(r.startsWith("-")){let s=r.slice(1),o=e[t+1],i=o&&!o.startsWith("-")?o:!0;if(typeof i==="string")t++;let a=q[s];if(a)a(i,n);else throw new h(`Unknown option: -${s}`)}else Ye.entry.handler(r,n,void 0)}return n}import{loadConfig as In}from"coffi";import F from"node:path";import jn from"chokidar";async function Qe(e,n){let t=new Set,r=H(e),s=R(r.entry);for(let c of s){let u=F.resolve(n,c.path),m=F.dirname(u);t.add(m)}let o=jn.watch(Array.from(t),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignoreInitial:!0,atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,F.join(n,r.outDir)]}),i=!1,a=async(c=!1)=>{if(i)return;i=!0;try{let u=performance.now();if(await W({...r,entry:s.map((m)=>m.path),clean:!1},n),!c)l.cli(`\uD83D\uDCE6 Rebuild finished in ${k(performance.now()-u)}`);await re()}catch(u){Y(u)}finally{i=!1}};o.on("change",(c)=>{let u=F.relative(n,c);l.cli(`File changed: ${u}`,{muted:!0,once:u}),a()}),o.on("error",(c)=>{throw new j(`Watcher error: ${b(c)}`)}),await a(!0)}async function _n(e=Bun.argv.slice(2)){let n=ze(e);M(n.silent);let t=process.cwd(),{config:r,filepath:s}=await In({name:"bunup.config",extensions:[".ts",".js",".mjs",".cjs"],maxDepth:1,preferredPath:n.config,packageJsonProperty:"bunup"}),o=!r?[{rootDir:t,options:n}]:await Ie(r,t);if(l.cli(`Using bunup v${D} and bun v${Bun.version}`,{muted:!0}),s)l.cli(`Using config file: ${y(s,2)}`,{muted:!0});let i=performance.now();l.cli("Build started"),await Promise.all(o.flatMap(({options:u,rootDir:m})=>{return fe(u).map(async(f)=>{let w={...f,...Nn(n)};return Un(w,m)})}));let a=performance.now()-i,c=k(a);if(l.cli(`\u26A1\uFE0F Build completed in ${c}`),await re(),n.watch)l.cli("\uD83D\uDC40 Watching for file changes");if(n.onSuccess)l.cli(`Running command: ${n.onSuccess}`,{muted:!0}),kn(n.onSuccess,[],{nodeOptions:{shell:!0,stdio:"inherit"}});if(!n.watch)process.exit(0)}function Nn(e){return{...e,onSuccess:void 0,config:void 0}}async function re(){if(E.size>0)await Ae(E),E.clear()}async function Un(e,n){if(e.watch)await Qe(e,n);else await W(e,n)}_n().catch((e)=>ce(e));export{re as validateDtsFiles};
20
+ `),console.log("For more information on available options, visit:"),console.log(`\x1B[36m\x1B[4m${Fn}\x1B[0m
21
+ `),process.exit(0)}function ke(){console.log(H),process.exit(0)}var Gn={name:{flags:["n","name"],handler:x("name")},format:{flags:["f","format"],handler:V("format")},outDir:{flags:["o","out-dir"],handler:x("outDir")},minify:{flags:["m","minify"],handler:p("minify")},watch:{flags:["w","watch"],handler:p("watch")},dts:{flags:["d","dts"],handler:p("dts")},banner:{flags:["bn","banner"],handler:x("banner")},footer:{flags:["ft","footer"],handler:x("footer")},external:{flags:["e","external"],handler:V("external")},sourcemap:{flags:["sm","sourcemap"],handler:Le("sourcemap")},target:{flags:["t","target"],handler:x("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:p("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:p("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:p("minifySyntax")},clean:{flags:["c","clean"],handler:p("clean")},splitting:{flags:["s","splitting"],handler:p("splitting")},noExternal:{flags:["ne","no-external"],handler:V("noExternal")},preferredTsconfigPath:{flags:["tsconfig","preferred-tsconfig-path"],handler:x("preferredTsconfigPath")},bytecode:{flags:["bc","bytecode"],handler:p("bytecode")},dtsOnly:{flags:["do","dts-only"],handler:p("dtsOnly")},silent:{flags:["silent"],handler:p("silent")},config:{flags:["config"],handler:x("config")},publicPath:{flags:["pp","public-path"],handler:x("publicPath")},env:{flags:["env"],handler:x("env")},shims:{flags:["shims"],handler:p("shims")},onSuccess:{flags:["onSuccess"],handler:x("onSuccess")},entry:{flags:["entry"],handler:(n,e,r)=>{if(typeof n!=="string")throw new h(`Entry${r?` --entry.${r}`:""} requires a string value`);let t=e.entry||{};if(r){if(t[r])m.warn(`Duplicate entry name '${r}' provided via --entry.${r}. Overwriting previous entry.`);t[r]=n}else{let s=_(n);if(t[s])m.warn(`Duplicate entry name '${s}' derived from '${n}'. Overwriting previous entry.`);t[s]=n}e.entry=t}},resolveDts:{flags:["rd","resolve-dts"],handler:(n,e)=>{if(!e.dts)e.dts={};if(typeof e.dts==="boolean")e.dts={};if(typeof n==="string")if(n==="true"||n==="false")e.dts.resolve=n==="true";else e.dts.resolve=n.split(",");else e.dts.resolve=!0}},help:{flags:["h","help"],handler:()=>Ae()},version:{flags:["v","version"],handler:()=>ke()}},v={};for(let n of Object.values(Gn))for(let e of n.flags)v[e]=n.handler;function Kn(n){let e={};for(let r=0;r<n.length;r++){let t=n[r];if(t.startsWith("--")){let s,o;if(t.includes("=")){let[i,c]=t.slice(2).split("=",2);s=i,o=c}else{s=t.slice(2);let i=n[r+1];if(o=i&&!i.startsWith("-")?i:!0,typeof o==="string")r++}if(s.includes(".")){let[i,c]=s.split(".",2),a=v[i];if(a)a(o,e,c);else throw new h(`Unknown option: --${s}`)}else{let i=v[s];if(i)i(o,e);else throw new h(`Unknown option: --${s}`)}}else if(t.startsWith("-")){let s=t.slice(1),o=n[r+1],i=o&&!o.startsWith("-")?o:!0;if(typeof i==="string")r++;let c=v[s];if(c)c(i,e);else throw new h(`Unknown option: -${s}`)}else Gn.entry.handler(t,e,void 0)}return e}import{loadConfig as Ie}from"coffi";import q from"node:path";import Me from"chokidar";async function Yn(n,e){let r=new Set,t=D(n),s=k(t.entry);for(let a of s){let l=q.resolve(e,a.fullEntryPath),u=q.dirname(l);r.add(u)}let o=Me.watch(Array.from(r),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignoreInitial:!0,atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,q.join(e,t.outDir)]}),i=!1,c=async(a=!1)=>{if(i)return;i=!0;try{let l=performance.now();if(await W({...t,entry:s.map((u)=>u.fullEntryPath),clean:!1},e),!a)m.cli(`\uD83D\uDCE6 Rebuild finished in ${I(performance.now()-l)}`);await J()}catch(l){F(l)}finally{i=!1}};o.on("change",(a)=>{let l=q.relative(e,a);m.cli(`File changed: ${l}`,{muted:!0,once:l}),c()}),o.on("error",(a)=>{throw new E(`Watcher error: ${b(a)}`)}),await c(!0)}async function Re(n=Bun.argv.slice(2)){let e=Kn(n);M(e.silent);let r=process.cwd(),{config:t,filepath:s}=await Ie({name:"bunup.config",extensions:[".ts",".js",".mjs",".cjs"],maxDepth:1,preferredPath:e.config,packageJsonProperty:"bunup"}),o=!t?[{rootDir:r,options:e}]:await En(t,r);if(m.cli(`Using bunup v${H} and bun v${Bun.version}`,{muted:!0}),s)m.cli(`Using config file: ${C(s,2)}`,{muted:!0});let i=performance.now();m.cli("Build started"),await Promise.all(o.flatMap(({options:l,rootDir:u})=>{return ln(l).map(async(d)=>{let T={...d,...je(e)};return Ue(T,u)})}));let c=performance.now()-i,a=I(c);if(m.cli(`\u26A1\uFE0F Build completed in ${a}`),await J(),e.watch)m.cli("\uD83D\uDC40 Watching for file changes");if(e.onSuccess)m.cli(`Running command: ${e.onSuccess}`,{muted:!0}),await Ee(e.onSuccess,[],{nodeOptions:{shell:!0,stdio:"inherit"}});if(!e.watch)process.exit(0)}function je(n){return{...n,onSuccess:void 0,config:void 0}}async function J(){if(S.size>0)await Tn(S),S.clear()}async function Ue(n,e){if(n.watch)await Yn(n,e);else await W(n,e)}Re().catch((n)=>on(n));export{J as validateDtsFiles};
package/dist/index.d.mts CHANGED
@@ -2,8 +2,8 @@ import _Bun from "bun";
2
2
 
3
3
  //#region \0dts:/home/runner/work/bunup/bunup/src/helpers/entry.d.ts
4
4
  type ProcessableEntry = {
5
+ fullEntryPath: string
5
6
  name: string
6
- path: string
7
7
  };
8
8
 
9
9
  //#endregion
@@ -61,6 +61,9 @@ type DtsOptions = {
61
61
  *
62
62
  * // Using named outputs as an object
63
63
  * entry: { myModule: 'src/index.ts', utils: 'src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
64
+ *
65
+ * // Organizing output with subdirectories
66
+ * entry: { "client/index": "src/client/index.ts", "server/index": "src/server/index.ts" } // Generates client/index.d.ts and server/index.d.ts
64
67
  */
65
68
  entry?: Entry
66
69
  /**
package/dist/index.d.ts CHANGED
@@ -2,8 +2,8 @@ import _Bun from "bun";
2
2
 
3
3
  //#region \0dts:/home/runner/work/bunup/bunup/src/helpers/entry.d.ts
4
4
  type ProcessableEntry = {
5
+ fullEntryPath: string
5
6
  name: string
6
- path: string
7
7
  };
8
8
 
9
9
  //#endregion
@@ -61,6 +61,9 @@ type DtsOptions = {
61
61
  *
62
62
  * // Using named outputs as an object
63
63
  * entry: { myModule: 'src/index.ts', utils: 'src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
64
+ *
65
+ * // Organizing output with subdirectories
66
+ * entry: { "client/index": "src/client/index.ts", "server/index": "src/server/index.ts" } // Generates client/index.d.ts and server/index.d.ts
64
67
  */
65
68
  entry?: Entry
66
69
  /**
package/dist/index.js CHANGED
@@ -1,26 +1,12 @@
1
- var Ke=require("node:module");var Ue=Object.create;var{getPrototypeOf:qe,defineProperty:B,getOwnPropertyNames:X,getOwnPropertyDescriptor:He}=Object,V=Object.prototype.hasOwnProperty;var h=(e,r,n)=>{n=e!=null?Ue(qe(e)):{};let t=r||!e||!e.__esModule?B(n,"default",{value:e,enumerable:!0}):n;for(let s of X(e))if(!V.call(t,s))B(t,s,{get:()=>e[s],enumerable:!0});return t},z=new WeakMap,Fe=(e)=>{var r=z.get(e),n;if(r)return r;if(r=B({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function")X(e).map((t)=>!V.call(r,t)&&B(r,t,{get:()=>e[t],enumerable:!(n=He(e,t))||n.enumerable}));return z.set(e,r),r};var Ge=(e,r)=>{for(var n in r)B(e,n,{get:r[n],enumerable:!0,configurable:!0,set:(t)=>r[n]=()=>t})};var ar={};Ge(ar,{defineWorkspace:()=>v,defineConfig:()=>J,build:()=>We});module.exports=Fe(ar);function J(e){return e}function v(e){return e}var P=!1;function ee(e){P=e??!1}class w{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",muted:"245",info:"117",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!w.instance)w.instance=new w;return w.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(e){if(!e?.once)return!0;if(this.loggedOnceMessages.has(e.once))return!1;return this.loggedOnceMessages.add(e.once),!0}formatMessage({colorCode:e,label:r,message:n,size:t,identifier:s,muted:i}){let o=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length)),a=i?`\x1B[38;5;${this.colors.muted}m${n}\x1B[0m`:n;if(t){let[c,...g]=a.split(" "),p=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),m=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${o}${c}${p} \x1B[38;5;${this.colors.size}m${t}\x1B[0m ${g.join(" ")}${m}`}let u=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${o}${a}${u}`}output(e,r={},n=console.log){if(P)return;if(!this.shouldLog(r))return;if(r.verticalSpace)console.log("");if(n(e),r.verticalSpace)console.log("")}cli(e,r={}){let n=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:r.identifier,muted:r.muted});this.output(n,r)}info(e,r={}){let n=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:r.identifier,muted:r.muted});this.output(n,r)}warn(e,r={}){let n=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:r.identifier,muted:r.muted});this.output(n,r,console.warn)}error(e,r={}){let n=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:r.identifier,muted:r.muted});this.output(n,r,console.error)}progress(e,r,n,t){let s=String(e),i=this.colors.default,o,a,u={};if(typeof n==="string")o=n,a=t;else if(n)o=n.size,a=n.identifier,u=n;for(let[g,p]of Object.entries(this.colors.progress))if(s.includes(g)){i=p;break}let c=this.formatMessage({colorCode:i,label:s,message:r,size:o,identifier:a,muted:u.muted});this.output(c,u)}}var f=w.getInstance();class _ extends Error{constructor(e){super(e);this.name="BunupError"}}class C extends _{constructor(e){super(e);this.name="BunupBuildError"}}class l extends _{constructor(e){super(e);this.name="BunupDTSBuildError"}}var d=(e)=>{if(e instanceof Error)return e.message;return String(e)};var D=h(require("node:fs/promises")),re=h(require("node:path"));function W(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ne(e=8){let r="";while(r.length<e)r+=Math.random().toString(36).substring(2);return r.substring(0,e)}function te(e,r){switch(e){case"esm":return $(r)?".js":".mjs";case"cjs":return $(r)?".cjs":".js";case"iife":return".global.js"}}function se(e,r){switch(e){case"esm":return $(r)?".d.ts":".d.mts";case"cjs":return $(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function k(e){return e==="node"||e==="bun"}function $(e){return e==="module"}function oe(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function U(e){if(e===0)return"0 B";let r=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(1024));if(n===0)return`${e} ${r[n]}`;return`${(e/1024**n).toFixed(2)} ${r[n]}`}function E(e,r=3){return e.split("/").slice(-r).join("/")}async function ie(e,r){let n=re.default.join(e,r);try{await D.default.rm(n,{recursive:!0,force:!0})}catch(t){throw new C(`Failed to clean output directory: ${t}`)}await D.default.mkdir(n,{recursive:!0})}function R(e){return[".ts",".mts",".cts",".tsx"].some((r)=>e.endsWith(r))}function ae(e){return e.map((r)=>typeof r==="string"?new RegExp(`^${W(r)}($|\\/|\\\\)`):r)}function O(e,r){return ae(e.external||[]).concat(oe(r).map((n)=>new RegExp(`^${W(n)}($|\\/|\\\\)`)))}function L(e){return ae(e.noExternal||[])}var G=h(require("node:path")),le=require("oxc-resolver");var ue=require("ts-import-resolver");var T="\x00dts:",ce=(e,r,n)=>{return{name:"bunup:virtual-dts",async resolveId(t,s){if(q(t))return t;if(!s||!q(s))return null;let i=r.tsconfig?ue.resolveTsImportPath({path:t,importer:S(s),tsconfig:r.tsconfig,rootDir:n}):null;if(!i)return null;let o=x(i);if(e.has(o))return M(o);return null},load(t){if(t.startsWith(T)){let s=S(t),i=e.get(s);if(i)return me.add(s),i}return null}}};var H=/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/;function ge(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}function fe(e){return H.test(e)&&!ge(e)}function x(e){if(ge(e))return e;if(e.endsWith(".mts"))return`${e.slice(0,-4)}.d.mts`;if(e.endsWith(".cts"))return`${e.slice(0,-4)}.d.cts`;if(H.test(e))return e.replace(H,".d.ts");return`${e}.d.ts`}function q(e){return e.startsWith(T)}function S(e){return e.replace(T,"")}function M(e){return`${T}${e}`}function pe(e,r,n,t){if(typeof t==="boolean"&&t)return!1;if(Array.isArray(t)){for(let s of t)if(typeof s==="string"&&e===s)return!1;else if(s instanceof RegExp&&s.test(e))return!1}return r.some((s)=>s.test(e))&&!n.some((s)=>s.test(e))}var F;function de(e,r){return{name:"bunup:types-resolve",buildStart(){F||=new le.ResolverFactory({mainFields:["types","typings","module","main"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".d.mts",".d.cts",".ts",".mts",".cts"],...e.path&&{tsconfig:{configFile:e.path}},modules:["node_modules","node_modules/@types"]})},async resolveId(n,t){if(r===!1)return;if(n==="bun")return;let s=t?S(t):void 0;if(/\0/.test(n))return;if(Array.isArray(r)){if(!r.some((u)=>typeof u==="string"?u===n:u.test(n)))return}let i=s?G.default.dirname(s):process.cwd(),{path:o}=await F.async(i,n);if(!o)return;if(fe(o)){let a=x(o);try{let{path:u}=await F.async(G.default.dirname(o),a);if(u)return u}catch(u){}return}return o}}}var Ye=import("rolldown"),Qe=import("rolldown-plugin-dts");async function xe(e,r,n,t,s,i){let o=(await Ye).build,a=(await Qe).dts,u=x(e),c=M(u),g=O(n,t),p=L(n),m=typeof n.dts==="object"&&"resolve"in n.dts?n.dts.resolve:void 0;try{let{output:y}=await o({input:c,output:{dir:n.outDir},write:!1,...s.path&&{resolve:{tsconfigFilename:s.path}},onwarn(b,j){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(b.code??""))return;j(b)},plugins:[ce(r,s,i),m&&de(s,m),a({dtsInput:!0,emitDtsOnly:!0})],external:(b)=>pe(b,g,p,m)});if(!y[0]?.code)return f.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return y[0].code}catch(y){throw new l(`DTS bundling failed for entry "${e}": ${d(y)}`)}}var be=require("ts-import-resolver");var Ze=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,ze=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Xe=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ve=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Je=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,ve=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Pe=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function er(e){let r=new Set,n=[Ze,ze,Xe,Ve,Je,ve,Pe];for(let t of n){let s=e.matchAll(t);for(let i of s)if(i[1])r.add(i[1])}return r}async function he(e,r,n){let t=new Set([e]),s=[e];while(s.length){let i=s.pop();if(!i)continue;try{let o=await Bun.file(i).text(),a=er(o);for(let u of a){let c=r.tsconfig?be.resolveTsImportPath({path:u,importer:i,tsconfig:r.tsconfig,rootDir:n}):null;if(!c)continue;if(!t.has(c))t.add(c),s.push(c)}}catch(o){f.warn(`Error processing ${i}: ${d(o)}`)}}return t}var ye=require("oxc-transform");async function we(e){let r=new Map;return await Promise.all([...e].map(async(n)=>{try{let t=x(n);if(!await Bun.file(n).exists())return;let i=await Bun.file(n).text(),{code:o}=ye.isolatedDeclaration(n,i);if(o)r.set(t,o)}catch(t){f.warn(`Failed to generate declaration for ${n}: ${d(t)}`)}})),r}var K=h(require("node:fs/promises")),A=h(require("node:path")),rr=require("oxc-transform");async function Ce(e,r){let n=A.default.resolve(e),t=A.default.resolve(n,r);if(!await K.default.exists(n))throw new l(`Root directory does not exist: ${n}`);if(!await Bun.file(t).exists())throw new l(`Entry file does not exist: ${t}`);if(!R(t))throw new l(`Entry file must be a TypeScript file: ${t}`);if(A.default.relative(n,t).startsWith(".."))throw new l(`Entry file must be within rootDir: ${t}`);return{absoluteRootDir:n,absoluteEntry:t}}async function $e(e,r,n,t,s){let{absoluteEntry:i}=await Ce(e,r),o=await he(i,t,e),a=await we(o);return xe(i,a,n,s,t,e)}var I=require("node:path");function Ee(e){let r=I.basename(e),n=I.extname(r);return n?r.slice(0,-n.length):r}function Y(e,{warnOnConflict:r=!0}={}){let n=[],t=new Set,s={};function i(o,a){if(t.has(o)){let u=ne(),c=`${o}_${u}`;if(r)f.warn(`Output name conflict: "${o}" is used by multiple files.
2
- Bunup uses filenames without extensions as output names by default.
3
-
4
- ${s[o]} -> ${o}.js
5
- ${a} -> ${c}.js (auto-renamed to avoid conflict)
6
-
7
- To fix this, use named entries in your configuration:
8
- {
9
- entry: {
10
- custom_name: "${s[o]}",
11
- another_name: "${a}"
12
- }
13
- }
14
-
15
- See: https://bunup.dev/documentation/#named-entries`,{muted:!0,verticalSpace:!0});n.push({name:c,path:a})}else n.push({name:o,path:a}),t.add(o),s[o]=a}if(Array.isArray(e))for(let o of e){let a=Ee(o);i(a,o)}else if(typeof e==="object")for(let[o,a]of Object.entries(e))i(o,a);else{let o=Ee(e);i(o,e)}return n}function Be(e){return e.filter((r)=>R(r.path))}function Se(e,r){return`[dir]/${e}${r}`}var Q=require("coffi");async function Te(e){let{config:r,filepath:n}=await Q.loadConfig({name:"package",cwd:e,extensions:[".json"],maxDepth:3});return{packageJson:r,path:n}}async function Re(e,r){let{config:n,filepath:t}=await Q.loadConfig({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:r,maxDepth:3});return{tsconfig:n,path:t}}var nr={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function Oe(e){return{...nr,...e}}function Le(e){let{minify:r,minifyWhitespace:n,minifyIdentifiers:t,minifySyntax:s}=e,i=r===!0;return{whitespace:n??i,identifiers:t??i,syntax:s??i}}function Me(e,r){return r==="cjs"?e:void 0}function Ae(e,r,n,t){return{...typeof n==="object"&&Object.keys(n).reduce((s,i)=>{let o=JSON.stringify(n[i]);return s[`process.env.${i}`]=o,s[`import.meta.env.${i}`]=o,s},{}),...e,...t==="cjs"&&(r===!0||typeof r==="object"&&r.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Ie(e,r){return e===void 0?r==="esm":e}function je(e){return typeof e==="string"?e:void 0}function Ne(e,r){return{name:"bunup:external-plugin",setup(n){n.onResolve({filter:/.*/},(t)=>{let s=t.path;if(e.some((o)=>o.test(s))&&!r.some((o)=>o.test(s)))return{path:s,external:!0};return null})}}}var tr=/\.(js|ts|jsx|tsx|mts|cts)$/,Z={dirnameFilename:{appliesTo:(e,r)=>e==="esm"&&k(r),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
1
+ var Fr=require("node:module");var kr=Object.create;var{getPrototypeOf:Wr,defineProperty:$,getOwnPropertyNames:Z,getOwnPropertyDescriptor:_r}=Object,X=Object.prototype.hasOwnProperty;var b=(r,n,e)=>{e=r!=null?kr(Wr(r)):{};let t=n||!r||!r.__esModule?$(e,"default",{value:r,enumerable:!0}):e;for(let o of Z(r))if(!X.call(t,o))$(t,o,{get:()=>r[o],enumerable:!0});return t},Q=new WeakMap,Ur=(r)=>{var n=Q.get(r),e;if(n)return n;if(n=$({},"__esModule",{value:!0}),r&&typeof r==="object"||typeof r==="function")Z(r).map((t)=>!X.call(n,t)&&$(n,t,{get:()=>r[t],enumerable:!(e=_r(r,t))||e.enumerable}));return Q.set(r,n),n};var qr=(r,n)=>{for(var e in n)$(r,e,{get:n[e],enumerable:!0,configurable:!0,set:(t)=>n[e]=()=>t})};var on={};qr(on,{defineWorkspace:()=>z,defineConfig:()=>N,build:()=>Or});module.exports=Ur(on);function N(r){return r}function z(r){return r}var V=!1;function J(r){V=r??!1}class C{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",muted:"245",info:"117",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!C.instance)C.instance=new C;return C.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(r){if(!r?.once)return!0;if(this.loggedOnceMessages.has(r.once))return!1;return this.loggedOnceMessages.add(r.once),!0}formatMessage({colorCode:r,label:n,message:e,size:t,identifier:o,muted:i}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-n.length)),u=i?`\x1B[38;5;${this.colors.muted}m${e}\x1B[0m`:e;if(t){let[a,...m]=u.split(" "),g=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-a.length)),l=o?` \x1B[48;5;${r};38;5;0m ${o} \x1B[0m`:"";return`\x1B[38;5;${r}m${n}\x1B[0m ${s}${a}${g} \x1B[38;5;${this.colors.size}m${t}\x1B[0m ${m.join(" ")}${l}`}let c=o?` \x1B[48;5;${r};38;5;0m ${o} \x1B[0m`:"";return`\x1B[38;5;${r}m${n}\x1B[0m ${s}${u}${c}`}output(r,n={},e=console.log){if(V)return;if(!this.shouldLog(n))return;if(n.verticalSpace)console.log("");if(e(r),n.verticalSpace)console.log("")}cli(r,n={}){let e=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n)}info(r,n={}){let e=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n)}warn(r,n={}){let e=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n,console.warn)}error(r,n={}){let e=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n,console.error)}progress(r,n,e,t){let o=String(r),i=this.colors.default,s,u,c={};if(typeof e==="string")s=e,u=t;else if(e)s=e.size,u=e.identifier,c=e;for(let[m,g]of Object.entries(this.colors.progress))if(o.includes(m)){i=g;break}let a=this.formatMessage({colorCode:i,label:o,message:n,size:s,identifier:u,muted:c.muted});this.output(a,c)}}var f=C.getInstance();class y extends Error{constructor(r){super(r);this.name="BunupError"}}class w extends y{constructor(r){super(r);this.name="BunupBuildError"}}class p extends y{constructor(r){super(r);this.name="BunupDTSBuildError"}}var d=(r)=>{if(r instanceof Error)return r.message;return String(r)};var U=b(require("node:path")),mr=require("oxc-resolver");var j=b(require("node:fs/promises")),v=b(require("node:path"));function P(r,n){switch(r){case"esm":return B(n)?".js":".mjs";case"cjs":return B(n)?".cjs":".js";case"iife":return".global.js"}}function rr(r,n){switch(r){case"esm":return B(n)?".d.ts":".d.mts";case"cjs":return B(n)?".d.cts":".d.ts";case"iife":return".d.ts"}}function O(r){return r==="node"||r==="bun"}function B(r){return r==="module"}function nr(r){if(!r)return[];return Array.from(new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.peerDependencies||{})]))}function D(r){if(r===0)return"0 B";let n=["B","KB","MB","GB"],e=Math.floor(Math.log(r)/Math.log(1024));if(e===0)return`${r} ${n[e]}`;return`${(r/1024**e).toFixed(2)} ${n[e]}`}function L(r,n=3){return r.split("/").slice(-n).join("/")}async function er(r,n){let e=v.default.join(r,n);try{await j.default.rm(e,{recursive:!0,force:!0})}catch(t){throw new w(`Failed to clean output directory: ${t}`)}await j.default.mkdir(e,{recursive:!0})}function E(r){return[".ts",".mts",".cts",".tsx"].some((n)=>r.endsWith(n))}function Gr(r){return nr(r).map((n)=>new RegExp(`^${n}($|\\/|\\\\)`))}function tr(r,n){return typeof n==="string"?n===r:n.test(r)}function M(r,n,e){let o=Gr(e).some((s)=>s.test(r))||n.external?.some((s)=>tr(r,s)),i=n.noExternal?.some((s)=>tr(r,s));return o&&!i}var or=require("ts-import-resolver");var T="\x00dts:",ir=(r,n,e)=>{return{name:"bunup:virtual-dts",async resolveId(t,o){if(k(t))return t;if(!o||!k(o))return null;let i=n.tsconfig?or.resolveTsImportPath({path:t,importer:S(o),tsconfig:n.tsconfig,rootDir:e}):null;if(!i)return null;let s=x(i);if(r.has(s))return R(s);return null},load(t){if(t.startsWith(T)){let o=S(t),i=r.get(o);if(i)return sr.add(o),i}return null}}};var W=/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/;function cr(r){return r.endsWith(".d.ts")||r.endsWith(".d.mts")||r.endsWith(".d.cts")}function ur(r){return W.test(r)&&!cr(r)}function x(r){if(cr(r))return r;if(r.endsWith(".mts"))return`${r.slice(0,-4)}.d.mts`;if(r.endsWith(".cts"))return`${r.slice(0,-4)}.d.cts`;if(W.test(r))return r.replace(W,".d.ts");return`${r}.d.ts`}function k(r){return r.startsWith(T)}function S(r){return r.replace(T,"")}function R(r){return`${T}${r}`}function ar(r,n,e,t){if(typeof t==="boolean"&&t)return!1;if(Array.isArray(t)){for(let o of t)if(typeof o==="string"&&r===o)return!1;else if(o instanceof RegExp&&o.test(r))return!1}return M(r,n,e)}var _;function gr(r,n){return{name:"bunup:types-resolve",buildStart(){_||=new mr.ResolverFactory({mainFields:["types","typings","module","main"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".d.mts",".d.cts",".ts",".mts",".cts"],...r.path&&{tsconfig:{configFile:r.path}},modules:["node_modules","node_modules/@types"]})},async resolveId(e,t){if(n===!1)return;if(e==="bun")return;let o=t?S(t):void 0;if(/\0/.test(e))return;if(Array.isArray(n)){if(!n.some((c)=>typeof c==="string"?c===e:c.test(e)))return}let i=o?U.default.dirname(o):process.cwd(),{path:s}=await _.async(i,e);if(!s)return;if(ur(s)){let u=x(s);try{let{path:c}=await _.async(U.default.dirname(s),u);if(c)return c}catch(c){}return}return s}}}var Hr=import("rolldown"),Kr=import("rolldown-plugin-dts");async function fr(r,n,e,t,o,i){let s=(await Hr).build,u=(await Kr).dts,c=x(r),a=R(c),m=typeof e.dts==="object"&&"resolve"in e.dts?e.dts.resolve:void 0;try{let{output:g}=await s({input:a,output:{dir:e.outDir},write:!1,...o.path&&{resolve:{tsconfigFilename:o.path}},onwarn(l,I){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(l.code??""))return;I(l)},plugins:[ir(n,o,i),m&&gr(o,m),u({dtsInput:!0,emitDtsOnly:!0})],external:(l)=>ar(l,e,t,m)});if(!g[0]?.code)return f.warn(`Generated empty declaration file for entry "${r}"`,{muted:!0}),"";return g[0].code}catch(g){throw new p(`DTS bundling failed for entry "${r}": ${d(g)}`)}}var lr=require("ts-import-resolver");var Yr=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Qr=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Zr=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Xr=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Nr=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,zr=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Vr=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function Jr(r){let n=new Set,e=[Yr,Qr,Zr,Xr,Nr,zr,Vr];for(let t of e){let o=r.matchAll(t);for(let i of o)if(i[1])n.add(i[1])}return n}async function pr(r,n,e){let t=new Set([r]),o=[r];while(o.length){let i=o.pop();if(!i)continue;try{let s=await Bun.file(i).text(),u=Jr(s);for(let c of u){let a=n.tsconfig?lr.resolveTsImportPath({path:c,importer:i,tsconfig:n.tsconfig,rootDir:e}):null;if(!a)continue;if(!t.has(a))t.add(a),o.push(a)}}catch(s){f.warn(`Error processing ${i}: ${d(s)}`)}}return t}var dr=require("oxc-transform");async function xr(r){let n=new Map;return await Promise.all([...r].map(async(e)=>{try{let t=x(e);if(!await Bun.file(e).exists())return;let i=await Bun.file(e).text(),{code:s}=dr.isolatedDeclaration(e,i);if(s)n.set(t,s)}catch(t){f.warn(`Failed to generate declaration for ${e}: ${d(t)}`)}})),n}var q=b(require("node:fs/promises")),A=b(require("node:path")),vr=require("oxc-transform");async function br(r,n){let e=A.default.resolve(r),t=A.default.resolve(e,n);if(!await q.default.exists(e))throw new p(`Root directory does not exist: ${e}`);if(!await Bun.file(t).exists())throw new p(`Entry file does not exist: ${t}`);if(!E(t))throw new p(`Entry file must be a TypeScript file: ${t}`);if(A.default.relative(e,t).startsWith(".."))throw new p(`Entry file must be within rootDir: ${t}`);return{absoluteRootDir:e,absoluteEntry:t}}async function Cr(r,n,e,t,o){let{absoluteEntry:i}=await br(r,n),s=await pr(i,t,r),u=await xr(s);return fr(i,u,e,o,t,r)}var h=require("node:path");function wr(r){let n=h.basename(r),e=h.extname(n);return e?n.slice(0,-e.length):n}function F(r){if(typeof r==="string")return[{fullEntryPath:r,name:wr(r)}];if(typeof r==="object"&&!Array.isArray(r))return Object.entries(r).map(([t,o])=>({fullEntryPath:o,name:t}));let n=[],e=new Set;for(let t of r){let o=wr(t);if(!e.has(o)){n.push({fullEntryPath:t,name:o}),e.add(o);continue}let s=h.dirname(t).split("/").filter((c)=>c!=="."&&c!=="");if(s.length===0){let c=1,a;do a=`${o}_${c++}`;while(e.has(a));n.push({fullEntryPath:t,name:a}),e.add(a);continue}let u=!1;for(let c=1;c<=s.length&&!u;c++){let m=`${s.slice(-c).join("/")}/${o}`;if(!e.has(m))n.push({fullEntryPath:t,name:m}),e.add(m),u=!0}if(!u){let c=1,a;do a=`${s.join("/")}/${o}_${c++}`;while(e.has(a));n.push({fullEntryPath:t,name:a}),e.add(a)}}return n}function Br(r){return r.filter((n)=>E(n.fullEntryPath))}function hr(r,n){return`[dir]/${r}${n}`}var G=require("coffi");async function $r(r){let{config:n,filepath:e}=await G.loadConfig({name:"package",cwd:r,extensions:[".json"],maxDepth:3});return{packageJson:n,path:e}}async function Sr(r,n){let{config:e,filepath:t}=await G.loadConfig({name:"tsconfig",cwd:r,extensions:[".json"],preferredPath:n,maxDepth:3});return{tsconfig:e,path:t}}var Pr={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function Tr(r){return{...Pr,...r}}function Lr(r){let{minify:n,minifyWhitespace:e,minifyIdentifiers:t,minifySyntax:o}=r,i=n===!0;return{whitespace:e??i,identifiers:t??i,syntax:o??i}}function Er(r,n){return n==="cjs"?r:void 0}function Mr(r,n,e,t){return{...typeof e==="object"&&Object.keys(e).reduce((o,i)=>{let s=JSON.stringify(e[i]);return o[`process.env.${i}`]=s,o[`import.meta.env.${i}`]=s,o},{}),...r,...t==="cjs"&&(n===!0||typeof n==="object"&&n.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Rr(r,n){return r===void 0?n==="esm":r}function Ar(r){return typeof r==="string"?r:void 0}function Ir(r,n){return{name:"bunup:external-plugin",setup(e){e.onResolve({filter:/.*/},(t)=>{let o=t.path;if(M(o,r,n))return{path:o,external:!0};return null})}}}var rn=/\.(js|ts|jsx|tsx|mts|cts)$/,H={dirnameFilename:{appliesTo:(r,n)=>r==="esm"&&O(n),isNeededInFile:(r)=>/\b__dirname\b/.test(r)||/\b__filename\b/.test(r),generateCode:()=>`import { fileURLToPath } from 'url';
16
2
  import { dirname } from 'path';
17
3
 
18
4
  const __filename = fileURLToPath(import.meta.url);
19
5
  const __dirname = dirname(__filename);
20
6
 
21
- `},importMetaUrl:{appliesTo:(e,r)=>e==="cjs"&&k(r),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
7
+ `},importMetaUrl:{appliesTo:(r,n)=>r==="cjs"&&O(n),isNeededInFile:(r)=>/\bimport\.meta\.url\b/.test(r),generateCode:()=>`import { pathToFileURL } from 'url';
22
8
 
23
9
  const importMetaUrl = pathToFileURL(__filename).href;
24
10
 
25
- `}};function _e({format:e,target:r,shims:n}){let s=sr(n).map((i)=>Z[i]).filter((i)=>i.appliesTo(e,r));if(s.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(i){i.onLoad({filter:tr},async({path:o})=>{let a=await Bun.file(o).text(),u=s.filter((m)=>m.isNeededInFile(a));if(u.length===0)return;let{shebangLine:c,codeContent:g}=or(a),p=u.map((m)=>m.generateCode()).join("");return{contents:c+p+g}})}}}function sr(e){if(e===!0)return Object.keys(Z);if(!e)return[];return Object.entries(e).filter(([r,n])=>n&&(r in Z)).map(([r])=>r)}function or(e){if(!e.startsWith("#!"))return{shebangLine:"",codeContent:e};let r=e.indexOf(`
26
- `);return r===-1?{shebangLine:"",codeContent:e}:{shebangLine:e.slice(0,r+1),codeContent:e.slice(r+1)}}function De(e){return e.filter((r)=>r.type==="bun").map((r)=>r.plugin)}var me=new Set;async function We(e,r=process.cwd()){let n=Oe(e);if(!n.entry||n.entry.length===0||!n.outDir)throw new C("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(n.clean)ie(r,n.outDir);ee(n.silent);let{packageJson:t,path:s}=await Te(r);if(t&&s)f.cli(`Using package.json: ${E(s,2)}`,{muted:!0,identifier:n.name,once:`${s}:${n.name}`});let i=Y(n.entry),o=t?.type,a=O(n,t),u=L(n);if(!n.dtsOnly){let c=[Ne(a,u),...De(n.plugins??[])],g=n.format.flatMap((p)=>i.map((m)=>{return ir(n,r,m,p,o,c)}));await Promise.all(g)}if(n.dts||n.dtsOnly){let c=await Re(r,n.preferredTsconfigPath);if(c.path)f.cli(`Using tsconfig: ${E(c.path,2)}`,{muted:!0,identifier:n.name,once:`${c.path}:${n.name}`});let g=n.format.filter((m)=>{if(m==="iife"&&!$(o)&&n.format.includes("cjs"))return!1;return!0}),p=typeof n.dts==="object"&&n.dts.entry?Y(n.dts.entry):Be(i);try{await Promise.all(p.map(async(m)=>{let y=await $e(r,m.path,n,c,t);await Promise.all(g.map(async(b)=>{let j=n.outputExtension?.({format:b,packageType:o,options:n,entry:m}).dts??se(b,o),N=`${r}/${n.outDir}/${m.name}${j}`;await Bun.write(N,y);let ke=Bun.file(N).size||0;f.progress("DTS",E(N),U(ke),n.name)}))}))}catch(m){throw new l(d(m))}}if(n.onBuildSuccess)await n.onBuildSuccess(n)}async function ir(e,r,n,t,s,i){let o=e.outputExtension?.({format:t,packageType:s,options:e,entry:n}).js??te(t,s),a=await Bun.build({entrypoints:[`${r}/${n.path}`],format:t,naming:{entry:Se(n.name,o)},splitting:Ie(e.splitting,t),bytecode:Me(e.bytecode,t),define:Ae(e.define,e.shims,e.env,t),minify:Le(e),outdir:`${r}/${e.outDir}`,target:e.target,sourcemap:e.sourcemap,loader:e.loader,drop:e.drop,banner:e.banner,footer:e.footer,publicPath:e.publicPath,env:je(e.env),plugins:[...i,_e({format:t,target:e.target,shims:e.shims})],throw:!1});if(!a.success)for(let g of a.logs){if(g.level==="error")throw new C(g.message);if(g.level==="warning")f.warn(g.message);else if(g.level==="info")f.info(g.message)}let u=`${r}/${e.outDir}/${n.name}${o}`,c=Bun.file(u).size||0;f.progress(t.toUpperCase(),E(u),U(c),e.name)}
11
+ `}};function yr({format:r,target:n,shims:e}){let o=nn(e).map((i)=>H[i]).filter((i)=>i.appliesTo(r,n));if(o.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(i){i.onLoad({filter:rn},async({path:s})=>{let u=await Bun.file(s).text(),c=o.filter((l)=>l.isNeededInFile(u));if(c.length===0)return;let{shebangLine:a,codeContent:m}=en(u),g=c.map((l)=>l.generateCode()).join("");return{contents:a+g+m}})}}}function nn(r){if(r===!0)return Object.keys(H);if(!r)return[];return Object.entries(r).filter(([n,e])=>e&&(n in H)).map(([n])=>n)}function en(r){if(!r.startsWith("#!"))return{shebangLine:"",codeContent:r};let n=r.indexOf(`
12
+ `);return n===-1?{shebangLine:"",codeContent:r}:{shebangLine:r.slice(0,n+1),codeContent:r.slice(n+1)}}function jr(r){return r.filter((n)=>n.type==="bun").map((n)=>n.plugin)}var sr=new Set;async function Or(r,n=process.cwd()){let e=Tr(r);if(!e.entry||e.entry.length===0||!e.outDir)throw new w("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(e.clean)er(n,e.outDir);J(e.silent);let{packageJson:t,path:o}=await $r(n);if(t&&o)f.cli(`Using package.json: ${L(o,2)}`,{muted:!0,identifier:e.name,once:`${o}:${e.name}`});let i=F(e.entry),s=t?.type;if(!e.dtsOnly){let u=[Ir(e,t),...jr(e.plugins??[])],c=e.format.flatMap((a)=>i.map((m)=>{return tn(e,n,m,a,s,u)}));await Promise.all(c)}if(e.dts||e.dtsOnly){let u=await Sr(n,e.preferredTsconfigPath);if(u.path)f.cli(`Using tsconfig: ${L(u.path,2)}`,{muted:!0,identifier:e.name,once:`${u.path}:${e.name}`});let c=e.format.filter((m)=>{if(m==="iife"&&!B(s)&&e.format.includes("cjs"))return!1;return!0}),a=typeof e.dts==="object"&&e.dts.entry?F(e.dts.entry):Br(i);try{await Promise.all(a.map(async(m)=>{let g=await Cr(n,m.fullEntryPath,e,u,t);await Promise.all(c.map(async(l)=>{let I=e.outputExtension?.({format:l,packageType:s,options:e,entry:m}).dts??rr(l,s),K=`${e.outDir}/${m.name}${I}`,Y=`${n}/${K}`;await Bun.write(Y,g);let Dr=Bun.file(Y).size||0;f.progress("DTS",K,D(Dr),e.name)}))}))}catch(m){throw new p(d(m))}}if(e.onBuildSuccess)await e.onBuildSuccess(e)}async function tn(r,n,e,t,o,i){let s=r.outputExtension?.({format:t,packageType:o,options:r,entry:e}).js??P(t,o),u=await Bun.build({entrypoints:[`${n}/${e.fullEntryPath}`],format:t,naming:{entry:hr(e.name,s)},splitting:Rr(r.splitting,t),bytecode:Er(r.bytecode,t),define:Mr(r.define,r.shims,r.env,t),minify:Lr(r),outdir:`${n}/${r.outDir}`,target:r.target,sourcemap:r.sourcemap,loader:r.loader,drop:r.drop,banner:r.banner,footer:r.footer,publicPath:r.publicPath,env:Ar(r.env),plugins:[...i,yr({format:t,target:r.target,shims:r.shims})],throw:!1});if(!u.success)for(let g of u.logs){if(g.level==="error")throw new w(g.message);if(g.level==="warning")f.warn(g.message);else if(g.level==="info")f.info(g.message)}let c=`${r.outDir}/${e.name}${s}`,a=`${n}/${c}`,m=Bun.file(a).size||0;f.progress(t.toUpperCase(),c,D(m),r.name)}
package/dist/index.mjs CHANGED
@@ -1,26 +1,12 @@
1
- import{createRequire as Ie}from"node:module";var Oe=Object.create;var{getPrototypeOf:Le,defineProperty:H,getOwnPropertyNames:Me}=Object;var Ae=Object.prototype.hasOwnProperty;var F=(e,r,n)=>{n=e!=null?Oe(Le(e)):{};let t=r||!e||!e.__esModule?H(n,"default",{value:e,enumerable:!0}):n;for(let s of Me(e))if(!Ae.call(t,s))H(t,s,{get:()=>e[s],enumerable:!0});return t};var G=Ie(import.meta.url);function je(e){return e}function Ne(e){return e}var K=!1;function Y(e){K=e??!1}class y{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",muted:"245",info:"117",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!y.instance)y.instance=new y;return y.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(e){if(!e?.once)return!0;if(this.loggedOnceMessages.has(e.once))return!1;return this.loggedOnceMessages.add(e.once),!0}formatMessage({colorCode:e,label:r,message:n,size:t,identifier:s,muted:i}){let o=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length)),a=i?`\x1B[38;5;${this.colors.muted}m${n}\x1B[0m`:n;if(t){let[c,...g]=a.split(" "),p=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),m=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${o}${c}${p} \x1B[38;5;${this.colors.size}m${t}\x1B[0m ${g.join(" ")}${m}`}let u=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${o}${a}${u}`}output(e,r={},n=console.log){if(K)return;if(!this.shouldLog(r))return;if(r.verticalSpace)console.log("");if(n(e),r.verticalSpace)console.log("")}cli(e,r={}){let n=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:r.identifier,muted:r.muted});this.output(n,r)}info(e,r={}){let n=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:r.identifier,muted:r.muted});this.output(n,r)}warn(e,r={}){let n=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:r.identifier,muted:r.muted});this.output(n,r,console.warn)}error(e,r={}){let n=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:r.identifier,muted:r.muted});this.output(n,r,console.error)}progress(e,r,n,t){let s=String(e),i=this.colors.default,o,a,u={};if(typeof n==="string")o=n,a=t;else if(n)o=n.size,a=n.identifier,u=n;for(let[g,p]of Object.entries(this.colors.progress))if(s.includes(g)){i=p;break}let c=this.formatMessage({colorCode:i,label:s,message:r,size:o,identifier:a,muted:u.muted});this.output(c,u)}}var f=y.getInstance();class A extends Error{constructor(e){super(e);this.name="BunupError"}}class w extends A{constructor(e){super(e);this.name="BunupBuildError"}}class l extends A{constructor(e){super(e);this.name="BunupDTSBuildError"}}var d=(e)=>{if(e instanceof Error)return e.message;return String(e)};import Q from"node:fs/promises";import _e from"node:path";function I(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Z(e=8){let r="";while(r.length<e)r+=Math.random().toString(36).substring(2);return r.substring(0,e)}function z(e,r){switch(e){case"esm":return C(r)?".js":".mjs";case"cjs":return C(r)?".cjs":".js";case"iife":return".global.js"}}function X(e,r){switch(e){case"esm":return C(r)?".d.ts":".d.mts";case"cjs":return C(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function j(e){return e==="node"||e==="bun"}function C(e){return e==="module"}function V(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function N(e){if(e===0)return"0 B";let r=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(1024));if(n===0)return`${e} ${r[n]}`;return`${(e/1024**n).toFixed(2)} ${r[n]}`}function $(e,r=3){return e.split("/").slice(-r).join("/")}async function J(e,r){let n=_e.join(e,r);try{await Q.rm(n,{recursive:!0,force:!0})}catch(t){throw new w(`Failed to clean output directory: ${t}`)}await Q.mkdir(n,{recursive:!0})}function S(e){return[".ts",".mts",".cts",".tsx"].some((r)=>e.endsWith(r))}function v(e){return e.map((r)=>typeof r==="string"?new RegExp(`^${I(r)}($|\\/|\\\\)`):r)}function T(e,r){return v(e.external||[]).concat(V(r).map((n)=>new RegExp(`^${I(n)}($|\\/|\\\\)`)))}function R(e){return v(e.noExternal||[])}import se from"node:path";import{ResolverFactory as We}from"oxc-resolver";import{resolveTsImportPath as De}from"ts-import-resolver";var B="\x00dts:",P=(e,r,n)=>{return{name:"bunup:virtual-dts",async resolveId(t,s){if(_(t))return t;if(!s||!_(s))return null;let i=r.tsconfig?De({path:t,importer:E(s),tsconfig:r.tsconfig,rootDir:n}):null;if(!i)return null;let o=x(i);if(e.has(o))return O(o);return null},load(t){if(t.startsWith(B)){let s=E(t),i=e.get(s);if(i)return ee.add(s),i}return null}}};var D=/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/;function re(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}function ne(e){return D.test(e)&&!re(e)}function x(e){if(re(e))return e;if(e.endsWith(".mts"))return`${e.slice(0,-4)}.d.mts`;if(e.endsWith(".cts"))return`${e.slice(0,-4)}.d.cts`;if(D.test(e))return e.replace(D,".d.ts");return`${e}.d.ts`}function _(e){return e.startsWith(B)}function E(e){return e.replace(B,"")}function O(e){return`${B}${e}`}function te(e,r,n,t){if(typeof t==="boolean"&&t)return!1;if(Array.isArray(t)){for(let s of t)if(typeof s==="string"&&e===s)return!1;else if(s instanceof RegExp&&s.test(e))return!1}return r.some((s)=>s.test(e))&&!n.some((s)=>s.test(e))}var W;function oe(e,r){return{name:"bunup:types-resolve",buildStart(){W||=new We({mainFields:["types","typings","module","main"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".d.mts",".d.cts",".ts",".mts",".cts"],...e.path&&{tsconfig:{configFile:e.path}},modules:["node_modules","node_modules/@types"]})},async resolveId(n,t){if(r===!1)return;if(n==="bun")return;let s=t?E(t):void 0;if(/\0/.test(n))return;if(Array.isArray(r)){if(!r.some((u)=>typeof u==="string"?u===n:u.test(n)))return}let i=s?se.dirname(s):process.cwd(),{path:o}=await W.async(i,n);if(!o)return;if(ne(o)){let a=x(o);try{let{path:u}=await W.async(se.dirname(o),a);if(u)return u}catch(u){}return}return o}}}var ke=import("rolldown"),Ue=import("rolldown-plugin-dts");async function ie(e,r,n,t,s,i){let o=(await ke).build,a=(await Ue).dts,u=x(e),c=O(u),g=T(n,t),p=R(n),m=typeof n.dts==="object"&&"resolve"in n.dts?n.dts.resolve:void 0;try{let{output:h}=await o({input:c,output:{dir:n.outDir},write:!1,...s.path&&{resolve:{tsconfigFilename:s.path}},onwarn(b,L){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(b.code??""))return;L(b)},plugins:[P(r,s,i),m&&oe(s,m),a({dtsInput:!0,emitDtsOnly:!0})],external:(b)=>te(b,g,p,m)});if(!h[0]?.code)return f.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return h[0].code}catch(h){throw new l(`DTS bundling failed for entry "${e}": ${d(h)}`)}}import{resolveTsImportPath as qe}from"ts-import-resolver";var He=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Fe=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Ge=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ke=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ye=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Qe=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Ze=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function ze(e){let r=new Set,n=[He,Fe,Ge,Ke,Ye,Qe,Ze];for(let t of n){let s=e.matchAll(t);for(let i of s)if(i[1])r.add(i[1])}return r}async function ae(e,r,n){let t=new Set([e]),s=[e];while(s.length){let i=s.pop();if(!i)continue;try{let o=await Bun.file(i).text(),a=ze(o);for(let u of a){let c=r.tsconfig?qe({path:u,importer:i,tsconfig:r.tsconfig,rootDir:n}):null;if(!c)continue;if(!t.has(c))t.add(c),s.push(c)}}catch(o){f.warn(`Error processing ${i}: ${d(o)}`)}}return t}import{isolatedDeclaration as Xe}from"oxc-transform";async function ue(e){let r=new Map;return await Promise.all([...e].map(async(n)=>{try{let t=x(n);if(!await Bun.file(n).exists())return;let i=await Bun.file(n).text(),{code:o}=Xe(n,i);if(o)r.set(t,o)}catch(t){f.warn(`Failed to generate declaration for ${n}: ${d(t)}`)}})),r}import ce from"node:fs/promises";import k from"node:path";import{isolatedDeclaration as Qr}from"oxc-transform";async function me(e,r){let n=k.resolve(e),t=k.resolve(n,r);if(!await ce.exists(n))throw new l(`Root directory does not exist: ${n}`);if(!await Bun.file(t).exists())throw new l(`Entry file does not exist: ${t}`);if(!S(t))throw new l(`Entry file must be a TypeScript file: ${t}`);if(k.relative(n,t).startsWith(".."))throw new l(`Entry file must be within rootDir: ${t}`);return{absoluteRootDir:n,absoluteEntry:t}}async function ge(e,r,n,t,s){let{absoluteEntry:i}=await me(e,r),o=await ae(i,t,e),a=await ue(o);return ie(i,a,n,s,t,e)}import{basename as Ve,extname as Je}from"node:path";function fe(e){let r=Ve(e),n=Je(r);return n?r.slice(0,-n.length):r}function U(e,{warnOnConflict:r=!0}={}){let n=[],t=new Set,s={};function i(o,a){if(t.has(o)){let u=Z(),c=`${o}_${u}`;if(r)f.warn(`Output name conflict: "${o}" is used by multiple files.
2
- Bunup uses filenames without extensions as output names by default.
3
-
4
- ${s[o]} -> ${o}.js
5
- ${a} -> ${c}.js (auto-renamed to avoid conflict)
6
-
7
- To fix this, use named entries in your configuration:
8
- {
9
- entry: {
10
- custom_name: "${s[o]}",
11
- another_name: "${a}"
12
- }
13
- }
14
-
15
- See: https://bunup.dev/documentation/#named-entries`,{muted:!0,verticalSpace:!0});n.push({name:c,path:a})}else n.push({name:o,path:a}),t.add(o),s[o]=a}if(Array.isArray(e))for(let o of e){let a=fe(o);i(a,o)}else if(typeof e==="object")for(let[o,a]of Object.entries(e))i(o,a);else{let o=fe(e);i(o,e)}return n}function pe(e){return e.filter((r)=>S(r.path))}function le(e,r){return`[dir]/${e}${r}`}import{loadConfig as de}from"coffi";async function xe(e){let{config:r,filepath:n}=await de({name:"package",cwd:e,extensions:[".json"],maxDepth:3});return{packageJson:r,path:n}}async function be(e,r){let{config:n,filepath:t}=await de({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:r,maxDepth:3});return{tsconfig:n,path:t}}var ve={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function he(e){return{...ve,...e}}function ye(e){let{minify:r,minifyWhitespace:n,minifyIdentifiers:t,minifySyntax:s}=e,i=r===!0;return{whitespace:n??i,identifiers:t??i,syntax:s??i}}function we(e,r){return r==="cjs"?e:void 0}function Ce(e,r,n,t){return{...typeof n==="object"&&Object.keys(n).reduce((s,i)=>{let o=JSON.stringify(n[i]);return s[`process.env.${i}`]=o,s[`import.meta.env.${i}`]=o,s},{}),...e,...t==="cjs"&&(r===!0||typeof r==="object"&&r.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function $e(e,r){return e===void 0?r==="esm":e}function Ee(e){return typeof e==="string"?e:void 0}function Be(e,r){return{name:"bunup:external-plugin",setup(n){n.onResolve({filter:/.*/},(t)=>{let s=t.path;if(e.some((o)=>o.test(s))&&!r.some((o)=>o.test(s)))return{path:s,external:!0};return null})}}}var Pe=/\.(js|ts|jsx|tsx|mts|cts)$/,q={dirnameFilename:{appliesTo:(e,r)=>e==="esm"&&j(r),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
1
+ import{createRequire as Rr}from"node:module";var Tr=Object.create;var{getPrototypeOf:Lr,defineProperty:U,getOwnPropertyNames:Er}=Object;var Mr=Object.prototype.hasOwnProperty;var q=(r,n,e)=>{e=r!=null?Tr(Lr(r)):{};let t=n||!r||!r.__esModule?U(e,"default",{value:r,enumerable:!0}):e;for(let o of Er(r))if(!Mr.call(t,o))U(t,o,{get:()=>r[o],enumerable:!0});return t};var F=Rr(import.meta.url);function Ar(r){return r}function Ir(r){return r}var G=!1;function H(r){G=r??!1}class b{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",muted:"245",info:"117",warn:"179",error:"174",progress:{ESM:"172",CJS:"108",IIFE:"146",DTS:"110"},default:"252",size:"65"};labels={cli:"CLI",info:"INFO",warn:"WARN",error:"ERROR"};constructor(){}static getInstance(){if(!b.instance)b.instance=new b;return b.instance}dispose(){this.loggedOnceMessages.clear()}shouldLog(r){if(!r?.once)return!0;if(this.loggedOnceMessages.has(r.once))return!1;return this.loggedOnceMessages.add(r.once),!0}formatMessage({colorCode:r,label:n,message:e,size:t,identifier:o,muted:i}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-n.length)),u=i?`\x1B[38;5;${this.colors.muted}m${e}\x1B[0m`:e;if(t){let[a,...m]=u.split(" "),g=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-a.length)),l=o?` \x1B[48;5;${r};38;5;0m ${o} \x1B[0m`:"";return`\x1B[38;5;${r}m${n}\x1B[0m ${s}${a}${g} \x1B[38;5;${this.colors.size}m${t}\x1B[0m ${m.join(" ")}${l}`}let c=o?` \x1B[48;5;${r};38;5;0m ${o} \x1B[0m`:"";return`\x1B[38;5;${r}m${n}\x1B[0m ${s}${u}${c}`}output(r,n={},e=console.log){if(G)return;if(!this.shouldLog(n))return;if(n.verticalSpace)console.log("");if(e(r),n.verticalSpace)console.log("")}cli(r,n={}){let e=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n)}info(r,n={}){let e=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n)}warn(r,n={}){let e=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n,console.warn)}error(r,n={}){let e=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:r,identifier:n.identifier,muted:n.muted});this.output(e,n,console.error)}progress(r,n,e,t){let o=String(r),i=this.colors.default,s,u,c={};if(typeof e==="string")s=e,u=t;else if(e)s=e.size,u=e.identifier,c=e;for(let[m,g]of Object.entries(this.colors.progress))if(o.includes(m)){i=g;break}let a=this.formatMessage({colorCode:i,label:o,message:n,size:s,identifier:u,muted:c.muted});this.output(a,c)}}var f=b.getInstance();class M extends Error{constructor(r){super(r);this.name="BunupError"}}class C extends M{constructor(r){super(r);this.name="BunupBuildError"}}class p extends M{constructor(r){super(r);this.name="BunupDTSBuildError"}}var d=(r)=>{if(r instanceof Error)return r.message;return String(r)};import rr from"node:path";import{ResolverFactory as Dr}from"oxc-resolver";import K from"node:fs/promises";import yr from"node:path";function Y(r,n){switch(r){case"esm":return w(n)?".js":".mjs";case"cjs":return w(n)?".cjs":".js";case"iife":return".global.js"}}function Q(r,n){switch(r){case"esm":return w(n)?".d.ts":".d.mts";case"cjs":return w(n)?".d.cts":".d.ts";case"iife":return".d.ts"}}function R(r){return r==="node"||r==="bun"}function w(r){return r==="module"}function Z(r){if(!r)return[];return Array.from(new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.peerDependencies||{})]))}function A(r){if(r===0)return"0 B";let n=["B","KB","MB","GB"],e=Math.floor(Math.log(r)/Math.log(1024));if(e===0)return`${r} ${n[e]}`;return`${(r/1024**e).toFixed(2)} ${n[e]}`}function $(r,n=3){return r.split("/").slice(-n).join("/")}async function X(r,n){let e=yr.join(r,n);try{await K.rm(e,{recursive:!0,force:!0})}catch(t){throw new C(`Failed to clean output directory: ${t}`)}await K.mkdir(e,{recursive:!0})}function S(r){return[".ts",".mts",".cts",".tsx"].some((n)=>r.endsWith(n))}function jr(r){return Z(r).map((n)=>new RegExp(`^${n}($|\\/|\\\\)`))}function N(r,n){return typeof n==="string"?n===r:n.test(r)}function T(r,n,e){let o=jr(e).some((s)=>s.test(r))||n.external?.some((s)=>N(r,s)),i=n.noExternal?.some((s)=>N(r,s));return o&&!i}import{resolveTsImportPath as Or}from"ts-import-resolver";var h="\x00dts:",z=(r,n,e)=>{return{name:"bunup:virtual-dts",async resolveId(t,o){if(I(t))return t;if(!o||!I(o))return null;let i=n.tsconfig?Or({path:t,importer:B(o),tsconfig:n.tsconfig,rootDir:e}):null;if(!i)return null;let s=x(i);if(r.has(s))return L(s);return null},load(t){if(t.startsWith(h)){let o=B(t),i=r.get(o);if(i)return V.add(o),i}return null}}};var y=/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/;function J(r){return r.endsWith(".d.ts")||r.endsWith(".d.mts")||r.endsWith(".d.cts")}function v(r){return y.test(r)&&!J(r)}function x(r){if(J(r))return r;if(r.endsWith(".mts"))return`${r.slice(0,-4)}.d.mts`;if(r.endsWith(".cts"))return`${r.slice(0,-4)}.d.cts`;if(y.test(r))return r.replace(y,".d.ts");return`${r}.d.ts`}function I(r){return r.startsWith(h)}function B(r){return r.replace(h,"")}function L(r){return`${h}${r}`}function P(r,n,e,t){if(typeof t==="boolean"&&t)return!1;if(Array.isArray(t)){for(let o of t)if(typeof o==="string"&&r===o)return!1;else if(o instanceof RegExp&&o.test(r))return!1}return T(r,n,e)}var j;function nr(r,n){return{name:"bunup:types-resolve",buildStart(){j||=new Dr({mainFields:["types","typings","module","main"],conditionNames:["types","typings","import","require"],extensions:[".d.ts",".d.mts",".d.cts",".ts",".mts",".cts"],...r.path&&{tsconfig:{configFile:r.path}},modules:["node_modules","node_modules/@types"]})},async resolveId(e,t){if(n===!1)return;if(e==="bun")return;let o=t?B(t):void 0;if(/\0/.test(e))return;if(Array.isArray(n)){if(!n.some((c)=>typeof c==="string"?c===e:c.test(e)))return}let i=o?rr.dirname(o):process.cwd(),{path:s}=await j.async(i,e);if(!s)return;if(v(s)){let u=x(s);try{let{path:c}=await j.async(rr.dirname(s),u);if(c)return c}catch(c){}return}return s}}}var kr=import("rolldown"),Wr=import("rolldown-plugin-dts");async function er(r,n,e,t,o,i){let s=(await kr).build,u=(await Wr).dts,c=x(r),a=L(c),m=typeof e.dts==="object"&&"resolve"in e.dts?e.dts.resolve:void 0;try{let{output:g}=await s({input:a,output:{dir:e.outDir},write:!1,...o.path&&{resolve:{tsconfigFilename:o.path}},onwarn(l,E){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(l.code??""))return;E(l)},plugins:[z(n,o,i),m&&nr(o,m),u({dtsInput:!0,emitDtsOnly:!0})],external:(l)=>P(l,e,t,m)});if(!g[0]?.code)return f.warn(`Generated empty declaration file for entry "${r}"`,{muted:!0}),"";return g[0].code}catch(g){throw new p(`DTS bundling failed for entry "${r}": ${d(g)}`)}}import{resolveTsImportPath as _r}from"ts-import-resolver";var Ur=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,qr=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Fr=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Gr=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Hr=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Kr=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Yr=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function Qr(r){let n=new Set,e=[Ur,qr,Fr,Gr,Hr,Kr,Yr];for(let t of e){let o=r.matchAll(t);for(let i of o)if(i[1])n.add(i[1])}return n}async function tr(r,n,e){let t=new Set([r]),o=[r];while(o.length){let i=o.pop();if(!i)continue;try{let s=await Bun.file(i).text(),u=Qr(s);for(let c of u){let a=n.tsconfig?_r({path:c,importer:i,tsconfig:n.tsconfig,rootDir:e}):null;if(!a)continue;if(!t.has(a))t.add(a),o.push(a)}}catch(s){f.warn(`Error processing ${i}: ${d(s)}`)}}return t}import{isolatedDeclaration as Zr}from"oxc-transform";async function or(r){let n=new Map;return await Promise.all([...r].map(async(e)=>{try{let t=x(e);if(!await Bun.file(e).exists())return;let i=await Bun.file(e).text(),{code:s}=Zr(e,i);if(s)n.set(t,s)}catch(t){f.warn(`Failed to generate declaration for ${e}: ${d(t)}`)}})),n}import ir from"node:fs/promises";import O from"node:path";import{isolatedDeclaration as Qn}from"oxc-transform";async function sr(r,n){let e=O.resolve(r),t=O.resolve(e,n);if(!await ir.exists(e))throw new p(`Root directory does not exist: ${e}`);if(!await Bun.file(t).exists())throw new p(`Entry file does not exist: ${t}`);if(!S(t))throw new p(`Entry file must be a TypeScript file: ${t}`);if(O.relative(e,t).startsWith(".."))throw new p(`Entry file must be within rootDir: ${t}`);return{absoluteRootDir:e,absoluteEntry:t}}async function cr(r,n,e,t,o){let{absoluteEntry:i}=await sr(r,n),s=await tr(i,t,r),u=await or(s);return er(i,u,e,o,t,r)}import{basename as Xr,dirname as Nr,extname as zr}from"node:path";function ur(r){let n=Xr(r),e=zr(n);return e?n.slice(0,-e.length):n}function D(r){if(typeof r==="string")return[{fullEntryPath:r,name:ur(r)}];if(typeof r==="object"&&!Array.isArray(r))return Object.entries(r).map(([t,o])=>({fullEntryPath:o,name:t}));let n=[],e=new Set;for(let t of r){let o=ur(t);if(!e.has(o)){n.push({fullEntryPath:t,name:o}),e.add(o);continue}let s=Nr(t).split("/").filter((c)=>c!=="."&&c!=="");if(s.length===0){let c=1,a;do a=`${o}_${c++}`;while(e.has(a));n.push({fullEntryPath:t,name:a}),e.add(a);continue}let u=!1;for(let c=1;c<=s.length&&!u;c++){let m=`${s.slice(-c).join("/")}/${o}`;if(!e.has(m))n.push({fullEntryPath:t,name:m}),e.add(m),u=!0}if(!u){let c=1,a;do a=`${s.join("/")}/${o}_${c++}`;while(e.has(a));n.push({fullEntryPath:t,name:a}),e.add(a)}}return n}function ar(r){return r.filter((n)=>S(n.fullEntryPath))}function mr(r,n){return`[dir]/${r}${n}`}import{loadConfig as gr}from"coffi";async function fr(r){let{config:n,filepath:e}=await gr({name:"package",cwd:r,extensions:[".json"],maxDepth:3});return{packageJson:n,path:e}}async function lr(r,n){let{config:e,filepath:t}=await gr({name:"tsconfig",cwd:r,extensions:[".json"],preferredPath:n,maxDepth:3});return{tsconfig:e,path:t}}var Vr={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function pr(r){return{...Vr,...r}}function dr(r){let{minify:n,minifyWhitespace:e,minifyIdentifiers:t,minifySyntax:o}=r,i=n===!0;return{whitespace:e??i,identifiers:t??i,syntax:o??i}}function xr(r,n){return n==="cjs"?r:void 0}function br(r,n,e,t){return{...typeof e==="object"&&Object.keys(e).reduce((o,i)=>{let s=JSON.stringify(e[i]);return o[`process.env.${i}`]=s,o[`import.meta.env.${i}`]=s,o},{}),...r,...t==="cjs"&&(n===!0||typeof n==="object"&&n.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Cr(r,n){return r===void 0?n==="esm":r}function wr(r){return typeof r==="string"?r:void 0}function Br(r,n){return{name:"bunup:external-plugin",setup(e){e.onResolve({filter:/.*/},(t)=>{let o=t.path;if(T(o,r,n))return{path:o,external:!0};return null})}}}var Jr=/\.(js|ts|jsx|tsx|mts|cts)$/,k={dirnameFilename:{appliesTo:(r,n)=>r==="esm"&&R(n),isNeededInFile:(r)=>/\b__dirname\b/.test(r)||/\b__filename\b/.test(r),generateCode:()=>`import { fileURLToPath } from 'url';
16
2
  import { dirname } from 'path';
17
3
 
18
4
  const __filename = fileURLToPath(import.meta.url);
19
5
  const __dirname = dirname(__filename);
20
6
 
21
- `},importMetaUrl:{appliesTo:(e,r)=>e==="cjs"&&j(r),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
7
+ `},importMetaUrl:{appliesTo:(r,n)=>r==="cjs"&&R(n),isNeededInFile:(r)=>/\bimport\.meta\.url\b/.test(r),generateCode:()=>`import { pathToFileURL } from 'url';
22
8
 
23
9
  const importMetaUrl = pathToFileURL(__filename).href;
24
10
 
25
- `}};function Se({format:e,target:r,shims:n}){let s=er(n).map((i)=>q[i]).filter((i)=>i.appliesTo(e,r));if(s.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(i){i.onLoad({filter:Pe},async({path:o})=>{let a=await Bun.file(o).text(),u=s.filter((m)=>m.isNeededInFile(a));if(u.length===0)return;let{shebangLine:c,codeContent:g}=rr(a),p=u.map((m)=>m.generateCode()).join("");return{contents:c+p+g}})}}}function er(e){if(e===!0)return Object.keys(q);if(!e)return[];return Object.entries(e).filter(([r,n])=>n&&(r in q)).map(([r])=>r)}function rr(e){if(!e.startsWith("#!"))return{shebangLine:"",codeContent:e};let r=e.indexOf(`
26
- `);return r===-1?{shebangLine:"",codeContent:e}:{shebangLine:e.slice(0,r+1),codeContent:e.slice(r+1)}}function Te(e){return e.filter((r)=>r.type==="bun").map((r)=>r.plugin)}var ee=new Set;async function nr(e,r=process.cwd()){let n=he(e);if(!n.entry||n.entry.length===0||!n.outDir)throw new w("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(n.clean)J(r,n.outDir);Y(n.silent);let{packageJson:t,path:s}=await xe(r);if(t&&s)f.cli(`Using package.json: ${$(s,2)}`,{muted:!0,identifier:n.name,once:`${s}:${n.name}`});let i=U(n.entry),o=t?.type,a=T(n,t),u=R(n);if(!n.dtsOnly){let c=[Be(a,u),...Te(n.plugins??[])],g=n.format.flatMap((p)=>i.map((m)=>{return tr(n,r,m,p,o,c)}));await Promise.all(g)}if(n.dts||n.dtsOnly){let c=await be(r,n.preferredTsconfigPath);if(c.path)f.cli(`Using tsconfig: ${$(c.path,2)}`,{muted:!0,identifier:n.name,once:`${c.path}:${n.name}`});let g=n.format.filter((m)=>{if(m==="iife"&&!C(o)&&n.format.includes("cjs"))return!1;return!0}),p=typeof n.dts==="object"&&n.dts.entry?U(n.dts.entry):pe(i);try{await Promise.all(p.map(async(m)=>{let h=await ge(r,m.path,n,c,t);await Promise.all(g.map(async(b)=>{let L=n.outputExtension?.({format:b,packageType:o,options:n,entry:m}).dts??X(b,o),M=`${r}/${n.outDir}/${m.name}${L}`;await Bun.write(M,h);let Re=Bun.file(M).size||0;f.progress("DTS",$(M),N(Re),n.name)}))}))}catch(m){throw new l(d(m))}}if(n.onBuildSuccess)await n.onBuildSuccess(n)}async function tr(e,r,n,t,s,i){let o=e.outputExtension?.({format:t,packageType:s,options:e,entry:n}).js??z(t,s),a=await Bun.build({entrypoints:[`${r}/${n.path}`],format:t,naming:{entry:le(n.name,o)},splitting:$e(e.splitting,t),bytecode:we(e.bytecode,t),define:Ce(e.define,e.shims,e.env,t),minify:ye(e),outdir:`${r}/${e.outDir}`,target:e.target,sourcemap:e.sourcemap,loader:e.loader,drop:e.drop,banner:e.banner,footer:e.footer,publicPath:e.publicPath,env:Ee(e.env),plugins:[...i,Se({format:t,target:e.target,shims:e.shims})],throw:!1});if(!a.success)for(let g of a.logs){if(g.level==="error")throw new w(g.message);if(g.level==="warning")f.warn(g.message);else if(g.level==="info")f.info(g.message)}let u=`${r}/${e.outDir}/${n.name}${o}`,c=Bun.file(u).size||0;f.progress(t.toUpperCase(),$(u),N(c),e.name)}export{Ne as defineWorkspace,je as defineConfig,nr as build};
11
+ `}};function hr({format:r,target:n,shims:e}){let o=vr(e).map((i)=>k[i]).filter((i)=>i.appliesTo(r,n));if(o.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(i){i.onLoad({filter:Jr},async({path:s})=>{let u=await Bun.file(s).text(),c=o.filter((l)=>l.isNeededInFile(u));if(c.length===0)return;let{shebangLine:a,codeContent:m}=Pr(u),g=c.map((l)=>l.generateCode()).join("");return{contents:a+g+m}})}}}function vr(r){if(r===!0)return Object.keys(k);if(!r)return[];return Object.entries(r).filter(([n,e])=>e&&(n in k)).map(([n])=>n)}function Pr(r){if(!r.startsWith("#!"))return{shebangLine:"",codeContent:r};let n=r.indexOf(`
12
+ `);return n===-1?{shebangLine:"",codeContent:r}:{shebangLine:r.slice(0,n+1),codeContent:r.slice(n+1)}}function $r(r){return r.filter((n)=>n.type==="bun").map((n)=>n.plugin)}var V=new Set;async function rn(r,n=process.cwd()){let e=pr(r);if(!e.entry||e.entry.length===0||!e.outDir)throw new C("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(e.clean)X(n,e.outDir);H(e.silent);let{packageJson:t,path:o}=await fr(n);if(t&&o)f.cli(`Using package.json: ${$(o,2)}`,{muted:!0,identifier:e.name,once:`${o}:${e.name}`});let i=D(e.entry),s=t?.type;if(!e.dtsOnly){let u=[Br(e,t),...$r(e.plugins??[])],c=e.format.flatMap((a)=>i.map((m)=>{return nn(e,n,m,a,s,u)}));await Promise.all(c)}if(e.dts||e.dtsOnly){let u=await lr(n,e.preferredTsconfigPath);if(u.path)f.cli(`Using tsconfig: ${$(u.path,2)}`,{muted:!0,identifier:e.name,once:`${u.path}:${e.name}`});let c=e.format.filter((m)=>{if(m==="iife"&&!w(s)&&e.format.includes("cjs"))return!1;return!0}),a=typeof e.dts==="object"&&e.dts.entry?D(e.dts.entry):ar(i);try{await Promise.all(a.map(async(m)=>{let g=await cr(n,m.fullEntryPath,e,u,t);await Promise.all(c.map(async(l)=>{let E=e.outputExtension?.({format:l,packageType:s,options:e,entry:m}).dts??Q(l,s),W=`${e.outDir}/${m.name}${E}`,_=`${n}/${W}`;await Bun.write(_,g);let Sr=Bun.file(_).size||0;f.progress("DTS",W,A(Sr),e.name)}))}))}catch(m){throw new p(d(m))}}if(e.onBuildSuccess)await e.onBuildSuccess(e)}async function nn(r,n,e,t,o,i){let s=r.outputExtension?.({format:t,packageType:o,options:r,entry:e}).js??Y(t,o),u=await Bun.build({entrypoints:[`${n}/${e.fullEntryPath}`],format:t,naming:{entry:mr(e.name,s)},splitting:Cr(r.splitting,t),bytecode:xr(r.bytecode,t),define:br(r.define,r.shims,r.env,t),minify:dr(r),outdir:`${n}/${r.outDir}`,target:r.target,sourcemap:r.sourcemap,loader:r.loader,drop:r.drop,banner:r.banner,footer:r.footer,publicPath:r.publicPath,env:wr(r.env),plugins:[...i,hr({format:t,target:r.target,shims:r.shims})],throw:!1});if(!u.success)for(let g of u.logs){if(g.level==="error")throw new C(g.message);if(g.level==="warning")f.warn(g.message);else if(g.level==="info")f.info(g.message)}let c=`${r.outDir}/${e.name}${s}`,a=`${n}/${c}`,m=Bun.file(a).size||0;f.progress(t.toUpperCase(),c,A(m),r.name)}export{Ir as defineWorkspace,Ar as defineConfig,rn as build};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bunup",
3
3
  "description": "⚡ A blazing-fast build tool for your libraries built with Bun.",
4
- "version": "0.4.65",
4
+ "version": "0.4.67",
5
5
  "license": "MIT",
6
6
  "author": "Arshad Yaseen <m@arshadyaseen.com> (https://arshadyaseen.com)",
7
7
  "maintainers": [
@@ -72,7 +72,7 @@
72
72
  "@commitlint/config-conventional": "^19.5.0",
73
73
  "@types/bun": "^1.2.5",
74
74
  "bumpp": "^10.1.0",
75
- "bunup": "^0.4.23",
75
+ "bunup": "^0.4.65",
76
76
  "create-bunup": "create-bunup",
77
77
  "husky": "^9.1.7",
78
78
  "typescript": "^5.8.3"