@tochii/build 2.0.4 → 2.2.0

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.
@@ -0,0 +1,11 @@
1
+ import R from"chalk";import y from"node:fs";import E from"node:path";import K from"deepmerge";import d from"chalk";var g="tochibuild",l=d.cyan(g),a=class{};a.custom=(e,...t)=>{console[e](l,...t)},a.log=(...e)=>{console.log(l,...e)},a.debug=(...e)=>{console.debug(l,...e)},a.info=(...e)=>{console.info(l,...e)},a.warn=(...e)=>{console.warn(l,...[...e].map(t=>d.yellow(t)))},a.error=(e,...t)=>{console.error(d.red(g),d.bgRed(...t),e?.stack?`
2
+ ${d.gray(e.stack)}`:"")},a.success=(...e)=>{console.log(d.green(g),...e)};var f=a;var n=class n{};n.defaultConfigOptions={tsconfig:"tsconfig.json",dts:!0,format:["esm"],minify:!0,skipNodeModulesBundle:!0},n.ignoredEntries=["!build/**","!dist/**","!node_modules/**","!**/build/**","!**/dist/**","!**/node_modules/**","!**/*.d.ts","!**/{tochibuild,tsup}.*"],n.entriesCommon=["**/*.{js,ts}"],n.entriesIndex=["**/index.{js,ts}"],n.defaultEntriesIndex=[...n.ignoredEntries,...n.entriesIndex],n.defaultEntriesCommon=[...n.ignoredEntries,...n.entriesCommon],n.defaultOptions=e=>x(e,t=>{let r=h(t.entry,"ignoredEntries");return{...n.defaultConfigOptions,...t,entry:r}}),n.defaultOptionsWithIndexEntries=e=>x(e,t=>{let r=h(t.entry,"defaultEntriesIndex");return{...n.defaultConfigOptions,...t,entry:r}}),n.defaultOptionsWithCommonEntries=e=>x(e,t=>{let r=h(t.entry,"defaultEntriesCommon");return{...n.defaultConfigOptions,...t,entry:r}}),n.generateConfig=I;var u=n,M=u;function x(i,e){let t=s=>Array.isArray(s)?s.map(o=>K(e(o),s)):K(e(s),s);if(typeof i=="function"){let s=i;async function o(b){let p=await s(b);return t(p)}return o}return t(i)}function h(i,e){if(Array.isArray(i))return[...u[e],...i];let t={};return u[e].forEach(r=>t[r]=r),{...i,...t}}function w(i){return E.isAbsolute(i||".")?i:E.resolve(process.cwd(),i)}function I(i,e,t,r){let s="";try{let o=e?.ext||".ts",p=`${e?.filename||"tochibuild.config"}${o}`;(e?.outDir?.length?e.outDir:["."]).forEach(m=>{s=w(m),y.existsSync(m)||y.mkdirSync(m,{recursive:!0});let O=E.join(s,p),k=y.existsSync(O);!e?.overwrite&&k&&(f.warn(`the config '${p}' file already exists for this project.`),r&&process.exit(1));let q=" ",c="",C={clean:!1,splitting:!0},B=P=>{c+=P==="esm"?`import build from '${i}';
3
+
4
+ `:`const build = require('${i}');
5
+
6
+ `,c+=P==="esm"?`export default build.defineConfigWithIndexEntries({
7
+ `:`module.exports = build.defineConfigWithIndexEntries({
8
+ `,Object.entries(C).forEach(([$,j])=>{c+=`${q}${$}: ${JSON.stringify(j)},
9
+ `}),c+=`});
10
+ `};switch(o){case".ts":case".js":B("esm");break;case".cjs":B("cjs");break;case".json":c+=`${JSON.stringify({...C,entry:u.defaultEntriesIndex},null,2)}
11
+ `;break;default:f.error(void 0,`unsupported extension: ${o}`),process.exit(1)}y.writeFileSync(O,c),f.success(R.cyan("the config file has been created at:"),R.gray(O))})}catch(o){if(t)throw o;f.error(o,o.message?`failed to generate config file in ${s}: ${o.message}`:`failed to generate config file in ${s}`),r&&process.exit(1)}}export{f as a,u as b,M as c};
package/dist/cli.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as s,c as k}from"./chunk-LBH52VOU.mjs";import u from"chalk";import a from"fs";import l from"path";import{Command as B}from"commander";import{spawn as M}from"child_process";var P={name:"tochibuild",version:"2.0.4",description:"An extremely fast JavaScript/Typescript and CSS bundler with minimal configuration.",repository:"https://github.com/tochiResources/project/tree/main/packages/build/tochibuild.git",license:"MIT",keywords:["bundler","build","typescript","javascript","tsup","cli","node","tochi","tochiResources"],bin:"./dist/cli.mjs",scripts:{dev:"tsx cli.ts",build:"tsx cli.ts --config tochibuild.config.ts --entry index.ts --entry cli.ts --entry utils.ts","build:release":"bun run build && bun run release",release:"npm publish --access public --no-private"},dependencies:{chalk:"^5.4.1",commander:"^13.1.0",tsup:"^8.4.0"},devDependencies:{"@types/node":"^22.15.17",tsx:"^4.19.4",typescript:"^5.8.3"},engines:{node:">=18.17.0"},files:["dist"]};var $={node:"tsup --target=node18.17"},W={node:"tsup"},A=l.resolve(process.cwd(),"."),x=A.replace(/\\/g,"/").includes("packages/build"),p=x?void 0:l.join(A,"package.json"),F=p?a.existsSync(p):!1,E=p&&F?a.readFileSync(p,"utf-8"):void 0,d=E?JSON.parse(E):void 0;async function T(r){let w=process.cwd(),N=[l.join(w,"tochibuild.config.ts"),...[".ts",".js",".cjs",".json"].map(e=>l.join(w,`tsup.config${e}`))],C=d?.tochibuild,v=d?.tsup,j=!!Object.keys(C||{}).length||!!Object.keys(v||{}).length,S=j||N.some(e=>a.existsSync(e)),I=new B("tochibuild").name("tochibuild <command>").description("bundle a Node.js project powered by tsup (https://tsup.egoist.dev)").allowUnknownOption(!0).version(P.version).argument("[args...]","arguments to pass to tsup").action(async e=>O(e));I.command("config").description("generate config files").option("--ext <string>","the file extension to use excluding the file extension (defaults to .ts)",".ts").option("-f, --filename <string>","the file name to use (defaults to tochibuild.config)","tochibuild.config").option("-o, --overwrite","whether or not to overwrite the config file if it already exists (defaults to false)",!1).option("--outDir <string...>","the absolute/relative output directory paths to create the config files in (defaults to the working directory)").action(e=>R("node",e)),I.parseAsync(process.argv);async function O(e){return new Promise((g,h)=>{try{let c="node",t=[],f=e.includes("--config"),m=e.includes("--no-config"),b=f?e.findIndex(o=>o==="--config")+1:void 0;if(!f&&!m&&!S)s.log("no config file found, generating default config..."),k.generateConfig(r,void 0,!1,!0),t.push(...e);else if(!f&&!m&&S){if(j){let o=C||v;e.filter(n=>n.startsWith("-")).forEach(n=>{let i=e.findIndex(D=>D===n),G=n.startsWith("--")?n.slice(2):n.slice(1);if(o[G]||(t.push(n),t[i+1]?.startsWith("-")))return;let J=t[i+1];J&&t.push(J)}),Object.entries(o).forEach(([n,i])=>{typeof i=="boolean"||i==="true"||i==="false"?i&&t.push(`--${n}`):typeof i=="string"&&t.push(`--${n}`,i)}),t.push("--no-config")}}else{if(b!=null&&b>=0){let o=e[b]||"unspecified";a.existsSync(o)||(s.error(void 0,`config file '${o}' does not exist`),s.info(`try running '${u.magenta(r)} ${u.blue("config")} ${u.gray("-h")}' to get help on how to generate a config file`),process.exit(1))}t.push(...e)}s.log(`running build${x||d?.name?` for ${u.magenta(x?r:d.name)}`:""}...`);let y=M("npx",["--yes",`--package=${W[c]}`,"--package=typescript@5.8.3",`${$[c]}`,...!f&&!m?["--config","tochibuild.config.ts"]:[],...t],{stdio:"inherit",shell:!0,cwd:process.cwd(),env:process.env});y.on("exit",o=>{process.exit(o??1)}),process.on("SIGINT",()=>{h(),y.kill("SIGINT")}),process.on("SIGTERM",()=>{h(),y.kill("SIGTERM")}),g()}catch(c){h(c)}})}function R(e,g){switch($[e]){case"tsup --target=node18.17":k.generateConfig(r,g,!1,!0);break}}}T("@tochii/build");
2
+ import{a,c as J}from"./chunk-EOPXFG45.mjs";import r from"chalk";import d from"node:fs";import c from"node:path";import{fileURLToPath as M}from"node:url";import{spawn as U}from"node:child_process";import{Command as F}from"commander";var E={name:"tochibuild",version:"2.2.0",description:"An extremely fast JavaScript/Typescript and CSS bundler with minimal configuration.",repository:"https://github.com/tochiResources/project/tree/main/packages/build/tochibuild.git",license:"MIT",keywords:["bundler","build","typescript","javascript","tsup","esbuild","glob","cli","node","tochi","tochiResources"],bin:"./dist/cli.mjs",scripts:{dev:"tsx cli.ts",copybundler:"copyfiles ./tsup@8.4.0/* ./dist",build:"tsx cli.ts && bun run copybundler","build:release":"bun run build && bun run release",release:"bun publish --access public --no-private"},dependencies:{chalk:"^5.4.1",commander:"^13.1.0",deepmerge:"^4.3.1",tsup:"8.4.0"},devDependencies:{"@types/node":"^22.15.17",copyfiles:"^2.4.1",tsx:"^4.19.4",typescript:"^5.8.3"},engines:{node:">=18.17.0"},files:["dist"]};var L=M(import.meta.url),B=c.dirname(L),k=c.resolve(process.cwd(),"."),x=k.replace(/\\/g,"/").includes("packages/build"),p=x?void 0:c.join(k,"package.json"),_=p?d.existsSync(p):!1,T=p&&_?d.readFileSync(p,"utf-8"):void 0,f=T?JSON.parse(T):void 0;async function A(l){let R={node:c.join(B,"tsup@8.4.0/cli-node.js")},j=process.cwd(),N=[...[".ts",".js",".cjs",".json"].map(n=>c.join(j,`tochibuild.config${n}`)),...[".ts",".js",".cjs",".json"].map(n=>c.join(j,`tsup.config${n}`))],v=f?.tochibuild,w=f?.tsup,C=!!Object.keys(v||{}).length||!!Object.keys(w||{}).length,g=N.find(n=>d.existsSync(n)),$=C||g,P=new F("tochibuild").name("tochibuild <command>").description("bundle a Node.js project powered by tsup (https://tsup.egoist.dev)").allowUnknownOption(!0).version(E.version).argument("[args...]","arguments to pass to tsup").action(async(...n)=>O(n));P.command("config").description("generate config files").option("--ext <string>","the file extension to use excluding the file extension (defaults to .ts)",".ts").option("-f, --filename <string>","the file name to use (defaults to tochibuild.config)","tochibuild.config").option("-o, --overwrite","whether or not to overwrite the config file if it already exists (defaults to false)",!1).option("--outDir <string...>","the absolute/relative output directory paths to create the config files in (defaults to the working directory)").action(n=>J.generateConfig(l,n,!1,!0)),P.parseAsync(process.argv);async function O(n){let[i]=n;return new Promise((D,u)=>{try{let h="node",e=[],m=i.includes("--config"),S=i.includes("--no-config"),b=m?i.findIndex(t=>t==="--config")+1:void 0;if(!m&&!S&&!$){if(i[0]==null||i[0]?.startsWith("-")){a.custom("error",`${r.red("No input files, try")} '${r.magenta(l)} ${r.gray("[...files]")}' ${r.red("instead")}`),u();return}e.push(...i)}else if(!m&&!S&&$)if(C){let t=v||w;i.filter(s=>s.startsWith("-")).forEach(s=>{let o=i.findIndex(V=>V===s),G=s.startsWith("--")?s.slice(2):s.slice(1);if(t[G]||(e.push(s),e[o+1]?.startsWith("-")))return;let I=e[o+1];I&&e.push(I)}),Object.entries(t).forEach(([s,o])=>{typeof o=="boolean"||o==="true"||o==="false"?o&&e.push(`--${s}`):typeof o=="string"&&e.push(`--${s}`,o)}),e.push("--no-config")}else if(g){let t=c.relative(k,g).replace(/\\/g,"/");a.log(`using existing configuration file: ${r.gray(t)}`),e.push("--config",t),e.push(...i)}else e.push(...i);else{if(b!=null&&b>=0){let t=i[b]||"unspecified";d.existsSync(t)||(a.error(void 0,`config file '${t}' does not exist`),a.info(`try running '${r.magenta(l)} ${r.blue("config")} ${r.gray("-h")}' to get help on how to generate a config file`),process.exit(1))}e.push(...i)}a.log(`running build${x||f?.name?` for ${r.magenta(x?l:f.name)}`:""}...`);let y=U("node",[R[h],...e],{stdio:"inherit",shell:!0,cwd:process.cwd(),env:process.env});y.on("exit",t=>{process.exit(t??1)}),process.on("SIGINT",()=>{u(),y.kill("SIGINT")}),process.on("SIGTERM",()=>{u(),y.kill("SIGTERM")}),D()}catch(h){u(h)}})}}A("@tochii/build");
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as tsup from 'tsup';
2
- import { B as BuildUtils$1, c as BuildOptionsParams } from './utils-CwdN3Nrj.mjs';
2
+ import { B as BuildUtils$1, c as BuildOptionsParams } from './utils-CJIhwKYt.mjs';
3
3
 
