susee 1.5.6 → 1.5.7
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 +9 -3
- package/bin/susee +2 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -8
- package/dist/index.d.mts +52 -8
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -14
- package/dist/bin/index.d.mts +0 -2
- package/dist/bin/index.mjs +0 -2
- package/dist/bin/index.mjs.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,52 @@
|
|
|
1
|
-
import
|
|
1
|
+
import ts6 from "@suseejs/ts6";
|
|
2
|
+
import type { DepsFile, SuseePlugin, SuseePluginFunction, ValidExts } from "@suseejs/type";
|
|
3
|
+
type ValidExts = ".js" | ".cjs" | ".mjs" | ".ts" | ".cts" | ".mts" | ".tsx" | ".jsx" | ".json";
|
|
4
|
+
interface DepsFile {
|
|
5
|
+
file: string;
|
|
6
|
+
content: string;
|
|
7
|
+
bytes: number;
|
|
8
|
+
moduleType: "cjs" | "esm" | "json";
|
|
9
|
+
fileExt: ValidExts;
|
|
10
|
+
is_jsx: boolean;
|
|
11
|
+
is_entry: boolean;
|
|
12
|
+
}
|
|
13
|
+
type DepsFiles = DepsFile[];
|
|
14
|
+
type PostProcessPlugin = {
|
|
15
|
+
type: "post-process";
|
|
16
|
+
async: true;
|
|
17
|
+
func: (code: string, file?: string) => Promise<string>;
|
|
18
|
+
name?: string;
|
|
19
|
+
} | {
|
|
20
|
+
type: "post-process";
|
|
21
|
+
async: false;
|
|
22
|
+
func: (code: string, file?: string) => string;
|
|
23
|
+
name?: string;
|
|
24
|
+
};
|
|
25
|
+
type PreProcessPlugin = {
|
|
26
|
+
type: "pre-process";
|
|
27
|
+
async: true;
|
|
28
|
+
func: (code: string, file?: string) => Promise<string>;
|
|
29
|
+
name?: string;
|
|
30
|
+
} | {
|
|
31
|
+
type: "pre-process";
|
|
32
|
+
async: false;
|
|
33
|
+
func: (code: string, file?: string) => string;
|
|
34
|
+
name?: string;
|
|
35
|
+
};
|
|
36
|
+
type DependencyPlugin = {
|
|
37
|
+
type: "dependency";
|
|
38
|
+
async: true;
|
|
39
|
+
func: (depsFiles: DepsFiles, compilerOptions: ts6.CompilerOptions) => Promise<DepsFiles>;
|
|
40
|
+
name?: string;
|
|
41
|
+
} | {
|
|
42
|
+
type: "dependency";
|
|
43
|
+
async: false;
|
|
44
|
+
func: (DepsFiles: DepsFiles, compilerOptions: ts6.CompilerOptions) => DepsFiles;
|
|
45
|
+
name?: string;
|
|
46
|
+
};
|
|
47
|
+
type SuseePluginFunction = (...args: any[]) => DependencyPlugin | PostProcessPlugin | PreProcessPlugin;
|
|
48
|
+
type SuseePlugin = DependencyPlugin | PostProcessPlugin | PreProcessPlugin;
|
|
49
|
+
declare function bundle(entry: string): unknown;
|
|
2
50
|
type OutputFormat = ("commonjs" | "esm")[];
|
|
3
51
|
interface EntryPoint {
|
|
4
52
|
/**
|
|
@@ -33,14 +81,9 @@ interface EntryPoint {
|
|
|
33
81
|
* 3. default compiler options of susee
|
|
34
82
|
*
|
|
35
83
|
* default - undefined
|
|
36
|
-
*/
|
|
37
|
-
tsconfigFilePath?: string | undefined;
|
|
38
|
-
/**
|
|
39
|
-
* When bundling , if there are duplicate declared names , susee will auto rename , if renameDuplicates = false exist with code 1.
|
|
40
84
|
*
|
|
41
|
-
* default - true
|
|
42
85
|
*/
|
|
43
|
-
|
|
86
|
+
tsconfigFilePath?: string | undefined;
|
|
44
87
|
/**
|
|
45
88
|
* Array of susee plugins
|
|
46
89
|
*
|
|
@@ -79,6 +122,7 @@ interface SuSeeConfig {
|
|
|
79
122
|
*/
|
|
80
123
|
allowUpdatePackageJson?: boolean;
|
|
81
124
|
}
|
|
125
|
+
declare function suseeCliBuild(): any;
|
|
82
126
|
/**
|
|
83
127
|
* Run a Susee build.
|
|
84
128
|
*
|
|
@@ -90,5 +134,5 @@ interface SuSeeConfig {
|
|
|
90
134
|
*/
|
|
91
135
|
declare function build(options?: SuSeeConfig): any;
|
|
92
136
|
export type { SuSeeConfig };
|
|
93
|
-
export { build };
|
|
137
|
+
export { build, bundle as suseeBundler, suseeCliBuild };
|
|
94
138
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,52 @@
|
|
|
1
|
-
import
|
|
1
|
+
import ts6 from "@suseejs/ts6";
|
|
2
|
+
import type { DepsFile, SuseePlugin, SuseePluginFunction, ValidExts } from "@suseejs/type";
|
|
3
|
+
type ValidExts = ".js" | ".cjs" | ".mjs" | ".ts" | ".cts" | ".mts" | ".tsx" | ".jsx" | ".json";
|
|
4
|
+
interface DepsFile {
|
|
5
|
+
file: string;
|
|
6
|
+
content: string;
|
|
7
|
+
bytes: number;
|
|
8
|
+
moduleType: "cjs" | "esm" | "json";
|
|
9
|
+
fileExt: ValidExts;
|
|
10
|
+
is_jsx: boolean;
|
|
11
|
+
is_entry: boolean;
|
|
12
|
+
}
|
|
13
|
+
type DepsFiles = DepsFile[];
|
|
14
|
+
type PostProcessPlugin = {
|
|
15
|
+
type: "post-process";
|
|
16
|
+
async: true;
|
|
17
|
+
func: (code: string, file?: string) => Promise<string>;
|
|
18
|
+
name?: string;
|
|
19
|
+
} | {
|
|
20
|
+
type: "post-process";
|
|
21
|
+
async: false;
|
|
22
|
+
func: (code: string, file?: string) => string;
|
|
23
|
+
name?: string;
|
|
24
|
+
};
|
|
25
|
+
type PreProcessPlugin = {
|
|
26
|
+
type: "pre-process";
|
|
27
|
+
async: true;
|
|
28
|
+
func: (code: string, file?: string) => Promise<string>;
|
|
29
|
+
name?: string;
|
|
30
|
+
} | {
|
|
31
|
+
type: "pre-process";
|
|
32
|
+
async: false;
|
|
33
|
+
func: (code: string, file?: string) => string;
|
|
34
|
+
name?: string;
|
|
35
|
+
};
|
|
36
|
+
type DependencyPlugin = {
|
|
37
|
+
type: "dependency";
|
|
38
|
+
async: true;
|
|
39
|
+
func: (depsFiles: DepsFiles, compilerOptions: ts6.CompilerOptions) => Promise<DepsFiles>;
|
|
40
|
+
name?: string;
|
|
41
|
+
} | {
|
|
42
|
+
type: "dependency";
|
|
43
|
+
async: false;
|
|
44
|
+
func: (DepsFiles: DepsFiles, compilerOptions: ts6.CompilerOptions) => DepsFiles;
|
|
45
|
+
name?: string;
|
|
46
|
+
};
|
|
47
|
+
type SuseePluginFunction = (...args: any[]) => DependencyPlugin | PostProcessPlugin | PreProcessPlugin;
|
|
48
|
+
type SuseePlugin = DependencyPlugin | PostProcessPlugin | PreProcessPlugin;
|
|
49
|
+
declare function bundle(entry: string): unknown;
|
|
2
50
|
type OutputFormat = ("commonjs" | "esm")[];
|
|
3
51
|
interface EntryPoint {
|
|
4
52
|
/**
|
|
@@ -33,14 +81,9 @@ interface EntryPoint {
|
|
|
33
81
|
* 3. default compiler options of susee
|
|
34
82
|
*
|
|
35
83
|
* default - undefined
|
|
36
|
-
*/
|
|
37
|
-
tsconfigFilePath?: string | undefined;
|
|
38
|
-
/**
|
|
39
|
-
* When bundling , if there are duplicate declared names , susee will auto rename , if renameDuplicates = false exist with code 1.
|
|
40
84
|
*
|
|
41
|
-
* default - true
|
|
42
85
|
*/
|
|
43
|
-
|
|
86
|
+
tsconfigFilePath?: string | undefined;
|
|
44
87
|
/**
|
|
45
88
|
* Array of susee plugins
|
|
46
89
|
*
|
|
@@ -79,6 +122,7 @@ interface SuSeeConfig {
|
|
|
79
122
|
*/
|
|
80
123
|
allowUpdatePackageJson?: boolean;
|
|
81
124
|
}
|
|
125
|
+
declare function suseeCliBuild(): any;
|
|
82
126
|
/**
|
|
83
127
|
* Run a Susee build.
|
|
84
128
|
*
|
|
@@ -90,5 +134,5 @@ interface SuSeeConfig {
|
|
|
90
134
|
*/
|
|
91
135
|
declare function build(options?: SuSeeConfig): any;
|
|
92
136
|
export type { SuSeeConfig };
|
|
93
|
-
export { build };
|
|
137
|
+
export { build, bundle as suseeBundler, suseeCliBuild };
|
|
94
138
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.mjs
CHANGED
|
@@ -5,4 +5,4 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
|
5
5
|
this file except in compliance with the License. You may obtain a copy of the
|
|
6
6
|
License at http://www.apache.org/licenses/LICENSE-2.0
|
|
7
7
|
***************************************************************************** */
|
|
8
|
-
import tcolor from"@suseejs/color";import ts from"typescript";import{bundler}from"@suseejs/bundler";import{files}from"@suseejs/files";import{getCompilerOptions}from"@suseejs/tsoptions";import{suseeCompiler}from"@suseejs/compiler";import{utils}from"@suseejs/utilities";const getConfigPath=()=>{const e=["susee.config.ts","susee.config.js","susee.config.mjs"];let t;for(const s of e){const e=ts.sys.resolvePath(s);if(ts.sys.fileExists(e)){t=e;break}}return t};function checkEntries(e){e.length<1&&(console.error(tcolor.magenta("No entry found in susee.config file or build options, at least one entry required")),ts.sys.exit(1));const t={},s=[];for(const i of e){const e=i.exportPath;t[e]?s.push(`"${e}"`):t[e]=!0}s.length>0&&(console.error(tcolor.magenta(`Duplicate export paths/path (${s.join(",")}) found in your susee.config file or build options , that will error for bundled output`)),ts.sys.exit(1));for(const t of e)ts.sys.fileExists(ts.sys.resolvePath(t.entry))||(console.error(tcolor.magenta(`Entry file ${t.entry} dose not exists.`)),ts.sys.exit(1))}function generateBuildOptions(e){const t=e.outDir??"dist",s=[];checkEntries(e.entryPoints);for(const i of e.entryPoints){const e=i.entry,o=i.exportPath,n=i.tsconfigFilePath??void 0,r=i.format?[...new Set(i.format)]:["esm"],a=i.warning??!1,l=i.renameDuplicates??!0,c=i.plugins??[],f="."===i.exportPath?t:`${t}${i.exportPath.slice(1)}`;s.push({entry:e,exportPath:o,format:r,tsconfigFilePath:n,rename:l,plugins:c,warning:a,outputDirectoryPath:f})}return{buildEntryPoints:s,updatePackage:e.allowUpdatePackageJson??!1,outDir:t}}async function finalSuseeConfig(){const e=getConfigPath();if(e){return generateBuildOptions((await import(e)).default)}}class Compiler{_files;_object;constructor(e){this._object=e,this._files={commonjs:void 0,commonjsTypes:void 0,esm:void 0,esmTypes:void 0,main:void 0,module:void 0,types:void 0}}_update(){return this._object.updatePackage}async _commonjs(e){const t="."===e.exportPath,s=getCompilerOptions(e.tsconfigFilePath).commonjs(e.outputDirectoryPath),i=await bundler(e.entry,e.plugins,e.warning,e.rename),o=utils.checks.isJsxContent(i),n=suseeCompiler({sourceCode:i,fileName:e.entry,compilerOptions:s,isJsx:o});let r=n.code;const a=files.joinPath(n.out_dir,`${n.file_name}.cjs`),l=files.joinPath(n.out_dir,`${n.file_name}.d.cts`),c=files.joinPath(n.out_dir,`${n.file_name}.cjs.map`);if(r=r.replace(new RegExp(`${n.file_name}.js.map`,"gm"),`${n.file_name}.cjs.map`),e.plugins.length>0)for(const t of e.plugins){const s="function"==typeof t?t():t;"post-process"===s.type&&(r=s.async?await s.func(r,e.entry):s.func(r,e.entry))}this._update()&&(this._files.commonjs=a,n.dts&&(this._files.commonjsTypes=l),t&&e.format.includes("commonjs")&&(this._files.commonjs&&(this._files.main=this._files.commonjs),this._files.commonjsTypes&&(this._files.types=this._files.commonjsTypes))),await files.writeFile(a,r),n.dts&&await files.writeFile(l,n.dts),n.map&&await files.writeFile(c,n.map)}async _esm(e){const t="."===e.exportPath,s=getCompilerOptions(e.tsconfigFilePath).esm(e.outputDirectoryPath),i=await bundler(e.entry,e.plugins,e.warning,e.rename),o=utils.checks.isJsxContent(i),n=suseeCompiler({sourceCode:i,fileName:e.entry,compilerOptions:s,isJsx:o});let r=n.code;const a=files.joinPath(n.out_dir,`${n.file_name}.mjs`),l=files.joinPath(n.out_dir,`${n.file_name}.d.mts`),c=files.joinPath(n.out_dir,`${n.file_name}.mjs.map`);if(r=r.replace(new RegExp(`${n.file_name}.js.map`,"gm"),`${n.file_name}.mjs.map`),e.plugins.length>0)for(const t of e.plugins){const s="function"==typeof t?t():t;"post-process"===s.type&&(r=s.async?await s.func(r,e.entry):s.func(r,e.entry))}this._update()&&(this._files.esm=a,n.dts&&(this._files.esmTypes=l),t&&this._files.esm&&(this._files.module=this._files.esm)),await files.writeFile(a,r),n.dts&&await files.writeFile(l,n.dts),n.map&&await files.writeFile(c,n.map)}async compile(){await files.clearFolder(this._object.outDir);for(const e of this._object.buildEntryPoints)for(const t of e.format)switch(t){case"commonjs":await this._commonjs(e),this._update()&&files.writePackageJson(this._files,e.exportPath);break;case"esm":await this._esm(e),this._update()&&files.writePackageJson(this._files,e.exportPath)}}}async function build(e){console.time(tcolor.cyan("[Build] "));let t={};const s=await finalSuseeConfig();e||s||(console.error(`${tcolor.magenta("[Error]")} : Required build options or susee config file at root.\n Use ${tcolor.bold("npx susee init")} to create config file.`),process.exit(1)),e?t=generateBuildOptions(e):s&&(t=s);const i=new Compiler(t);await i.compile(),console.timeEnd(tcolor.cyan("[Build] "))}export{build};
|
|
8
|
+
import fs from"node:fs";import module from"node:module";import path from"node:path";import process from"node:process";import readline from"node:readline/promises";import tcolor from"@suseejs/color";import ts6 from"@suseejs/ts6";import{suseeTerser}from"@suseejs/terser-plugin";var files,utils;!function(e){const t=process.cwd();function s(e){return path.resolve(t,e)}function i(e){return fs.existsSync(s(e))}async function n(e){i(e)&&await fs.promises.unlink(e)}async function o(e){i(e)||(console.error(tcolor.magenta(`> ${e} does not exists `)),process.exit(1)),e=s(e);const t=await fs.promises.readFile(e);return{str:t.toString("utf8"),bytes:t.byteLength}}async function r(e){const t=await o(e);return JSON.parse(t.str)}async function a(e){i(e=s(e))||await fs.promises.mkdir(e,{recursive:!0})}function l(e){return path.dirname(s(e))}async function c(e,t){i(e)&&await n(e),await a(l(e)),e=s(e),await fs.promises.writeFile(e,t)}e.resolvePath=s,e.relativePath=function(e){return path.relative(t,e)},e.joinPath=function(...e){return path.join(...e)},e.existsPath=i,e.deleteFile=n,e.readFile=o,e.readJsonFile=r,e.createDirectory=a,e.parentPath=l,e.writeFile=c,e.clearFolder=async function(e){e=s(e);try{const t=await fs.promises.readdir(e,{withFileTypes:!0});await Promise.all(t.map(t=>fs.promises.rm(path.join(e,t.name),{recursive:!0})))}catch(e){if("ENOENT"!==e.code)throw e}};const p=e=>e.commonjs&&e.commonjsTypes,m=e=>e.esm&&e.esmTypes;function u(e,t){return p(e)&&m(e)?{[t]:{import:{types:`./${path.relative(process.cwd(),e.esmTypes)}`,default:`./${path.relative(process.cwd(),e.esm)}`},require:{types:`./${path.relative(process.cwd(),e.commonjsTypes)}`,default:`./${path.relative(process.cwd(),e.commonjs)}`}}}:p(e)&&!m(e)?{[t]:{require:{types:`./${path.relative(process.cwd(),e.commonjsTypes)}`,default:`./${path.relative(process.cwd(),e.commonjs)}`}}}:!p(e)&&m(e)?{[t]:{import:{types:`./${path.relative(process.cwd(),e.esmTypes)}`,default:`./${path.relative(process.cwd(),e.esm)}`}}}:{}}e.writePackageJson=async function(e,t){let i=!0;"."!==t&&(i=!1);const n=s("package.json"),o=await r(n);let{name:a,version:l,description:p,main:m,module:f,type:d,types:h,exports:g,...y}=o;d="module";let x={},w={},E={},b={};if(i)x=e.main?{main:path.relative(process.cwd(),e.main)}:{},w=e.module?{module:path.relative(process.cwd(),e.module)}:{},E=e.types?{types:path.relative(process.cwd(),e.types)}:{},b={exports:{...u(e,t)}};else{x=m?{main:m}:{},w=f?{module:f}:{},E=h?{types:h}:{};b={exports:{...g&&"object"==typeof g&&!Array.isArray(g)?{...g}:{},...u(e,t)}}}const j={name:a,version:l,description:p,type:d,...x,...E,...w,...b,...y};await c(n,JSON.stringify(j,null,2))}}(files||(files={})),function(e){let t,s,i;!function(e){e.moduleType=(e,t)=>{let s=0,i=0,n=0;const o=ts6.createSourceFile(t,e,ts6.ScriptTarget.Latest,!0);try{let e=!1,t=!1;!function s(i){if((ts6.isImportDeclaration(i)||ts6.isImportEqualsDeclaration(i)||ts6.isExportDeclaration(i)||ts6.isExportSpecifier(i)||ts6.isExportAssignment(i))&&(e=!0),(ts6.isVariableStatement(i)||ts6.isFunctionDeclaration(i)||ts6.isInterfaceDeclaration(i)||ts6.isTypeAliasDeclaration(i)||ts6.isEnumDeclaration(i)||ts6.isClassDeclaration(i))&&i.modifiers?.some(e=>e.kind===ts6.SyntaxKind.ExportKeyword)&&(e=!0),ts6.isCallExpression(i)&&ts6.isIdentifier(i.expression)&&"require"===i.expression.text&&i.arguments.length>0&&(t=!0),ts6.isPropertyAccessExpression(i)){const e=i.getText(o);(e.startsWith("module.exports")||e.startsWith("exports."))&&(t=!0)}ts6.forEachChild(i,s)}(o),e&&!t?s++:t&&!e?i++:e&&t&&s++}catch(e){console.error(tcolor.magenta(`Error checking module format for ${t} : \n ${e}`)),n++}return n>0&&(console.error(tcolor.magenta("Error checking module format.")),ts6.sys.exit(1)),{isCommonJs:i>0,isEsm:s>0}},e.isJsxContent=function(e){const t=ts6.createSourceFile("file.tsx",e,ts6.ScriptTarget.Latest,!0,ts6.ScriptKind.TSX);let s=!1;return function e(t){ts6.isJsxElement(t)||ts6.isJsxSelfClosingElement(t)||ts6.isJsxFragment(t)?s=!0:ts6.forEachChild(t,e)}(t),s},e.isInsideNamespace=e=>{let t=e.parent;for(;t;){if(ts6.isModuleDeclaration(t)&&t.flags===ts6.NodeFlags.Namespace)return!0;t=t.parent}return!1},e.isNodeBuiltinModule=e=>{const t=new Set(module.builtinModules);return e.startsWith("node:")||t.has(e)}}(t=e.checks||(e.checks={})),function(e){function t(e){const t=e[0],s=e.slice(1);return i=t,"[object AsyncFunction]"===Object.prototype.toString.call(i)||"AsyncFunction"===i.constructor.name?async()=>await t(...s):async()=>t(...s);var i}e.resolve=function(e){const s=e.map(e=>t(e));return{series:async()=>{const e=[];for(const[t,i]of s.entries())try{const t=await i();e.push(t)}catch(e){throw console.error(`Error in task ${t+1}`),e}return e},concurrent:async()=>{try{return await Promise.all(s.map(e=>e()))}catch(e){throw console.error("One of the functions rejected:",e),e}},allSettled:async()=>{try{const e=await Promise.allSettled(s.map(e=>e())),t=e.filter(e=>"fulfilled"===e.status),i=e.filter(e=>"rejected"===e.status);return i.length>0&&(console.warn("One of the functions rejected:",i[0]?.reason),process.exit(1)),t.map(e=>e.value)}catch(e){throw console.error("One of the functions rejected:",e),e}}}},e.run=async function(e,t,...s){return new Promise((i,n)=>{try{const n=t?0:t,o=e(...s);setTimeout(()=>i(o),n)}catch(e){n(e)}})}}(s=e.promises||(e.promises={})),function(e){e.mergeStringArr=e=>e.reduce((e,t)=>e.concat(t),[]),e.splitCamelCase=function(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/(_|-|\/)([a-z] || [A-Z])/g," ").replace(/([A-Z])/g,e=>e.toLowerCase()).replace(/^([a-z])/,e=>e.toUpperCase())},e.packageJson=function(){const e=fs.readFileSync(path.resolve(process.cwd(),"package.json"),"utf8"),t=JSON.parse(e),s=t.name??"",i=t.version??"";return{pkgNameVersion:()=>{let e="";return e=""!==s&&""!==i?`${s}@${i}`:""!==s&&""===i?`${s}`:""===s&&""!==i?`the project@${i}`:"the project",e},dependencies:()=>[...Object.keys(t.dependencies??{}),...Object.keys(t.devDependencies??{})]}},e.mergeImportsStatement=function(e){const t=new Map,s=new Map,i=new Map,n=new Map,o=new Map;for(const r of e){const e=r.match(/import\s+(?:type\s+)?(?:(.*?)\s+from\s+)?["']([^"']+)["'];?/);if(!e)continue;const[,a,l]=e,c=r.includes("import type"),p=l;if(!a){const e=r.match(/import\s+(?:type\s+)?(\w+)/);if(e){const t=e[1],s=c?n:i;s.has(p)||s.set(p,new Set),s.get(p)?.add(t)}continue}if(a.startsWith("{")){const e=c?s:t;e.has(p)||e.set(p,new Set);a.replace(/[{}]/g,"").split(",").map(e=>e.trim()).filter(Boolean).forEach(t=>e.get(p)?.add(t))}else if(a.startsWith("* as")){const e=a.match(/\*\s+as\s+(\w+)/);if(e){const t=e[1];o.has(p)||o.set(p,new Set),o.get(p)?.add(t)}}else{const e=c?n:i;e.has(p)||e.set(p,new Set),e.get(p)?.add(a.trim())}}const r=[];for(const[e,i]of t){const t=s.get(e)||new Set,n=new Set([...i]);for(const e of t)i.has(e)||n.add(e);if(n.size>0){const t=Array.from(n).sort().join(", ");r.push(`import { ${t} } from "${e}";`)}}for(const[e,i]of s)if(!t.has(e)&&i.size>0){const t=Array.from(i).sort().join(", ");r.push(`import type { ${t} } from "${e}";`)}for(const[e,t]of i){const s=n.get(e)||new Set,i=new Set([...t]);for(const e of s)t.has(e)||i.add(e);if(i.size>0){const t=Array.from(i).join(", ");r.push(`import ${t} from "${e}";`)}}for(const[e,t]of n)if(!i.has(e)&&t.size>0){const s=Array.from(t).join(", ");r.push(`import type ${s} from "${e}";`)}for(const[e,t]of o)if(t.size>0){const s=Array.from(t).join(", ");r.push(`import * as ${s} from "${e}";`)}return r.sort()},e.transformFunction=function(e,t,s){const i=ts6.transform(t,[e],s),n=i.transformed[0],o=ts6.createPrinter({newLine:ts6.NewLineKind.LineFeed,removeComments:!1}).printFile(n);return i.dispose(),o},e.findProperty=function(e){const t=[];return function e(s){ts6.isPropertyAccessExpression(s)&&ts6.isIdentifier(s.expression)&&t.push(s.expression.text),s.forEachChild(e)}(e),t}}(i=e.gen||(e.gen={}))}(utils||(utils={}));const duplicateNameMap=new Map,collectDuplicateDeclarations=(e,t)=>{const s=(e,t,i=!0)=>{if(i)if(ts6.isVariableStatement(t))t.declarationList.declarations.forEach(t=>{if(ts6.isIdentifier(t.name)){const s=t.name.text;duplicateNameMap.has(s)?duplicateNameMap.get(s)?.add({file:e}):duplicateNameMap.set(s,new Set([{file:e}]))}});else if(ts6.isFunctionDeclaration(t)||ts6.isClassDeclaration(t)||ts6.isEnumDeclaration(t)||ts6.isInterfaceDeclaration(t)||ts6.isTypeAliasDeclaration(t)){const s=t.name?.text;s&&(duplicateNameMap.has(s)?duplicateNameMap.get(s)?.add({file:e}):duplicateNameMap.set(s,new Set([{file:e}])))}ts6.isBlock(t)||ts6.isFunctionDeclaration(t)||ts6.isFunctionExpression(t)||ts6.isArrowFunction(t)||ts6.isMethodDeclaration(t)||ts6.isClassDeclaration(t)?ts6.isBlock(t)?t.statements.forEach(t=>s(e,t,!1)):ts6.forEachChild(t,t=>{s(e,t,!1)}):ts6.forEachChild(t,t=>{s(e,t,i)})};for(const i of e){const e=t(i.file,i.content);s(i.file,e,!0)}},checkDuplicates=(e,t)=>{let s=!1;return collectDuplicateDeclarations(e.depFiles,t),duplicateNameMap.forEach((e,t)=>{e.size>1&&(s=!0,console.warn(`Name -> ${t} declared in multiple files : `),e.forEach(e=>console.warn(` - ${e.file}`)))}),s&&process.exit(1),e};function handleImports(e,t){if(ts6.isImportDeclaration(e)&&e.moduleSpecifier){const s=e.moduleSpecifier.getText().replace(/^['"`]|['"`]$/g,"");return void t(s)}ts6.forEachChild(e,e=>handleImports(e,t))}function handleImportEqual(e,t){if(ts6.isImportEqualsDeclaration(e)&&ts6.isExternalModuleReference(e.moduleReference)&&ts6.isStringLiteral(e.moduleReference.expression)){const s=e.moduleReference.expression.text;return void t(s)}ts6.forEachChild(e,e=>handleImportEqual(e,t))}function handleAwaitImport(e,t){if(ts6.isAwaitExpression(e)&&ts6.isCallExpression(e.expression)&&e.expression.expression.kind===ts6.SyntaxKind.ImportKeyword){const s=e.expression.arguments[0];return void(s&&ts6.isStringLiteral(s)&&t(s.text))}ts6.forEachChild(e,e=>handleAwaitImport(e,t))}function handleRequire(e,t){if(ts6.isCallExpression(e)&&ts6.isIdentifier(e.expression)&&"require"===e.expression.text&&e.arguments.length>0){const s=e.arguments[0];return void(s&&ts6.isStringLiteral(s)&&t(s.text))}if(ts6.isPropertyAccessExpression(e)&&ts6.isCallExpression(e.expression)&&ts6.isIdentifier(e.expression.expression)&&"require"===e.expression.expression.text&&e.expression.arguments.length>0){const s=e.expression.arguments[0];return void(s&&ts6.isStringLiteral(s)&&t(s.text))}ts6.forEachChild(e,e=>handleRequire(e,t))}function handlers(e,t){Promise.all([handleImports(e,t),handleRequire(e,t),handleImportEqual(e,t),handleAwaitImport(e,t)])}const allowedExtensions=new Set(["js","cjs","mjs","ts","mts","cts","jsx","tsx","json"]);function isDir(e){try{return fs.lstatSync(e).isDirectory()}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}function getFileName(e){const t=path.basename(e).split(".")[0];return t?t.trim():""}function getExtensionName(e){return path.basename(e).split(".")[1]?.trim()||""}function resolveExtension(e){let t,s,i=!1;if(isDir(e)){const n=fs.readdirSync(e).find(e=>"index"===getFileName(e)&&allowedExtensions.has(getExtensionName(e)));n?(t=path.join(e,n),s=getExtensionName(n),i=!0):(console.error(`${e} is a directory and no index file with JS/TS extension found.`),process.exit(1))}else{const n=path.dirname(e),o=path.basename(e),[r,a=""]=o.split("."),l=ts6.sys.readDirectory(n).map(e=>{const[t,s=""]=path.basename(e).split(".");return{name:t,ext:s}}).find(e=>e.name===r&&allowedExtensions.has(e.ext));if(l)if(a)if(a===l.ext)t=e,s=l.ext;else{const i=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=e.replace(new RegExp(`\\.${i}$`),`.${l.ext}`),s=l.ext}else t=`${e}.${l.ext}`,s=l.ext;else if(isDir(e)){const n=fs.readdirSync(e).find(e=>"index"===getFileName(e)&&allowedExtensions.has(getExtensionName(e)));n&&(t=path.join(e,n),s=getExtensionName(n),i=!0)}}return t&&s||(console.error(`When checking ${e}, it's not a file or file with unsupported extension`),process.exit(1)),{result:t,ext:s,isDirPath:i}}function collectDependencies(e,t,s){const i=[],n=new Set,o=[],r=[],a=[];return function e(l,c){const p=path.resolve(s,l);if(n.has(p))return;n.add(p);const{result:m}=resolveExtension(p);fs.existsSync(m)||(i.push({file:p,index:c,importFiles:[]}),a.push([`File not found: ${m}`]));const u=fs.readFileSync(m,"utf8"),f=ts6.createSourceFile(l,u,ts6.ScriptTarget.Latest,!0),d=[],h=[],g=[],y=[];function x(e){if(e.startsWith(".")||e.startsWith("..")){const t=path.resolve(path.dirname(m),e);let i={};try{i=resolveExtension(t)}catch{i={result:t,ext:path.extname(t).slice(1),isDirPath:!1}}const n=path.relative(s,i.result);d.push(n)}else module.builtinModules.includes(e)?y.push(e):t.includes(e)?g.push(e):h.push(e)}ts6.forEachChild(f,e=>handlers(e,x)),i.push({file:p,index:c,importFiles:d}),o.push(g),r.push(y),a.push(h),d.forEach(t=>e(t,i.length))}(e,0),{dependencies:i,collectedNodeModules:r,collectedNpmModules:o,collectedWarning:a}}function getPackageJson(){const e=fs.readFileSync(path.resolve(process.cwd(),"package.json"),"utf8"),t=JSON.parse(e);return[...Object.keys(t.dependencies??{}),...Object.keys(t.devDependencies??{})]}function topoSort(e){const t=new Set,s=[];return Object.keys(e).forEach(function i(n){t.has(n)||(t.add(n),(e[n]||[]).forEach(i),s.push(n))}),s}const createGraph=e=>{const t={};for(const s of e){t[path.relative(process.cwd(),s.file)]=s.importFiles}return t};function generateGraph(e){const t=process.cwd(),s=collectDependencies(e,getPackageJson(),t),i=s.dependencies,n=utils.gen.mergeStringArr(s.collectedNpmModules),o=utils.gen.mergeStringArr(s.collectedNodeModules),r=utils.gen.mergeStringArr(s.collectedWarning),a=createGraph(i),l=topoSort(a);return{sort:()=>l,npm:()=>n,node:()=>o,deps:()=>a,warn:()=>r}}async function generateDependencies(e,t){const s=generateGraph(e),i=s.sort(),n={entry:e,npm:s.npm(),nodes:s.node(),warns:s.warn(),depFiles:[]},o=path.basename(e);for(const e of i){const t=path.basename(e),s=path.extname(e),i=await files.readFile(e),r=i.str,a=i.bytes,l=utils.checks.moduleType(r,e),c=".json"===s?"json":l.isCommonJs?"cjs":"esm",p=utils.checks.isJsxContent(r),m=o===t;n.depFiles.push({file:e,content:r,bytes:a,moduleType:c,fileExt:s,is_jsx:p,is_entry:m})}return checkDuplicates(n,t)}const profileEnvName="SUSEE_PROFILE",isProfileEnabled=()=>{const e=process.env[profileEnvName];return"1"===e||"true"===e},setProfileEnabled=e=>{e?process.env[profileEnvName]="1":delete process.env[profileEnvName]},formatProfileMs=e=>`${(Number(process.hrtime.bigint()-e)/1e6).toFixed(1)}ms`,logProfilePhase=(e,t,s)=>{isProfileEnabled()&&console.log(`[SUSEE_PROFILE][${e}] ${t}: ${formatProfileMs(s)}`)},isJSON=e=>!!e.depFiles.find(e=>".json"===e.fileExt&&"json"===e.moduleType),jsonExtToTs=e=>".json"===path.extname(e)?e.replace(/.json/g,".ts"):e,createBundledSourceFile=(e,t)=>ts6.createSourceFile(jsonExtToTs(e),t,ts6.ScriptTarget.Latest,!0),transformBundledSource=(e,t,s)=>utils.gen.transformFunction(s,e,t),normalizePathKey=e=>{const t=path.parse(e);let s=path.join(t.dir,t.name);return"index"===t.name&&(s=t.dir),path.normalize(s)},getFileKey=e=>normalizePathKey(e),getModuleKeyFromSpecifier=(e,t,s)=>{let i="";if(i=ts6.isStringLiteral(e)?e.text:e.getText(t).replace(/^['"]|['"]$/g,""),i.startsWith(".")||i.startsWith("/")){const e=path.dirname(s),t=path.isAbsolute(s)?path.resolve(e,i):path.normalize(path.join(e,i));return normalizePathKey(t)}return i};class UniqueName{_storedPrefix;constructor(){this._storedPrefix=new Map}setPrefix({key:e,value:t}){if(this._storedPrefix.has(e)){const[s,i]=this._storedPrefix.get(e);this._storedPrefix.set(e,[t,i+1])}else this._storedPrefix.set(e,[t,0]);return this}getName(e,t){const[s,i]=this._storedPrefix.get(e)||[],n=s?`${s}${t}_${(i??0)+1}`:`__susee__${t}_${(i??0)+1}`;return this._storedPrefix.set(e,[s??"__susee__",(i??0)+1]),n}getPrefix(e){const[t]=this._storedPrefix.get(e)||[];return t}}const uniqueName=new UniqueName,anonymousExportNameMap=[],anonymousImportNameMap=[],anonymousPrefixKey="AnonymousName",createAnonymousNameGenerator=()=>uniqueName.setPrefix({key:"AnonymousName",value:"__anonymous__"});let anonymousName=createAnonymousNameGenerator();function anonymousCallExpressionHandler(e){return({file:t,content:s,...i})=>{const n=createBundledSourceFile(t,s),o=transformBundledSource(n,e,e=>{const{factory:s}=e;function i(n){if(ts6.isCallExpression(n)){if(ts6.isIdentifier(n.expression)){const e=n.expression.text,i=anonymousImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateCallExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts6.isPropertyAccessExpression(n)){if(ts6.isIdentifier(n.expression)){const e=n.expression.text,i=anonymousImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updatePropertyAccessExpression(n,s.createIdentifier(i.newName),n.name)}}else if(ts6.isNewExpression(n)){if(ts6.isIdentifier(n.expression)){const e=n.expression.text,i=anonymousImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateNewExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts6.isExportSpecifier(n)&&ts6.isIdentifier(n.name)){const e=n.name.text,i=anonymousImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateExportSpecifier(n,n.isTypeOnly,n.propertyName,s.createIdentifier(i.newName))}return ts6.visitEachChild(n,i,e)}return e=>ts6.visitNode(e,i)});return{file:t,content:o,...i}}}function anonymousExportHandler(e){return({file:t,content:s,...i})=>{const n=createBundledSourceFile(t,s),o=transformBundledSource(n,e,e=>{const{factory:s}=e;function i(o){const r=path.basename(t).split(".")[0];if((ts6.isFunctionDeclaration(o)||ts6.isClassDeclaration(o))&&void 0===o.name){let e=!1,t=!1;if(o.modifiers?.forEach(s=>{s.kind===ts6.SyntaxKind.ExportKeyword&&(e=!0),s.kind===ts6.SyntaxKind.DefaultKeyword&&(t=!0)}),e&&t){const e=anonymousName.getName("AnonymousName",r);if(anonymousExportNameMap.push({base:e,file:r,newName:e,isEd:!0}),ts6.isFunctionDeclaration(o))return s.updateFunctionDeclaration(o,o.modifiers,o.asteriskToken,s.createIdentifier(e),o.typeParameters,o.parameters,o.type,o.body);if(ts6.isClassDeclaration(o))return s.updateClassDeclaration(o,o.modifiers,s.createIdentifier(e),o.typeParameters,o.heritageClauses,o.members)}}else if(ts6.isExportAssignment(o)&&!o.isExportEquals&&void 0===o.name){if(ts6.isArrowFunction(o.expression)){const e=anonymousName.getName("AnonymousName",r),t=s.createArrowFunction(o.expression.modifiers,o.expression.typeParameters,o.expression.parameters,o.expression.type,o.expression.equalsGreaterThanToken,o.expression.body),i=s.createVariableDeclaration(s.createIdentifier(e),o.expression.exclamationToken,o.expression.type,t),a=s.createVariableDeclarationList([i],ts6.NodeFlags.Const),l=s.createVariableStatement(o.expression.modifiers,a),c=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return anonymousExportNameMap.push({base:e,file:r,newName:e,isEd:!0}),s.updateSourceFile(n,[l,c],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts6.isObjectLiteralExpression(o.expression)){const e=anonymousName.getName("AnonymousName",r),t=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,o.expression),i=s.createVariableDeclarationList([t],ts6.NodeFlags.Const),a=s.createVariableStatement(void 0,i),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return anonymousExportNameMap.push({base:e,file:r,newName:e,isEd:!0}),s.updateSourceFile(n,[a,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts6.isArrayLiteralExpression(o.expression)){const e=anonymousName.getName("AnonymousName",r),t=s.createArrayLiteralExpression(o.expression.elements,!0),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),a=s.createVariableDeclarationList([i],ts6.NodeFlags.Const),l=s.createVariableStatement(void 0,a),c=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return anonymousExportNameMap.push({base:e,file:r,newName:e,isEd:!0}),s.updateSourceFile(n,[l,c],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts6.isStringLiteral(o.expression)){const e=anonymousName.getName("AnonymousName",r),t=s.createStringLiteral(o.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),a=s.createVariableDeclarationList([i],ts6.NodeFlags.Const),l=s.createVariableStatement(void 0,a),c=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return anonymousExportNameMap.push({base:e,file:r,newName:e,isEd:!0}),s.updateSourceFile(n,[l,c],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts6.isNumericLiteral(o.expression)){const e=anonymousName.getName("AnonymousName",r),t=s.createNumericLiteral(o.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),a=s.createVariableDeclarationList([i],ts6.NodeFlags.Const),l=s.createVariableStatement(void 0,a),c=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return anonymousExportNameMap.push({base:e,file:r,newName:e,isEd:!0}),s.updateSourceFile(n,[l,c],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}}return ts6.visitEachChild(o,i,e)}return e=>ts6.visitNode(e,i)});return{file:t,content:o,...i}}}function anonymousImportHandler(e){return({file:t,content:s,...i})=>{const n=createBundledSourceFile(t,s),o=transformBundledSource(n,e,e=>{const{factory:s}=e;function i(o){if(ts6.isImportDeclaration(o)){const e=o.moduleSpecifier.getText(n),i=path.basename(e).split(".")[0].trim();if(o.importClause?.name&&ts6.isIdentifier(o.importClause.name)){const e=o.importClause.name.text.trim(),n=anonymousExportNameMap.find(e=>e.file===i);if(n){anonymousImportNameMap.push({base:e,file:t,newName:n.newName,isEd:!0});const i=s.updateImportClause(o.importClause,o.importClause.phaseModifier,s.createIdentifier(n.newName),o.importClause.namedBindings);return s.updateImportDeclaration(o,o.modifiers,i,o.moduleSpecifier,o.attributes)}}}return ts6.visitEachChild(o,i,e)}return e=>ts6.visitNode(e,i)});return{file:t,content:o,...i}}}function resetAnonymousState(){anonymousExportNameMap.length=0,anonymousImportNameMap.length=0,anonymousName=createAnonymousNameGenerator()}const anonymousHandler=async(e,t)=>{resetAnonymousState();const s=utils.promises.resolve([[anonymousExportHandler,t],[anonymousImportHandler,t],[anonymousCallExpressionHandler,t]]),i=await s.concurrent();for(const t of i)e=e.map(t);return e},exportDefaultExportNameMap=[],exportDefaultImportNameMap=[],exportDefaultPrefixKey="ExportDefault",createExportDefaultNameGenerator=()=>uniqueName.setPrefix({key:"ExportDefault",value:"__exportDefault__"});let exportDefaultName=createExportDefaultNameGenerator();const toNameLookupKey=(e,t)=>`${e}\0${t}`,createNameLookup=e=>{const t=new Map;for(const s of e)t.set(toNameLookupKey(s.file,s.base),s.newName);return t},getMappedName=(e,t,s)=>e.get(toNameLookupKey(t,s)),hasExportDefaultModifiers=e=>{let t=!1,s=!1;return e.modifiers?.forEach(e=>{e.kind===ts6.SyntaxKind.ExportKeyword&&(t=!0),e.kind===ts6.SyntaxKind.DefaultKeyword&&(s=!0)}),t&&s},collectExportDefaultMappings=e=>{for(const t of e){if(".json"===t.fileExt||t.is_entry)continue;const e=getFileKey(t.file),s=createBundledSourceFile(t.file,t.content);for(const t of s.statements){if((ts6.isFunctionDeclaration(t)||ts6.isClassDeclaration(t))&&t.name&&ts6.isIdentifier(t.name)&&hasExportDefaultModifiers(t)){const s=t.name.text,i=exportDefaultName.getName("ExportDefault",s);exportDefaultExportNameMap.push({base:s,file:e,newName:i,isEd:!0});break}if(ts6.isExportAssignment(t)&&!t.isExportEquals&&ts6.isIdentifier(t.expression)){const s=t.expression.text,i=exportDefaultName.getName("ExportDefault",s);exportDefaultExportNameMap.push({base:s,file:e,newName:i,isEd:!0});break}}}};function exportDefaultImportAndUsageHandler(e){return({file:t,content:s,fileExt:i,...n})=>{if(".json"===i)return{file:t,content:s,fileExt:i,...n};const o=createBundledSourceFile(t,s),r=transformBundledSource(o,e,e=>{const{factory:s}=e,i=createNameLookup(exportDefaultExportNameMap),n=new Map,r=e=>n.get(e);function a(l){if(ts6.isImportDeclaration(l)){const e=getModuleKeyFromSpecifier(l.moduleSpecifier,o,t);if(l.importClause?.name&&ts6.isIdentifier(l.importClause.name)){const o=l.importClause.name.text.trim(),r=getMappedName(i,e,o);if(r){n.set(o,r),exportDefaultImportNameMap.push({base:o,file:t,newName:r,isEd:!0});const e=s.updateImportClause(l.importClause,l.importClause.phaseModifier,s.createIdentifier(r),l.importClause.namedBindings);return s.updateImportDeclaration(l,l.modifiers,e,l.moduleSpecifier,l.attributes)}}}if(ts6.isCallExpression(l)){if(ts6.isIdentifier(l.expression)){const e=r(l.expression.text);if(e)return s.updateCallExpression(l,s.createIdentifier(e),l.typeArguments,l.arguments)}}else if(ts6.isPropertyAccessExpression(l)){if(ts6.isIdentifier(l.expression)){const e=r(l.expression.text);if(e)return s.updatePropertyAccessExpression(l,s.createIdentifier(e),l.name)}}else if(ts6.isNewExpression(l)){if(ts6.isIdentifier(l.expression)){const e=r(l.expression.text);if(e)return s.updateNewExpression(l,s.createIdentifier(e),l.typeArguments,l.arguments)}}else if(ts6.isExportSpecifier(l)){if(ts6.isIdentifier(l.name)){const e=r(l.name.text);if(e)return s.updateExportSpecifier(l,l.isTypeOnly,l.propertyName,s.createIdentifier(e))}}else if(ts6.isIdentifier(l)&&!(e=>{const t=e.parent;return!(!(ts6.isVariableDeclaration(t)||ts6.isFunctionDeclaration(t)||ts6.isClassDeclaration(t)||ts6.isParameter(t)||ts6.isTypeAliasDeclaration(t)||ts6.isInterfaceDeclaration(t)||ts6.isEnumDeclaration(t)||ts6.isImportClause(t)||ts6.isNamespaceImport(t)||ts6.isImportSpecifier(t)||ts6.isExportSpecifier(t)||ts6.isTypeParameterDeclaration(t))||t.name!==e)||!(!ts6.isPropertyDeclaration(t)&&!ts6.isMethodDeclaration(t)||t.name!==e)})(l)){if(ts6.isPropertyAccessExpression(l.parent)&&l.parent.name===l)return l;if(ts6.isPropertyAssignment(l.parent)&&l.parent.name===l)return l;const e=r(l.text);if(e)return ts6.isShorthandPropertyAssignment(l.parent)&&l.parent.name===l?s.createPropertyAssignment(s.createIdentifier(l.text),s.createIdentifier(e)):s.createIdentifier(e)}return ts6.visitEachChild(l,a,e)}return e=>ts6.visitNode(e,a)});return{file:t,content:r,fileExt:i,...n}}}function exportDefaultLocalHandler(e){return({file:t,content:s,fileExt:i,is_entry:n,...o})=>{if(".json"===i)return{file:t,content:s,fileExt:i,is_entry:n,...o};const r=getFileKey(t),a=exportDefaultExportNameMap.find(e=>e.file===r);if(n||!a)return{file:t,content:s,fileExt:i,is_entry:n,...o};const l=createBundledSourceFile(t,s);return{file:t,content:transformBundledSource(l,e,e=>{const{factory:t}=e,{base:s,newName:i}=a;function n(o){if(ts6.isExportAssignment(o)&&!o.isExportEquals&&ts6.isIdentifier(o.expression)&&o.expression.text===s)return t.updateExportAssignment(o,o.modifiers,t.createIdentifier(i));if(ts6.isCallExpression(o)){if(ts6.isIdentifier(o.expression)&&o.expression.text===s)return t.updateCallExpression(o,t.createIdentifier(i),o.typeArguments,o.arguments)}else if(ts6.isPropertyAccessExpression(o)){if(ts6.isIdentifier(o.expression)&&o.expression.text===s)return t.updatePropertyAccessExpression(o,t.createIdentifier(i),o.name)}else if(ts6.isNewExpression(o)){if(ts6.isIdentifier(o.expression)&&o.expression.text===s)return t.updateNewExpression(o,t.createIdentifier(i),o.typeArguments,o.arguments)}else if(ts6.isIdentifier(o)&&o.text===s&&!(e=>{const t=e.parent;return!(!(ts6.isVariableDeclaration(t)||ts6.isFunctionDeclaration(t)||ts6.isClassDeclaration(t)||ts6.isParameter(t)||ts6.isTypeAliasDeclaration(t)||ts6.isInterfaceDeclaration(t)||ts6.isEnumDeclaration(t)||ts6.isImportClause(t)||ts6.isNamespaceImport(t)||ts6.isImportSpecifier(t)||ts6.isExportSpecifier(t)||ts6.isTypeParameterDeclaration(t))||t.name!==e)||!(!ts6.isPropertyDeclaration(t)&&!ts6.isMethodDeclaration(t)||t.name!==e)})(o))return ts6.isPropertyAccessExpression(o.parent)&&o.parent.name===o||ts6.isPropertyAssignment(o.parent)&&o.parent.name===o?o:ts6.isShorthandPropertyAssignment(o.parent)&&o.parent.name===o?t.createPropertyAssignment(t.createIdentifier(o.text),t.createIdentifier(i)):t.createIdentifier(i);if(ts6.isFunctionDeclaration(o)||ts6.isClassDeclaration(o)){if(o.name&&ts6.isIdentifier(o.name)&&o.name.text===s){if(ts6.isFunctionDeclaration(o)){const s=ts6.visitEachChild(o,n,e);return t.updateFunctionDeclaration(s,s.modifiers,s.asteriskToken,t.createIdentifier(i),s.typeParameters,s.parameters,s.type,s.body)}const s=ts6.visitEachChild(o,n,e);return t.updateClassDeclaration(s,s.modifiers,t.createIdentifier(i),s.typeParameters,s.heritageClauses,s.members)}}else if(ts6.isVariableStatement(o)){const e=o.declarationList.declarations;let n=!1;const r=e.map(e=>ts6.isIdentifier(e.name)&&e.name.text===s?(n=!0,t.updateVariableDeclaration(e,t.createIdentifier(i),e.exclamationToken,e.type,e.initializer)):e);if(n)return t.updateVariableStatement(o,o.modifiers,t.updateVariableDeclarationList(o.declarationList,r))}return ts6.visitEachChild(o,n,e)}return e=>ts6.visitNode(e,n)}),fileExt:i,is_entry:n,...o}}}function resetExportDefaultState(){exportDefaultExportNameMap.length=0,exportDefaultImportNameMap.length=0,exportDefaultName=createExportDefaultNameGenerator()}const exportDefaultHandler=async(e,t)=>(resetExportDefaultState(),collectExportDefaultMappings(e),e=(e=e.map(exportDefaultLocalHandler(t))).map(exportDefaultImportAndUsageHandler(t))),properties=[],propertiesSet=new Set,typeObj={},typesNames=new Set;function esmExportRemoveHandler(e){return({file:t,content:s,...i})=>{const n=createBundledSourceFile(t,s);return{file:t,content:transformBundledSource(n,e,e=>{const{factory:t}=e,s=i=>{if(!utils.checks.isInsideNamespace(i)&&(ts6.isFunctionDeclaration(i)||ts6.isClassDeclaration(i)||ts6.isInterfaceDeclaration(i)||ts6.isTypeAliasDeclaration(i)||ts6.isEnumDeclaration(i)||ts6.isVariableStatement(i))){const e=i.modifiers?.filter(e=>e.kind!==ts6.SyntaxKind.ExportKeyword&&e.kind!==ts6.SyntaxKind.DefaultKeyword);if(e?.length!==i.modifiers?.length){if(ts6.isFunctionDeclaration(i))return t.updateFunctionDeclaration(i,e,i.asteriskToken,i.name,i.typeParameters,i.parameters,i.type,i.body);if(ts6.isClassDeclaration(i))return t.updateClassDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts6.isInterfaceDeclaration(i))return t.updateInterfaceDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts6.isTypeAliasDeclaration(i))return t.updateTypeAliasDeclaration(i,e,i.name,i.typeParameters,i.type);if(ts6.isEnumDeclaration(i))return t.updateEnumDeclaration(i,e,i.name,i.members);if(ts6.isVariableStatement(i))return t.updateVariableStatement(i,e,i.declarationList)}}if(ts6.isExportDeclaration(i))return t.createEmptyStatement();if(ts6.isExportAssignment(i)){const e=i.expression;if(ts6.isIdentifier(e))return t.createEmptyStatement()}return ts6.visitEachChild(i,s,e)};return e=>ts6.visitNode(e,s)}),...i}}}function importAllRemoveHandler(e,t){return({file:s,content:i,...n})=>{const o=createBundledSourceFile(s,i),r=utils.checks.moduleType(i,s).isCommonJs;return{file:s,content:transformBundledSource(o,t,t=>{const s=new Set;for(const e of o.statements)if(ts6.isImportEqualsDeclaration(e)&&e.isTypeOnly){const t=e.moduleReference;ts6.isExternalModuleReference(t)&&ts6.isStringLiteral(t.expression)&&s.add(e.name.text)}const{factory:i}=t,n=a=>{ts6.isPropertyAccessExpression(a)&&ts6.isIdentifier(a.expression)&&(properties.push(a.expression.text),propertiesSet.add(a.expression.text));const l={isNamespace:!1,isTypeOnly:!1,isTypeNamespace:!1,source:"",importedString:void 0,importedObject:void 0};if(ts6.isTypeReferenceNode(a)&&ts6.isQualifiedName(a.typeName)&&ts6.isIdentifier(a.typeName.left)&&ts6.isIdentifier(a.typeName.right)){const e=a.typeName.left.text,t=a.typeName.right.text;if(typesNames.add(e),e in typeObj?typeObj[e]?.push(t):typeObj[e]=[t],r&&"ts"!==e&&!s.has(e))return i.updateTypeReferenceNode(a,i.createIdentifier(t),void 0)}if(ts6.isImportDeclaration(a)){const t=a.getText(o);return e.push(t),i.createEmptyStatement()}if(ts6.isImportEqualsDeclaration(a)){const t=a.name.text,n=a.moduleReference;let o;if(a.isTypeOnly&&(l.isTypeOnly=!0),l.importedString=t,l.isTypeOnly||propertiesSet.has(t)&&(l.isNamespace=!0),ts6.isExternalModuleReference(n)&&ts6.isStringLiteral(n.expression)&&(l.source=n.expression.text),l.importedString&&!l.importedObject&&(o=l.isTypeOnly?s.has(l.importedString)?`import type * as ${l.importedString} from "${l.source}";`:typesNames.has(l.importedString)?`import type { ${typeObj[l.importedString]?.join(",")} } from "${l.source}";`:`import type ${l.importedString} from "${l.source}";`:l.isNamespace&&l.source&&"typescript"!==l.source?`import * as ${l.importedString} from "${l.source}";`:`import ${l.importedString} from "${l.source}";`),!l.importedString&&l.importedObject&&(o=`import { ${l.importedObject.join(", ")} } from "${l.source}";`),o)return e.push(o),i.createEmptyStatement()}if(ts6.isVariableStatement(a)){const t=a.declarationList.declarations;if(1===t.length){const s=t[0];if(s.initializer&&ts6.isCallExpression(s.initializer)&&ts6.isIdentifier(s.initializer.expression)&&"require"===s.initializer.expression.escapedText){const t=s.initializer.arguments[0];if(ts6.isStringLiteral(t)&&(l.source=t.text),ts6.isIdentifier(s.name)){const e=s.name.text;l.importedString=e,propertiesSet.has(e)&&(l.isNamespace=!0)}else if(ts6.isObjectBindingPattern(s.name)){const e=[];for(const t of s.name.elements)ts6.isIdentifier(t.name)&&e.push(t.name.text);e.length>0&&(l.importedObject=e)}let n;if(l.importedString&&!l.importedObject&&(n=l.isNamespace?`import * as ${l.importedString} from "${l.source}";`:`import ${l.importedString} from "${l.source}";`),!l.importedString&&l.importedObject&&(n=`import { ${l.importedObject.join(", ")} } from "${l.source}";`),n)return e.push(n),i.createEmptyStatement()}}}return ts6.visitEachChild(a,n,t)};return e=>ts6.visitNode(e,n)}),...n}}}const removeHandlers=async(e,t)=>{const s=utils.promises.resolve([[importAllRemoveHandler,e,t],[esmExportRemoveHandler,t]]);return await s.series()},jsonPrefix="__jsonModule__",jsonModuleExportNameMap=[],jsonModuleImportNameMap=[],toIdentifier=e=>{const t=e.replace(/[^A-Za-z0-9_$]/g,"_"),s=/^[A-Za-z_$]/.test(t);return`${jsonPrefix}${s?t:`_${t}`}`},toJsonModuleCode=(e,t,s)=>{let i;try{i=JSON.parse(t)}catch{throw new Error(`Invalid JSON syntax in dependency file: ${s}`)}return`const ${e} = ${JSON.stringify(i)};\nexport default ${e}`},resolveJSONHandler=async e=>{const t=new Map;return e.map(e=>{if("json"!==e.moduleType||".json"!==e.fileExt)return e;const s=path.basename(e.file).split(".")[0],i=getFileKey(e.file),n=toIdentifier(i),o=t.get(n)??0,r=0===o?n:`${n}_${o+1}`;return t.set(n,o+1),jsonModuleExportNameMap.push({base:r,file:s,newName:r,isEd:!0}),{...e,content:toJsonModuleCode(r,e.content,e.file),moduleType:"esm"}})};function jsonModuleImportHandler(e){return({file:t,content:s,fileExt:i,...n})=>{const o=createBundledSourceFile(t,s),r=transformBundledSource(o,e,e=>{const{factory:s}=e;function i(n){if(ts6.isImportDeclaration(n)){const e=n.moduleSpecifier.getText(o),i=path.basename(e).split(".")[0].trim();if(n.importClause?.name&&ts6.isIdentifier(n.importClause.name)){const e=n.importClause.name.text.trim(),o=jsonModuleExportNameMap.find(e=>e.file===i);if(o){jsonModuleImportNameMap.push({base:e,file:t,newName:o.newName,isEd:!0});const i=s.updateImportClause(n.importClause,n.importClause.phaseModifier,s.createIdentifier(o.newName),n.importClause.namedBindings);return s.updateImportDeclaration(n,n.modifiers,i,n.moduleSpecifier,n.attributes)}}}return ts6.visitEachChild(n,i,e)}return e=>ts6.visitNode(e,i)});return{file:t,content:r,fileExt:i,...n}}}function jsonModuleCallExpressionHandler(e){return({file:t,content:s,fileExt:i,...n})=>{const o=createBundledSourceFile(t,s),r=transformBundledSource(o,e,e=>{const{factory:s}=e;function i(n){if(ts6.isCallExpression(n)){if(ts6.isIdentifier(n.expression)){const e=n.expression.text,i=jsonModuleImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateCallExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts6.isPropertyAccessExpression(n)){if(ts6.isIdentifier(n.expression)){const e=n.expression.text,i=jsonModuleImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updatePropertyAccessExpression(n,s.createIdentifier(i.newName),n.name)}}else if(ts6.isNewExpression(n)){if(ts6.isIdentifier(n.expression)){const e=n.expression.text,i=jsonModuleImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateNewExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts6.isExportSpecifier(n)&&ts6.isIdentifier(n.name)){const e=n.name.text,i=jsonModuleImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateExportSpecifier(n,n.isTypeOnly,n.propertyName,s.createIdentifier(i.newName))}return ts6.visitEachChild(n,i,e)}return e=>ts6.visitNode(e,i)});return{file:t,content:r,fileExt:i,...n}}}async function jsonModuleHandlers(e,t){return e=(e=(e=await resolveJSONHandler(e)).map(e=>jsonModuleImportHandler(t)(e))).map(e=>jsonModuleCallExpressionHandler(t)(e))}function collectBindingNames(e,t){ts6.isIdentifier(e)?t.push(e.text):(ts6.isObjectBindingPattern(e)||ts6.isArrayBindingPattern(e))&&e.elements.forEach(e=>{ts6.isBindingElement(e)&&e.name&&collectBindingNames(e.name,t)})}function __anonymous__unusedCode_2(e,t,s,i={treatExportsAsUsed:!0}){const n=createBundledSourceFile(t,e),o=new Map,r=new Set,a=(e,t=!1)=>{const s=o.get(e);o.set(e,{exported:!!s?.exported||t})},l=e=>{if(ts6.isImportDeclaration(e)&&e.importClause){const t=e.importClause;t.name&&ts6.isIdentifier(t.name)&&a(t.name.text,!1),t.namedBindings&&(ts6.isNamedImports(t.namedBindings)?t.namedBindings.elements.forEach(e=>{ts6.isImportSpecifier(e)&&ts6.isIdentifier(e.name)&&a(e.name.text,!1)}):ts6.isNamespaceImport(t.namedBindings)&&ts6.isIdentifier(t.namedBindings.name)&&a(t.namedBindings.name.text,!1))}else if(ts6.isImportEqualsDeclaration(e)&&ts6.isIdentifier(e.name))a(e.name.text,!1);else if(ts6.isVariableStatement(e)){const t=e.modifiers?.some(e=>e.kind===ts6.SyntaxKind.ExportKeyword)??!1;e.declarationList.declarations.forEach(e=>{collectBindingNames(e.name,[]);const s=[];collectBindingNames(e.name,s),s.forEach(e=>a(e,t))})}else if(ts6.isFunctionDeclaration(e)&&e.name&&ts6.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts6.SyntaxKind.ExportKeyword)??!1;a(e.name.text,t)}else if(ts6.isClassDeclaration(e)&&e.name&&ts6.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts6.SyntaxKind.ExportKeyword)??!1;a(e.name.text,t)}if(ts6.isIdentifier(e)){const t=e.parent;ts6.isVariableDeclaration(t)&&t.name===e||ts6.isFunctionDeclaration(t)&&t.name===e||ts6.isClassDeclaration(t)&&t.name===e||ts6.isImportClause(t)&&t.name===e||ts6.isImportSpecifier(t)&&t.name===e||ts6.isNamespaceImport(t)&&t.name===e||ts6.isBindingElement(t)&&t.name===e||ts6.isParameter(t)&&t.name===e||r.add(e.text)}ts6.forEachChild(e,l)};l(n);const c=new Set;o.forEach((e,t)=>{r.has(t)||i.treatExportsAsUsed&&e.exported||c.add(t)});return transformBundledSource(n,s,e=>{const t=s=>{if(ts6.isImportDeclaration(s)&&s.importClause){const e=s.importClause,t=e.name&&ts6.isIdentifier(e.name)?e.name.text:void 0;let i;const n=[];e.namedBindings&&(ts6.isNamedImports(e.namedBindings)?e.namedBindings.elements.forEach(e=>{ts6.isImportSpecifier(e)&&ts6.isIdentifier(e.name)&&n.push(e)}):ts6.isNamespaceImport(e.namedBindings)&&ts6.isIdentifier(e.namedBindings.name)&&(i=e.namedBindings.name.text));const o=!!t&&!c.has(t),r=!!i&&!c.has(i),a=n.filter(e=>!c.has(e.name.text));if(t&&!o||i&&!r)return ts6.factory.createNotEmittedStatement(s);if(n.length>0&&0===a.length&&!t)return ts6.factory.createNotEmittedStatement(s);if(a.length!==n.length){const e=ts6.factory.createImportClause(!1,t?ts6.factory.createIdentifier(t):void 0,ts6.factory.createNamedImports(a));return ts6.factory.updateImportDeclaration(s,s.modifiers,e,s.moduleSpecifier,s.assertClause)}return s}if((ts6.isFunctionDeclaration(s)||ts6.isClassDeclaration(s))&&s.name&&ts6.isIdentifier(s.name))return c.has(s.name.text)?ts6.factory.createNotEmittedStatement(s):s;if(ts6.isVariableStatement(s)){const e=[];s.declarationList.declarations.forEach(t=>collectBindingNames(t.name,e));return e.some(e=>!c.has(e))?s:ts6.factory.createNotEmittedStatement(s)}return ts6.visitEachChild(s,t,e)};return e=>ts6.visitNode(e,t)})}const logBundlerPhase=(e,t,s)=>{logProfilePhase(`bundler:${path.basename(e)}`,t,s)};async function bundler(e,t=[],s=!1){const i=process.hrtime.bigint();let n=[];const o=ts6.getDefaultCompilerOptions();let r=process.hrtime.bigint();const a=await generateDependencies(e,createBundledSourceFile);logBundlerPhase(e,"generateDependencies",r),s&&a.warns.length>0&&(console.warn(a.warns.join("\n")),process.exit(1));let l=a.depFiles;if(isJSON(a)&&(r=process.hrtime.bigint(),l=await jsonModuleHandlers(l,o),logBundlerPhase(e,"resolveJSON",r)),t.length>0)for(const s of t){const t="function"==typeof s?s():s;"dependency"===t.type&&(r=process.hrtime.bigint(),l=t.async?await t.func(l,o):t.func(l,o),logBundlerPhase(e,`dependencyPlugin:${t.name??"anonymous"}`,r))}l.find(e=>"cjs"===e.moduleType)&&(console.error('Bundler found commonjs module/modules in dependencies tree.Please use "@suseejs/commonjs-plugin" to solve it.'),process.exit(1)),r=process.hrtime.bigint(),l=await exportDefaultHandler(l,o),logBundlerPhase(e,"exportDefault",r),r=process.hrtime.bigint(),l=await anonymousHandler(l,o),logBundlerPhase(e,"anonymous",r),r=process.hrtime.bigint();const c=await removeHandlers(n,o);l=l.map(c[0]);const p=l.slice(0,-1).map(c[1]),m=l.slice(-1);logBundlerPhase(e,"removeImportsExports",r),r=process.hrtime.bigint();const u=/^\s*import(?:[\s\S]*?\sfrom\s+)?["']((?!\.{1,2}\/)[^"']+)["']/;n=n.filter(e=>u.test(e)),n=utils.gen.mergeImportsStatement(n);const f=n.join("\n").trim();logBundlerPhase(e,"mergeImports",r),r=process.hrtime.bigint();let d=`${f}\n${p.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}\n${m.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}`;if(d=d.replace(/^s*;\s*$/gm,"").trim(),logBundlerPhase(e,"mergeContent",r),r=process.hrtime.bigint(),d=__anonymous__unusedCode_2(d,a.entry,o),logBundlerPhase(e,"cleanUnusedCode",r),t.length>0)for(const s of t){const t="function"==typeof s?s():s;"pre-process"===t.type&&(r=process.hrtime.bigint(),d=t.async?await t.func(d,a.entry):t.func(d,a.entry),logBundlerPhase(e,`preProcessPlugin:${t.name??"anonymous"}`,r))}return logBundlerPhase(e,"total",i),d}async function bundle(e){return await bundler(e)}const __jsonModule__package={name:"susee",version:"1.5.7",description:"TypeScript-first bundler for library packages",type:"module",main:"dist/index.cjs",types:"dist/index.d.cts",module:"dist/index.mjs",exports:{".":{import:{types:"./dist/index.d.mts",default:"./dist/index.mjs"},require:{types:"./dist/index.d.cts",default:"./dist/index.cjs"}}},bin:{susee:"bin/susee"},scripts:{build:"tsx build.ts",lint:"biome check src --write",fmt:"biome format --write",test:"tsx --test",coverage:"npx tsx --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=__tests__/coverage/lcov.info","hooks:install":"bash scripts/install-hooks.sh","lint:test":"biome check tests --write",commit:"bash scripts/commit.sh","v:patch":"npm version patch --no-git-tag-version","v:minor":"npm version minor --no-git-tag-version","v:major":"npm version major --no-git-tag-version","vercel:install":"npm i mmcov shiki && bundle install","vercel:build":"bash scripts/vercel_build.sh","docs:dev":"bundle exec jekyll serve --profile","docs:init":"bash scripts/setup.sh"},keywords:["bundler","susee","suseejs"],author:{name:"Pho Thin Mg",email:"phothinmg@disroot.org",url:"https://phothinmg.github.io/"},license:"Apache-2.0",files:["package.json","README.md","LICENSE","dist/**/*","bin/**/*"],publishConfig:{provenance:!0,access:"public"},repository:{url:"git+https://github.com/phothinmg/susee.git",type:"git"},homepage:"https://susee.js.org/",bugs:{url:"https://github.com/phothinmg/susee/issues"},dependencies:{"@suseejs/color":"^0.0.7","@suseejs/ts6":"^1.0.0",mmcov:"^0.0.8",shiki:"^4.3.1"},devDependencies:{"@biomejs/biome":"^2.4.12","@suseejs/banner-text-plugin":"^0.0.7","@suseejs/terser-plugin":"^0.0.7","@suseejs/type":"^0.0.7","@types/node":"^25.6.0",tsx:"^4.21.0",typescript:"^7.0.2"},allowScripts:{"esbuild@0.28.1":!0}},getSuseeConfigPath=()=>{const e=["susee.config.ts","susee.config.js","susee.config.mjs"];let t;for(const s of e){const e=ts6.sys.resolvePath(s);if(ts6.sys.fileExists(e)){t=e;break}}return t};function checkEntries(e){e.length<1&&(console.error(tcolor.magenta("No entry found in susee.config file or build options, at least one entry required")),ts6.sys.exit(1));const t={},s=[];for(const i of e){const e=i.exportPath;t[e]?s.push(`"${e}"`):t[e]=!0}s.length>0&&(console.error(tcolor.magenta(`Duplicate export paths/path (${s.join(",")}) found in your susee.config file or build options , that will error for bundled output`)),ts6.sys.exit(1));for(const t of e)ts6.sys.fileExists(ts6.sys.resolvePath(t.entry))||(console.error(tcolor.magenta(`Entry file ${t.entry} dose not exists.`)),ts6.sys.exit(1))}function generateBuildOptions(e){const t=e.outDir??"dist",s=[];checkEntries(e.entryPoints);for(const i of e.entryPoints){const e=i.entry,n=i.exportPath,o=i.format?[...new Set(i.format)]:["esm"],r=i.warning??!1,a=i.plugins??[],l=i.tsconfigFilePath??void 0,c="."===i.exportPath?t:`${t}${i.exportPath.slice(1)}`;s.push({entry:e,exportPath:n,format:o,plugins:a,warning:r,outputDirectoryPath:c,tsconfigFilePath:l})}return{buildEntryPoints:s,updatePackage:e.allowUpdatePackageJson??!1,outDir:t}}async function finalSuseeConfig(){const e=getSuseeConfigPath();if(e){return generateBuildOptions((await import(e)).default)}}function jsxCompilerOptions(e,t,s){if(!s)return t;if(!/import\s+(?:.*?)\s+from\s+(?:"react"|"react\/.*"|"react-dom\/.*"|"react-dom")/gm.test(e)){t.jsxImportSource||(console.error("[jsx-runtime-error]:\nJSX syntax found in bundled code,but its not react runtime,you need to be set jsxImportSource in tsconfig."),process.exit(1));const s=t.jsxImportSource;new RegExp(`import\\s+(?:.*?)\\s+from\\s+("${s}"|"${s}\\/.*")`,"gm").test(e)||(console.error("[jsx-runtime-mismatch-error]:\nJSX syntax found in bundled code,but its not react runtime and jsx-runtime from bundled code and jsxImportSource from tsconfig are mismatched.`"),process.exit(1))}const{jsx:i,lib:n,...o}=t;return{lib:["dom","dom.iterable","esnext"],jsx:i??ts6.JsxEmit.ReactJSX,...o}}function createHost(e,t){const s={},i={getSourceFile:(s,i)=>{if(s===t)return ts6.createSourceFile(s,e,i)},writeFile:(e,t)=>{s[e]=t},getDefaultLibFileName:e=>ts6.getDefaultLibFilePath(e),getCurrentDirectory:()=>"",getDirectories:()=>[],fileExists:e=>e===t,readFile:s=>s===t?e:void 0,getCanonicalFileName:e=>e,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n"};return{createdFiles:s,host:i}}function suseeCompiler({sourceCode:e,fileName:t,compilerOptions:s,isJsx:i=!1}){s=jsxCompilerOptions(e,s,i);const n=createHost(e,t),o=n.createdFiles,r=n.host;let a,l;ts6.createProgram([t],s,r).emit();let c="",p="",m="";for(const e of Object.keys(o))e.endsWith(".js")&&(c=o[e]),e.endsWith(".d.ts")&&(a=o[e]),e.endsWith(".js.map")&&(l=o[e]),p=path.basename(e).split(".")[0],m=path.dirname(e);return{code:c,file_name:p,out_dir:m,dts:a,map:l}}function getTsConfigPath(e){let t;return e?(ts6.sys.fileExists(ts6.sys.resolvePath(e))||(console.error(`> ${tcolor.magenta(`Given custom file ${e} does not exists`)}`),ts6.sys.exit(1)),t=e,t):(t=ts6.findConfigFile(ts6.sys.getCurrentDirectory(),ts6.sys.fileExists),t)}function getCompilerOptions(e){let t;const s=getTsConfigPath(e);if(s){const e=ts6.readConfigFile(s,ts6.sys.readFile),i=path.dirname(s),n=ts6.parseJsonConfigFileContent(e.config,ts6.sys,i);t={...n.options}}return{commonjs:e=>{const s=e||"dist";if(void 0!==t){const{rootDir:e,outDir:i,module:n,allowJs:o,declarationDir:r,...a}=t;return{outDir:s,module:ts6.ModuleKind.CommonJS,allowJs:!0,...a}}return{outDir:s,module:ts6.ModuleKind.CommonJS,target:ts6.ScriptTarget.Latest}},esm:e=>{const s=e||"dist";if(void 0!==t){const{rootDir:e,outDir:i,module:n,allowJs:o,declarationDir:r,...a}=t;return{outDir:s,module:ts6.ModuleKind.ES2020,allowJs:!0,...a}}return{outDir:s,module:ts6.ModuleKind.ES2020,target:ts6.ScriptTarget.Latest}},defaultOptions:ts6.getDefaultCompilerOptions}}const logCompilerPhase=(e,t,s,i)=>{logProfilePhase(`compiler:${t}:${e}`,s,i)};class Compiler{_files;_object;_bundledCodeCache;constructor(e){this._object=e,this._bundledCodeCache=new WeakMap,this._files={commonjs:void 0,commonjsTypes:void 0,esm:void 0,esmTypes:void 0,main:void 0,module:void 0,types:void 0}}_update(){return this._object.updatePackage}async _bundle(e){let t=this._bundledCodeCache.get(e);return t||(t=bundler(e.entry,e.plugins,e.warning,e.rename),this._bundledCodeCache.set(e,t)),t}async _commonjs(e){const t="."===e.exportPath,s=getCompilerOptions(e.tsconfigFilePath).commonjs(e.outputDirectoryPath);let i=process.hrtime.bigint();const n=await this._bundle(e);logCompilerPhase(e.entry,"commonjs","bundle",i);const o=utils.checks.isJsxContent(n);i=process.hrtime.bigint();const r=suseeCompiler({sourceCode:n,fileName:e.entry,compilerOptions:s,isJsx:o});logCompilerPhase(e.entry,"commonjs","typescriptEmit",i);let a=r.code;const l=files.joinPath(r.out_dir,`${r.file_name}.cjs`),c=files.joinPath(r.out_dir,`${r.file_name}.d.cts`),p=files.joinPath(r.out_dir,`${r.file_name}.cjs.map`);if(a=a.replace(new RegExp(`${r.file_name}.js.map`,"gm"),`${r.file_name}.cjs.map`),e.plugins.length>0)for(const t of e.plugins){const s="function"==typeof t?t():t;"post-process"===s.type&&(i=process.hrtime.bigint(),a=s.async?await s.func(a,e.entry):s.func(a,e.entry),logCompilerPhase(e.entry,"commonjs",`postProcessPlugin:${s.name??"anonymous"}`,i))}this._update()&&(this._files.commonjs=l,r.dts&&(this._files.commonjsTypes=c),t&&e.format.includes("commonjs")&&(this._files.commonjs&&(this._files.main=this._files.commonjs),this._files.commonjsTypes&&(this._files.types=this._files.commonjsTypes))),i=process.hrtime.bigint(),await files.writeFile(l,a),r.dts&&await files.writeFile(c,r.dts),r.map&&await files.writeFile(p,r.map),logCompilerPhase(e.entry,"commonjs","writeFiles",i)}async _esm(e){const t="."===e.exportPath,s=getCompilerOptions(e.tsconfigFilePath).esm(e.outputDirectoryPath);let i=process.hrtime.bigint();const n=await this._bundle(e);logCompilerPhase(e.entry,"esm","bundle",i);const o=utils.checks.isJsxContent(n);i=process.hrtime.bigint();const r=suseeCompiler({sourceCode:n,fileName:e.entry,compilerOptions:s,isJsx:o});logCompilerPhase(e.entry,"esm","typescriptEmit",i);let a=r.code;const l=files.joinPath(r.out_dir,`${r.file_name}.mjs`),c=files.joinPath(r.out_dir,`${r.file_name}.d.mts`),p=files.joinPath(r.out_dir,`${r.file_name}.mjs.map`);if(a=a.replace(new RegExp(`${r.file_name}.js.map`,"gm"),`${r.file_name}.mjs.map`),e.plugins.length>0)for(const t of e.plugins){const s="function"==typeof t?t():t;"post-process"===s.type&&(i=process.hrtime.bigint(),a=s.async?await s.func(a,e.entry):s.func(a,e.entry),logCompilerPhase(e.entry,"esm",`postProcessPlugin:${s.name??"anonymous"}`,i))}this._update()&&(this._files.esm=l,r.dts&&(this._files.esmTypes=c),t&&this._files.esm&&(this._files.module=this._files.esm)),i=process.hrtime.bigint(),await files.writeFile(l,a),r.dts&&await files.writeFile(c,r.dts),r.map&&await files.writeFile(p,r.map),logCompilerPhase(e.entry,"esm","writeFiles",i)}async compile(){await files.clearFolder(this._object.outDir);for(const e of this._object.buildEntryPoints)for(const t of e.format)switch(t){case"commonjs":await this._commonjs(e),this._update()&&await files.writePackageJson(this._files,e.exportPath);break;case"esm":await this._esm(e),this._update()&&await files.writePackageJson(this._files,e.exportPath)}}}async function cliBuild(){console.time(tcolor.cyan("[Build] "));const e=await finalSuseeConfig();e||(console.error(tcolor.magenta('No susee.config file ("susee.config.ts", "susee.config.js", "susee.config.mjs") found')),ts6.sys.exit(1));const t=new Compiler(e);await t.compile(),console.timeEnd(tcolor.cyan("[Build] "))}function fail(e){console.error(`${tcolor.magenta("[Error]")} : ${tcolor.gray(e)}`),process.exit(1)}function isFile(e){return[".js",".ts",".mts",".mjs",".cjs",".cts"].includes(path.extname(e))}function isEmptyObject(e){return"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length}function parseBooleanFlag(e,t){return"true"===t||"false"!==t&&void fail(`Type of ${e} must be boolean.`)}function parseArgs(e){const t={entry:""};for(let s=0;s<e.length;s+=1){const i=e[s];if(0===s&&!i.startsWith("--")&&isFile(i)){t.entry=i;continue}const[n,o]=i.split("=",2),r=e[s+1],a=o??r;switch(n){case"--entry":a&&!a.startsWith("--")||fail("Entry point required."),""!==t.entry&&isFile(t.entry)&&fail("Entry point already exists."),t.entry=a,void 0===o&&(s+=1);break;case"--outdir":a&&!a.startsWith("--")||fail("Output directory required."),t.outDir=a,void 0===o&&(s+=1);break;case"--format":"cjs"!==a&&"commonjs"!==a&&"esm"!==a&&fail("Format must be cjs, commonjs, or esm."),t.format="cjs"===a?"commonjs":a,void 0===o&&(s+=1);break;case"--tsconfig":a&&!a.startsWith("--")||fail("Tsconfig path required."),t.tsconfig=a,void 0===o&&(s+=1);break;case"--rename":void 0!==o?t.rename=parseBooleanFlag("rename",o):"true"===r||"false"===r?(t.rename=parseBooleanFlag("rename",r),s+=1):t.rename=!0;break;case"--allow-update":void 0!==o?t.allowUpdate=parseBooleanFlag("allow update",o):"true"===r||"false"===r?(t.allowUpdate=parseBooleanFlag("allow update",r),s+=1):t.allowUpdate=!0;break;case"--minify":void 0!==o?t.minify=parseBooleanFlag("minify",o):"true"===r||"false"===r?(t.minify=parseBooleanFlag("minify",r),s+=1):t.minify=!0;break;case"--warning":void 0!==o?t.warning=parseBooleanFlag("warning",o):"true"===r||"false"===r?(t.warning=parseBooleanFlag("warning",r),s+=1):t.warning=!0;break;case"--profile":void 0!==o?t.profile=parseBooleanFlag("profile",o):"true"===r||"false"===r?(t.profile=parseBooleanFlag("profile",r),s+=1):t.profile=!0}}return(isEmptyObject(t)||""===t.entry)&&fail("Entry point required"),t}function getDefaultOptions(e){return{entry:e.entry,outDir:e.outDir??"dist",format:e.format??"esm",tsconfig:e.tsconfig??void 0,rename:e.rename??!0,allowUpdate:e.allowUpdate??!1,minify:e.minify??!1,warning:e.warning??!1,profile:e.profile??!1,plugins:[]}}const logCliCompilerPhase=(e,t,s,i)=>{logProfilePhase(`compiler:${t}:${e}`,s,i)};class CliCompiler{_files;_update;constructor(){this._files={commonjs:void 0,commonjsTypes:void 0,esm:void 0,esmTypes:void 0,main:void 0,module:void 0,types:void 0},this._update=!1}async _commonjs(e){this._update=e.allowUpdate;const t=getCompilerOptions(e.tsconfig).commonjs(e.outDir);let s=process.hrtime.bigint();const i=await bundler(e.entry,e.plugins,e.warning);logCliCompilerPhase(e.entry,"commonjs","bundle",s);const n=utils.checks.isJsxContent(i);s=process.hrtime.bigint();const o=suseeCompiler({sourceCode:i,fileName:e.entry,compilerOptions:t,isJsx:n});logCliCompilerPhase(e.entry,"commonjs","typescriptEmit",s);let r=o.code;const a=files.joinPath(o.out_dir,`${o.file_name}.cjs`),l=files.joinPath(o.out_dir,`${o.file_name}.d.cts`),c=files.joinPath(o.out_dir,`${o.file_name}.cjs.map`);if(r=r.replace(new RegExp(`${o.file_name}.js.map`,"gm"),`${o.file_name}.cjs.map`),e.minify&&(e.plugins=[suseeTerser,...e.plugins],e.plugins=[...new Set(e.plugins)]),e.plugins.length>0)for(const t of e.plugins){const i="function"==typeof t?t():t;"post-process"===i.type&&(s=process.hrtime.bigint(),r=i.async?await i.func(r,e.entry):i.func(r,e.entry),logCliCompilerPhase(e.entry,"commonjs",`postProcessPlugin:${i.name??"anonymous"}`,s))}this._update&&(this._files.commonjs=a,o.dts&&(this._files.commonjsTypes=l),e.format.includes("commonjs")&&(this._files.commonjs&&(this._files.main=this._files.commonjs),this._files.commonjsTypes&&(this._files.types=this._files.commonjsTypes))),s=process.hrtime.bigint(),await files.writeFile(a,r),o.dts&&await files.writeFile(l,o.dts),o.map&&await files.writeFile(c,o.map),logCliCompilerPhase(e.entry,"commonjs","writeFiles",s)}async _esm(e){this._update=e.allowUpdate;const t=getCompilerOptions(e.tsconfig).esm(e.outDir);let s=process.hrtime.bigint();const i=await bundler(e.entry,e.plugins,e.warning);logCliCompilerPhase(e.entry,"esm","bundle",s);const n=utils.checks.isJsxContent(i);s=process.hrtime.bigint();const o=suseeCompiler({sourceCode:i,fileName:e.entry,compilerOptions:t,isJsx:n});logCliCompilerPhase(e.entry,"esm","typescriptEmit",s);let r=o.code;const a=files.joinPath(o.out_dir,`${o.file_name}.mjs`),l=files.joinPath(o.out_dir,`${o.file_name}.d.mts`),c=files.joinPath(o.out_dir,`${o.file_name}.mjs.map`);if(r=r.replace(new RegExp(`${o.file_name}.js.map`,"gm"),`${o.file_name}.mjs.map`),e.minify&&(e.plugins=[suseeTerser,...e.plugins],e.plugins=[...new Set(e.plugins)]),e.plugins.length>0)for(const t of e.plugins){const i="function"==typeof t?t():t;"post-process"===i.type&&(s=process.hrtime.bigint(),r=i.async?await i.func(r,e.entry):i.func(r,e.entry),logCliCompilerPhase(e.entry,"esm",`postProcessPlugin:${i.name??"anonymous"}`,s))}this._update&&(this._files.esm=a,o.dts&&(this._files.esmTypes=l),this._files.esm&&(this._files.module=this._files.esm)),s=process.hrtime.bigint(),await files.writeFile(a,r),o.dts&&await files.writeFile(l,o.dts),o.map&&await files.writeFile(c,o.map),logCliCompilerPhase(e.entry,"esm","writeFiles",s)}async compile(e){switch(await files.clearFolder(e.outDir),e.format){case"commonjs":await this._commonjs(e),this._update&&await files.writePackageJson(this._files,".");break;case"esm":await this._esm(e),this._update&&await files.writePackageJson(this._files,".")}}}const cliCompiler=new CliCompiler;function printHelp(){console.log("Susee CLI.\n\nUsage:\n susee Build using susee.config.{ts,js,mjs}\n susee init Generate susee.config.{ts,js,mjs}\n susee --help Show this message\n susee build <entry> [options] Build from a single entry file\n\nOptions:\n --entry <path> Entry file (optional if provided as positional <entry>)\n --outdir <path> Output directory\n --format <cjs|commonjs|esm> Output module format\n --tsconfig <path> Custom tsconfig path\n --rename[=true|false] Enable/disable renaming\n --allow-update[=true|false] Enable/disable dependency update\n --minify[=true|false] Enable/disable minification\n --profile[=true|false] Print bundler/compiler phase timings\n\nExamples:\n susee build src/index.ts --outdir dist\n susee build src/index.ts --format commonjs\n susee build --entry src/index.ts --format esm --minify\n susee build src/index.ts --profile\n susee --profile\n \n")}const tsFileText='\nimport type { SuSeeConfig } from "susee";\n\nconst config: SuSeeConfig = {\n // Array of entry point objects.\n // ----------------------------\n entryPoints: [\n // You can add more entry points for different export paths.\n // NOTE: duplicate export paths are not allowed.\n // --------------------------------------------\n {\n // (required) Entry file path.\n entry: "src/index.ts", // replace with your entry file\n // (required) Export path for this entry.\n exportPath: ".", // "." stands for the main export path and can be set to "./foo", "./bar", etc.\n // (optional) Output module formats ["commonjs"] or ["esm", "commonjs"], default: ["esm"].\n // Uncomment the following line to edit.\n //format: ["esm"],\n // (optional) Rename duplicate declarations, default: true.\n // Uncomment the following line to edit.\n //renameDuplicates: true,\n // (optional) Custom tsconfig.json path, default: undefined.\n // Uncomment the following line to edit.\n //tsconfigFilePath: undefined,\n // (optional) Array of susee plugins, default: [].\n // Uncomment the following line to edit.\n //plugins: [],\n // (optional) Warning messages, if it true and warning message exist(1), default: false.\n // Uncomment the following line to edit.\n //warning: false,\n },\n ],\n // NOTE: the following options apply to all entry points.\n // ----------------------------------------------------------\n // (optional) Output directory, default: dist.\n // Uncomment the following line to edit.\n //outDir: "dist",\n // (optional) Allow susee to update your package.json, default: false.\n // Uncomment the following line to edit.\n //allowUpdatePackageJson: false,\n};\n\nexport default config;\n'.trim(),jsFileText='\n/**\n * @type {import("susee").SuSeeConfig}\n */\nconst config = {\n // Array of entry point objects.\n // ----------------------------\n entryPoints: [\n // You can add more entry points for different export paths.\n // NOTE: duplicate export paths are not allowed.\n // --------------------------------------------\n {\n // (required) Entry file path.\n entry: "src/index.ts", // replace with your entry file\n // (required) Export path for this entry.\n exportPath: ".", // "." stands for the main export path and can be set to "./foo", "./bar", etc.\n // (optional) Output module formats ["commonjs"] or ["esm", "commonjs"], default: ["esm"].\n // Uncomment the following line to edit.\n //format: ["esm"],\n // (optional) Rename duplicate declarations, default: true.\n // Uncomment the following line to edit.\n //renameDuplicates: true,\n // (optional) Custom tsconfig.json path, default: undefined.\n // Uncomment the following line to edit.\n //tsconfigFilePath: undefined,\n // (optional) Array of susee plugins, default: [].\n // Uncomment the following line to edit.\n //plugins: [],\n // (optional) Warning messages, if it true and warning message exist(1), default: false.\n // Uncomment the following line to edit.\n //warning: false,\n },\n ],\n // NOTE: the following options apply to all entry points.\n // ----------------------------------------------------------\n // (optional) Output directory, default: dist.\n // Uncomment the following line to edit.\n //outDir: "dist",\n // (optional) Allow susee to update your package.json, default: false.\n // Uncomment the following line to edit.\n //allowUpdatePackageJson: false,\n};\n\nexport default config;\n'.trim();async function getPackageType(){const e=path.resolve(process.cwd(),"package.json"),t=await fs.promises.readFile(e,"utf8");JSON.parse(t);return"module"===__jsonModule__package.type?"esm":"commonjs"}async function cliInit(){const e=readline.createInterface({input:process.stdin,output:process.stdout});console.log(`${tcolor.gray("┌")} ${tcolor.green("Welcome to Susee!")}`),console.log(""),console.log(`${tcolor.gray("│")}`);const t=await e.question(`${tcolor.cyan("◇")} Is TypeScript Project(y/n) : `),s=!("y"!==t&&"Y"!==t&&""!==t);e.close();let i="",n="";if(s)i="susee.config.ts",n=tsFileText;else{n=jsFileText;switch(await getPackageType()){case"commonjs":i="susee.config.mjs";break;case"esm":i="susee.config.js"}}const o=path.resolve(process.cwd(),i);fs.existsSync(o)&&await fs.promises.unlink(o),await fs.promises.writeFile(o,n),console.log(""),console.log(`${tcolor.gray("│")}`),console.log(""),console.info(`${tcolor.gray("└")} Done! Susee config file ${tcolor.cyan(i)} is created at project root`)}function extractProfileFlag(e){const t=[];let s=!1;for(let i=0;i<e.length;i+=1){const n=e[i],[o,r]=n.split("=",2);if("--profile"!==o){t.push(n);continue}const a=e[i+1];void 0===r?"true"!==a&&"false"!==a?s=!0:(s=parseBooleanFlag("profile",a),i+=1):s=parseBooleanFlag("profile",r)}return{args:t,profile:s}}async function suseeCliBuild(){const e=process.argv.slice(2),{args:t,profile:s}=extractProfileFlag(e);if(s&&setProfileEnabled(!0),0===t.length)await cliBuild();else if(1===t.length)"--version"!==t[0]&&"-v"!==t[0]||console.log(tcolor.cyan(`susee v${__jsonModule__package.version}`)),"--help"!==t[0]&&"-h"!==t[0]||printHelp(),"init"===t[0]&&await cliInit(),"build"===t[0]&&printHelp();else if(t.length>1&&"build"===t[0]&&("--help"===t[1]||"-h"===t[1]))printHelp();else if(t.length>1&&"build"===t[0]){const e=getDefaultOptions(parseArgs(t.slice(1)));await cliCompiler.compile(e)}else console.error("Unknown CLI usage"),process.exit(1)}async function build(e){console.time(tcolor.cyan("[Build] "));let t={};const s=await finalSuseeConfig();e||s||(console.error(`${tcolor.magenta("[Error]")} : Required build options or susee config file at root.\n Use ${tcolor.bold("npx susee init")} to create config file.`),process.exit(1)),e?t=generateBuildOptions(e):s&&(t=s);const i=new Compiler(t);await i.compile(),console.timeEnd(tcolor.cyan("[Build] "))}export{build,bundle as suseeBundler,suseeCliBuild};
|