bunup 0.4.36 → 0.4.38

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
@@ -7,10 +7,10 @@ Bunup is the **high-performance build tool** for TypeScript and JavaScript libra
7
7
 
8
8
  | Bundler | Format | Build Time | Build Time (with dts) |
9
9
  | ------- | -------- | -------------- | --------------------- |
10
- | bunup | esm, cjs | **3.14ms ⚡️** | **19.86ms ⚡️** |
11
- | tsdown | esm, cjs | 5.60ms | 56.87ms |
12
- | unbuild | esm, cjs | 41.19ms | 321.09ms |
13
- | tsup | esm, cjs | 62.59ms | 937.64ms |
10
+ | bunup | esm, cjs | **3.52ms ⚡️** | **20.84ms ⚡️** |
11
+ | tsdown | esm, cjs | 5.65ms | 434.67ms |
12
+ | unbuild | esm, cjs | 43.13ms | 275.80ms |
13
+ | tsup | esm, cjs | 63.39ms | 904.67ms |
14
14
 
15
15
  _Lower is better. Benchmarks run on identical code and output formats._
16
16
 
package/build/cli.mjs CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{exec as yt}from"tinyexec";import{build as Ye}from"rolldown";import{dts as Ke}from"rolldown-plugin-dts";var te=!1;function B(e){te=e??!1}class E{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",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(!E.instance)E.instance=new E;return E.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:t,message:n,size:r,identifier:s,muted:o}){let i=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-t.length)),a=o?`\x1B[38;5;${this.colors.info}m${n}\x1B[0m`:n;if(r){let[c,...f]=a.split(" "),m=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),p=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${t}\x1B[0m ${i}${c}${m} \x1B[38;5;${this.colors.size}m${r}\x1B[0m ${f.join(" ")}${p}`}let l=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${t}\x1B[0m ${i}${a}${l}`}output(e,t={},n=console.log){if(te)return;if(!this.shouldLog(t))return;if(t.verticalSpace)console.log("");if(n(e),t.verticalSpace)console.log("")}cli(e,t={}){let n=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t)}info(e,t={}){let n=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t)}warn(e,t={}){let n=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t,console.warn)}error(e,t={}){let n=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:t.identifier,muted:t.muted});this.output(n,t,console.error)}progress(e,t,n,r){let s=String(e),o=this.colors.default,i,a,l={};if(typeof n==="string")i=n,a=r;else if(n)i=n.size,a=n.identifier,l=n;for(let[f,m]of Object.entries(this.colors.progress))if(s.includes(f)){o=m;break}let c=this.formatMessage({colorCode:o,label:s,message:t,size:i,identifier:a,muted:l.muted});this.output(c,l)}}var u=E.getInstance();class O extends Error{constructor(e){super(e);this.name="BunupError"}}class C extends O{constructor(e){super(e);this.name="BunupBuildError"}}class g extends O{constructor(e){super(e);this.name="BunupDTSBuildError"}}class b extends O{constructor(e){super(e);this.name="BunupCLIError"}}class L extends O{constructor(e){super(e);this.name="BunupWatchError"}}var h=(e)=>{if(e instanceof Error)return e.message;return String(e)},qe=[{pattern:/Could not resolve: "bun"/i,errorType:"BUILD ERROR",logSolution:()=>{u.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")}}],q=(e,t)=>{let n=h(e),r=t?`[${t}] `:"",s="ERROR";if(e instanceof C)s="BUILD ERROR";else if(e instanceof g)s="DTS ERROR";else if(e instanceof b)s="CLI ERROR";else if(e instanceof L)s="WATCH ERROR";else if(e instanceof O)s="BUNUP ERROR";let o=qe.find((i)=>i.pattern.test(n)&&(i.errorType===s||!i.errorType));if(!o)console.error(`\x1B[31m${s}\x1B[0m ${r}${n}`);if(o)console.log(`
4
- `),o.logSolution(n),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")},ne=(e,t)=>{q(e,t),process.exit(1)};import re from"node:fs/promises";import Ve from"node:path";function V(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function se(e=8){let t="";while(t.length<e)t+=Math.random().toString(36).substring(2);return t.substring(0,e)}function ie(e,t,n){return Array.isArray(e)?e.map((r)=>({...r,[t]:n})):{...e,[t]:n}}function oe(e){return Array.isArray(e)?e:[e]}function ae(e,t){switch(e){case"esm":return S(t)?".js":".mjs";case"cjs":return S(t)?".cjs":".js";case"iife":return".global.js"}}function le(e,t){switch(e){case"esm":return S(t)?".d.ts":".d.mts";case"cjs":return S(t)?".d.cts":".d.ts";case"iife":return".d.ts"}}function G(e){return e==="node"||e==="bun"}function S(e){return e==="module"}function D(e){return e>=1000?`${(e/1000).toFixed(2)}s`:`${Math.round(e)}ms`}function ce(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function X(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(1024));if(n===0)return`${e} ${t[n]}`;return`${(e/1024**n).toFixed(2)} ${t[n]}`}function y(e,t=3){return e.split("/").slice(-t).join("/")}async function ue(e,t){let n=Ve.join(e,t);try{await re.rm(n,{recursive:!0,force:!0})}catch(r){throw new C(`Failed to clean output directory: ${r}`)}await re.mkdir(n,{recursive:!0})}function I(e){return[".ts",".mts",".cts",".tsx"].some((t)=>e.endsWith(t))}function fe(e){return e.map((t)=>typeof t==="string"?new RegExp(`^${V(t)}($|\\/|\\\\)`):t)}function A(e,t){return fe(e.external||[]).concat(ce(t).map((n)=>new RegExp(`^${V(n)}($|\\/|\\\\)`)))}function M(e){return fe(e.noExternal||[])}import he from"node:path";import{ResolverFactory as Xe}from"oxc-resolver";import{resolveTsImportPath as Ge}from"ts-import-resolver";var R="\x00dts:",pe=(e,t,n)=>{return{name:"bunup:virtual-dts",async resolveId(r,s){if(Y(r))return r;if(!s||!Y(s))return null;let o=t.tsconfig?Ge({path:r,importer:T(s),tsconfig:t.tsconfig,rootDir:n}):null;if(!o)return null;let i=w(o);if(e.has(i))return j(i);return null},load(r){if(r.startsWith(R)){let s=T(r),o=e.get(s);if(o)return $.add(s),o}return null}}};function me(e){return e.tsconfig.compilerOptions??{}}function de(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}function ge(e){return/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/.test(e)&&!de(e)}function w(e){if(de(e))return e;return e.replace(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,".d.ts")}function Y(e){return e.startsWith(R)}function T(e){return e.replace(R,"")}function j(e){return`${R}${e}`}var K;function be(e,t){return{name:"bunup:types-resolve",buildStart(){K||=new Xe({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,r){if(n==="bun")return;let s=r?T(r):void 0;if(/\0/.test(n))return;if(t){if(!t.some((l)=>typeof l==="string"?l===n:l.test(n)))return}let o=s?he.dirname(s):process.cwd(),{path:i}=await K.async(o,n);if(!i)return;if(ge(i)){let a=w(i);try{let{path:l}=await K.async(he.dirname(i),a);if(l)return l}catch(l){}return}return i}}}async function xe(e,t,n,r,s,o){let i=w(e),a=j(i),l=A(n,r),c=M(n);try{let{output:f}=await Ye({input:a,output:{dir:n.outDir},write:!1,onwarn(m,p){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(m.code??""))return;p(m)},plugins:[pe(t,s,o),typeof n.dts==="object"&&"resolve"in n.dts&&be(s,typeof n.dts.resolve==="boolean"?void 0:n.dts.resolve),Ke({dtsInput:!0,emitDtsOnly:!0,compilerOptions:{...me(s),declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:99}})],external:(m)=>l.some((p)=>p.test(m))&&!c.some((p)=>p.test(m))});if(!f[0]?.code)return u.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return f[0].code}catch(f){throw new g(`DTS bundling failed for entry "${e}": ${h(f)}`)}}import{resolveTsImportPath as Je}from"ts-import-resolver";var ze=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Qe=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Ze=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,et=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,tt=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,nt=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,rt=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function st(e){let t=new Set,n=[ze,Qe,Ze,et,tt,nt,rt];for(let r of n){let s=e.matchAll(r);for(let o of s)if(o[1])t.add(o[1])}return t}async function ye(e,t,n){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=st(i);for(let l of a){let c=t.tsconfig?Je({path:l,importer:o,tsconfig:t.tsconfig,rootDir:n}):null;if(!c)continue;if(!r.has(c))r.add(c),s.push(c)}}catch(i){u.warn(`Error processing ${o}: ${h(i)}`)}}return r}import{isolatedDeclaration as it}from"oxc-transform";async function we(e){let t=new Map;return await Promise.all([...e].map(async(n)=>{try{let r=w(n);if(!await Bun.file(n).exists())return;let o=await Bun.file(n).text(),{code:i}=it(n,o);if(i)t.set(r,i)}catch(r){u.warn(`Failed to generate declaration for ${n}: ${h(r)}`)}})),t}import Ce from"node:fs/promises";import J from"node:path";import{isolatedDeclaration as ot}from"oxc-transform";async function Ee(e,t){let n=J.resolve(e),r=J.resolve(n,t);if(!await Ce.exists(n))throw new g(`Root directory does not exist: ${n}`);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(J.relative(n,r).startsWith(".."))throw new g(`Entry file must be within rootDir: ${r}`);return{absoluteRootDir:n,absoluteEntry:r}}async function Oe(e){let t=!1;if(await Promise.all([...e].map(async(n)=>{try{let r=n.replace(/\.d\.ts$/,".ts"),s=await Bun.file(r).text(),{errors:o}=ot(r,s);for(let i of o){if(!t)console.log(`
6
- `);let a=i.labels[0],l=a?at(s,a.start):"",f=`${y(r)}${l}: ${lt(i.message)}`;u.warn(f),t=!0}}catch{}})),t)u.info(`
3
+ import{exec as $n}from"tinyexec";import{build as Qe}from"rolldown";import{dts as Ze}from"rolldown-plugin-dts";var ne=!1;function A(e){ne=e??!1}class ${static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",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(!$.instance)$.instance=new $;return $.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.info}m${t}\x1B[0m`:t;if(r){let[l,...f]=a.split(" "),p=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-l.length)),m=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${n}\x1B[0m ${i}${l}${p} \x1B[38;5;${this.colors.size}m${r}\x1B[0m ${f.join(" ")}${m}`}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(ne)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[f,p]of Object.entries(this.colors.progress))if(s.includes(f)){o=p;break}let l=this.formatMessage({colorCode:o,label:s,message:n,size:i,identifier:a,muted:c.muted});this.output(l,c)}}var u=$.getInstance();class O extends Error{constructor(e){super(e);this.name="BunupError"}}class C extends O{constructor(e){super(e);this.name="BunupBuildError"}}class g extends O{constructor(e){super(e);this.name="BunupDTSBuildError"}}class b extends O{constructor(e){super(e);this.name="BunupCLIError"}}class M extends O{constructor(e){super(e);this.name="BunupWatchError"}}var h=(e)=>{if(e instanceof Error)return e.message;return String(e)},Ke=[{pattern:/Could not resolve: "bun"/i,errorType:"BUILD ERROR",logSolution:()=>{u.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=(e,n)=>{let t=h(e),r=n?`[${n}] `:"",s="ERROR";if(e instanceof C)s="BUILD ERROR";else if(e instanceof g)s="DTS ERROR";else if(e instanceof b)s="CLI ERROR";else if(e instanceof M)s="WATCH ERROR";else if(e instanceof O)s="BUNUP ERROR";let o=Ke.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")},te=(e,n)=>{F(e,n),process.exit(1)};import re from"node:fs/promises";import Ye from"node:path";function G(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function se(e=8){let n="";while(n.length<e)n+=Math.random().toString(36).substring(2);return n.substring(0,e)}function ie(e,n,t){return Array.isArray(e)?e.map((r)=>({...r,[n]:t})):{...e,[n]:t}}function oe(e){return Array.isArray(e)?e:[e]}function ae(e,n){switch(e){case"esm":return S(n)?".js":".mjs";case"cjs":return S(n)?".cjs":".js";case"iife":return".global.js"}}function ce(e,n){switch(e){case"esm":return S(n)?".d.ts":".d.mts";case"cjs":return S(n)?".d.cts":".d.ts";case"iife":return".d.ts"}}function K(e){return e==="node"||e==="bun"}function S(e){return e==="module"}function j(e){return e>=1000?`${(e/1000).toFixed(2)}s`:`${Math.round(e)}ms`}function le(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function Y(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 ue(e,n){let t=Ye.join(e,n);try{await re.rm(t,{recursive:!0,force:!0})}catch(r){throw new C(`Failed to clean output directory: ${r}`)}await re.mkdir(t,{recursive:!0})}function I(e){return[".ts",".mts",".cts",".tsx"].some((n)=>e.endsWith(n))}function fe(e){return e.map((n)=>typeof n==="string"?new RegExp(`^${G(n)}($|\\/|\\\\)`):n)}function k(e,n){return fe(e.external||[]).concat(le(n).map((t)=>new RegExp(`^${G(t)}($|\\/|\\\\)`)))}function _(e){return fe(e.noExternal||[])}import be from"node:path";import{ResolverFactory as ze}from"oxc-resolver";import{resolveTsImportPath as Xe}from"ts-import-resolver";var L="\x00dts:",me=(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?Xe({path:r,importer:E(s),tsconfig:n.tsconfig,rootDir:t}):null;if(!o)return null;let i=w(o);if(e.has(i))return N(i);return null},load(r){if(r.startsWith(L)){let s=E(r),o=e.get(s);if(o)return B.add(s),o}return null}}};function pe(e){return e.tsconfig.compilerOptions??{}}function de(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}function ge(e){return/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/.test(e)&&!de(e)}function w(e){if(de(e))return e;return e.replace(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,".d.ts")}function X(e){return e.startsWith(L)}function E(e){return e.replace(L,"")}function N(e){return`${L}${e}`}function he(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 z;function xe(e,n){return{name:"bunup:types-resolve",buildStart(){z||=new ze({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?E(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?be.dirname(s):process.cwd(),{path:i}=await z.async(o,t);if(!i)return;if(ge(i)){let a=w(i);try{let{path:c}=await z.async(be.dirname(i),a);if(c)return c}catch(c){}return}return i}}}async function ye(e,n,t,r,s,o){let i=w(e),a=N(i),c=k(t,r),l=_(t),f=typeof t.dts==="object"&&"resolve"in t.dts?t.dts.resolve:void 0;try{let{output:p}=await Qe({input:a,output:{dir:t.outDir},write:!1,onwarn(m,T){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(m.code??""))return;T(m)},plugins:[me(n,s,o),f&&xe(s,f),Ze({dtsInput:!0,emitDtsOnly:!0,compilerOptions:{...pe(s),declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:99}})],external:(m)=>he(m,c,l,f)});if(!p[0]?.code)return u.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return p[0].code}catch(p){throw new g(`DTS bundling failed for entry "${e}": ${h(p)}`)}}import{resolveTsImportPath as Je}from"ts-import-resolver";var Ve=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,en=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,nn=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,tn=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,rn=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,sn=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,on=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function an(e){let n=new Set,t=[Ve,en,nn,tn,rn,sn,on];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 we(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=an(i);for(let c of a){let l=n.tsconfig?Je({path:c,importer:o,tsconfig:n.tsconfig,rootDir:t}):null;if(!l)continue;if(!r.has(l))r.add(l),s.push(l)}}catch(i){u.warn(`Error processing ${o}: ${h(i)}`)}}return r}import{isolatedDeclaration as cn}from"oxc-transform";async function Ce(e){let n=new Map;return await Promise.all([...e].map(async(t)=>{try{let r=w(t);if(!await Bun.file(t).exists())return;let o=await Bun.file(t).text(),{code:i}=cn(t,o);if(i)n.set(r,i)}catch(r){u.warn(`Failed to generate declaration for ${t}: ${h(r)}`)}})),n}import $e from"node:fs/promises";import Q from"node:path";import{isolatedDeclaration as ln}from"oxc-transform";async function Oe(e,n){let t=Q.resolve(e),r=Q.resolve(t,n);if(!await $e.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(Q.relative(t,r).startsWith(".."))throw new g(`Entry file must be within rootDir: ${r}`);return{absoluteRootDir:t,absoluteEntry:r}}async function Se(e){let n=!1;if(await Promise.all([...e].map(async(t)=>{try{let r=t.replace(/\.d\.ts$/,".ts"),s=await Bun.file(r).text(),{errors:o}=ln(r,s);for(let i of o){if(!n)console.log(`
6
+ `);let a=i.labels[0],c=a?un(s,a.start):"",f=`${y(r)}${c}: ${fn(i.message)}`;u.warn(f),n=!0}}catch{}})),n)u.info(`
7
7
  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. Other bundlers might not show these warnings because they use different, potentially less precise methods. 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.
8
- `)}function at(e,t){if(t===void 0)return"";let n=e.slice(0,t).split(`
9
- `),r=n.length,s=n[n.length-1].length+1;return` (${r}:${s})`}function lt(e){return e.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}async function Se(e,t,n,r,s){let{absoluteEntry:o}=await Ee(e,t),i=await ye(o,r,e),a=await we(i);return xe(o,a,n,s,r,e)}function _(e){return e.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function P(e,{warnOnConflict:t=!0}={}){let n=[],r=new Set,s={};function o(i,a){if(r.has(i)){let l=se(),c=`${i}_${l}`;if(t)u.warn(`Output name conflict: "${i}" is used by multiple files.
8
+ `)}function un(e,n){if(n===void 0)return"";let t=e.slice(0,n).split(`
9
+ `),r=t.length,s=t[t.length-1].length+1;return` (${r}:${s})`}function fn(e){return e.replace(" with --isolatedDeclarations","").replace(" with --isolatedDeclaration","")}async function Be(e,n,t,r,s){let{absoluteEntry:o}=await Oe(e,n),i=await we(o,r,e),a=await Ce(i);return ye(o,a,t,s,r,e)}function P(e){return e.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function R(e,{warnOnConflict:n=!0}={}){let t=[],r=new Set,s={};function o(i,a){if(r.has(i)){let c=se(),l=`${i}_${c}`;if(n)u.warn(`Output name conflict: "${i}" is used by multiple files.
10
10
  Bunup uses filenames without extensions as output names by default.
11
11
 
12
12
  ${s[i]} -> ${i}.js
13
- ${a} -> ${c}.js (auto-renamed to avoid conflict)
13
+ ${a} -> ${l}.js (auto-renamed to avoid conflict)
14
14
 
15
15
  To fix this, use named entries in your configuration:
16
16
  {
@@ -20,18 +20,18 @@ To fix this, use named entries in your configuration:
20
20
  }
21
21
  }
22
22
 
23
- See: https://bunup.arshadyaseen.com/documentation/#named-entries`,{muted:!0,verticalSpace:!0});n.push({name:c,path:a})}else n.push({name:i,path:a}),r.add(i),s[i]=a}if(Array.isArray(e))for(let i of e){let a=_(i);o(a,i)}else if(typeof e==="object")for(let[i,a]of Object.entries(e))o(i,a);else{let i=_(e);o(i,e)}return n}function $e(e){return e.filter((t)=>I(t.path))}function Te(e,t){return`[dir]/${e}${t}`}import{loadConfig as Re}from"coffi";async function Pe(e,t){return Array.isArray(e)&&"root"in e[0]?e.map((n)=>({rootDir:n.root,options:ie(n.config,"name",n.name)})):[{rootDir:t,options:e}]}async function Be(e){let{config:t,filepath:n}=await Re({name:"package",cwd:e,extensions:[".json"],maxDepth:3});return{packageJson:t,path:n}}async function Le(e,t){let{config:n,filepath:r}=await Re({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:t,maxDepth:3});return{tsconfig:n,path:r}}var ct={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function k(e){return{...ct,...e}}function De(e){let{minify:t,minifyWhitespace:n,minifyIdentifiers:r,minifySyntax:s}=e,o=t===!0;return{whitespace:n??o,identifiers:r??o,syntax:s??o}}function Ie(e,t){return t==="cjs"?e:void 0}function Ae(e,t,n,r){return{...typeof n==="object"&&Object.keys(n).reduce((s,o)=>{let i=JSON.stringify(n[o]);return s[`process.env.${o}`]=i,s[`import.meta.env.${o}`]=i,s},{}),...e,...r==="cjs"&&(t===!0||typeof t==="object"&&t.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Me(e,t){return e===void 0?t==="esm":e}function je(e){return typeof e==="string"?e:void 0}function _e(e,t){return{name:"bunup:external-plugin",setup(n){n.onResolve({filter:/.*/},(r)=>{let s=r.path;if(e.some((i)=>i.test(s))&&!t.some((i)=>i.test(s)))return{path:s,external:!0};return null})}}}var ut=/\.(js|ts|jsx|tsx|mts|cts)$/,z={dirnameFilename:{appliesTo:(e,t)=>e==="esm"&&G(t),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
23
+ See: https://bunup.arshadyaseen.com/documentation/#named-entries`,{muted:!0,verticalSpace:!0});t.push({name:l,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=P(i);o(a,i)}else if(typeof e==="object")for(let[i,a]of Object.entries(e))o(i,a);else{let i=P(e);o(i,e)}return t}function Te(e){return e.filter((n)=>I(n.path))}function Ee(e,n){return`[dir]/${e}${n}`}import{loadConfig as Le}from"coffi";async function Re(e,n){return Array.isArray(e)&&"root"in e[0]?e.map((t)=>({rootDir:t.root,options:ie(t.config,"name",t.name)})):[{rootDir:n,options:e}]}async function Ae(e){let{config:n,filepath:t}=await Le({name:"package",cwd:e,extensions:[".json"],maxDepth:3});return{packageJson:n,path:t}}async function Me(e,n){let{config:t,filepath:r}=await Le({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:n,maxDepth:3});return{tsconfig:t,path:r}}var mn={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function U(e){return{...mn,...e}}function je(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 Ie(e,n){return n==="cjs"?e:void 0}function ke(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 _e(e,n){return e===void 0?n==="esm":e}function Ne(e){return typeof e==="string"?e:void 0}function Pe(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 pn=/\.(js|ts|jsx|tsx|mts|cts)$/,Z={dirnameFilename:{appliesTo:(e,n)=>e==="esm"&&K(n),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
24
24
  import { dirname } from 'path';
25
25
 
26
26
  const __filename = fileURLToPath(import.meta.url);
27
27
  const __dirname = dirname(__filename);
28
28
 
29
- `},importMetaUrl:{appliesTo:(e,t)=>e==="cjs"&&G(t),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
29
+ `},importMetaUrl:{appliesTo:(e,n)=>e==="cjs"&&K(n),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
30
30
 
31
31
  const importMetaUrl = pathToFileURL(__filename).href;
32
32
 
33
- `}};function ke({format:e,target:t,shims:n}){let s=ft(n).map((o)=>z[o]).filter((o)=>o.appliesTo(e,t));if(s.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:ut},async({path:i})=>{let a=await Bun.file(i).text(),l=s.filter((p)=>p.isNeededInFile(a));if(l.length===0)return;let{shebangLine:c,codeContent:f}=pt(a),m=l.map((p)=>p.generateCode()).join("");return{contents:c+m+f}})}}}function ft(e){if(e===!0)return Object.keys(z);if(!e)return[];return Object.entries(e).filter(([t,n])=>n&&(t in z)).map(([t])=>t)}function pt(e){if(!e.startsWith("#!"))return{shebangLine:"",codeContent:e};let t=e.indexOf(`
34
- `);return t===-1?{shebangLine:"",codeContent:e}:{shebangLine:e.slice(0,t+1),codeContent:e.slice(t+1)}}var $=new Set;async function v(e,t){let n=k(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)ue(t,n.outDir);B(n.silent);let{packageJson:r,path:s}=await Be(t);if(r&&s)u.cli(`Using package.json: ${y(s,2)}`,{muted:!0,identifier:n.name,once:`${s}:${n.name}`});let o=P(n.entry),i=r?.type,a=A(n,r),l=M(n);if(!n.dtsOnly){let c=[_e(a,l)],f=n.format.flatMap((m)=>o.map((p)=>{return mt(n,t,p,m,i,c)}));await Promise.all(f)}if(n.dts||n.dtsOnly){let c=await Le(t,n.preferredTsconfigPath);if(c.path)u.cli(`Using tsconfig: ${y(c.path,2)}`,{muted:!0,identifier:n.name,once:`${c.path}:${n.name}`});let f=n.format.filter((p)=>{if(p==="iife"&&!S(i)&&n.format.includes("cjs"))return!1;return!0}),m=typeof n.dts==="object"&&n.dts.entry?P(n.dts.entry):$e(o);try{await Promise.all(m.map(async(p)=>{let W=await Se(t,p.path,n,c,r);await Promise.all(f.map(async(ee)=>{let We=n.outputExtension?.({format:ee,packageType:i,options:n,entry:p}).dts??le(ee,i),H=`${t}/${n.outDir}/${p.name}${We}`;await Bun.write(H,W);let He=Bun.file(H).size||0;u.progress("DTS",y(H),X(He),n.name)}))}))}catch(p){throw new g(h(p))}}if(n.onBuildSuccess)await n.onBuildSuccess(n)}async function mt(e,t,n,r,s,o){let i=e.outputExtension?.({format:r,packageType:s,options:e,entry:n}).js??ae(r,s),a=await Bun.build({entrypoints:[`${t}/${n.path}`],format:r,naming:{entry:Te(n.name,i)},splitting:Me(e.splitting,r),bytecode:Ie(e.bytecode,r),define:Ae(e.define,e.shims,e.env,r),minify:De(e),outdir:`${t}/${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:[...o,ke({format:r,target:e.target,shims:e.shims}),...e.bunBuildPlugins??[]],throw:!1});if(!a.success)for(let f of a.logs){if(f.level==="error")throw new C(f.message);if(f.level==="warning")u.warn(f.message);else if(f.level==="info")u.info(f.message)}let l=`${t}/${e.outDir}/${n.name}${i}`,c=Bun.file(l).size||0;u.progress(r.toUpperCase(),y(l),X(c),e.name)}var U="0.4.36";var ve="https://bunup.arshadyaseen.com/documentation/#cli-options";function d(e){return(t,n)=>{n[e]=t===!0||t==="true"}}function x(e){return(t,n)=>{if(typeof t==="string")n[e]=t;else throw new b(`Option --${e} requires a string value`)}}function Q(e){return(t,n)=>{if(typeof t==="string")n[e]=t.split(",");else throw new b(`Option --${e} requires a string value`)}}function gt(e){return(t,n)=>{if(typeof t==="boolean")n[e]=t;else if(typeof t==="string")if(t.toLowerCase()==="true"||t.toLowerCase()==="false")n[e]=t.toLowerCase()==="true";else n[e]=t;else throw new b(`Option --${e} requires a boolean or string value`)}}function ht(){console.log(`
33
+ `}};function Ue({format:e,target:n,shims:t}){let s=dn(t).map((o)=>Z[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:pn},async({path:i})=>{let a=await Bun.file(i).text(),c=s.filter((m)=>m.isNeededInFile(a));if(c.length===0)return;let{shebangLine:l,codeContent:f}=gn(a),p=c.map((m)=>m.generateCode()).join("");return{contents:l+p+f}})}}}function dn(e){if(e===!0)return Object.keys(Z);if(!e)return[];return Object.entries(e).filter(([n,t])=>t&&(n in Z)).map(([n])=>n)}function gn(e){if(!e.startsWith("#!"))return{shebangLine:"",codeContent:e};let n=e.indexOf(`
34
+ `);return n===-1?{shebangLine:"",codeContent:e}:{shebangLine:e.slice(0,n+1),codeContent:e.slice(n+1)}}function He(e){return e.filter((n)=>n.type==="bun").map((n)=>n.plugin)}var B=new Set;async function H(e,n){let t=U(e);if(!t.entry||t.entry.length===0||!t.outDir)throw new C("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)ue(n,t.outDir);A(t.silent);let{packageJson:r,path:s}=await Ae(n);if(r&&s)u.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=k(t,r),c=_(t);if(!t.dtsOnly){let l=[Pe(a,c),...He(t.plugins??[])],f=t.format.flatMap((p)=>o.map((m)=>{return hn(t,n,m,p,i,l)}));await Promise.all(f)}if(t.dts||t.dtsOnly){let l=await Me(n,t.preferredTsconfigPath);if(l.path)u.cli(`Using tsconfig: ${y(l.path,2)}`,{muted:!0,identifier:t.name,once:`${l.path}:${t.name}`});let f=t.format.filter((m)=>{if(m==="iife"&&!S(i)&&t.format.includes("cjs"))return!1;return!0}),p=typeof t.dts==="object"&&t.dts.entry?R(t.dts.entry):Te(o);try{await Promise.all(p.map(async(m)=>{let T=await Be(n,m.path,t,l,r);await Promise.all(f.map(async(ee)=>{let Fe=t.outputExtension?.({format:ee,packageType:i,options:t,entry:m}).dts??ce(ee,i),q=`${n}/${t.outDir}/${m.name}${Fe}`;await Bun.write(q,T);let Ge=Bun.file(q).size||0;u.progress("DTS",y(q),Y(Ge),t.name)}))}))}catch(m){throw new g(h(m))}}if(t.onBuildSuccess)await t.onBuildSuccess(t)}async function hn(e,n,t,r,s,o){let i=e.outputExtension?.({format:r,packageType:s,options:e,entry:t}).js??ae(r,s),a=await Bun.build({entrypoints:[`${n}/${t.path}`],format:r,naming:{entry:Ee(t.name,i)},splitting:_e(e.splitting,r),bytecode:Ie(e.bytecode,r),define:ke(e.define,e.shims,e.env,r),minify:je(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:Ne(e.env),plugins:[...o,Ue({format:r,target:e.target,shims:e.shims})],throw:!1});if(!a.success)for(let f of a.logs){if(f.level==="error")throw new C(f.message);if(f.level==="warning")u.warn(f.message);else if(f.level==="info")u.info(f.message)}let c=`${n}/${e.outDir}/${t.name}${i}`,l=Bun.file(c).size||0;u.progress(r.toUpperCase(),y(c),Y(l),e.name)}var W="0.4.38";var We="https://bunup.arshadyaseen.com/documentation/#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 b(`Option --${e} requires a string value`)}}function J(e){return(n,t)=>{if(typeof n==="string")t[e]=n.split(",");else throw new b(`Option --${e} requires a string value`)}}function xn(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 b(`Option --${e} requires a boolean or string value`)}}function yn(){console.log(`
35
35
  Bunup - An extremely fast, zero-config bundler for JavaScript and TypeScript, powered by Bun.
36
- `),console.log("For more information on available options, visit:"),console.log(`\x1B[36m\x1B[4m${ve}\x1B[0m
37
- `),process.exit(0)}function bt(){console.log(U),process.exit(0)}var Ue={name:{flags:["n","name"],handler:x("name")},format:{flags:["f","format"],handler:Q("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:Q("external")},sourcemap:{flags:["sm","sourcemap"],handler:gt("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:Q("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,t,n)=>{if(typeof e!=="string")throw new b(`Entry${n?` --entry.${n}`:""} requires a string value`);let r=t.entry||{};if(n){if(r[n])u.warn(`Duplicate entry name '${n}' provided via --entry.${n}. Overwriting previous entry.`);r[n]=e}else{let s=_(e);if(r[s])u.warn(`Duplicate entry name '${s}' derived from '${e}'. Overwriting previous entry.`);r[s]=e}t.entry=r}},resolveDts:{flags:["rd","resolve-dts"],handler:(e,t)=>{if(!t.dts)t.dts={};if(typeof t.dts==="boolean")t.dts={};if(typeof e==="string")if(e==="true"||e==="false")t.dts.resolve=e==="true";else t.dts.resolve=e.split(",");else t.dts.resolve=!0}},help:{flags:["h","help"],handler:()=>ht()},version:{flags:["v","version"],handler:()=>bt()}},N={};for(let e of Object.values(Ue))for(let t of e.flags)N[t]=e.handler;function Ne(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];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[n+1];if(o=i&&!i.startsWith("-")?i:!0,typeof o==="string")n++}if(s.includes(".")){let[i,a]=s.split(".",2),l=N[i];if(l)l(o,t,a);else throw new b(`Unknown option: --${s}`)}else{let i=N[s];if(i)i(o,t);else throw new b(`Unknown option: --${s}`)}}else if(r.startsWith("-")){let s=r.slice(1),o=e[n+1],i=o&&!o.startsWith("-")?o:!0;if(typeof i==="string")n++;let a=N[s];if(a)a(i,t);else throw new b(`Unknown option: -${s}`)}else Ue.entry.handler(r,t,void 0)}return t}import{loadConfig as wt}from"coffi";import F from"node:path";import xt from"chokidar";async function Fe(e,t){let n=new Set,r=k(e),s=P(r.entry);for(let l of s){let c=F.resolve(t,l.path),f=F.dirname(c);n.add(f)}let o=xt.watch(Array.from(n),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignoreInitial:!0,atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,F.join(t,r.outDir)]}),i=!1,a=async(l=!1)=>{if(i)return;i=!0;try{let c=performance.now();if(await v({...r,entry:s.map((f)=>f.path),clean:!1},t),!l)u.cli(`\uD83D\uDCE6 Rebuild finished in ${D(performance.now()-c)}`);await Z()}catch(c){q(c)}finally{i=!1}};o.on("change",(l)=>{let c=F.relative(t,l);u.cli(`File changed: ${c}`,{muted:!0,once:c}),a()}),o.on("error",(l)=>{throw new L(`Watcher error: ${h(l)}`)}),await a(!0)}async function Ct(e=Bun.argv.slice(2)){let t=Ne(e);B(t.silent);let n=process.cwd(),{config:r,filepath:s}=await wt({name:"bunup.config",extensions:[".ts",".js",".mjs",".cjs"],maxDepth:1,preferredPath:t.config}),o=!r?[{rootDir:n,options:t}]:await Pe(r,n);if(u.cli(`Using bunup v${U} and bun v${Bun.version}`,{muted:!0}),s)u.cli(`Using config file: ${y(s,2)}`,{muted:!0});let i=performance.now();u.cli("Build started"),await Promise.all(o.flatMap(({options:c,rootDir:f})=>{return oe(c).map(async(p)=>{let W={...p,...Et(t)};return Ot(W,f)})}));let a=performance.now()-i,l=D(a);if(u.cli(`\u26A1\uFE0F Build completed in ${l}`),await Z(),t.watch)u.cli("\uD83D\uDC40 Watching for file changes");if(t.onSuccess)u.cli(`Running command: ${t.onSuccess}`,{muted:!0}),yt(t.onSuccess,[],{nodeOptions:{shell:!0,stdio:"inherit"}});if(!t.watch)process.exit(0)}function Et(e){return{...e,onSuccess:void 0,config:void 0}}async function Z(){if($.size>0)await Oe($),$.clear()}async function Ot(e,t){if(e.watch)await Fe(e,t);else await v(e,t)}Ct().catch((e)=>ne(e));export{Z as validateDtsFiles};
36
+ `),console.log("For more information on available options, visit:"),console.log(`\x1B[36m\x1B[4m${We}\x1B[0m
37
+ `),process.exit(0)}function wn(){console.log(W),process.exit(0)}var De={name:{flags:["n","name"],handler:x("name")},format:{flags:["f","format"],handler:J("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:J("external")},sourcemap:{flags:["sm","sourcemap"],handler:xn("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:J("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 b(`Entry${t?` --entry.${t}`:""} requires a string value`);let r=n.entry||{};if(t){if(r[t])u.warn(`Duplicate entry name '${t}' provided via --entry.${t}. Overwriting previous entry.`);r[t]=e}else{let s=P(e);if(r[s])u.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:()=>yn()},version:{flags:["v","version"],handler:()=>wn()}},D={};for(let e of Object.values(De))for(let n of e.flags)D[n]=e.handler;function ve(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=D[i];if(c)c(o,n,a);else throw new b(`Unknown option: --${s}`)}else{let i=D[s];if(i)i(o,n);else throw new b(`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=D[s];if(a)a(i,n);else throw new b(`Unknown option: -${s}`)}else De.entry.handler(r,n,void 0)}return n}import{loadConfig as On}from"coffi";import v from"node:path";import Cn from"chokidar";async function qe(e,n){let t=new Set,r=U(e),s=R(r.entry);for(let c of s){let l=v.resolve(n,c.path),f=v.dirname(l);t.add(f)}let o=Cn.watch(Array.from(t),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignoreInitial:!0,atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,v.join(n,r.outDir)]}),i=!1,a=async(c=!1)=>{if(i)return;i=!0;try{let l=performance.now();if(await H({...r,entry:s.map((f)=>f.path),clean:!1},n),!c)u.cli(`\uD83D\uDCE6 Rebuild finished in ${j(performance.now()-l)}`);await V()}catch(l){F(l)}finally{i=!1}};o.on("change",(c)=>{let l=v.relative(n,c);u.cli(`File changed: ${l}`,{muted:!0,once:l}),a()}),o.on("error",(c)=>{throw new M(`Watcher error: ${h(c)}`)}),await a(!0)}async function Sn(e=Bun.argv.slice(2)){let n=ve(e);A(n.silent);let t=process.cwd(),{config:r,filepath:s}=await On({name:"bunup.config",extensions:[".ts",".js",".mjs",".cjs"],maxDepth:1,preferredPath:n.config}),o=!r?[{rootDir:t,options:n}]:await Re(r,t);if(u.cli(`Using bunup v${W} and bun v${Bun.version}`,{muted:!0}),s)u.cli(`Using config file: ${y(s,2)}`,{muted:!0});let i=performance.now();u.cli("Build started"),await Promise.all(o.flatMap(({options:l,rootDir:f})=>{return oe(l).map(async(m)=>{let T={...m,...Bn(n)};return Tn(T,f)})}));let a=performance.now()-i,c=j(a);if(u.cli(`\u26A1\uFE0F Build completed in ${c}`),await V(),n.watch)u.cli("\uD83D\uDC40 Watching for file changes");if(n.onSuccess)u.cli(`Running command: ${n.onSuccess}`,{muted:!0}),$n(n.onSuccess,[],{nodeOptions:{shell:!0,stdio:"inherit"}});if(!n.watch)process.exit(0)}function Bn(e){return{...e,onSuccess:void 0,config:void 0}}async function V(){if(B.size>0)await Se(B),B.clear()}async function Tn(e,n){if(e.watch)await qe(e,n);else await H(e,n)}Sn().catch((e)=>te(e));export{V as validateDtsFiles};
package/build/index.d.mts CHANGED
@@ -6,6 +6,13 @@ type ProcessableEntry = {
6
6
  path: string
7
7
  };
8
8
 
9
+ //#endregion
10
+ //#region \0dts:/home/runner/work/bunup/bunup/src/plugins/types.d.ts
11
+ type Plugin<T extends "bun" = "bun"> = {
12
+ type: T
13
+ plugin: T extends "bun" ? BunPlugin : never
14
+ };
15
+
9
16
  //#endregion
10
17
  //#region \0dts:/home/runner/work/bunup/bunup/src/options.d.ts
11
18
  type Loader = NonNullable<BunBuildOptions["loader"]>[string];
@@ -27,6 +34,7 @@ type ShimOptions = {
27
34
  importMetaUrl?: boolean
28
35
  };
29
36
  type Shims = boolean | ShimOptions;
37
+ type DtsResolve = boolean | (string | RegExp)[];
30
38
  type DtsOptions = {
31
39
  /**
32
40
  * Entry point files for TypeScript declaration file generation
@@ -58,7 +66,7 @@ type DtsOptions = {
58
66
  /**
59
67
  * Resolve external types used in dts files from node_modules
60
68
  */
61
- resolve?: boolean | (string | RegExp)[]
69
+ resolve?: DtsResolve
62
70
  };
63
71
  interface BuildOptions {
64
72
  /**
@@ -341,11 +349,32 @@ interface BuildOptions {
341
349
  */
342
350
  env?: Env;
343
351
  /**
344
- * Custom Bun.build plugins to be applied during the build process..
352
+ * Plugins to extend the build process functionality
345
353
  *
346
- * @see https://bun.sh/docs/bundler/plugins for more information about Bun's plugin system
347
- */
348
- bunBuildPlugins?: BunPlugin[];
354
+ * The Plugin type uses a discriminated union pattern with the 'type' field
355
+ * to support different plugin systems. Currently, only "bun" plugins are supported,
356
+ * but in the future, this will be extended to include "bunup" plugins as well.
357
+ *
358
+ * Each plugin type has its own specific plugin implementation:
359
+ * - "bun": Uses Bun's native plugin system (BunPlugin)
360
+ * - "bunup": Will use bunup's own plugin system (coming in future versions)
361
+ *
362
+ * This architecture allows for extensibility as more plugin systems are added.
363
+ *
364
+ * @example
365
+ * plugins: [
366
+ * {
367
+ * type: "bun",
368
+ * plugin: myBunPlugin()
369
+ * },
370
+ * // In the future:
371
+ * // {
372
+ * // type: "bunup",
373
+ * // plugin: myBunupPlugin()
374
+ * // }
375
+ * ]
376
+ */
377
+ plugins?: Plugin[];
349
378
  /**
350
379
  * Customize the output file extension for each format.
351
380
  *
@@ -397,4 +426,4 @@ declare function defineWorkspace(options: DefineWorkspaceItem[]): DefineWorkspac
397
426
  declare function build(partialOptions: Partial<BuildOptions>, rootDir: string): Promise<void>;
398
427
 
399
428
  //#endregion
400
- export { BuildOptions, DefineConfigItem, DefineWorkspaceItem, build, defineConfig, defineWorkspace };
429
+ export { BuildOptions, DefineConfigItem, DefineWorkspaceItem, Plugin, build, defineConfig, defineWorkspace };
package/build/index.d.ts CHANGED
@@ -6,6 +6,13 @@ type ProcessableEntry = {
6
6
  path: string
7
7
  };
8
8
 
9
+ //#endregion
10
+ //#region \0dts:/home/runner/work/bunup/bunup/src/plugins/types.d.ts
11
+ type Plugin<T extends "bun" = "bun"> = {
12
+ type: T
13
+ plugin: T extends "bun" ? BunPlugin : never
14
+ };
15
+
9
16
  //#endregion
10
17
  //#region \0dts:/home/runner/work/bunup/bunup/src/options.d.ts
11
18
  type Loader = NonNullable<BunBuildOptions["loader"]>[string];
@@ -27,6 +34,7 @@ type ShimOptions = {
27
34
  importMetaUrl?: boolean
28
35
  };
29
36
  type Shims = boolean | ShimOptions;
37
+ type DtsResolve = boolean | (string | RegExp)[];
30
38
  type DtsOptions = {
31
39
  /**
32
40
  * Entry point files for TypeScript declaration file generation
@@ -58,7 +66,7 @@ type DtsOptions = {
58
66
  /**
59
67
  * Resolve external types used in dts files from node_modules
60
68
  */
61
- resolve?: boolean | (string | RegExp)[]
69
+ resolve?: DtsResolve
62
70
  };
63
71
  interface BuildOptions {
64
72
  /**
@@ -341,11 +349,32 @@ interface BuildOptions {
341
349
  */
342
350
  env?: Env;
343
351
  /**
344
- * Custom Bun.build plugins to be applied during the build process..
352
+ * Plugins to extend the build process functionality
345
353
  *
346
- * @see https://bun.sh/docs/bundler/plugins for more information about Bun's plugin system
347
- */
348
- bunBuildPlugins?: BunPlugin[];
354
+ * The Plugin type uses a discriminated union pattern with the 'type' field
355
+ * to support different plugin systems. Currently, only "bun" plugins are supported,
356
+ * but in the future, this will be extended to include "bunup" plugins as well.
357
+ *
358
+ * Each plugin type has its own specific plugin implementation:
359
+ * - "bun": Uses Bun's native plugin system (BunPlugin)
360
+ * - "bunup": Will use bunup's own plugin system (coming in future versions)
361
+ *
362
+ * This architecture allows for extensibility as more plugin systems are added.
363
+ *
364
+ * @example
365
+ * plugins: [
366
+ * {
367
+ * type: "bun",
368
+ * plugin: myBunPlugin()
369
+ * },
370
+ * // In the future:
371
+ * // {
372
+ * // type: "bunup",
373
+ * // plugin: myBunupPlugin()
374
+ * // }
375
+ * ]
376
+ */
377
+ plugins?: Plugin[];
349
378
  /**
350
379
  * Customize the output file extension for each format.
351
380
  *
@@ -397,4 +426,4 @@ declare function defineWorkspace(options: DefineWorkspaceItem[]): DefineWorkspac
397
426
  declare function build(partialOptions: Partial<BuildOptions>, rootDir: string): Promise<void>;
398
427
 
399
428
  //#endregion
400
- export { BuildOptions, DefineConfigItem, DefineWorkspaceItem, build, defineConfig, defineWorkspace };
429
+ export { BuildOptions, DefineConfigItem, DefineWorkspaceItem, Plugin, build, defineConfig, defineWorkspace };
package/build/index.js CHANGED
@@ -1,26 +1,26 @@
1
- var Ge=require("node:module");var Fe=Object.create;var{getPrototypeOf:ke,defineProperty:w,getOwnPropertyNames:X,getOwnPropertyDescriptor:We}=Object,H=Object.prototype.hasOwnProperty;var C=(e,r,t)=>{t=e!=null?Fe(ke(e)):{};let n=r||!e||!e.__esModule?w(t,"default",{value:e,enumerable:!0}):t;for(let i of X(e))if(!H.call(n,i))w(n,i,{get:()=>e[i],enumerable:!0});return n},q=new WeakMap,Ue=(e)=>{var r=q.get(e),t;if(r)return r;if(r=w({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function")X(e).map((n)=>!H.call(r,n)&&w(r,n,{get:()=>e[n],enumerable:!(t=We(e,n))||t.enumerable}));return q.set(e,r),r};var Ve=(e,r)=>{for(var t in r)w(e,t,{get:r[t],enumerable:!0,configurable:!0,set:(n)=>r[t]=()=>n})};var st={};Ve(st,{defineWorkspace:()=>Y,defineConfig:()=>K,build:()=>Ae});module.exports=Ue(st);function K(e){return e}function Y(e){return e}var fe=require("rolldown"),ge=require("rolldown-plugin-dts");var v=!1;function J(e){v=e??!1}class h{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",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(!h.instance)h.instance=new h;return h.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:t,size:n,identifier:i,muted:o}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length)),a=o?`\x1B[38;5;${this.colors.info}m${t}\x1B[0m`:t;if(n){let[c,...l]=a.split(" "),g=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),m=i?` \x1B[48;5;${e};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${s}${c}${g} \x1B[38;5;${this.colors.size}m${n}\x1B[0m ${l.join(" ")}${m}`}let u=i?` \x1B[48;5;${e};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${s}${a}${u}`}output(e,r={},t=console.log){if(v)return;if(!this.shouldLog(r))return;if(r.verticalSpace)console.log("");if(t(e),r.verticalSpace)console.log("")}cli(e,r={}){let t=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r)}info(e,r={}){let t=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r)}warn(e,r={}){let t=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r,console.warn)}error(e,r={}){let t=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r,console.error)}progress(e,r,t,n){let i=String(e),o=this.colors.default,s,a,u={};if(typeof t==="string")s=t,a=n;else if(t)s=t.size,a=t.identifier,u=t;for(let[l,g]of Object.entries(this.colors.progress))if(i.includes(l)){o=g;break}let c=this.formatMessage({colorCode:o,label:i,message:r,size:s,identifier:a,muted:u.muted});this.output(c,u)}}var f=h.getInstance();class L extends Error{constructor(e){super(e);this.name="BunupError"}}class b extends L{constructor(e){super(e);this.name="BunupBuildError"}}class p extends L{constructor(e){super(e);this.name="BunupDTSBuildError"}}var d=(e)=>{if(e instanceof Error)return e.message;return String(e)};var I=C(require("node:fs/promises")),Q=C(require("node:path"));function M(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 y(r)?".js":".mjs";case"cjs":return y(r)?".cjs":".js";case"iife":return".global.js"}}function ee(e,r){switch(e){case"esm":return y(r)?".d.ts":".d.mts";case"cjs":return y(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function A(e){return e==="node"||e==="bun"}function y(e){return e==="module"}function te(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function j(e){if(e===0)return"0 B";let r=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(1024));if(t===0)return`${e} ${r[t]}`;return`${(e/1024**t).toFixed(2)} ${r[t]}`}function E(e,r=3){return e.split("/").slice(-r).join("/")}async function re(e,r){let t=Q.default.join(e,r);try{await I.default.rm(t,{recursive:!0,force:!0})}catch(n){throw new b(`Failed to clean output directory: ${n}`)}await I.default.mkdir(t,{recursive:!0})}function S(e){return[".ts",".mts",".cts",".tsx"].some((r)=>e.endsWith(r))}function ne(e){return e.map((r)=>typeof r==="string"?new RegExp(`^${M(r)}($|\\/|\\\\)`):r)}function T(e,r){return ne(e.external||[]).concat(te(r).map((t)=>new RegExp(`^${M(t)}($|\\/|\\\\)`)))}function B(e){return ne(e.noExternal||[])}var F=C(require("node:path")),le=require("oxc-resolver");var se=require("ts-import-resolver");var $="\x00dts:",ie=(e,r,t)=>{return{name:"bunup:virtual-dts",async resolveId(n,i){if(_(n))return n;if(!i||!_(i))return null;let o=r.tsconfig?se.resolveTsImportPath({path:n,importer:R(i),tsconfig:r.tsconfig,rootDir:t}):null;if(!o)return null;let s=x(o);if(e.has(s))return P(s);return null},load(n){if(n.startsWith($)){let i=R(n),o=e.get(i);if(o)return oe.add(i),o}return null}}};function ae(e){return e.tsconfig.compilerOptions??{}}function ue(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}function ce(e){return/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/.test(e)&&!ue(e)}function x(e){if(ue(e))return e;return e.replace(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,".d.ts")}function _(e){return e.startsWith($)}function R(e){return e.replace($,"")}function P(e){return`${$}${e}`}var N;function me(e,r){return{name:"bunup:types-resolve",buildStart(){N||=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(t,n){if(t==="bun")return;let i=n?R(n):void 0;if(/\0/.test(t))return;if(r){if(!r.some((u)=>typeof u==="string"?u===t:u.test(t)))return}let o=i?F.default.dirname(i):process.cwd(),{path:s}=await N.async(o,t);if(!s)return;if(ce(s)){let a=x(s);try{let{path:u}=await N.async(F.default.dirname(s),a);if(u)return u}catch(u){}return}return s}}}async function pe(e,r,t,n,i,o){let s=x(e),a=P(s),u=T(t,n),c=B(t);try{let{output:l}=await fe.build({input:a,output:{dir:t.outDir},write:!1,onwarn(g,m){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(g.code??""))return;m(g)},plugins:[ie(r,i,o),typeof t.dts==="object"&&"resolve"in t.dts&&me(i,typeof t.dts.resolve==="boolean"?void 0:t.dts.resolve),ge.dts({dtsInput:!0,emitDtsOnly:!0,compilerOptions:{...ae(i),declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:99}})],external:(g)=>u.some((m)=>m.test(g))&&!c.some((m)=>m.test(g))});if(!l[0]?.code)return f.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return l[0].code}catch(l){throw new p(`DTS bundling failed for entry "${e}": ${d(l)}`)}}var de=require("ts-import-resolver");var qe=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Xe=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,He=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ke=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ye=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,ve=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Je=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function Qe(e){let r=new Set,t=[qe,Xe,He,Ke,Ye,ve,Je];for(let n of t){let i=e.matchAll(n);for(let o of i)if(o[1])r.add(o[1])}return r}async function xe(e,r,t){let n=new Set([e]),i=[e];while(i.length){let o=i.pop();if(!o)continue;try{let s=await Bun.file(o).text(),a=Qe(s);for(let u of a){let c=r.tsconfig?de.resolveTsImportPath({path:u,importer:o,tsconfig:r.tsconfig,rootDir:t}):null;if(!c)continue;if(!n.has(c))n.add(c),i.push(c)}}catch(s){f.warn(`Error processing ${o}: ${d(s)}`)}}return n}var he=require("oxc-transform");async function be(e){let r=new Map;return await Promise.all([...e].map(async(t)=>{try{let n=x(t);if(!await Bun.file(t).exists())return;let o=await Bun.file(t).text(),{code:s}=he.isolatedDeclaration(t,o);if(s)r.set(n,s)}catch(n){f.warn(`Failed to generate declaration for ${t}: ${d(n)}`)}})),r}var k=C(require("node:fs/promises")),D=C(require("node:path")),Ze=require("oxc-transform");async function ye(e,r){let t=D.default.resolve(e),n=D.default.resolve(t,r);if(!await k.default.exists(t))throw new p(`Root directory does not exist: ${t}`);if(!await Bun.file(n).exists())throw new p(`Entry file does not exist: ${n}`);if(!S(n))throw new p(`Entry file must be a TypeScript file: ${n}`);if(D.default.relative(t,n).startsWith(".."))throw new p(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:t,absoluteEntry:n}}async function Ee(e,r,t,n,i){let{absoluteEntry:o}=await ye(e,r),s=await xe(o,n,e),a=await be(s);return pe(o,a,t,i,n,e)}function we(e){return e.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function W(e,{warnOnConflict:r=!0}={}){let t=[],n=new Set,i={};function o(s,a){if(n.has(s)){let u=Z(),c=`${s}_${u}`;if(r)f.warn(`Output name conflict: "${s}" is used by multiple files.
1
+ var Ke=require("node:module");var Ue=Object.create;var{getPrototypeOf:Ge,defineProperty:C,getOwnPropertyNames:X,getOwnPropertyDescriptor:qe}=Object,Y=Object.prototype.hasOwnProperty;var $=(e,r,t)=>{t=e!=null?Ue(Ge(e)):{};let n=r||!e||!e.__esModule?C(t,"default",{value:e,enumerable:!0}):t;for(let s of X(e))if(!Y.call(n,s))C(n,s,{get:()=>e[s],enumerable:!0});return n},K=new WeakMap,Fe=(e)=>{var r=K.get(e),t;if(r)return r;if(r=C({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function")X(e).map((n)=>!Y.call(r,n)&&C(r,n,{get:()=>e[n],enumerable:!(t=qe(e,n))||t.enumerable}));return K.set(e,r),r};var He=(e,r)=>{for(var t in r)C(e,t,{get:r[t],enumerable:!0,configurable:!0,set:(n)=>r[t]=()=>n})};var or={};He(or,{defineWorkspace:()=>Z,defineConfig:()=>Q,build:()=>We});module.exports=Fe(or);function Q(e){return e}function Z(e){return e}var pe=require("rolldown"),de=require("rolldown-plugin-dts");var z=!1;function J(e){z=e??!1}class b{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",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:r,message:t,size:n,identifier:s,muted:o}){let i=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length)),a=o?`\x1B[38;5;${this.colors.info}m${t}\x1B[0m`:t;if(n){let[c,...m]=a.split(" "),g=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),l=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${i}${c}${g} \x1B[38;5;${this.colors.size}m${n}\x1B[0m ${m.join(" ")}${l}`}let u=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${i}${a}${u}`}output(e,r={},t=console.log){if(z)return;if(!this.shouldLog(r))return;if(r.verticalSpace)console.log("");if(t(e),r.verticalSpace)console.log("")}cli(e,r={}){let t=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r)}info(e,r={}){let t=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r)}warn(e,r={}){let t=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r,console.warn)}error(e,r={}){let t=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r,console.error)}progress(e,r,t,n){let s=String(e),o=this.colors.default,i,a,u={};if(typeof t==="string")i=t,a=n;else if(t)i=t.size,a=t.identifier,u=t;for(let[m,g]of Object.entries(this.colors.progress))if(s.includes(m)){o=g;break}let c=this.formatMessage({colorCode:o,label:s,message:r,size:i,identifier:a,muted:u.muted});this.output(c,u)}}var f=b.getInstance();class j extends Error{constructor(e){super(e);this.name="BunupError"}}class h extends j{constructor(e){super(e);this.name="BunupBuildError"}}class p extends j{constructor(e){super(e);this.name="BunupDTSBuildError"}}var d=(e)=>{if(e instanceof Error)return e.message;return String(e)};var I=$(require("node:fs/promises")),V=$(require("node:path"));function N(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v(e=8){let r="";while(r.length<e)r+=Math.random().toString(36).substring(2);return r.substring(0,e)}function ee(e,r){switch(e){case"esm":return y(r)?".js":".mjs";case"cjs":return y(r)?".cjs":".js";case"iife":return".global.js"}}function re(e,r){switch(e){case"esm":return y(r)?".d.ts":".d.mts";case"cjs":return y(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function _(e){return e==="node"||e==="bun"}function y(e){return e==="module"}function te(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function D(e){if(e===0)return"0 B";let r=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(1024));if(t===0)return`${e} ${r[t]}`;return`${(e/1024**t).toFixed(2)} ${r[t]}`}function w(e,r=3){return e.split("/").slice(-r).join("/")}async function ne(e,r){let t=V.default.join(e,r);try{await I.default.rm(t,{recursive:!0,force:!0})}catch(n){throw new h(`Failed to clean output directory: ${n}`)}await I.default.mkdir(t,{recursive:!0})}function B(e){return[".ts",".mts",".cts",".tsx"].some((r)=>e.endsWith(r))}function se(e){return e.map((r)=>typeof r==="string"?new RegExp(`^${N(r)}($|\\/|\\\\)`):r)}function T(e,r){return se(e.external||[]).concat(te(r).map((t)=>new RegExp(`^${N(t)}($|\\/|\\\\)`)))}function R(e){return se(e.noExternal||[])}var P=$(require("node:path")),fe=require("oxc-resolver");var ie=require("ts-import-resolver");var S="\x00dts:",oe=(e,r,t)=>{return{name:"bunup:virtual-dts",async resolveId(n,s){if(W(n))return n;if(!s||!W(s))return null;let o=r.tsconfig?ie.resolveTsImportPath({path:n,importer:E(s),tsconfig:r.tsconfig,rootDir:t}):null;if(!o)return null;let i=x(o);if(e.has(i))return O(i);return null},load(n){if(n.startsWith(S)){let s=E(n),o=e.get(s);if(o)return ae.add(s),o}return null}}};function ue(e){return e.tsconfig.compilerOptions??{}}function ce(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}function me(e){return/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/.test(e)&&!ce(e)}function x(e){if(ce(e))return e;return e.replace(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,".d.ts")}function W(e){return e.startsWith(S)}function E(e){return e.replace(S,"")}function O(e){return`${S}${e}`}function le(e,r,t,n){if(typeof n==="boolean"&&n)return!1;if(Array.isArray(n)){for(let s of n)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))&&!t.some((s)=>s.test(e))}var k;function ge(e,r){return{name:"bunup:types-resolve",buildStart(){k||=new fe.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(t,n){if(r===!1)return;if(t==="bun")return;let s=n?E(n):void 0;if(/\0/.test(t))return;if(Array.isArray(r)){if(!r.some((u)=>typeof u==="string"?u===t:u.test(t)))return}let o=s?P.default.dirname(s):process.cwd(),{path:i}=await k.async(o,t);if(!i)return;if(me(i)){let a=x(i);try{let{path:u}=await k.async(P.default.dirname(i),a);if(u)return u}catch(u){}return}return i}}}async function xe(e,r,t,n,s,o){let i=x(e),a=O(i),u=T(t,n),c=R(t),m=typeof t.dts==="object"&&"resolve"in t.dts?t.dts.resolve:void 0;try{let{output:g}=await pe.build({input:a,output:{dir:t.outDir},write:!1,onwarn(l,M){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(l.code??""))return;M(l)},plugins:[oe(r,s,o),m&&ge(s,m),de.dts({dtsInput:!0,emitDtsOnly:!0,compilerOptions:{...ue(s),declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:99}})],external:(l)=>le(l,u,c,m)});if(!g[0]?.code)return f.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return g[0].code}catch(g){throw new p(`DTS bundling failed for entry "${e}": ${d(g)}`)}}var be=require("ts-import-resolver");var Xe=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Ye=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Qe=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ze=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,ze=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Je=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Ve=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function ve(e){let r=new Set,t=[Xe,Ye,Qe,Ze,ze,Je,Ve];for(let n of t){let s=e.matchAll(n);for(let o of s)if(o[1])r.add(o[1])}return r}async function he(e,r,t){let n=new Set([e]),s=[e];while(s.length){let o=s.pop();if(!o)continue;try{let i=await Bun.file(o).text(),a=ve(i);for(let u of a){let c=r.tsconfig?be.resolveTsImportPath({path:u,importer:o,tsconfig:r.tsconfig,rootDir:t}):null;if(!c)continue;if(!n.has(c))n.add(c),s.push(c)}}catch(i){f.warn(`Error processing ${o}: ${d(i)}`)}}return n}var ye=require("oxc-transform");async function we(e){let r=new Map;return await Promise.all([...e].map(async(t)=>{try{let n=x(t);if(!await Bun.file(t).exists())return;let o=await Bun.file(t).text(),{code:i}=ye.isolatedDeclaration(t,o);if(i)r.set(n,i)}catch(n){f.warn(`Failed to generate declaration for ${t}: ${d(n)}`)}})),r}var U=$(require("node:fs/promises")),L=$(require("node:path")),er=require("oxc-transform");async function Ce(e,r){let t=L.default.resolve(e),n=L.default.resolve(t,r);if(!await U.default.exists(t))throw new p(`Root directory does not exist: ${t}`);if(!await Bun.file(n).exists())throw new p(`Entry file does not exist: ${n}`);if(!B(n))throw new p(`Entry file must be a TypeScript file: ${n}`);if(L.default.relative(t,n).startsWith(".."))throw new p(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:t,absoluteEntry:n}}async function $e(e,r,t,n,s){let{absoluteEntry:o}=await Ce(e,r),i=await he(o,n,e),a=await we(i);return xe(o,a,t,s,n,e)}function Ee(e){return e.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function G(e,{warnOnConflict:r=!0}={}){let t=[],n=new Set,s={};function o(i,a){if(n.has(i)){let u=v(),c=`${i}_${u}`;if(r)f.warn(`Output name conflict: "${i}" is used by multiple files.
2
2
  Bunup uses filenames without extensions as output names by default.
3
3
 
4
- ${i[s]} -> ${s}.js
4
+ ${s[i]} -> ${i}.js
5
5
  ${a} -> ${c}.js (auto-renamed to avoid conflict)
6
6
 
7
7
  To fix this, use named entries in your configuration:
8
8
  {
9
9
  entry: {
10
- custom_name: "${i[s]}",
10
+ custom_name: "${s[i]}",
11
11
  another_name: "${a}"
12
12
  }
13
13
  }
14
14
 
15
- See: https://bunup.arshadyaseen.com/documentation/#named-entries`,{muted:!0,verticalSpace:!0});t.push({name:c,path:a})}else t.push({name:s,path:a}),n.add(s),i[s]=a}if(Array.isArray(e))for(let s of e){let a=we(s);o(a,s)}else if(typeof e==="object")for(let[s,a]of Object.entries(e))o(s,a);else{let s=we(e);o(s,e)}return t}function Ce(e){return e.filter((r)=>S(r.path))}function Re(e,r){return`[dir]/${e}${r}`}var U=require("coffi");async function $e(e){let{config:r,filepath:t}=await U.loadConfig({name:"package",cwd:e,extensions:[".json"],maxDepth:3});return{packageJson:r,path:t}}async function Se(e,r){let{config:t,filepath:n}=await U.loadConfig({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:r,maxDepth:3});return{tsconfig:t,path:n}}var ze={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function Te(e){return{...ze,...e}}function Be(e){let{minify:r,minifyWhitespace:t,minifyIdentifiers:n,minifySyntax:i}=e,o=r===!0;return{whitespace:t??o,identifiers:n??o,syntax:i??o}}function Pe(e,r){return r==="cjs"?e:void 0}function De(e,r,t,n){return{...typeof t==="object"&&Object.keys(t).reduce((i,o)=>{let s=JSON.stringify(t[o]);return i[`process.env.${o}`]=s,i[`import.meta.env.${o}`]=s,i},{}),...e,...n==="cjs"&&(r===!0||typeof r==="object"&&r.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function Oe(e,r){return e===void 0?r==="esm":e}function Le(e){return typeof e==="string"?e:void 0}function Ie(e,r){return{name:"bunup:external-plugin",setup(t){t.onResolve({filter:/.*/},(n)=>{let i=n.path;if(e.some((s)=>s.test(i))&&!r.some((s)=>s.test(i)))return{path:i,external:!0};return null})}}}var et=/\.(js|ts|jsx|tsx|mts|cts)$/,V={dirnameFilename:{appliesTo:(e,r)=>e==="esm"&&A(r),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
15
+ See: https://bunup.arshadyaseen.com/documentation/#named-entries`,{muted:!0,verticalSpace:!0});t.push({name:c,path:a})}else t.push({name:i,path:a}),n.add(i),s[i]=a}if(Array.isArray(e))for(let i of e){let a=Ee(i);o(a,i)}else if(typeof e==="object")for(let[i,a]of Object.entries(e))o(i,a);else{let i=Ee(e);o(i,e)}return t}function Se(e){return e.filter((r)=>B(r.path))}function Be(e,r){return`[dir]/${e}${r}`}var q=require("coffi");async function Te(e){let{config:r,filepath:t}=await q.loadConfig({name:"package",cwd:e,extensions:[".json"],maxDepth:3});return{packageJson:r,path:t}}async function Re(e,r){let{config:t,filepath:n}=await q.loadConfig({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:r,maxDepth:3});return{tsconfig:t,path:n}}var rr={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function Oe(e){return{...rr,...e}}function Le(e){let{minify:r,minifyWhitespace:t,minifyIdentifiers:n,minifySyntax:s}=e,o=r===!0;return{whitespace:t??o,identifiers:n??o,syntax:s??o}}function Me(e,r){return r==="cjs"?e:void 0}function Ae(e,r,t,n){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,...n==="cjs"&&(r===!0||typeof r==="object"&&r.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function je(e,r){return e===void 0?r==="esm":e}function Ie(e){return typeof e==="string"?e:void 0}function Ne(e,r){return{name:"bunup:external-plugin",setup(t){t.onResolve({filter:/.*/},(n)=>{let s=n.path;if(e.some((i)=>i.test(s))&&!r.some((i)=>i.test(s)))return{path:s,external:!0};return null})}}}var tr=/\.(js|ts|jsx|tsx|mts|cts)$/,F={dirnameFilename:{appliesTo:(e,r)=>e==="esm"&&_(r),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
16
16
  import { dirname } from 'path';
17
17
 
18
18
  const __filename = fileURLToPath(import.meta.url);
19
19
  const __dirname = dirname(__filename);
20
20
 
21
- `},importMetaUrl:{appliesTo:(e,r)=>e==="cjs"&&A(r),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
21
+ `},importMetaUrl:{appliesTo:(e,r)=>e==="cjs"&&_(r),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
22
22
 
23
23
  const importMetaUrl = pathToFileURL(__filename).href;
24
24
 
25
- `}};function Me({format:e,target:r,shims:t}){let i=tt(t).map((o)=>V[o]).filter((o)=>o.appliesTo(e,r));if(i.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:et},async({path:s})=>{let a=await Bun.file(s).text(),u=i.filter((m)=>m.isNeededInFile(a));if(u.length===0)return;let{shebangLine:c,codeContent:l}=rt(a),g=u.map((m)=>m.generateCode()).join("");return{contents:c+g+l}})}}}function tt(e){if(e===!0)return Object.keys(V);if(!e)return[];return Object.entries(e).filter(([r,t])=>t&&(r in V)).map(([r])=>r)}function rt(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)}}var oe=new Set;async function Ae(e,r){let t=Te(e);if(!t.entry||t.entry.length===0||!t.outDir)throw new b("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)re(r,t.outDir);J(t.silent);let{packageJson:n,path:i}=await $e(r);if(n&&i)f.cli(`Using package.json: ${E(i,2)}`,{muted:!0,identifier:t.name,once:`${i}:${t.name}`});let o=W(t.entry),s=n?.type,a=T(t,n),u=B(t);if(!t.dtsOnly){let c=[Ie(a,u)],l=t.format.flatMap((g)=>o.map((m)=>{return nt(t,r,m,g,s,c)}));await Promise.all(l)}if(t.dts||t.dtsOnly){let c=await Se(r,t.preferredTsconfigPath);if(c.path)f.cli(`Using tsconfig: ${E(c.path,2)}`,{muted:!0,identifier:t.name,once:`${c.path}:${t.name}`});let l=t.format.filter((m)=>{if(m==="iife"&&!y(s)&&t.format.includes("cjs"))return!1;return!0}),g=typeof t.dts==="object"&&t.dts.entry?W(t.dts.entry):Ce(o);try{await Promise.all(g.map(async(m)=>{let je=await Ee(r,m.path,t,c,n);await Promise.all(l.map(async(G)=>{let _e=t.outputExtension?.({format:G,packageType:s,options:t,entry:m}).dts??ee(G,s),O=`${r}/${t.outDir}/${m.name}${_e}`;await Bun.write(O,je);let Ne=Bun.file(O).size||0;f.progress("DTS",E(O),j(Ne),t.name)}))}))}catch(m){throw new p(d(m))}}if(t.onBuildSuccess)await t.onBuildSuccess(t)}async function nt(e,r,t,n,i,o){let s=e.outputExtension?.({format:n,packageType:i,options:e,entry:t}).js??z(n,i),a=await Bun.build({entrypoints:[`${r}/${t.path}`],format:n,naming:{entry:Re(t.name,s)},splitting:Oe(e.splitting,n),bytecode:Pe(e.bytecode,n),define:De(e.define,e.shims,e.env,n),minify:Be(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:Le(e.env),plugins:[...o,Me({format:n,target:e.target,shims:e.shims}),...e.bunBuildPlugins??[]],throw:!1});if(!a.success)for(let l of a.logs){if(l.level==="error")throw new b(l.message);if(l.level==="warning")f.warn(l.message);else if(l.level==="info")f.info(l.message)}let u=`${r}/${e.outDir}/${t.name}${s}`,c=Bun.file(u).size||0;f.progress(n.toUpperCase(),E(u),j(c),e.name)}
25
+ `}};function _e({format:e,target:r,shims:t}){let s=nr(t).map((o)=>F[o]).filter((o)=>o.appliesTo(e,r));if(s.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:tr},async({path:i})=>{let a=await Bun.file(i).text(),u=s.filter((l)=>l.isNeededInFile(a));if(u.length===0)return;let{shebangLine:c,codeContent:m}=sr(a),g=u.map((l)=>l.generateCode()).join("");return{contents:c+g+m}})}}}function nr(e){if(e===!0)return Object.keys(F);if(!e)return[];return Object.entries(e).filter(([r,t])=>t&&(r in F)).map(([r])=>r)}function sr(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 ae=new Set;async function We(e,r){let t=Oe(e);if(!t.entry||t.entry.length===0||!t.outDir)throw new h("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)ne(r,t.outDir);J(t.silent);let{packageJson:n,path:s}=await Te(r);if(n&&s)f.cli(`Using package.json: ${w(s,2)}`,{muted:!0,identifier:t.name,once:`${s}:${t.name}`});let o=G(t.entry),i=n?.type,a=T(t,n),u=R(t);if(!t.dtsOnly){let c=[Ne(a,u),...De(t.plugins??[])],m=t.format.flatMap((g)=>o.map((l)=>{return ir(t,r,l,g,i,c)}));await Promise.all(m)}if(t.dts||t.dtsOnly){let c=await Re(r,t.preferredTsconfigPath);if(c.path)f.cli(`Using tsconfig: ${w(c.path,2)}`,{muted:!0,identifier:t.name,once:`${c.path}:${t.name}`});let m=t.format.filter((l)=>{if(l==="iife"&&!y(i)&&t.format.includes("cjs"))return!1;return!0}),g=typeof t.dts==="object"&&t.dts.entry?G(t.dts.entry):Se(o);try{await Promise.all(g.map(async(l)=>{let M=await $e(r,l.path,t,c,n);await Promise.all(m.map(async(H)=>{let ke=t.outputExtension?.({format:H,packageType:i,options:t,entry:l}).dts??re(H,i),A=`${r}/${t.outDir}/${l.name}${ke}`;await Bun.write(A,M);let Pe=Bun.file(A).size||0;f.progress("DTS",w(A),D(Pe),t.name)}))}))}catch(l){throw new p(d(l))}}if(t.onBuildSuccess)await t.onBuildSuccess(t)}async function ir(e,r,t,n,s,o){let i=e.outputExtension?.({format:n,packageType:s,options:e,entry:t}).js??ee(n,s),a=await Bun.build({entrypoints:[`${r}/${t.path}`],format:n,naming:{entry:Be(t.name,i)},splitting:je(e.splitting,n),bytecode:Me(e.bytecode,n),define:Ae(e.define,e.shims,e.env,n),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:Ie(e.env),plugins:[...o,_e({format:n,target:e.target,shims:e.shims})],throw:!1});if(!a.success)for(let m of a.logs){if(m.level==="error")throw new h(m.message);if(m.level==="warning")f.warn(m.message);else if(m.level==="info")f.info(m.message)}let u=`${r}/${e.outDir}/${t.name}${i}`,c=Bun.file(u).size||0;f.progress(n.toUpperCase(),w(u),D(c),e.name)}
package/build/index.mjs CHANGED
@@ -1,26 +1,26 @@
1
- function Re(e){return e}function $e(e){return e}import{build as Pe}from"rolldown";import{dts as De}from"rolldown-plugin-dts";var F=!1;function k(e){F=e??!1}class h{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",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(!h.instance)h.instance=new h;return h.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:t,size:n,identifier:i,muted:o}){let s=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length)),a=o?`\x1B[38;5;${this.colors.info}m${t}\x1B[0m`:t;if(n){let[c,...l]=a.split(" "),g=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),m=i?` \x1B[48;5;${e};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${s}${c}${g} \x1B[38;5;${this.colors.size}m${n}\x1B[0m ${l.join(" ")}${m}`}let u=i?` \x1B[48;5;${e};38;5;0m ${i} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${s}${a}${u}`}output(e,r={},t=console.log){if(F)return;if(!this.shouldLog(r))return;if(r.verticalSpace)console.log("");if(t(e),r.verticalSpace)console.log("")}cli(e,r={}){let t=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r)}info(e,r={}){let t=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r)}warn(e,r={}){let t=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r,console.warn)}error(e,r={}){let t=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r,console.error)}progress(e,r,t,n){let i=String(e),o=this.colors.default,s,a,u={};if(typeof t==="string")s=t,a=n;else if(t)s=t.size,a=t.identifier,u=t;for(let[l,g]of Object.entries(this.colors.progress))if(i.includes(l)){o=g;break}let c=this.formatMessage({colorCode:o,label:i,message:r,size:s,identifier:a,muted:u.muted});this.output(c,u)}}var f=h.getInstance();class P extends Error{constructor(e){super(e);this.name="BunupError"}}class b extends P{constructor(e){super(e);this.name="BunupBuildError"}}class p extends P{constructor(e){super(e);this.name="BunupDTSBuildError"}}var d=(e)=>{if(e instanceof Error)return e.message;return String(e)};import W from"node:fs/promises";import Se from"node:path";function D(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(e=8){let r="";while(r.length<e)r+=Math.random().toString(36).substring(2);return r.substring(0,e)}function V(e,r){switch(e){case"esm":return y(r)?".js":".mjs";case"cjs":return y(r)?".cjs":".js";case"iife":return".global.js"}}function G(e,r){switch(e){case"esm":return y(r)?".d.ts":".d.mts";case"cjs":return y(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function O(e){return e==="node"||e==="bun"}function y(e){return e==="module"}function q(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function L(e){if(e===0)return"0 B";let r=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(1024));if(t===0)return`${e} ${r[t]}`;return`${(e/1024**t).toFixed(2)} ${r[t]}`}function E(e,r=3){return e.split("/").slice(-r).join("/")}async function X(e,r){let t=Se.join(e,r);try{await W.rm(t,{recursive:!0,force:!0})}catch(n){throw new b(`Failed to clean output directory: ${n}`)}await W.mkdir(t,{recursive:!0})}function R(e){return[".ts",".mts",".cts",".tsx"].some((r)=>e.endsWith(r))}function H(e){return e.map((r)=>typeof r==="string"?new RegExp(`^${D(r)}($|\\/|\\\\)`):r)}function $(e,r){return H(e.external||[]).concat(q(r).map((t)=>new RegExp(`^${D(t)}($|\\/|\\\\)`)))}function S(e){return H(e.noExternal||[])}import Z from"node:path";import{ResolverFactory as Be}from"oxc-resolver";import{resolveTsImportPath as Te}from"ts-import-resolver";var C="\x00dts:",K=(e,r,t)=>{return{name:"bunup:virtual-dts",async resolveId(n,i){if(I(n))return n;if(!i||!I(i))return null;let o=r.tsconfig?Te({path:n,importer:w(i),tsconfig:r.tsconfig,rootDir:t}):null;if(!o)return null;let s=x(o);if(e.has(s))return T(s);return null},load(n){if(n.startsWith(C)){let i=w(n),o=e.get(i);if(o)return Y.add(i),o}return null}}};function v(e){return e.tsconfig.compilerOptions??{}}function J(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}function Q(e){return/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/.test(e)&&!J(e)}function x(e){if(J(e))return e;return e.replace(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,".d.ts")}function I(e){return e.startsWith(C)}function w(e){return e.replace(C,"")}function T(e){return`${C}${e}`}var M;function z(e,r){return{name:"bunup:types-resolve",buildStart(){M||=new Be({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,n){if(t==="bun")return;let i=n?w(n):void 0;if(/\0/.test(t))return;if(r){if(!r.some((u)=>typeof u==="string"?u===t:u.test(t)))return}let o=i?Z.dirname(i):process.cwd(),{path:s}=await M.async(o,t);if(!s)return;if(Q(s)){let a=x(s);try{let{path:u}=await M.async(Z.dirname(s),a);if(u)return u}catch(u){}return}return s}}}async function ee(e,r,t,n,i,o){let s=x(e),a=T(s),u=$(t,n),c=S(t);try{let{output:l}=await Pe({input:a,output:{dir:t.outDir},write:!1,onwarn(g,m){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(g.code??""))return;m(g)},plugins:[K(r,i,o),typeof t.dts==="object"&&"resolve"in t.dts&&z(i,typeof t.dts.resolve==="boolean"?void 0:t.dts.resolve),De({dtsInput:!0,emitDtsOnly:!0,compilerOptions:{...v(i),declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:99}})],external:(g)=>u.some((m)=>m.test(g))&&!c.some((m)=>m.test(g))});if(!l[0]?.code)return f.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return l[0].code}catch(l){throw new p(`DTS bundling failed for entry "${e}": ${d(l)}`)}}import{resolveTsImportPath as Oe}from"ts-import-resolver";var Le=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Ie=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,Me=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,Ae=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,je=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,_e=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Ne=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function Fe(e){let r=new Set,t=[Le,Ie,Me,Ae,je,_e,Ne];for(let n of t){let i=e.matchAll(n);for(let o of i)if(o[1])r.add(o[1])}return r}async function te(e,r,t){let n=new Set([e]),i=[e];while(i.length){let o=i.pop();if(!o)continue;try{let s=await Bun.file(o).text(),a=Fe(s);for(let u of a){let c=r.tsconfig?Oe({path:u,importer:o,tsconfig:r.tsconfig,rootDir:t}):null;if(!c)continue;if(!n.has(c))n.add(c),i.push(c)}}catch(s){f.warn(`Error processing ${o}: ${d(s)}`)}}return n}import{isolatedDeclaration as ke}from"oxc-transform";async function re(e){let r=new Map;return await Promise.all([...e].map(async(t)=>{try{let n=x(t);if(!await Bun.file(t).exists())return;let o=await Bun.file(t).text(),{code:s}=ke(t,o);if(s)r.set(n,s)}catch(n){f.warn(`Failed to generate declaration for ${t}: ${d(n)}`)}})),r}import ne from"node:fs/promises";import A from"node:path";import{isolatedDeclaration as Mt}from"oxc-transform";async function se(e,r){let t=A.resolve(e),n=A.resolve(t,r);if(!await ne.exists(t))throw new p(`Root directory does not exist: ${t}`);if(!await Bun.file(n).exists())throw new p(`Entry file does not exist: ${n}`);if(!R(n))throw new p(`Entry file must be a TypeScript file: ${n}`);if(A.relative(t,n).startsWith(".."))throw new p(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:t,absoluteEntry:n}}async function ie(e,r,t,n,i){let{absoluteEntry:o}=await se(e,r),s=await te(o,n,e),a=await re(s);return ee(o,a,t,i,n,e)}function oe(e){return e.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function j(e,{warnOnConflict:r=!0}={}){let t=[],n=new Set,i={};function o(s,a){if(n.has(s)){let u=U(),c=`${s}_${u}`;if(r)f.warn(`Output name conflict: "${s}" is used by multiple files.
1
+ function Be(e){return e}function Te(e){return e}import{build as Me}from"rolldown";import{dts as Ae}from"rolldown-plugin-dts";var P=!1;function U(e){P=e??!1}class b{static instance;loggedOnceMessages=new Set;MAX_LABEL_LENGTH=3;MAX_MESSAGE_LENGTH=25;colors={cli:"147",info:"245",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:r,message:t,size:n,identifier:s,muted:o}){let i=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length)),a=o?`\x1B[38;5;${this.colors.info}m${t}\x1B[0m`:t;if(n){let[c,...m]=a.split(" "),g=" ".repeat(Math.max(0,this.MAX_MESSAGE_LENGTH-c.length)),l=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${i}${c}${g} \x1B[38;5;${this.colors.size}m${n}\x1B[0m ${m.join(" ")}${l}`}let u=s?` \x1B[48;5;${e};38;5;0m ${s} \x1B[0m`:"";return`\x1B[38;5;${e}m${r}\x1B[0m ${i}${a}${u}`}output(e,r={},t=console.log){if(P)return;if(!this.shouldLog(r))return;if(r.verticalSpace)console.log("");if(t(e),r.verticalSpace)console.log("")}cli(e,r={}){let t=this.formatMessage({colorCode:this.colors.cli,label:this.labels.cli,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r)}info(e,r={}){let t=this.formatMessage({colorCode:this.colors.info,label:this.labels.info,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r)}warn(e,r={}){let t=this.formatMessage({colorCode:this.colors.warn,label:this.labels.warn,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r,console.warn)}error(e,r={}){let t=this.formatMessage({colorCode:this.colors.error,label:this.labels.error,message:e,identifier:r.identifier,muted:r.muted});this.output(t,r,console.error)}progress(e,r,t,n){let s=String(e),o=this.colors.default,i,a,u={};if(typeof t==="string")i=t,a=n;else if(t)i=t.size,a=t.identifier,u=t;for(let[m,g]of Object.entries(this.colors.progress))if(s.includes(m)){o=g;break}let c=this.formatMessage({colorCode:o,label:s,message:r,size:i,identifier:a,muted:u.muted});this.output(c,u)}}var f=b.getInstance();class L extends Error{constructor(e){super(e);this.name="BunupError"}}class h extends L{constructor(e){super(e);this.name="BunupBuildError"}}class p extends L{constructor(e){super(e);this.name="BunupDTSBuildError"}}var d=(e)=>{if(e instanceof Error)return e.message;return String(e)};import G from"node:fs/promises";import Re from"node:path";function M(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function q(e=8){let r="";while(r.length<e)r+=Math.random().toString(36).substring(2);return r.substring(0,e)}function F(e,r){switch(e){case"esm":return y(r)?".js":".mjs";case"cjs":return y(r)?".cjs":".js";case"iife":return".global.js"}}function H(e,r){switch(e){case"esm":return y(r)?".d.ts":".d.mts";case"cjs":return y(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function A(e){return e==="node"||e==="bun"}function y(e){return e==="module"}function K(e){if(!e)return[];return Array.from(new Set([...Object.keys(e.dependencies||{}),...Object.keys(e.peerDependencies||{})]))}function j(e){if(e===0)return"0 B";let r=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(1024));if(t===0)return`${e} ${r[t]}`;return`${(e/1024**t).toFixed(2)} ${r[t]}`}function w(e,r=3){return e.split("/").slice(-r).join("/")}async function X(e,r){let t=Re.join(e,r);try{await G.rm(t,{recursive:!0,force:!0})}catch(n){throw new h(`Failed to clean output directory: ${n}`)}await G.mkdir(t,{recursive:!0})}function E(e){return[".ts",".mts",".cts",".tsx"].some((r)=>e.endsWith(r))}function Y(e){return e.map((r)=>typeof r==="string"?new RegExp(`^${M(r)}($|\\/|\\\\)`):r)}function S(e,r){return Y(e.external||[]).concat(K(r).map((t)=>new RegExp(`^${M(t)}($|\\/|\\\\)`)))}function B(e){return Y(e.noExternal||[])}import ee from"node:path";import{ResolverFactory as Le}from"oxc-resolver";import{resolveTsImportPath as Oe}from"ts-import-resolver";var $="\x00dts:",Q=(e,r,t)=>{return{name:"bunup:virtual-dts",async resolveId(n,s){if(I(n))return n;if(!s||!I(s))return null;let o=r.tsconfig?Oe({path:n,importer:C(s),tsconfig:r.tsconfig,rootDir:t}):null;if(!o)return null;let i=x(o);if(e.has(i))return T(i);return null},load(n){if(n.startsWith($)){let s=C(n),o=e.get(s);if(o)return Z.add(s),o}return null}}};function z(e){return e.tsconfig.compilerOptions??{}}function J(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}function V(e){return/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/.test(e)&&!J(e)}function x(e){if(J(e))return e;return e.replace(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,".d.ts")}function I(e){return e.startsWith($)}function C(e){return e.replace($,"")}function T(e){return`${$}${e}`}function v(e,r,t,n){if(typeof n==="boolean"&&n)return!1;if(Array.isArray(n)){for(let s of n)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))&&!t.some((s)=>s.test(e))}var N;function re(e,r){return{name:"bunup:types-resolve",buildStart(){N||=new Le({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,n){if(r===!1)return;if(t==="bun")return;let s=n?C(n):void 0;if(/\0/.test(t))return;if(Array.isArray(r)){if(!r.some((u)=>typeof u==="string"?u===t:u.test(t)))return}let o=s?ee.dirname(s):process.cwd(),{path:i}=await N.async(o,t);if(!i)return;if(V(i)){let a=x(i);try{let{path:u}=await N.async(ee.dirname(i),a);if(u)return u}catch(u){}return}return i}}}async function te(e,r,t,n,s,o){let i=x(e),a=T(i),u=S(t,n),c=B(t),m=typeof t.dts==="object"&&"resolve"in t.dts?t.dts.resolve:void 0;try{let{output:g}=await Me({input:a,output:{dir:t.outDir},write:!1,onwarn(l,R){if(["UNRESOLVED_IMPORT","CIRCULAR_DEPENDENCY","EMPTY_BUNDLE"].includes(l.code??""))return;R(l)},plugins:[Q(r,s,o),m&&re(s,m),Ae({dtsInput:!0,emitDtsOnly:!0,compilerOptions:{...z(s),declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:99}})],external:(l)=>v(l,u,c,m)});if(!g[0]?.code)return f.warn(`Generated empty declaration file for entry "${e}"`,{muted:!0}),"";return g[0].code}catch(g){throw new p(`DTS bundling failed for entry "${e}": ${d(g)}`)}}import{resolveTsImportPath as je}from"ts-import-resolver";var Ie=/^\s*import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Ne=/^\s*export\s+.*from\s+['"]([^'"]+)['"]/gm,_e=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,De=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,We=/import\s+\w+\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,ke=/\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/g,Pe=/\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/g;function Ue(e){let r=new Set,t=[Ie,Ne,_e,De,We,ke,Pe];for(let n of t){let s=e.matchAll(n);for(let o of s)if(o[1])r.add(o[1])}return r}async function ne(e,r,t){let n=new Set([e]),s=[e];while(s.length){let o=s.pop();if(!o)continue;try{let i=await Bun.file(o).text(),a=Ue(i);for(let u of a){let c=r.tsconfig?je({path:u,importer:o,tsconfig:r.tsconfig,rootDir:t}):null;if(!c)continue;if(!n.has(c))n.add(c),s.push(c)}}catch(i){f.warn(`Error processing ${o}: ${d(i)}`)}}return n}import{isolatedDeclaration as Ge}from"oxc-transform";async function se(e){let r=new Map;return await Promise.all([...e].map(async(t)=>{try{let n=x(t);if(!await Bun.file(t).exists())return;let o=await Bun.file(t).text(),{code:i}=Ge(t,o);if(i)r.set(n,i)}catch(n){f.warn(`Failed to generate declaration for ${t}: ${d(n)}`)}})),r}import ie from"node:fs/promises";import _ from"node:path";import{isolatedDeclaration as _r}from"oxc-transform";async function oe(e,r){let t=_.resolve(e),n=_.resolve(t,r);if(!await ie.exists(t))throw new p(`Root directory does not exist: ${t}`);if(!await Bun.file(n).exists())throw new p(`Entry file does not exist: ${n}`);if(!E(n))throw new p(`Entry file must be a TypeScript file: ${n}`);if(_.relative(t,n).startsWith(".."))throw new p(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:t,absoluteEntry:n}}async function ae(e,r,t,n,s){let{absoluteEntry:o}=await oe(e,r),i=await ne(o,n,e),a=await se(i);return te(o,a,t,s,n,e)}function ue(e){return e.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function D(e,{warnOnConflict:r=!0}={}){let t=[],n=new Set,s={};function o(i,a){if(n.has(i)){let u=q(),c=`${i}_${u}`;if(r)f.warn(`Output name conflict: "${i}" is used by multiple files.
2
2
  Bunup uses filenames without extensions as output names by default.
3
3
 
4
- ${i[s]} -> ${s}.js
4
+ ${s[i]} -> ${i}.js
5
5
  ${a} -> ${c}.js (auto-renamed to avoid conflict)
6
6
 
7
7
  To fix this, use named entries in your configuration:
8
8
  {
9
9
  entry: {
10
- custom_name: "${i[s]}",
10
+ custom_name: "${s[i]}",
11
11
  another_name: "${a}"
12
12
  }
13
13
  }
14
14
 
15
- See: https://bunup.arshadyaseen.com/documentation/#named-entries`,{muted:!0,verticalSpace:!0});t.push({name:c,path:a})}else t.push({name:s,path:a}),n.add(s),i[s]=a}if(Array.isArray(e))for(let s of e){let a=oe(s);o(a,s)}else if(typeof e==="object")for(let[s,a]of Object.entries(e))o(s,a);else{let s=oe(e);o(s,e)}return t}function ae(e){return e.filter((r)=>R(r.path))}function ue(e,r){return`[dir]/${e}${r}`}import{loadConfig as ce}from"coffi";async function le(e){let{config:r,filepath:t}=await ce({name:"package",cwd:e,extensions:[".json"],maxDepth:3});return{packageJson:r,path:t}}async function me(e,r){let{config:t,filepath:n}=await ce({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:r,maxDepth:3});return{tsconfig:t,path:n}}var We={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function fe(e){return{...We,...e}}function ge(e){let{minify:r,minifyWhitespace:t,minifyIdentifiers:n,minifySyntax:i}=e,o=r===!0;return{whitespace:t??o,identifiers:n??o,syntax:i??o}}function pe(e,r){return r==="cjs"?e:void 0}function de(e,r,t,n){return{...typeof t==="object"&&Object.keys(t).reduce((i,o)=>{let s=JSON.stringify(t[o]);return i[`process.env.${o}`]=s,i[`import.meta.env.${o}`]=s,i},{}),...e,...n==="cjs"&&(r===!0||typeof r==="object"&&r.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function xe(e,r){return e===void 0?r==="esm":e}function he(e){return typeof e==="string"?e:void 0}function be(e,r){return{name:"bunup:external-plugin",setup(t){t.onResolve({filter:/.*/},(n)=>{let i=n.path;if(e.some((s)=>s.test(i))&&!r.some((s)=>s.test(i)))return{path:i,external:!0};return null})}}}var Ue=/\.(js|ts|jsx|tsx|mts|cts)$/,_={dirnameFilename:{appliesTo:(e,r)=>e==="esm"&&O(r),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
15
+ See: https://bunup.arshadyaseen.com/documentation/#named-entries`,{muted:!0,verticalSpace:!0});t.push({name:c,path:a})}else t.push({name:i,path:a}),n.add(i),s[i]=a}if(Array.isArray(e))for(let i of e){let a=ue(i);o(a,i)}else if(typeof e==="object")for(let[i,a]of Object.entries(e))o(i,a);else{let i=ue(e);o(i,e)}return t}function ce(e){return e.filter((r)=>E(r.path))}function me(e,r){return`[dir]/${e}${r}`}import{loadConfig as le}from"coffi";async function fe(e){let{config:r,filepath:t}=await le({name:"package",cwd:e,extensions:[".json"],maxDepth:3});return{packageJson:r,path:t}}async function ge(e,r){let{config:t,filepath:n}=await le({name:"tsconfig",cwd:e,extensions:[".json"],preferredPath:r,maxDepth:3});return{tsconfig:t,path:n}}var qe={entry:[],format:["cjs"],outDir:"dist",target:"node",clean:!0};function pe(e){return{...qe,...e}}function de(e){let{minify:r,minifyWhitespace:t,minifyIdentifiers:n,minifySyntax:s}=e,o=r===!0;return{whitespace:t??o,identifiers:n??o,syntax:s??o}}function xe(e,r){return r==="cjs"?e:void 0}function be(e,r,t,n){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,...n==="cjs"&&(r===!0||typeof r==="object"&&r.importMetaUrl)&&{"import.meta.url":"importMetaUrl"}}}function he(e,r){return e===void 0?r==="esm":e}function ye(e){return typeof e==="string"?e:void 0}function we(e,r){return{name:"bunup:external-plugin",setup(t){t.onResolve({filter:/.*/},(n)=>{let s=n.path;if(e.some((i)=>i.test(s))&&!r.some((i)=>i.test(s)))return{path:s,external:!0};return null})}}}var Fe=/\.(js|ts|jsx|tsx|mts|cts)$/,W={dirnameFilename:{appliesTo:(e,r)=>e==="esm"&&A(r),isNeededInFile:(e)=>/\b__dirname\b/.test(e)||/\b__filename\b/.test(e),generateCode:()=>`import { fileURLToPath } from 'url';
16
16
  import { dirname } from 'path';
17
17
 
18
18
  const __filename = fileURLToPath(import.meta.url);
19
19
  const __dirname = dirname(__filename);
20
20
 
21
- `},importMetaUrl:{appliesTo:(e,r)=>e==="cjs"&&O(r),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
21
+ `},importMetaUrl:{appliesTo:(e,r)=>e==="cjs"&&A(r),isNeededInFile:(e)=>/\bimport\.meta\.url\b/.test(e),generateCode:()=>`import { pathToFileURL } from 'url';
22
22
 
23
23
  const importMetaUrl = pathToFileURL(__filename).href;
24
24
 
25
- `}};function ye({format:e,target:r,shims:t}){let i=Ve(t).map((o)=>_[o]).filter((o)=>o.appliesTo(e,r));if(i.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:Ue},async({path:s})=>{let a=await Bun.file(s).text(),u=i.filter((m)=>m.isNeededInFile(a));if(u.length===0)return;let{shebangLine:c,codeContent:l}=Ge(a),g=u.map((m)=>m.generateCode()).join("");return{contents:c+g+l}})}}}function Ve(e){if(e===!0)return Object.keys(_);if(!e)return[];return Object.entries(e).filter(([r,t])=>t&&(r in _)).map(([r])=>r)}function Ge(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)}}var Y=new Set;async function qe(e,r){let t=fe(e);if(!t.entry||t.entry.length===0||!t.outDir)throw new b("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)X(r,t.outDir);k(t.silent);let{packageJson:n,path:i}=await le(r);if(n&&i)f.cli(`Using package.json: ${E(i,2)}`,{muted:!0,identifier:t.name,once:`${i}:${t.name}`});let o=j(t.entry),s=n?.type,a=$(t,n),u=S(t);if(!t.dtsOnly){let c=[be(a,u)],l=t.format.flatMap((g)=>o.map((m)=>{return Xe(t,r,m,g,s,c)}));await Promise.all(l)}if(t.dts||t.dtsOnly){let c=await me(r,t.preferredTsconfigPath);if(c.path)f.cli(`Using tsconfig: ${E(c.path,2)}`,{muted:!0,identifier:t.name,once:`${c.path}:${t.name}`});let l=t.format.filter((m)=>{if(m==="iife"&&!y(s)&&t.format.includes("cjs"))return!1;return!0}),g=typeof t.dts==="object"&&t.dts.entry?j(t.dts.entry):ae(o);try{await Promise.all(g.map(async(m)=>{let Ee=await ie(r,m.path,t,c,n);await Promise.all(l.map(async(N)=>{let we=t.outputExtension?.({format:N,packageType:s,options:t,entry:m}).dts??G(N,s),B=`${r}/${t.outDir}/${m.name}${we}`;await Bun.write(B,Ee);let Ce=Bun.file(B).size||0;f.progress("DTS",E(B),L(Ce),t.name)}))}))}catch(m){throw new p(d(m))}}if(t.onBuildSuccess)await t.onBuildSuccess(t)}async function Xe(e,r,t,n,i,o){let s=e.outputExtension?.({format:n,packageType:i,options:e,entry:t}).js??V(n,i),a=await Bun.build({entrypoints:[`${r}/${t.path}`],format:n,naming:{entry:ue(t.name,s)},splitting:xe(e.splitting,n),bytecode:pe(e.bytecode,n),define:de(e.define,e.shims,e.env,n),minify:ge(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:he(e.env),plugins:[...o,ye({format:n,target:e.target,shims:e.shims}),...e.bunBuildPlugins??[]],throw:!1});if(!a.success)for(let l of a.logs){if(l.level==="error")throw new b(l.message);if(l.level==="warning")f.warn(l.message);else if(l.level==="info")f.info(l.message)}let u=`${r}/${e.outDir}/${t.name}${s}`,c=Bun.file(u).size||0;f.progress(n.toUpperCase(),E(u),L(c),e.name)}export{$e as defineWorkspace,Re as defineConfig,qe as build};
25
+ `}};function Ce({format:e,target:r,shims:t}){let s=He(t).map((o)=>W[o]).filter((o)=>o.appliesTo(e,r));if(s.length===0)return{name:"bunup:inject-shims",setup(){}};return{name:"bunup:inject-shims",setup(o){o.onLoad({filter:Fe},async({path:i})=>{let a=await Bun.file(i).text(),u=s.filter((l)=>l.isNeededInFile(a));if(u.length===0)return;let{shebangLine:c,codeContent:m}=Ke(a),g=u.map((l)=>l.generateCode()).join("");return{contents:c+g+m}})}}}function He(e){if(e===!0)return Object.keys(W);if(!e)return[];return Object.entries(e).filter(([r,t])=>t&&(r in W)).map(([r])=>r)}function Ke(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 $e(e){return e.filter((r)=>r.type==="bun").map((r)=>r.plugin)}var Z=new Set;async function Xe(e,r){let t=pe(e);if(!t.entry||t.entry.length===0||!t.outDir)throw new h("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");if(t.clean)X(r,t.outDir);U(t.silent);let{packageJson:n,path:s}=await fe(r);if(n&&s)f.cli(`Using package.json: ${w(s,2)}`,{muted:!0,identifier:t.name,once:`${s}:${t.name}`});let o=D(t.entry),i=n?.type,a=S(t,n),u=B(t);if(!t.dtsOnly){let c=[we(a,u),...$e(t.plugins??[])],m=t.format.flatMap((g)=>o.map((l)=>{return Ye(t,r,l,g,i,c)}));await Promise.all(m)}if(t.dts||t.dtsOnly){let c=await ge(r,t.preferredTsconfigPath);if(c.path)f.cli(`Using tsconfig: ${w(c.path,2)}`,{muted:!0,identifier:t.name,once:`${c.path}:${t.name}`});let m=t.format.filter((l)=>{if(l==="iife"&&!y(i)&&t.format.includes("cjs"))return!1;return!0}),g=typeof t.dts==="object"&&t.dts.entry?D(t.dts.entry):ce(o);try{await Promise.all(g.map(async(l)=>{let R=await ae(r,l.path,t,c,n);await Promise.all(m.map(async(k)=>{let Ee=t.outputExtension?.({format:k,packageType:i,options:t,entry:l}).dts??H(k,i),O=`${r}/${t.outDir}/${l.name}${Ee}`;await Bun.write(O,R);let Se=Bun.file(O).size||0;f.progress("DTS",w(O),j(Se),t.name)}))}))}catch(l){throw new p(d(l))}}if(t.onBuildSuccess)await t.onBuildSuccess(t)}async function Ye(e,r,t,n,s,o){let i=e.outputExtension?.({format:n,packageType:s,options:e,entry:t}).js??F(n,s),a=await Bun.build({entrypoints:[`${r}/${t.path}`],format:n,naming:{entry:me(t.name,i)},splitting:he(e.splitting,n),bytecode:xe(e.bytecode,n),define:be(e.define,e.shims,e.env,n),minify:de(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:ye(e.env),plugins:[...o,Ce({format:n,target:e.target,shims:e.shims})],throw:!1});if(!a.success)for(let m of a.logs){if(m.level==="error")throw new h(m.message);if(m.level==="warning")f.warn(m.message);else if(m.level==="info")f.info(m.message)}let u=`${r}/${e.outDir}/${t.name}${i}`,c=Bun.file(u).size||0;f.progress(n.toUpperCase(),w(u),j(c),e.name)}export{Te as defineWorkspace,Be as defineConfig,Xe as build};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunup",
3
- "version": "0.4.36",
3
+ "version": "0.4.38",
4
4
  "description": "An extremely fast, zero-config bundler for TypeScript & JavaScript, powered by Bun.",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -21,7 +21,7 @@
21
21
  "bunup": "^0.4.23",
22
22
  "husky": "^9.1.7",
23
23
  "typescript": "^5.8.3",
24
- "create-bunup": "0.4.36"
24
+ "create-bunup": "0.4.38"
25
25
  },
26
26
  "peerDependencies": {
27
27
  "typescript": ">=4.5.0"