4
4
  type DefineConfigOptions = BuildOptionsParams<'entry' | 'clean' | 'splitting'>;
5
5
  type DefineConfigOptionsIndexEntries = BuildOptionsParams<'clean' | 'splitting'>;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{c as n}from"./chunk-LBH52VOU.mjs";import{defineConfig as t}from"tsup";var l=n,e={utils:n,defineConfig:o,defineConfigWithIndexEntries:r,defineConfigWithCommonEntries:f};function o(i){return t(n.defaultOptions(i))}function r(i){return t(n.defaultOptionsWithIndexEntries(i))}function f(i){return t(n.defaultOptionsWithCommonEntries(i))}var a=e;export{l as BuildUtils,a as default,o as defineConfig,f as defineConfigWithCommonEntries,r as defineConfigWithIndexEntries};
1
+ import{c as n}from"./chunk-EOPXFG45.mjs";import{defineConfig as t}from"tsup";var l=n,e={utils:n,defineConfig:o,defineConfigWithIndexEntries:r,defineConfigWithCommonEntries:f};function o(i){return t(n.defaultOptions(i))}function r(i){return t(n.defaultOptionsWithIndexEntries(i))}function f(i){return t(n.defaultOptionsWithCommonEntries(i))}var a=e;export{l as BuildUtils,a as default,o as defineConfig,f as defineConfigWithCommonEntries,r as defineConfigWithIndexEntries};
@@ -0,0 +1,6 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// package.json
2
+ var version = "8.4.0";
3
+
4
+
5
+
6
+ exports.version = version;
@@ -0,0 +1,153 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }
2
+
3
+ var _chunkBYH4XDRHjs = require('./chunk-BYH4XDRH.js');
4
+
5
+
6
+ var _chunkTWFEYLU4js = require('./chunk-TWFEYLU4.js');
7
+
8
+ // src/cli-main.ts
9
+ var _cac = require('cac');
10
+
11
+ // node_modules/.pnpm/flat@6.0.1/node_modules/flat/index.js
12
+ function isBuffer(obj) {
13
+ return obj && obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
14
+ }
15
+ function keyIdentity(key) {
16
+ return key;
17
+ }
18
+ function flatten(target, opts) {
19
+ opts = opts || {};
20
+ const delimiter = opts.delimiter || ".";
21
+ const maxDepth = opts.maxDepth;
22
+ const transformKey = opts.transformKey || keyIdentity;
23
+ const output = {};
24
+ function step(object, prev, currentDepth) {
25
+ currentDepth = currentDepth || 1;
26
+ Object.keys(object).forEach(function(key) {
27
+ const value = object[key];
28
+ const isarray = opts.safe && Array.isArray(value);
29
+ const type = Object.prototype.toString.call(value);
30
+ const isbuffer = isBuffer(value);
31
+ const isobject = type === "[object Object]" || type === "[object Array]";
32
+ const newKey = prev ? prev + delimiter + transformKey(key) : transformKey(key);
33
+ if (!isarray && !isbuffer && isobject && Object.keys(value).length && (!opts.maxDepth || currentDepth < maxDepth)) {
34
+ return step(value, newKey, currentDepth + 1);
35
+ }
36
+ output[newKey] = value;
37
+ });
38
+ }
39
+ step(target);
40
+ return output;
41
+ }
42
+
43
+ // src/cli-main.ts
44
+ function ensureArray(input) {
45
+ return Array.isArray(input) ? input : input.split(",");
46
+ }
47
+ async function main(options = {}) {
48
+ const cli = _cac.cac.call(void 0, "tsup");
49
+ cli.command("[...files]", "Bundle files", {
50
+ ignoreOptionDefaultValue: true
51
+ }).option("--entry.* <file>", "Use a key-value pair as entry files").option("-d, --out-dir <dir>", "Output directory", { default: "dist" }).option("--format <format>", 'Bundle format, "cjs", "iife", "esm"', {
52
+ default: "cjs"
53
+ }).option("--minify [terser]", "Minify bundle").option("--minify-whitespace", "Minify whitespace").option("--minify-identifiers", "Minify identifiers").option("--minify-syntax", "Minify syntax").option(
54
+ "--keep-names",
55
+ "Keep original function and class names in minified code"
56
+ ).option("--target <target>", 'Bundle target, "es20XX" or "esnext"', {
57
+ default: "es2017"
58
+ }).option(
59
+ "--legacy-output",
60
+ "Output different formats to different folder instead of using different extensions"
61
+ ).option("--dts [entry]", "Generate declaration file").option("--dts-resolve", "Resolve externals types used for d.ts files").option("--dts-only", "Emit declaration files only").option(
62
+ "--experimental-dts [entry]",
63
+ "Generate declaration file (experimental)"
64
+ ).option(
65
+ "--sourcemap [inline]",
66
+ "Generate external sourcemap, or inline source: --sourcemap inline"
67
+ ).option(
68
+ "--watch [path]",
69
+ 'Watch mode, if path is not specified, it watches the current folder ".". Repeat "--watch" for more than one path'
70
+ ).option("--ignore-watch <path>", "Ignore custom paths in watch mode").option(
71
+ "--onSuccess <command>",
72
+ "Execute command after successful build, specially useful for watch mode"
73
+ ).option("--env.* <value>", "Define compile-time env variables").option(
74
+ "--inject <file>",
75
+ "Replace a global variable with an import from another file"
76
+ ).option("--define.* <value>", "Define compile-time constants").option(
77
+ "--external <name>",
78
+ "Mark specific packages / package.json (dependencies and peerDependencies) as external"
79
+ ).option("--global-name <name>", "Global variable name for iife format").option("--jsxFactory <jsxFactory>", "Name of JSX factory function", {
80
+ default: "React.createElement"
81
+ }).option("--jsxFragment <jsxFragment>", "Name of JSX fragment function", {
82
+ default: "React.Fragment"
83
+ }).option("--replaceNodeEnv", "Replace process.env.NODE_ENV").option("--no-splitting", "Disable code splitting").option("--clean", "Clean output directory").option(
84
+ "--silent",
85
+ 'Suppress non-error logs (excluding "onSuccess" process output)'
86
+ ).option("--pure <express>", "Mark specific expressions as pure").option("--metafile", "Emit esbuild metafile (a JSON file)").option("--platform <platform>", "Target platform", {
87
+ default: "node"
88
+ }).option("--loader <ext=loader>", "Specify the loader for a file extension").option("--tsconfig <filename>", "Use a custom tsconfig").option("--config <filename>", "Use a custom config file").option("--no-config", "Disable config file").option("--shims", "Enable cjs and esm shims").option("--inject-style", "Inject style tag to document head").option(
89
+ "--treeshake [strategy]",
90
+ 'Using Rollup for treeshaking instead, "recommended" or "smallest" or "safest"'
91
+ ).option("--publicDir [dir]", "Copy public directory to output directory").option(
92
+ "--killSignal <signal>",
93
+ 'Signal to kill child process, "SIGTERM" or "SIGKILL"'
94
+ ).option("--cjsInterop", "Enable cjs interop").action(async (files, flags) => {
95
+ const { build } = await Promise.resolve().then(() => _interopRequireWildcard(require("./index.js")));
96
+ Object.assign(options, {
97
+ ...flags
98
+ });
99
+ if (!options.entry && files.length > 0) {
100
+ options.entry = files.map(_chunkTWFEYLU4js.slash);
101
+ }
102
+ if (flags.format) {
103
+ const format = ensureArray(flags.format);
104
+ options.format = format;
105
+ }
106
+ if (flags.external) {
107
+ const external = ensureArray(flags.external);
108
+ options.external = external;
109
+ }
110
+ if (flags.target) {
111
+ options.target = flags.target.includes(",") ? flags.target.split(",") : flags.target;
112
+ }
113
+ if (flags.dts || flags.dtsResolve || flags.dtsOnly) {
114
+ options.dts = {};
115
+ if (typeof flags.dts === "string") {
116
+ options.dts.entry = flags.dts;
117
+ }
118
+ if (flags.dtsResolve) {
119
+ options.dts.resolve = flags.dtsResolve;
120
+ }
121
+ if (flags.dtsOnly) {
122
+ options.dts.only = true;
123
+ }
124
+ }
125
+ if (flags.inject) {
126
+ const inject = ensureArray(flags.inject);
127
+ options.inject = inject;
128
+ }
129
+ if (flags.define) {
130
+ const define = flatten(flags.define);
131
+ options.define = define;
132
+ }
133
+ if (flags.loader) {
134
+ const loader = ensureArray(flags.loader);
135
+ options.loader = loader.reduce((result, item) => {
136
+ const parts = item.split("=");
137
+ return {
138
+ ...result,
139
+ [parts[0]]: parts[1]
140
+ };
141
+ }, {});
142
+ }
143
+ await build(options);
144
+ });
145
+ cli.help();
146
+ cli.version(_chunkBYH4XDRHjs.version);
147
+ cli.parse(process.argv, { run: false });
148
+ await cli.runMatchedCommand();
149
+ }
150
+
151
+
152
+
153
+ exports.main = main;
@@ -0,0 +1,42 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/errors.ts
2
+ var _worker_threads = require('worker_threads');
3
+ var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
4
+ var PrettyError = class extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = this.constructor.name;
8
+ if (typeof Error.captureStackTrace === "function") {
9
+ Error.captureStackTrace(this, this.constructor);
10
+ } else {
11
+ this.stack = new Error(message).stack;
12
+ }
13
+ }
14
+ };
15
+ function handleError(error) {
16
+ if (error.loc) {
17
+ console.error(
18
+ _picocolors2.default.bold(
19
+ _picocolors2.default.red(
20
+ `Error parsing: ${error.loc.file}:${error.loc.line}:${error.loc.column}`
21
+ )
22
+ )
23
+ );
24
+ }
25
+ if (error.frame) {
26
+ console.error(_picocolors2.default.red(error.message));
27
+ console.error(_picocolors2.default.dim(error.frame));
28
+ } else if (error instanceof PrettyError) {
29
+ console.error(_picocolors2.default.red(error.message));
30
+ } else {
31
+ console.error(_picocolors2.default.red(error.stack));
32
+ }
33
+ process.exitCode = 1;
34
+ if (!_worker_threads.isMainThread && _worker_threads.parentPort) {
35
+ _worker_threads.parentPort.postMessage("error");
36
+ }
37
+ }
38
+
39
+
40
+
41
+
42
+ exports.PrettyError = PrettyError; exports.handleError = handleError;
@@ -0,0 +1,352 @@
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 __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // src/utils.ts
34
+ var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
35
+ var _path = require('path'); var _path2 = _interopRequireDefault(_path);
36
+ var _resolvefrom = require('resolve-from'); var _resolvefrom2 = _interopRequireDefault(_resolvefrom);
37
+
38
+ // node_modules/.pnpm/strip-json-comments@5.0.1/node_modules/strip-json-comments/index.js
39
+ var singleComment = Symbol("singleComment");
40
+ var multiComment = Symbol("multiComment");
41
+ var stripWithoutWhitespace = () => "";
42
+ var stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, " ");
43
+ var isEscaped = (jsonString, quotePosition) => {
44
+ let index = quotePosition - 1;
45
+ let backslashCount = 0;
46
+ while (jsonString[index] === "\\") {
47
+ index -= 1;
48
+ backslashCount += 1;
49
+ }
50
+ return Boolean(backslashCount % 2);
51
+ };
52
+ function stripJsonComments(jsonString, { whitespace = true, trailingCommas = false } = {}) {
53
+ if (typeof jsonString !== "string") {
54
+ throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``);
55
+ }
56
+ const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace;
57
+ let isInsideString = false;
58
+ let isInsideComment = false;
59
+ let offset = 0;
60
+ let buffer = "";
61
+ let result = "";
62
+ let commaIndex = -1;
63
+ for (let index = 0; index < jsonString.length; index++) {
64
+ const currentCharacter = jsonString[index];
65
+ const nextCharacter = jsonString[index + 1];
66
+ if (!isInsideComment && currentCharacter === '"') {
67
+ const escaped = isEscaped(jsonString, index);
68
+ if (!escaped) {
69
+ isInsideString = !isInsideString;
70
+ }
71
+ }
72
+ if (isInsideString) {
73
+ continue;
74
+ }
75
+ if (!isInsideComment && currentCharacter + nextCharacter === "//") {
76
+ buffer += jsonString.slice(offset, index);
77
+ offset = index;
78
+ isInsideComment = singleComment;
79
+ index++;
80
+ } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
81
+ index++;
82
+ isInsideComment = false;
83
+ buffer += strip(jsonString, offset, index);
84
+ offset = index;
85
+ continue;
86
+ } else if (isInsideComment === singleComment && currentCharacter === "\n") {
87
+ isInsideComment = false;
88
+ buffer += strip(jsonString, offset, index);
89
+ offset = index;
90
+ } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
91
+ buffer += jsonString.slice(offset, index);
92
+ offset = index;
93
+ isInsideComment = multiComment;
94
+ index++;
95
+ continue;
96
+ } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
97
+ index++;
98
+ isInsideComment = false;
99
+ buffer += strip(jsonString, offset, index + 1);
100
+ offset = index + 1;
101
+ continue;
102
+ } else if (trailingCommas && !isInsideComment) {
103
+ if (commaIndex !== -1) {
104
+ if (currentCharacter === "}" || currentCharacter === "]") {
105
+ buffer += jsonString.slice(offset, index);
106
+ result += strip(buffer, 0, 1) + buffer.slice(1);
107
+ buffer = "";
108
+ offset = index;
109
+ commaIndex = -1;
110
+ } else if (currentCharacter !== " " && currentCharacter !== " " && currentCharacter !== "\r" && currentCharacter !== "\n") {
111
+ buffer += jsonString.slice(offset, index);
112
+ offset = index;
113
+ commaIndex = -1;
114
+ }
115
+ } else if (currentCharacter === ",") {
116
+ result += buffer + jsonString.slice(offset, index);
117
+ buffer = "";
118
+ offset = index;
119
+ commaIndex = index;
120
+ }
121
+ }
122
+ }
123
+ return result + buffer + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
124
+ }
125
+
126
+ // src/utils.ts
127
+ var _tinyglobby = require('tinyglobby');
128
+ function getPostcss() {
129
+ return localRequire("postcss");
130
+ }
131
+ function getApiExtractor() {
132
+ return localRequire("@microsoft/api-extractor");
133
+ }
134
+ function localRequire(moduleName) {
135
+ const p = _resolvefrom2.default.silent(process.cwd(), moduleName);
136
+ return p && __require(p);
137
+ }
138
+ async function removeFiles(patterns, dir) {
139
+ const files = await _tinyglobby.glob.call(void 0, patterns, {
140
+ cwd: dir,
141
+ absolute: true
142
+ });
143
+ files.forEach((file) => _fs2.default.existsSync(file) && _fs2.default.unlinkSync(file));
144
+ }
145
+ function debouncePromise(fn, delay, onError) {
146
+ let timeout;
147
+ let promiseInFly;
148
+ let callbackPending;
149
+ return function debounced(...args) {
150
+ if (promiseInFly) {
151
+ callbackPending = () => {
152
+ debounced(...args);
153
+ callbackPending = void 0;
154
+ };
155
+ } else {
156
+ if (timeout != null) clearTimeout(timeout);
157
+ timeout = setTimeout(() => {
158
+ timeout = void 0;
159
+ promiseInFly = fn(...args).catch(onError).finally(() => {
160
+ promiseInFly = void 0;
161
+ if (callbackPending) callbackPending();
162
+ });
163
+ }, delay);
164
+ }
165
+ };
166
+ }
167
+ function slash(path2) {
168
+ const isExtendedLengthPath = path2.startsWith("\\\\?\\");
169
+ if (isExtendedLengthPath) {
170
+ return path2;
171
+ }
172
+ return path2.replace(/\\/g, "/");
173
+ }
174
+ function truthy(value) {
175
+ return Boolean(value);
176
+ }
177
+ function jsoncParse(data) {
178
+ try {
179
+ return new Function(`return ${stripJsonComments(data).trim()}`)();
180
+ } catch (e2) {
181
+ return {};
182
+ }
183
+ }
184
+ function defaultOutExtension({
185
+ format,
186
+ pkgType
187
+ }) {
188
+ let jsExtension = ".js";
189
+ let dtsExtension = ".d.ts";
190
+ const isModule = pkgType === "module";
191
+ if (isModule && format === "cjs") {
192
+ jsExtension = ".cjs";
193
+ dtsExtension = ".d.cts";
194
+ }
195
+ if (!isModule && format === "esm") {
196
+ jsExtension = ".mjs";
197
+ dtsExtension = ".d.mts";
198
+ }
199
+ if (format === "iife") {
200
+ jsExtension = ".global.js";
201
+ }
202
+ return {
203
+ js: jsExtension,
204
+ dts: dtsExtension
205
+ };
206
+ }
207
+ function ensureTempDeclarationDir() {
208
+ const cwd = process.cwd();
209
+ const dirPath = _path2.default.join(cwd, ".tsup", "declaration");
210
+ if (_fs2.default.existsSync(dirPath)) {
211
+ return dirPath;
212
+ }
213
+ _fs2.default.mkdirSync(dirPath, { recursive: true });
214
+ const gitIgnorePath = _path2.default.join(cwd, ".tsup", ".gitignore");
215
+ writeFileSync(gitIgnorePath, "**/*\n");
216
+ return dirPath;
217
+ }
218
+ var toObjectEntry = (entry) => {
219
+ if (typeof entry === "string") {
220
+ entry = [entry];
221
+ }
222
+ if (!Array.isArray(entry)) {
223
+ return entry;
224
+ }
225
+ entry = entry.map((e) => e.replace(/\\/g, "/"));
226
+ const ancestor = findLowestCommonAncestor(entry);
227
+ return entry.reduce(
228
+ (result, item) => {
229
+ const key = item.replace(ancestor, "").replace(/^\//, "").replace(/\.[a-z]+$/, "");
230
+ return {
231
+ ...result,
232
+ [key]: item
233
+ };
234
+ },
235
+ {}
236
+ );
237
+ };
238
+ var findLowestCommonAncestor = (filepaths) => {
239
+ if (filepaths.length <= 1) return "";
240
+ const [first, ...rest] = filepaths;
241
+ let ancestor = first.split("/");
242
+ for (const filepath of rest) {
243
+ const directories = filepath.split("/", ancestor.length);
244
+ let index = 0;
245
+ for (const directory of directories) {
246
+ if (directory === ancestor[index]) {
247
+ index += 1;
248
+ } else {
249
+ ancestor = ancestor.slice(0, index);
250
+ break;
251
+ }
252
+ }
253
+ ancestor = ancestor.slice(0, index);
254
+ }
255
+ return ancestor.length <= 1 && ancestor[0] === "" ? `/${ancestor[0]}` : ancestor.join("/");
256
+ };
257
+ function toAbsolutePath(p, cwd) {
258
+ if (_path2.default.isAbsolute(p)) {
259
+ return p;
260
+ }
261
+ return slash(_path2.default.normalize(_path2.default.join(cwd || process.cwd(), p)));
262
+ }
263
+ function writeFileSync(filePath, content) {
264
+ _fs2.default.mkdirSync(_path2.default.dirname(filePath), { recursive: true });
265
+ _fs2.default.writeFileSync(filePath, content);
266
+ }
267
+ function replaceDtsWithJsExtensions(dtsFilePath) {
268
+ return dtsFilePath.replace(
269
+ /\.d\.(ts|mts|cts)$/,
270
+ (_, fileExtension) => {
271
+ switch (fileExtension) {
272
+ case "ts":
273
+ return ".js";
274
+ case "mts":
275
+ return ".mjs";
276
+ case "cts":
277
+ return ".cjs";
278
+ default:
279
+ return "";
280
+ }
281
+ }
282
+ );
283
+ }
284
+ var convertArrayEntriesToObjectEntries = (arrayOfEntries) => {
285
+ const objectEntries = Object.fromEntries(
286
+ arrayOfEntries.map(
287
+ (entry) => [
288
+ _path2.default.posix.join(
289
+ ...entry.split(_path2.default.posix.sep).slice(1, -1).concat(_path2.default.parse(entry).name)
290
+ ),
291
+ entry
292
+ ]
293
+ )
294
+ );
295
+ return objectEntries;
296
+ };
297
+ var resolveEntryPaths = async (entryPaths) => {
298
+ const resolvedEntryPaths = typeof entryPaths === "string" || Array.isArray(entryPaths) ? convertArrayEntriesToObjectEntries(await _tinyglobby.glob.call(void 0, entryPaths)) : entryPaths;
299
+ return resolvedEntryPaths;
300
+ };
301
+ var resolveExperimentalDtsConfig = async (options, tsconfig) => {
302
+ const resolvedEntryPaths = await resolveEntryPaths(
303
+ _optionalChain([options, 'access', _2 => _2.experimentalDts, 'optionalAccess', _3 => _3.entry]) || options.entry
304
+ );
305
+ const experimentalDtsObjectEntry = Object.keys(resolvedEntryPaths).length === 0 ? Array.isArray(options.entry) ? convertArrayEntriesToObjectEntries(options.entry) : options.entry : resolvedEntryPaths;
306
+ const normalizedExperimentalDtsConfig = {
307
+ compilerOptions: {
308
+ ...tsconfig.data.compilerOptions || {},
309
+ ..._optionalChain([options, 'access', _4 => _4.experimentalDts, 'optionalAccess', _5 => _5.compilerOptions]) || {}
310
+ },
311
+ entry: experimentalDtsObjectEntry
312
+ };
313
+ return normalizedExperimentalDtsConfig;
314
+ };
315
+ var resolveInitialExperimentalDtsConfig = async (experimentalDts) => {
316
+ if (experimentalDts == null) {
317
+ return;
318
+ }
319
+ if (typeof experimentalDts === "boolean")
320
+ return experimentalDts ? { entry: {} } : void 0;
321
+ if (typeof experimentalDts === "string") {
322
+ return {
323
+ entry: convertArrayEntriesToObjectEntries(await _tinyglobby.glob.call(void 0, experimentalDts))
324
+ };
325
+ }
326
+ return {
327
+ ...experimentalDts,
328
+ entry: _optionalChain([experimentalDts, 'optionalAccess', _6 => _6.entry]) == null ? {} : await resolveEntryPaths(experimentalDts.entry)
329
+ };
330
+ };
331
+
332
+
333
+
334
+
335
+
336
+
337
+
338
+
339
+
340
+
341
+
342
+
343
+
344
+
345
+
346
+
347
+
348
+
349
+
350
+
351
+
352
+ exports.__require = __require; exports.__commonJS = __commonJS; exports.__toESM = __toESM; exports.getPostcss = getPostcss; exports.getApiExtractor = getApiExtractor; exports.localRequire = localRequire; exports.removeFiles = removeFiles; exports.debouncePromise = debouncePromise; exports.slash = slash; exports.truthy = truthy; exports.jsoncParse = jsoncParse; exports.defaultOutExtension = defaultOutExtension; exports.ensureTempDeclarationDir = ensureTempDeclarationDir; exports.toObjectEntry = toObjectEntry; exports.toAbsolutePath = toAbsolutePath; exports.writeFileSync = writeFileSync; exports.replaceDtsWithJsExtensions = replaceDtsWithJsExtensions; exports.resolveExperimentalDtsConfig = resolveExperimentalDtsConfig; exports.resolveInitialExperimentalDtsConfig = resolveInitialExperimentalDtsConfig;