bunup 0.1.16 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/cli.mjs ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+ import I from"node:fs";import vt from"node:path";import{isMainThread as Pt,parentPort as T,Worker as bt,workerData as $t}from"node:worker_threads";import P from"node:fs";import y from"node:path";import mt from"oxc-transform";import{rollup as dt}from"rollup";import yt from"rollup-plugin-dts";import C from"typescript";var d=t=>t instanceof Error?t.message:String(t),A=(t,r)=>{let e=d(t),n=r?`[${r}] `:"";console.error(`\x1B[31m[ERROR]\x1B[0m ${n}${e}`),process.env.NODE_ENV!=="production"&&t instanceof Error&&t.stack&&console.error("\x1B[2m"+t.stack.split(`
3
+ `).slice(1).join(`
4
+ `)+"\x1B[0m")};function F(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function L(t=8){return Math.random().toString(36).substring(2,2+t)}function _(t,r){switch(t){case"esm":return".mjs";case"cjs":return D(r)?".cjs":".js";case"iife":return".global.js"}}function U(t,r){switch(t){case"esm":return".d.mts";case"cjs":return D(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function D(t){return t==="module"}function B(t){return t>=1e3?`${(t/1e3).toFixed(2)}s`:`${Math.round(t)}ms`}function H(t){return t?Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})])):[]}function J(t,r){return t===void 0?r==="esm":t}function q(t){return t.map(r=>typeof r=="string"?new RegExp(`^${F(r)}($|\\/|\\\\)`):r)}function S(t,r){return q(t.external||[]).concat(H(r).map(e=>new RegExp(`^${F(e)}($|\\/|\\\\)`)))}function k(t){return q(t.noExternal||[])}import O from"node:fs";import G from"node:path";var a={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,r,e){let n=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${t}m[${r}]\x1B[0m ${n}${e}`},cli(t){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,t))},info(t){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,t))},warn(t){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,t))},error(t){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,t))},progress(t,r){let e=String(t),n=this.colors.default;for(let[o,s]of Object.entries(this.colors.progress))if(e.includes(o)){n=s;break}console.log(this.formatMessage(n,e,r))}};function z(t,r){return`${r?`${r.replace(/-/g,"_")}_`:""}${t}`.toUpperCase()}var w={entry:[],format:["cjs"],outDir:"dist",minify:!1,watch:!1,dts:!1,target:"node",external:[],clean:!0};function V(t,r){return{outdir:`${r}/${t.outDir}`,minify:gt(t),target:t.target,splitting:t.splitting}}function gt(t){let{minify:r,minifyWhitespace:e,minifyIdentifiers:n,minifySyntax:o}=t,s=r===!0;return{whitespace:e??s,identifiers:n??s,syntax:o??s}}async function X(t){let r=[];for(let e of[".ts",".js",".mjs",".cjs",".mts",".cts",".json",".jsonc"]){let n=G.join(t,`bunup.config${e}`);try{if(!O.existsSync(n))continue;let o;if(e===".json"||e===".jsonc"){let s=O.readFileSync(n,"utf8");o=JSON.parse(s)}else{let s=await import(`file://${n}`);o=s.default||s,o||(a.warn(`No default export found in ${n}`),o={})}if(Array.isArray(o))for(let s of o)r.push({options:{...w,...s},rootDir:t});else r.push({options:{...w,...o},rootDir:t});break}catch(o){a.error(`Failed to load config from ${n}: ${d(o)}`)}if(r.length>0)break}return r}function v(t){let r=G.join(t,"package.json");try{if(!O.existsSync(r))return null;let e=O.readFileSync(r,"utf8");return JSON.parse(e)}catch(e){return a.error(`Failed to load package.json at ${r}: ${d(e)}`),null}}function Y(t){try{if(!O.existsSync(t))return{};let r=O.readFileSync(t,"utf8");return JSON.parse(r)||{}}catch(r){return a.warn(`Failed to parse tsconfig at ${t}: ${d(r)}`),{}}}async function K(t,r,e,n){let{absoluteRootDir:o,absoluteEntry:s}=Ot(t,r),i=await ht(s),l=await Et(i);return wt(s,l,e,n,o)}async function ht(t){let r=new Set,e=[t];for(;e.length>0;){let n=e.pop();if(!(!n||r.has(n))){r.add(n);try{let o=await P.promises.readFile(n,"utf8"),s=xt(o);for(let i of s){let l=y.dirname(n),c=y.resolve(l,i),u=[c,`${c}.ts`,`${c}.tsx`,`${c}/index.ts`,`${c}/index.tsx`];for(let p of u)if(P.existsSync(p)&&p.endsWith(".ts")&&!r.has(p)){e.push(p);break}}}catch(o){a.warn(`Error processing ${n}: ${o instanceof Error?o.message:String(o)}`)}}}return r}function xt(t){let r=new Set;try{let e=/(?:import|export)(?:(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*)|[\s\n]+)(["'`])([^'"]+)\1/g,n;for(;(n=e.exec(t))!==null;){let i=n[2];i.startsWith(".")&&r.add(i)}let o=/import\s+(["'`])([^'"]+)\1\s*;?/g;for(;(n=o.exec(t))!==null;){let i=n[2];i.startsWith(".")&&r.add(i)}let s=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;for(;(n=s.exec(t))!==null;){let i=n[2];i.startsWith(".")&&r.add(i)}}catch(e){a.warn(`Error extracting imports: ${e instanceof Error?e.message:String(e)}`)}return Array.from(r)}async function Et(t){let r=new Map;return await Promise.all(Array.from(t).map(async e=>{try{let n=e.replace(/\.tsx?$/,".d.ts"),o=await P.promises.readFile(e,"utf8"),{code:s}=mt.isolatedDeclaration(e,o);s&&r.set(n,s)}catch(n){a.warn(`Failed to generate declaration for ${e}: ${n instanceof Error?n.message:String(n)}`)}})),r}async function wt(t,r,e,n,o){let s="\0virtual:",i=t.replace(/\.tsx?$/,".d.ts"),l=`${s}${i}`,c=typeof n.dts=="object"?n.dts:{},u=c.preferredTsconfigPath?y.resolve(c.preferredTsconfigPath):y.join(o,"tsconfig.json"),m=(await Y(u)).compilerOptions,x={name:"bunup:virtual-dts",resolveId(f,g){if(f.startsWith(s))return f;if(g?.startsWith(s)){let E=g.slice(s.length),ut=y.dirname(E);if(f.startsWith(".")){let pt=y.resolve(ut,f);for(let ft of["",".d.ts","/index.d.ts"]){let N=`${pt}${ft}`;if(r.has(N))return`${s}${N}`}}}return null},load(f){if(f.startsWith(s)){let g=f.slice(s.length);return r.get(g)||null}return null}},at=v(o),lt=S(n,at),ct=k(n),$;try{$=await dt({input:l,onwarn(g,E){g.code==="UNRESOLVED_IMPORT"||g.code==="CIRCULAR_DEPENDENCY"||g.code==="EMPTY_BUNDLE"||E(g)},plugins:[x,yt({tsconfig:u,compilerOptions:{...m?C.parseJsonConfigFileContent({compilerOptions:m},C.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:C.ScriptTarget.ESNext}})],external:g=>lt.some(E=>E.test(g))&&!ct.some(E=>E.test(g))});let{output:f}=await $.generate({format:e});if(!f[0]?.code)throw new Error("Generated bundle is empty");return f[0].code}catch(f){throw new Error(`DTS bundling failed: ${d(f)}`)}finally{$&&await $.close()}}function Ot(t,r){let e=y.resolve(t),n=y.resolve(e,r);if(!P.existsSync(e))throw new Error(`Root directory does not exist: ${e}`);if(!P.existsSync(n))throw new Error(`Entry file does not exist: ${n}`);if(!n.endsWith(".ts"))throw new Error(`Entry file must be a TypeScript file (.ts): ${n}`);if(y.relative(e,n).startsWith(".."))throw new Error(`Entry file must be within rootDir: ${n}`);return{absoluteRootDir:e,absoluteEntry:n}}async function Q(t,r,e,n,o){return new Promise((s,i)=>{let l={rootDir:t,entries:r,formats:e,options:n,packageType:o},c=new bt(new URL("./dtsWorker.js",import.meta.url),{workerData:l});c.on("message",u=>{if(u.success){if(u.timeMs){let p=B(u.timeMs);a.progress("DTS",`Bundled types in ${p}`)}s()}else i(new Error(u.error||"Unknown DTS worker error"))}),c.on("error",i),c.on("exit",u=>{u!==0&&i(new Error(`DTS worker stopped with exit code ${u}`))})})}if(!Pt&&T){let{rootDir:t,entries:r,formats:e,options:n,packageType:o}=$t,s=performance.now();a.progress("DTS","Bundling types");try{let i=e.flatMap(l=>r.map(async c=>{let u=await K(t,c.path,l,n),p=U(l,o),m=`${n.outDir}/${c.name}${p}`,x=`${t}/${m}`;await Bun.write(x,u),a.progress("DTS",m)}));Promise.all(i).then(()=>{let l=performance.now()-s;T?.postMessage({success:!0,timeMs:l})}).catch(l=>{T?.postMessage({success:!1,error:l instanceof Error?l.message:String(l)})})}catch(i){T?.postMessage({success:!1,error:i instanceof Error?i.message:String(i)})}}function Dt(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function b(t){let r=[],e=new Set;function n(o,s){if(e.has(o)){let i=L();r.push({name:`${o}_${i}`,path:s})}else r.push({name:o,path:s}),e.add(o)}if(Array.isArray(t))for(let o of t){let s=Dt(o);n(s,o)}else Object.entries(t).forEach(([o,s])=>{n(o,s)});return r}function Z(t,r){return`[dir]/${t}${r}`}function tt(t,r){return{name:"bunup:external-plugin",setup(e){e.onResolve({filter:/.*/},n=>{let o=n.path;return t.some(i=>i.test(o))&&!r.some(i=>i.test(o))?{path:o,external:!0}:null})}}}async function R(t,r){if(!t.entry||t.entry.length===0||!t.outDir){a.cli("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");return}let e=performance.now();a.cli("Build started");let n=v(r),o=n?.type,s=S(t,n),i=k(t),l=[tt(s,i)],c=b(t.entry),u=t.format.flatMap(p=>c.map(m=>Bt(t,r,m,p,o,l)));try{await Promise.all(u);let p=performance.now()-e,m=B(p);a.cli(`\u26A1 Build success in ${m}`)}catch{a.error("Build process encountered errors."),process.exit(1)}if(t.dts){a.progress("DTS","Bundling types");let p=t.format.filter(x=>!(x==="iife"&&!D(o)&&t.format.includes("cjs"))),m=t.dts===!0?c:b(t.dts.entry);try{await Q(r,m,p,t,o)}catch(x){a.error(`DTS build process encountered errors: ${d(x)}`)}}}async function Bt(t,r,e,n,o,s){let i=_(n,o),l=V(t,r),c=await Bun.build({...l,entrypoints:[`${r}/${e.path}`],format:n,naming:{entry:Z(e.name,i)},splitting:J(t.splitting,n),plugins:s,throw:!1});if(!c.success)throw c.logs.forEach(u=>{u.level==="error"?a.error(u.message):u.level==="warning"?a.warn(u.message):u.level==="info"&&a.info(u.message)}),new Error(`Build failed for ${e} (${n})`);a.progress(z(n,t.name),`${t.outDir}/${e.name}${i}`)}function h(t){return(r,e)=>{e[t]=r===!0?!0:r==="true"}}function M(t){return(r,e)=>{typeof r=="string"?e[t]=r:a.error(`Option --${t} requires a string value`)}}function rt(t){return(r,e)=>{typeof r=="string"?e[t]=r.split(","):a.error(`Option --${t} requires a string value`)}}var St={name:{flags:["n","name"],handler:M("name")},format:{flags:["f","format"],handler:(t,r)=>{typeof t=="string"?r.format=t.split(","):a.error("Option --format requires a string value")}},outDir:{flags:["o","out-dir"],handler:M("outDir")},minify:{flags:["m","minify"],handler:h("minify")},watch:{flags:["w","watch"],handler:h("watch")},dts:{flags:["d","dts"],handler:h("dts")},external:{flags:["e","external"],handler:rt("external")},target:{flags:["t","target"],handler:M("target")},minifyWhitespace:{flags:["mw","minify-whitespace"],handler:h("minifyWhitespace")},minifyIdentifiers:{flags:["mi","minify-identifiers"],handler:h("minifyIdentifiers")},minifySyntax:{flags:["ms","minify-syntax"],handler:h("minifySyntax")},clean:{flags:["c","clean"],handler:h("clean")},splitting:{flags:["s","splitting"],handler:h("splitting")},noExternal:{flags:["ne","no-external"],handler:rt("noExternal")}},j={};for(let t of Object.values(St))if(t)for(let r of t.flags)j[r]=t.handler;function et(t){return t.split("/").pop()?.split(".").slice(0,-1).join(".")||""}function nt(t){let r={},e={},n=0;for(;n<t.length;){let o=t[n];if(o.startsWith("--")){let s,i;if(o.includes("=")){let[l,c]=o.slice(2).split("=",2);s=l,i=c}else{s=o.slice(2);let l=t[n+1];i=l&&!l.startsWith("-")?l:!0,typeof i=="string"&&n++}if(s==="entry")if(typeof i=="string"){let l=et(i);e[l]&&a.warn(`Duplicate entry name '${l}' derived from '${i}'. Overwriting previous entry.`),e[l]=i}else a.error("Option --entry requires a string value");else if(s.startsWith("entry.")){let l=s.slice(6);typeof i=="string"?(e[l]&&a.warn(`Duplicate entry name '${l}' provided via --entry.${l}. Overwriting previous entry.`),e[l]=i):a.error(`Option --entry.${l} requires a string value`)}else{let l=j[s];l?l(i,r):a.error(`Unknown option: --${s}`)}}else if(o.startsWith("-")){let s=o.slice(1),i=t[n+1],l=i&&!i.startsWith("-")?i:!0;typeof l=="string"&&n++;let c=j[s];c?c(l,r):a.error(`Unknown option: -${s}`)}else{let s=et(o);e[s]&&a.warn(`Duplicate entry name '${s}' derived from positional argument '${o}'. Overwriting previous entry.`),e[s]=o}n++}return Object.keys(e).length>0&&(r.entry=e),r}typeof Bun>"u"&&(a.error(`Bunup requires Bun to run.
5
+ To install Bun, visit https://bun.sh/docs/installation`),process.exit(1));import W from"node:path";import kt from"chokidar";async function ot(t,r){let e=new Set;b(t.entry).forEach(c=>{let u=W.resolve(r,c.path),p=W.dirname(u);e.add(p)});let o=kt.watch(Array.from(e),{persistent:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},atomic:!0,ignorePermissionErrors:!0,ignored:[/[\\/]\.git[\\/]/,/[\\/]node_modules[\\/]/,t.outDir]}),s=null,i=!1,l=async c=>{if(!i){i=!0;try{await R({...t,entry:[c],clean:!1},r)}catch(u){a.error(`Build failed: ${u}`)}finally{i=!1}}};o.on("change",c=>{let u=W.relative(r,c);a.cli(`File changed: ${u}`),s&&clearTimeout(s),s=setTimeout(()=>l(u),300)}),o.on("error",c=>{a.error(`Watcher error: ${c}`)})}async function Tt(t=Bun.argv.slice(2)){let r=nt(t),e=await X(process.cwd()),n=process.cwd();if(r.watch&&(a.cli("Starting watch mode"),a.cli("Watching for file changes")),e.length===0){let o={...w,...r};o.clean&&it(n,o.outDir),await st(o,n)}else{for(let{options:o,rootDir:s}of e)o.clean&&it(s,o.outDir);await Promise.all(e.map(async({options:o,rootDir:s})=>{let i={...w,...o,...r};await st(i,s)}))}r.watch||process.exit(0)}async function st(t,r){t.watch?await ot(t,r):await R(t,r)}function it(t,r){let e=vt.join(t,r);if(I.existsSync(e))try{I.rmSync(e,{recursive:!0,force:!0})}catch(n){a.error(`Failed to clean output directory: ${n}`)}I.mkdirSync(e,{recursive:!0})}Tt().catch(t=>{A(t),process.exit(1)});export{Tt as main};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _worker_threads = require('worker_threads');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var _path = require('path'); var _path2 = _interopRequireDefault(_path);var _oxctransform = require('oxc-transform'); var _oxctransform2 = _interopRequireDefault(_oxctransform);var _rollup = require('rollup');var _rollupplugindts = require('rollup-plugin-dts'); var _rollupplugindts2 = _interopRequireDefault(_rollupplugindts);var _typescript = require('typescript'); var _typescript2 = _interopRequireDefault(_typescript);var h=t=>t instanceof Error?t.message:String(t);function b(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function O(t,r){switch(t){case"esm":return".d.mts";case"cjs":return _(r)?".d.cts":".d.ts";case"iife":return".d.ts"}}function _(t){return t==="module"}function k(t){return t>=1e3?`${(t/1e3).toFixed(2)}s`:`${Math.round(t)}ms`}function R(t){return t?Array.from(new Set([...Object.keys(t.dependencies||{}),...Object.keys(t.peerDependencies||{})])):[]}function T(t){return t.map(r=>typeof r=="string"?new RegExp(`^${b(r)}($|\\/|\\\\)`):r)}function B(t,r){return T(t.external||[]).concat(R(r).map(n=>new RegExp(`^${b(n)}($|\\/|\\\\)`)))}function M(t){return T(t.noExternal||[])}var u={MAX_LABEL_LENGTH:5,colors:{cli:"183",info:"240",warn:"221",error:"203",progress:{ESM:"214",CJS:"114",IIFE:"105",DTS:"75"},default:"255"},labels:{cli:"BUNUP",info:"INFO",warn:"WARN",error:"ERROR"},formatMessage(t,r,n){let e=" ".repeat(Math.max(0,this.MAX_LABEL_LENGTH-r.length));return`\x1B[38;5;${t}m[${r}]\x1B[0m ${e}${n}`},cli(t){let r=this.labels.cli;console.log(this.formatMessage(this.colors.cli,r,t))},info(t){let r=this.labels.info;console.log(this.formatMessage(this.colors.info,r,t))},warn(t){let r=this.labels.warn;console.warn(this.formatMessage(this.colors.warn,r,t))},error(t){let r=this.labels.error;console.error(this.formatMessage(this.colors.error,r,t))},progress(t,r){let n=String(t),e=this.colors.default;for(let[i,s]of Object.entries(this.colors.progress))if(n.includes(i)){e=s;break}console.log(this.formatMessage(e,n,r))}};function F(t){let r=_path2.default.join(t,"package.json");try{if(!_fs2.default.existsSync(r))return null;let n=_fs2.default.readFileSync(r,"utf8");return JSON.parse(n)}catch(n){return u.error(`Failed to load package.json at ${r}: ${h(n)}`),null}}function C(t){try{if(!_fs2.default.existsSync(t))return{};let r=_fs2.default.readFileSync(t,"utf8");return JSON.parse(r)||{}}catch(r){return u.warn(`Failed to parse tsconfig at ${t}: ${h(r)}`),{}}}async function v(t,r,n,e){let{absoluteRootDir:i,absoluteEntry:s}=z(t,r),o=await X(s),a=await Y(o);return q(s,a,n,e,i)}async function X(t){let r=new Set,n=[t];for(;n.length>0;){let e=n.pop();if(!(!e||r.has(e))){r.add(e);try{let i=await _fs2.default.promises.readFile(e,"utf8"),s=H(i);for(let o of s){let a=_path2.default.dirname(e),c=_path2.default.resolve(a,o),l=[c,`${c}.ts`,`${c}.tsx`,`${c}/index.ts`,`${c}/index.tsx`];for(let g of l)if(_fs2.default.existsSync(g)&&g.endsWith(".ts")&&!r.has(g)){n.push(g);break}}}catch(i){u.warn(`Error processing ${e}: ${i instanceof Error?i.message:String(i)}`)}}}return r}function H(t){let r=new Set;try{let n=/(?:import|export)(?:(?:[\s\n]*(?:type[\s\n]+)?(?:\*|\{[^}]*\}|[\w$]+)[\s\n]+from[\s\n]*)|[\s\n]+)(["'`])([^'"]+)\1/g,e;for(;(e=n.exec(t))!==null;){let o=e[2];o.startsWith(".")&&r.add(o)}let i=/import\s+(["'`])([^'"]+)\1\s*;?/g;for(;(e=i.exec(t))!==null;){let o=e[2];o.startsWith(".")&&r.add(o)}let s=/import\s*\(\s*(["'`])([^'"]+)\1\s*\)/g;for(;(e=s.exec(t))!==null;){let o=e[2];o.startsWith(".")&&r.add(o)}}catch(n){u.warn(`Error extracting imports: ${n instanceof Error?n.message:String(n)}`)}return Array.from(r)}async function Y(t){let r=new Map;return await Promise.all(Array.from(t).map(async n=>{try{let e=n.replace(/\.tsx?$/,".d.ts"),i=await _fs2.default.promises.readFile(n,"utf8"),{code:s}=_oxctransform2.default.isolatedDeclaration(n,i);s&&r.set(e,s)}catch(e){u.warn(`Failed to generate declaration for ${n}: ${e instanceof Error?e.message:String(e)}`)}})),r}async function q(t,r,n,e,i){let s="\0virtual:",o=t.replace(/\.tsx?$/,".d.ts"),a=`${s}${o}`,c=typeof e.dts=="object"?e.dts:{},l=c.preferredTsconfigPath?_path2.default.resolve(c.preferredTsconfigPath):_path2.default.join(i,"tsconfig.json"),x=(await C(l)).compilerOptions,$={name:"bunup:virtual-dts",resolveId(p,f){if(p.startsWith(s))return p;if(_optionalChain([f, 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3(s)])){let d=f.slice(s.length),N=_path2.default.dirname(d);if(p.startsWith(".")){let L=_path2.default.resolve(N,p);for(let A of["",".d.ts","/index.d.ts"]){let S=`${L}${A}`;if(r.has(S))return`${s}${S}`}}}return null},load(p){if(p.startsWith(s)){let f=p.slice(s.length);return r.get(f)||null}return null}},j=F(i),I=B(e,j),W=M(e),E;try{E=await _rollup.rollup.call(void 0, {input:a,onwarn(f,d){f.code==="UNRESOLVED_IMPORT"||f.code==="CIRCULAR_DEPENDENCY"||f.code==="EMPTY_BUNDLE"||d(f)},plugins:[$,_rollupplugindts2.default.call(void 0, {tsconfig:l,compilerOptions:{...x?_typescript2.default.parseJsonConfigFileContent({compilerOptions:x},_typescript2.default.sys,"./").options:{},declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!1,target:_typescript2.default.ScriptTarget.ESNext}})],external:f=>I.some(d=>d.test(f))&&!W.some(d=>d.test(f))});let{output:p}=await E.generate({format:n});if(!_optionalChain([p, 'access', _4 => _4[0], 'optionalAccess', _5 => _5.code]))throw new Error("Generated bundle is empty");return p[0].code}catch(p){throw new Error(`DTS bundling failed: ${h(p)}`)}finally{E&&await E.close()}}function z(t,r){let n=_path2.default.resolve(t),e=_path2.default.resolve(n,r);if(!_fs2.default.existsSync(n))throw new Error(`Root directory does not exist: ${n}`);if(!_fs2.default.existsSync(e))throw new Error(`Entry file does not exist: ${e}`);if(!e.endsWith(".ts"))throw new Error(`Entry file must be a TypeScript file (.ts): ${e}`);if(_path2.default.relative(n,e).startsWith(".."))throw new Error(`Entry file must be within rootDir: ${e}`);return{absoluteRootDir:n,absoluteEntry:e}}async function Bt(t,r,n,e,i){return new Promise((s,o)=>{let a={rootDir:t,entries:r,formats:n,options:e,packageType:i},c=new (0, _worker_threads.Worker)(new URL("./dtsWorker.js",import.meta.url),{workerData:a});c.on("message",l=>{if(l.success){if(l.timeMs){let g=k(l.timeMs);u.progress("DTS",`Bundled types in ${g}`)}s()}else o(new Error(l.error||"Unknown DTS worker error"))}),c.on("error",o),c.on("exit",l=>{l!==0&&o(new Error(`DTS worker stopped with exit code ${l}`))})})}if(!_worker_threads.isMainThread&&_worker_threads.parentPort){let{rootDir:t,entries:r,formats:n,options:e,packageType:i}=_worker_threads.workerData,s=performance.now();u.progress("DTS","Bundling types");try{let o=n.flatMap(a=>r.map(async c=>{let l=await v(t,c.path,a,e),g=O(a,i),x=`${e.outDir}/${c.name}${g}`,$=`${t}/${x}`;await Bun.write($,l),u.progress("DTS",x)}));Promise.all(o).then(()=>{let a=performance.now()-s;_optionalChain([_worker_threads.parentPort, 'optionalAccess', _6 => _6.postMessage, 'call', _7 => _7({success:!0,timeMs:a})])}).catch(a=>{_optionalChain([_worker_threads.parentPort, 'optionalAccess', _8 => _8.postMessage, 'call', _9 => _9({success:!1,error:a instanceof Error?a.message:String(a)})])})}catch(o){_optionalChain([_worker_threads.parentPort, 'optionalAccess', _10 => _10.postMessage, 'call', _11 => _11({success:!1,error:o instanceof Error?o.message:String(o)})])}}exports.runDtsInWorker = Bt;
@@ -0,0 +1,144 @@
1
+ type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
2
+
3
+ type Format = 'esm' | 'cjs' | 'iife';
4
+ type Target = 'bun' | 'node' | 'browser';
5
+ type External = string[];
6
+ type Entry = string[] | Record<string, string>;
7
+ type DtsOptions = {
8
+ /**
9
+ * Entry point files for TypeScript declaration file generation
10
+ *
11
+ * This can be:
12
+ * - An array of file paths
13
+ * - An object where keys are output names and values are input file paths
14
+ *
15
+ * The key names are used for the generated declaration files.
16
+ * For example, {custom: './src/index.ts'} will generate custom.d.ts
17
+ *
18
+ * If not specified, the main entry points will be used for declaration file generation.
19
+ *
20
+ * If a string path is provided in an array, the file name (without extension)
21
+ * will be used as the name for the output declaration file.
22
+ *
23
+ * @example
24
+ * // Using string paths in an array
25
+ * entry: ['./src/index.ts'] // Generates index.d.ts
26
+ *
27
+ * // Using named outputs as an object
28
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
29
+ */
30
+ entry: Entry;
31
+ /**
32
+ * Path to a preferred tsconfig.json file to use for declaration generation
33
+ *
34
+ * If not specified, the tsconfig.json in the project root will be used.
35
+ * This option allows you to use a different TypeScript configuration
36
+ * specifically for declaration file generation.
37
+ *
38
+ * @example
39
+ * preferredTsconfigPath: './tsconfig.build.json'
40
+ */
41
+ preferredTsconfigPath?: string;
42
+ };
43
+ interface BunupOptions {
44
+ /**
45
+ * Name of the build configuration
46
+ * Used for logging and identification purposes
47
+ */
48
+ name?: string;
49
+ /**
50
+ * Entry point files for the build
51
+ *
52
+ * This can be:
53
+ * - An array of file paths
54
+ * - An object where keys are output names and values are input file paths
55
+ *
56
+ * The key names are used for the generated output files.
57
+ * For example, {custom: './src/index.ts'} will generate custom.js
58
+ *
59
+ * If a string path is provided in an array, the file name (without extension)
60
+ * will be used as the name for the output file.
61
+ *
62
+ * @example
63
+ * // Using string paths in an array
64
+ * entry: ['./src/index.ts'] // Generates index.js
65
+ *
66
+ * // Using named outputs as an object
67
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
68
+ */
69
+ entry: Entry;
70
+ /**
71
+ * Output directory for the bundled files
72
+ * Defaults to 'dist' if not specified
73
+ */
74
+ outDir: string;
75
+ /**
76
+ * Output formats for the bundle
77
+ * Can include 'esm', 'cjs', and/or 'iife'
78
+ * Defaults to ['cjs'] if not specified
79
+ */
80
+ format: Format[];
81
+ /**
82
+ * Whether to enable all minification options
83
+ * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
84
+ */
85
+ minify?: boolean;
86
+ /**
87
+ * Whether to enable code splitting
88
+ * Defaults to true for ESM format, false for CJS format
89
+ */
90
+ splitting?: boolean;
91
+ /**
92
+ * Whether to minify whitespace in the output
93
+ * Removes unnecessary whitespace to reduce file size
94
+ */
95
+ minifyWhitespace?: boolean;
96
+ /**
97
+ * Whether to minify identifiers in the output
98
+ * Renames variables and functions to shorter names
99
+ */
100
+ minifyIdentifiers?: boolean;
101
+ /**
102
+ * Whether to minify syntax in the output
103
+ * Optimizes code structure for smaller file size
104
+ */
105
+ minifySyntax?: boolean;
106
+ /**
107
+ * Whether to watch for file changes and rebuild automatically
108
+ */
109
+ watch?: boolean;
110
+ /**
111
+ * Whether to generate TypeScript declaration files (.d.ts)
112
+ * When set to true, generates declaration files for all entry points
113
+ * Can also be configured with DtsOptions for more control
114
+ */
115
+ dts?: boolean | DtsOptions;
116
+ /**
117
+ * External packages that should not be bundled
118
+ * Useful for dependencies that should be kept as external imports
119
+ */
120
+ external?: External;
121
+ /**
122
+ * Packages that should be bundled even if they are in external
123
+ * Useful for dependencies that should be included in the bundle
124
+ */
125
+ noExternal?: External;
126
+ /**
127
+ * The target environment for the bundle
128
+ * Can be 'browser', 'bun', 'node', etc.
129
+ * Defaults to 'node' if not specified
130
+ */
131
+ target?: Target;
132
+ /**
133
+ * Whether to clean the output directory before building
134
+ * When true, removes all files in the outDir before starting a new build
135
+ * Defaults to true if not specified
136
+ */
137
+ clean?: boolean;
138
+ }
139
+
140
+ type DefineConfigOption = WithOptional<BunupOptions, 'outDir' | 'format'>;
141
+ type DefineConfigOptions = DefineConfigOption | DefineConfigOption[];
142
+ declare function defineConfig(options: DefineConfigOptions): DefineConfigOptions;
143
+
144
+ export { defineConfig };
@@ -0,0 +1,144 @@
1
+ type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
2
+
3
+ type Format = 'esm' | 'cjs' | 'iife';
4
+ type Target = 'bun' | 'node' | 'browser';
5
+ type External = string[];
6
+ type Entry = string[] | Record<string, string>;
7
+ type DtsOptions = {
8
+ /**
9
+ * Entry point files for TypeScript declaration file generation
10
+ *
11
+ * This can be:
12
+ * - An array of file paths
13
+ * - An object where keys are output names and values are input file paths
14
+ *
15
+ * The key names are used for the generated declaration files.
16
+ * For example, {custom: './src/index.ts'} will generate custom.d.ts
17
+ *
18
+ * If not specified, the main entry points will be used for declaration file generation.
19
+ *
20
+ * If a string path is provided in an array, the file name (without extension)
21
+ * will be used as the name for the output declaration file.
22
+ *
23
+ * @example
24
+ * // Using string paths in an array
25
+ * entry: ['./src/index.ts'] // Generates index.d.ts
26
+ *
27
+ * // Using named outputs as an object
28
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.d.ts and utils.d.ts
29
+ */
30
+ entry: Entry;
31
+ /**
32
+ * Path to a preferred tsconfig.json file to use for declaration generation
33
+ *
34
+ * If not specified, the tsconfig.json in the project root will be used.
35
+ * This option allows you to use a different TypeScript configuration
36
+ * specifically for declaration file generation.
37
+ *
38
+ * @example
39
+ * preferredTsconfigPath: './tsconfig.build.json'
40
+ */
41
+ preferredTsconfigPath?: string;
42
+ };
43
+ interface BunupOptions {
44
+ /**
45
+ * Name of the build configuration
46
+ * Used for logging and identification purposes
47
+ */
48
+ name?: string;
49
+ /**
50
+ * Entry point files for the build
51
+ *
52
+ * This can be:
53
+ * - An array of file paths
54
+ * - An object where keys are output names and values are input file paths
55
+ *
56
+ * The key names are used for the generated output files.
57
+ * For example, {custom: './src/index.ts'} will generate custom.js
58
+ *
59
+ * If a string path is provided in an array, the file name (without extension)
60
+ * will be used as the name for the output file.
61
+ *
62
+ * @example
63
+ * // Using string paths in an array
64
+ * entry: ['./src/index.ts'] // Generates index.js
65
+ *
66
+ * // Using named outputs as an object
67
+ * entry: { myModule: './src/index.ts', utils: './src/utility-functions.ts' } // Generates myModule.js and utils.js
68
+ */
69
+ entry: Entry;
70
+ /**
71
+ * Output directory for the bundled files
72
+ * Defaults to 'dist' if not specified
73
+ */
74
+ outDir: string;
75
+ /**
76
+ * Output formats for the bundle
77
+ * Can include 'esm', 'cjs', and/or 'iife'
78
+ * Defaults to ['cjs'] if not specified
79
+ */
80
+ format: Format[];
81
+ /**
82
+ * Whether to enable all minification options
83
+ * When true, enables minifyWhitespace, minifyIdentifiers, and minifySyntax
84
+ */
85
+ minify?: boolean;
86
+ /**
87
+ * Whether to enable code splitting
88
+ * Defaults to true for ESM format, false for CJS format
89
+ */
90
+ splitting?: boolean;
91
+ /**
92
+ * Whether to minify whitespace in the output
93
+ * Removes unnecessary whitespace to reduce file size
94
+ */
95
+ minifyWhitespace?: boolean;
96
+ /**
97
+ * Whether to minify identifiers in the output
98
+ * Renames variables and functions to shorter names
99
+ */
100
+ minifyIdentifiers?: boolean;
101
+ /**
102
+ * Whether to minify syntax in the output
103
+ * Optimizes code structure for smaller file size
104
+ */
105
+ minifySyntax?: boolean;
106
+ /**
107
+ * Whether to watch for file changes and rebuild automatically
108
+ */
109
+ watch?: boolean;
110
+ /**
111
+ * Whether to generate TypeScript declaration files (.d.ts)
112
+ * When set to true, generates declaration files for all entry points
113
+ * Can also be configured with DtsOptions for more control
114
+ */
115
+ dts?: boolean | DtsOptions;
116
+ /**
117
+ * External packages that should not be bundled
118
+ * Useful for dependencies that should be kept as external imports
119
+ */
120
+ external?: External;
121
+ /**
122
+ * Packages that should be bundled even if they are in external
123
+ * Useful for dependencies that should be included in the bundle
124
+ */
125
+ noExternal?: External;
126
+ /**
127
+ * The target environment for the bundle
128
+ * Can be 'browser', 'bun', 'node', etc.
129
+ * Defaults to 'node' if not specified
130
+ */
131
+ target?: Target;
132
+ /**
133
+ * Whether to clean the output directory before building
134
+ * When true, removes all files in the outDir before starting a new build
135
+ * Defaults to true if not specified
136
+ */
137
+ clean?: boolean;
138
+ }
139
+
140
+ type DefineConfigOption = WithOptional<BunupOptions, 'outDir' | 'format'>;
141
+ type DefineConfigOptions = DefineConfigOption | DefineConfigOption[];
142
+ declare function defineConfig(options: DefineConfigOptions): DefineConfigOptions;
143
+
144
+ export { defineConfig };
package/build/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});function n(i){return i}exports.defineConfig = n;
@@ -0,0 +1 @@
1
+ function n(i){return i}export{n as defineConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunup",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
4
4
  "description": "A extremely fast, zero-config bundler for TypeScript & JavaScript, powered by Bun.",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -18,10 +18,11 @@
18
18
  "@types/bun": "^1.2.5",
19
19
  "@typescript-eslint/eslint-plugin": "^7.3.1",
20
20
  "bumpp": "^10.1.0",
21
- "bunup": "^0.1.12",
21
+ "bunup": "^0.1.16",
22
22
  "eslint": "^8.57.0",
23
23
  "husky": "^9.1.6",
24
24
  "prettier": "^3.2.5",
25
+ "tsup": "^8.4.0",
25
26
  "typescript": "^5.4.3",
26
27
  "vitest": "^2.0.5"
27
28
  },
@@ -58,8 +59,8 @@
58
59
  "rollup-plugin-dts": "^6.1.1"
59
60
  },
60
61
  "scripts": {
61
- "build": "bunup",
62
- "dev": "bunup --watch",
62
+ "build": "tsup",
63
+ "dev": "tsup --watch",
63
64
  "build:docs": "pnpm -C docs build",
64
65
  "dev:docs": "pnpm -C docs dev",
65
66
  "test-build": "pnpm -C tests build",