susee 1.0.4 → 1.5.1

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/dist/index.d.cts CHANGED
@@ -1,7 +1,5 @@
1
1
  import type { SuseePlugin, SuseePluginFunction } from "@suseejs/types";
2
- /**
3
- * Entry point for SuSee configuration
4
- */
2
+ type OutputFormat = ("commonjs" | "esm")[];
5
3
  interface EntryPoint {
6
4
  /**
7
5
  * Entry of file path of package
@@ -25,7 +23,7 @@ interface EntryPoint {
25
23
  *
26
24
  * default - esm
27
25
  */
28
- format?: "commonjs" | "esm" | "both";
26
+ format?: OutputFormat;
29
27
  /**
30
28
  * Custom tsconfig.json path for package typescript compiler options
31
29
  *
@@ -43,6 +41,9 @@ interface EntryPoint {
43
41
  * default - true
44
42
  */
45
43
  renameDuplicates?: boolean;
44
+ binary?: {
45
+ name: string;
46
+ } | undefined;
46
47
  }
47
48
  /**
48
49
  * Configuration for Susee Bundler
@@ -61,7 +62,7 @@ interface SuSeeConfig {
61
62
  */
62
63
  outDir?: string;
63
64
  /**
64
- * Array of susee extension
65
+ * Array of susee plugins
65
66
  *
66
67
  * default - []
67
68
  */
@@ -69,19 +70,22 @@ interface SuSeeConfig {
69
70
  /**
70
71
  * Allow bundler to update your package.json.
71
72
  *
72
- * default - true
73
+ * default - false
73
74
  */
74
75
  allowUpdatePackageJson?: boolean;
75
76
  }
76
77
  /**
77
- * Main entry point for susee.
78
- * It will:
79
- * 1. Collect all entry points from the configuration.
80
- * 2. Bundle all the entry points.
81
- * 3. Compile the bundled code.
82
- * The function will return a promise that resolves when the compilation is done.
78
+ * Main entry point for SuSee
79
+ *
80
+ * This function is the main entry point for the SuSee bundler.
81
+ * It initializes the bundling process, resolves the dependency tree,
82
+ * compiles the resolved dependencies, and writes the compiled output
83
+ * to disk.
84
+ *
85
+ * @returns {Promise<void>} A promise that resolves when the bundling
86
+ * process is complete.
83
87
  */
84
88
  declare function susee(): Promise<void>;
85
89
  export type { SuSeeConfig };
86
90
  export { susee };
87
- //# sourceMappingURL=index.d.ts.map
91
+ //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAmL,WAAW,EAAE,mBAAmB,EAAW,MAAM,gBAAgB,CAAC;AAuKjQ;;GAEG;AACH,UAAU,UAAU;IAChB;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH;;;;OAIG;IACH,UAAU,EAAE,GAAG,GAAG,KAAK,MAAM,EAAE,CAAC;IAChC;;;;OAIG;IACH,MAAM,CAAC,EAAE,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;IACrC;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC9B;AACD;;GAEG;AACH,UAAU,WAAW;IACjB;;;;OAIG;IACH,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,WAAW,GAAG,mBAAmB,CAAC,EAAE,CAAC;IAChD;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACpC;AAy3DD;;;;;;;GAOG;AACH,iBAAe,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAUpC;AACD,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAoI,WAAW,EAAE,mBAAmB,EAAW,MAAM,gBAAgB,CAAC;AAIlN,KAAK,YAAY,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,EAAE,CAAC;AA2C3C,UAAU,UAAU;IAChB;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH;;;;OAIG;IACH,UAAU,EAAE,GAAG,GAAG,KAAK,MAAM,EAAE,CAAC;IAChC;;;;OAIG;IACH,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,MAAM,CAAC,EAAE;QACL,IAAI,EAAE,MAAM,CAAC;KAChB,GAAG,SAAS,CAAC;CACjB;AACD;;GAEG;AACH,UAAU,WAAW;IACjB;;;;OAIG;IACH,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,WAAW,GAAG,mBAAmB,CAAC,EAAE,CAAC;IAChD;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACpC;AAuqED;;;;;;;;;;GAUG;AACH,iBAAe,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAWpC;AACD,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,CAAC"}
package/dist/index.d.mts CHANGED
@@ -1,7 +1,5 @@
1
1
  import type { SuseePlugin, SuseePluginFunction } from "@suseejs/types";
2
- /**
3
- * Entry point for SuSee configuration
4
- */
2
+ type OutputFormat = ("commonjs" | "esm")[];
5
3
  interface EntryPoint {
6
4
  /**
7
5
  * Entry of file path of package
@@ -25,7 +23,7 @@ interface EntryPoint {
25
23
  *
26
24
  * default - esm
27
25
  */
28
- format?: "commonjs" | "esm" | "both";
26
+ format?: OutputFormat;
29
27
  /**
30
28
  * Custom tsconfig.json path for package typescript compiler options
31
29
  *
@@ -43,6 +41,9 @@ interface EntryPoint {
43
41
  * default - true
44
42
  */
45
43
  renameDuplicates?: boolean;
44
+ binary?: {
45
+ name: string;
46
+ } | undefined;
46
47
  }
47
48
  /**
48
49
  * Configuration for Susee Bundler
@@ -61,7 +62,7 @@ interface SuSeeConfig {
61
62
  */
62
63
  outDir?: string;
63
64
  /**
64
- * Array of susee extension
65
+ * Array of susee plugins
65
66
  *
66
67
  * default - []
67
68
  */
@@ -69,19 +70,22 @@ interface SuSeeConfig {
69
70
  /**
70
71
  * Allow bundler to update your package.json.
71
72
  *
72
- * default - true
73
+ * default - false
73
74
  */
74
75
  allowUpdatePackageJson?: boolean;
75
76
  }
76
77
  /**
77
- * Main entry point for susee.
78
- * It will:
79
- * 1. Collect all entry points from the configuration.
80
- * 2. Bundle all the entry points.
81
- * 3. Compile the bundled code.
82
- * The function will return a promise that resolves when the compilation is done.
78
+ * Main entry point for SuSee
79
+ *
80
+ * This function is the main entry point for the SuSee bundler.
81
+ * It initializes the bundling process, resolves the dependency tree,
82
+ * compiles the resolved dependencies, and writes the compiled output
83
+ * to disk.
84
+ *
85
+ * @returns {Promise<void>} A promise that resolves when the bundling
86
+ * process is complete.
83
87
  */
84
88
  declare function susee(): Promise<void>;
85
89
  export type { SuSeeConfig };
86
90
  export { susee };
87
- //# sourceMappingURL=index.d.ts.map
91
+ //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAmL,WAAW,EAAE,mBAAmB,EAAW,MAAM,gBAAgB,CAAC;AAuKjQ;;GAEG;AACH,UAAU,UAAU;IAChB;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH;;;;OAIG;IACH,UAAU,EAAE,GAAG,GAAG,KAAK,MAAM,EAAE,CAAC;IAChC;;;;OAIG;IACH,MAAM,CAAC,EAAE,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;IACrC;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC9B;AACD;;GAEG;AACH,UAAU,WAAW;IACjB;;;;OAIG;IACH,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,WAAW,GAAG,mBAAmB,CAAC,EAAE,CAAC;IAChD;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACpC;AAy3DD;;;;;;;GAOG;AACH,iBAAe,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAUpC;AACD,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAoI,WAAW,EAAE,mBAAmB,EAAW,MAAM,gBAAgB,CAAC;AAIlN,KAAK,YAAY,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,EAAE,CAAC;AA2C3C,UAAU,UAAU;IAChB;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH;;;;OAIG;IACH,UAAU,EAAE,GAAG,GAAG,KAAK,MAAM,EAAE,CAAC;IAChC;;;;OAIG;IACH,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,MAAM,CAAC,EAAE;QACL,IAAI,EAAE,MAAM,CAAC;KAChB,GAAG,SAAS,CAAC;CACjB;AACD;;GAEG;AACH,UAAU,WAAW;IACjB;;;;OAIG;IACH,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,WAAW,GAAG,mBAAmB,CAAC,EAAE,CAAC;IAChD;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACpC;AAuqED;;;;;;;;;;GAUG;AACH,iBAAe,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAWpC;AACD,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,CAAC"}
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 TsConfig from"@suseejs/tsconfig";import fs from"node:fs";import mhaehko from"mhaehko";import path from"node:path";import resolves from"@phothinmaung/resolves";import tcolor from"@suseejs/tcolor";import transformFunction from"@suseejs/transformer";import ts from"typescript";import{Buffer}from"node:buffer";const depHooks=[],preProcessHooks=[];var utilities;!function(e){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.wait=e=>new Promise(t=>setTimeout(t,e)),e.checkModuleType=(e,t)=>{let s=0,i=0,n=0;try{let t=!1,n=!1;!function s(i){if((ts.isImportDeclaration(i)||ts.isImportEqualsDeclaration(i)||ts.isExportDeclaration(i)||ts.isExportSpecifier(i)||ts.isExportAssignment(i))&&(t=!0),(ts.isVariableStatement(i)||ts.isFunctionDeclaration(i)||ts.isInterfaceDeclaration(i)||ts.isTypeAliasDeclaration(i)||ts.isEnumDeclaration(i)||ts.isClassDeclaration(i))&&i.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)&&(t=!0),ts.isCallExpression(i)&&ts.isIdentifier(i.expression)&&"require"===i.expression.text&&i.arguments.length>0&&(n=!0),ts.isPropertyAccessExpression(i)){const t=i.getText(e);(t.startsWith("module.exports")||t.startsWith("exports."))&&(n=!0)}ts.forEachChild(i,s)}(e),t&&!n?s++:n&&!t?i++:t&&n&&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.")),ts.sys.exit(1)),{isCommonJs:i>0,isEsm:s>0}},e.isJsxContent=function(e){const t=ts.createSourceFile("file.tsx",e,ts.ScriptTarget.Latest,!0,ts.ScriptKind.TSX);let s=!1;return function e(t){ts.isJsxElement(t)||ts.isJsxSelfClosingElement(t)||ts.isJsxFragment(t)?s=!0:ts.forEachChild(t,e)}(t),s},e.writeCompileFile=async function(t,s){const i=ts.sys.resolvePath(t),n=path.dirname(i);ts.sys.directoryExists(n)||await fs.promises.mkdir(n,{recursive:!0}),await e.wait(500),await fs.promises.writeFile(i,s)},e.isInsideNamespace=e=>{let t=e.parent;for(;t;){if(ts.isModuleDeclaration(t)&&t.flags===ts.NodeFlags.Namespace)return!0;t=t.parent}return!1},e.clearFolder=async function(e){e=path.resolve(process.cwd(),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}}}(utilities||(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, 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 , 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))}async function finalSuseeConfig(){const e=getConfigPath();void 0===e&&(console.error(tcolor.magenta('No susee.config file ("susee.config.ts", "susee.config.js", "susee.config.mjs") found')),ts.sys.exit(1));const t=(await import(e)).default,s=resolves([[checkEntries,t.entryPoints]]);await s.series(),await utilities.wait(1e3);const i=t.outDir??"dist",n=[];for(const e of t.entryPoints){const t={entry:e.entry,exportPath:e.exportPath,format:e.format??"esm",tsconfigFilePath:e.tsconfigFilePath??void 0,renameDuplicates:e.renameDuplicates??!0,outDirPath:"."===e.exportPath?i:`${i}${e.exportPath.slice(1)}`};n.push(t)}return{points:n,plugins:t.plugins??[],allowUpdatePackageJson:t.allowUpdatePackageJson??!0,outDir:i}}class CompilerOptions{constructor(e){this._point=e,this._options={}}__init(){const e=new TsConfig(this._point.tsconfigFilePath);e.removeCompilerOption("rootDir"),e.removeCompilerOption("module"),e.editCompilerOptions({moduleResolution:ts.ModuleResolutionKind.NodeNext,outDir:this._point.outDirPath,allowJs:!0}),this._options=e.getCompilerOptions()}__init2(){this.__init();let{types:e,lib:t,...s}=this._options;return e?e.includes("node")||(e=["node",...e]):e=["node"],t=t?[...new Set(["ESNext",...t])]:["ESNext"],{types:e,lib:t,...s}}get commonjs(){const e=this.__init2(),{module:t,...s}=e;return{module:ts.ModuleKind.CommonJS,...s}}get esm(){const e=this.__init2(),{module:t,...s}=e;return{module:ts.ModuleKind.ES2020,...s}}get default(){return this.__init2()}}function compilerOptions(e){return new CompilerOptions(e)}async function fileSizes(e){const t=await fs.promises.stat(e);return{logical:t.size,allocated:null!==t.blocks?512*t.blocks:null}}const checkExport=(e,t)=>!!(e.match(/export default .*/gm)||e.match(/export = .*/gm)&&t.match(/.cts/g));async function generateDependencies(e){const t=(await mhaehko(e)).sort(),s=[];for(const e of t){const t=ts.sys.resolvePath(e),i=await fs.promises.readFile(t,"utf8"),n=path.extname(t),r=await fileSizes(t),a=i.length,o=checkExport(i,t),c=ts.createSourceFile(t,i,ts.ScriptTarget.Latest,!0),l=utilities.checkModuleType(c,t).isCommonJs?"cjs":"esm",p={file:t,content:i,length:a,includeDefExport:o,size:{logical:r.logical,allocated:r.allocated,utf8:(new TextEncoder).encode(i).length,buffBytes:Buffer.byteLength(i,"utf8")},moduleType:l,fileExt:n,isJsx:utilities.isJsxContent(i)};s.push(p)}return s}function _typesCheck(e,t){if(!t.noCheck){const s=e.map(e=>e.file);let i=!1;const n=ts.createProgram(s,t);for(const e of s){const t=n.getSourceFile(e);t||(console.error(tcolor.magenta(`File not found: ${e}`)),ts.sys.exit(1));const s=[...n.getSyntacticDiagnostics(t),...n.getSemanticDiagnostics(t),...n.getDeclarationDiagnostics(t)];if(s.length>0){const e={getCurrentDirectory:()=>process.cwd(),getCanonicalFileName:e=>e,getNewLine:()=>ts.sys.newLine};console.error(ts.formatDiagnosticsWithColorAndContext(s,e)),i=!0}}if(!i)return!0;ts.sys.exit(1)}}async function typeCheck(e,t){const s=resolves([[_typesCheck,e,t]]);return(await s.series())[0]}async function depPluginParser(e,t,s){if(t.length)for(const i of t){const t="function"==typeof i?i():i;"dependency"===t.type&&(e=t.async?await t.func(e,s):t.func(e,s))}return e}async function depHookParser(e,t){if(depHooks.length)for(const s of depHooks)e=s.async?await s.func(e,t):s.func(e,t);return e}async function initializer(){console.time(`${tcolor.cyan("Collected Data")}`);const e=await finalSuseeConfig(),t=e.points,s=e.plugins,i=[];for(const e of t){const t=compilerOptions(e);let n=await generateDependencies(e.entry);await typeCheck(n,t.esm)||ts.sys.exit(1),n=await depPluginParser(n,s,t.default),await utilities.wait(1e3),n=await depHookParser(n,t.default),await utilities.wait(1e3);const r={fileName:e.entry,exportPath:e.exportPath,format:e.format,rename:e.renameDuplicates,outDir:e.outDirPath,tsOptions:{cjs:t.commonjs,esm:t.esm,default:t.default},depFiles:n,plugins:s};i.push(r)}return console.timeEnd(`${tcolor.cyan("Collected Data")}`),{points:i,allowUpdatePackageJson:e.allowUpdatePackageJson}}function uniqueName(){const e=new Map,t={setPrefix({key:s,value:i}){if(e.has(s))throw console.warn(`${s} already exist`),new Error;return e.set(s,[i,0]),t},getName(t,s){const[i,n]=e.get(t)||[],r=i?`${i}${s}_${(n??0)+1}`:`$nyein${s}_${(n??0)+1}`;return e.set(t,[i??"$nyein",(n??0)+1]),r},getPrefix(t){const[s]=e.get(t)||[];return s}};return t}const exportDefaultExportNameMap=[],exportDefaultImportNameMap=[],prefixKey="AnonymousName",genName=uniqueName().setPrefix({key:prefixKey,value:"__anonymous__"});function anonymousCallExpressionHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=n=>{if(ts.isCallExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateCallExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts.isPropertyAccessExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updatePropertyAccessExpression(n,s.createIdentifier(i.newName),n.name)}}else if(ts.isNewExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateNewExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts.isExportSpecifier(n)&&ts.isIdentifier(n.name)){const e=n.name.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateExportSpecifier(n,n.isTypeOnly,n.propertyName,s.createIdentifier(i.newName))}return ts.visitEachChild(n,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}function anonymousExportHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=r=>{const a=path.basename(t).split(".")[0];if((ts.isFunctionDeclaration(r)||ts.isClassDeclaration(r))&&void 0===r.name){let e=!1,t=!1;if(r.modifiers?.forEach(s=>{s.kind===ts.SyntaxKind.ExportKeyword&&(e=!0),s.kind===ts.SyntaxKind.DefaultKeyword&&(t=!0)}),e&&t){const e=genName.getName(prefixKey,a);if(exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),ts.isFunctionDeclaration(r))return s.updateFunctionDeclaration(r,r.modifiers,r.asteriskToken,s.createIdentifier(e),r.typeParameters,r.parameters,r.type,r.body);if(ts.isClassDeclaration(r))return s.updateClassDeclaration(r,r.modifiers,s.createIdentifier(e),r.typeParameters,r.heritageClauses,r.members)}}else if(ts.isExportAssignment(r)&&!r.name&&!r.isExportEquals){if(ts.isArrowFunction(r.expression)){const e=genName.getName(prefixKey,a),t=s.createArrowFunction(r.expression.modifiers,r.expression.typeParameters,r.expression.parameters,r.expression.type,r.expression.equalsGreaterThanToken,r.expression.body),i=s.createVariableDeclaration(s.createIdentifier(e),r.expression.exclamationToken,r.expression.type,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(r.expression.modifiers,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isObjectLiteralExpression(r.expression)){const e=genName.getName(prefixKey,a),t=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,r.expression),i=s.createVariableDeclarationList([t],ts.NodeFlags.Const),o=s.createVariableStatement(void 0,i),c=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[o,c],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isArrayLiteralExpression(r.expression)){const e=genName.getName(prefixKey,a),t=s.createArrayLiteralExpression(r.expression.elements,!0),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isStringLiteral(r.expression)){const e=genName.getName(prefixKey,a),t=s.createStringLiteral(r.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isNumericLiteral(r.expression)){const e=genName.getName(prefixKey,a),t=s.createNumericLiteral(r.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}}return ts.visitEachChild(r,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}function anonymousImportHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=r=>{if(ts.isImportDeclaration(r)){const e=r.moduleSpecifier.getText(n),i=path.basename(e).split(".")[0].trim();if(r.importClause?.name&&ts.isIdentifier(r.importClause.name)){const e=r.importClause.name.text.trim(),n=exportDefaultExportNameMap.find(e=>e.file===i);if(n){exportDefaultImportNameMap.push({base:e,file:t,newName:n.newName,isEd:!0});const i=s.updateImportClause(r.importClause,r.importClause.phaseModifier,s.createIdentifier(n.newName),r.importClause.namedBindings);return s.updateImportDeclaration(r,r.modifiers,i,r.moduleSpecifier,r.attributes)}}}return ts.visitEachChild(r,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}const anonymousHandler=async(e,t)=>{const s=resolves([[anonymousExportHandler,t],[anonymousImportHandler,t],[anonymousCallExpressionHandler,t]]),i=await s.concurrent();for(const t of i)e=e.map(t);return e};function duplicates(e,t,s){const i=ts.createSourceFile(t,e,ts.ScriptTarget.Latest,!0),n=new Map;for(const e of i.statements){if(!ts.isImportDeclaration(e)||!e.importClause)continue;const t=e.importClause;if(t.name&&ts.isIdentifier(t.name)){const e=t.name.text;n.set(e,(n.get(e)||[]).concat({name:e,node:t}))}else if(t.namedBindings&&ts.isNamespaceImport(t.namedBindings)&&ts.isIdentifier(t.namedBindings.name)){const e=t.namedBindings.name.text;n.set(e,(n.get(e)||[]).concat({name:e,node:t.namedBindings}))}else if(t.namedBindings&&ts.isNamedImports(t.namedBindings))for(const e of t.namedBindings.elements)if(ts.isIdentifier(e.name)){const t=e.name.text;n.set(t,(n.get(t)||[]).concat({name:t,node:e}))}}const r=new Map,a=uniqueName();a.setPrefix({key:"DuplicateImport",value:"__dup__"});for(const[e,t]of n.entries())if(t.length>1)for(let s=1;s<t.length;s++){const t=a.getName("DuplicateImport",`${e}_`);r.set(`${e}::${s}`,t),r.set(`${e}::occurrence_${s}`,t)}const o=new Map;for(const[e,t]of n.entries())if(t.length>1)for(let s=1;s<t.length;s++){const i=t[s];i?.node&&o.set(i.node.pos,r.get(`${e}::${s}`))}return transformFunction(e=>{const{factory:t}=e,s=i=>{if(ts.isImportDeclaration(i)&&i.importClause){const e=i.importClause;let s=!1,n=e;if(e.name&&ts.isIdentifier(e.name)){e.pos;const i=o.get(e.pos);i&&(n=t.updateImportClause(e,e.isTypeOnly,t.createIdentifier(i),e.namedBindings),s=!0)}if(e.namedBindings&&ts.isNamespaceImport(e.namedBindings)&&ts.isIdentifier(e.namedBindings.name)){const i=o.get(e.namedBindings.pos);if(i){const e=t.createNamespaceImport(t.createIdentifier(i));n=t.updateImportClause(n,n.isTypeOnly,n.name,e),s=!0}}if(e.namedBindings&&ts.isNamedImports(e.namedBindings)){const i=e.namedBindings.elements.map(e=>{if(ts.isIdentifier(e.name)){const i=o.get(e.pos);if(i)return s=!0,t.updateImportSpecifier(e,e.isTypeOnly,e.propertyName,t.createIdentifier(i))}return e});if(s){const e=t.createNamedImports(i);n=t.updateImportClause(n,n.isTypeOnly,n.name,e)}}if(s)return t.updateImportDeclaration(i,i.modifiers,n,i.moduleSpecifier,i.assertClause)}if(ts.isIdentifier(i)){const e=i.text;if(!(e=>{const t=e.parent;if(!t)return!1;switch(t.kind){case ts.SyntaxKind.ImportSpecifier:case ts.SyntaxKind.NamespaceImport:case ts.SyntaxKind.ImportClause:case ts.SyntaxKind.VariableDeclaration:case ts.SyntaxKind.FunctionDeclaration:case ts.SyntaxKind.ClassDeclaration:case ts.SyntaxKind.InterfaceDeclaration:case ts.SyntaxKind.TypeAliasDeclaration:case ts.SyntaxKind.EnumDeclaration:case ts.SyntaxKind.Parameter:case ts.SyntaxKind.PropertyDeclaration:case ts.SyntaxKind.MethodDeclaration:case ts.SyntaxKind.BindingElement:return!0;default:return!1}})(i)){if(i.parent&&ts.isPropertyAccessExpression(i.parent)&&i.parent.name===i)return i;const s=n.get(e);if(s&&s.length>1)for(let i=1;i<s.length;i++){const s=r.get(`${e}::occurrence_${i}`)||r.get(`${e}::${i}`);if(s)return t.createIdentifier(s)}}}return ts.visitEachChild(i,s,e)};return e=>ts.visitNode(e,s)},i,s)}function mergeImportsStatement(e){const t=new Map,s=new Map,i=new Map,n=new Map,r=new Map;for(const a of e){const e=a.match(/import\s+(?:type\s+)?(?:(.*?)\s+from\s+)?["']([^"']+)["'];?/);if(!e)continue;const[,o,c]=e,l=a.includes("import type"),p=c;if(!o){const e=a.match(/import\s+(?:type\s+)?(\w+)/);if(e){const t=e[1],s=l?n:i;s.has(p)||s.set(p,new Set),s.get(p)?.add(t)}continue}if(o.startsWith("{")){const e=l?s:t;e.has(p)||e.set(p,new Set);o.replace(/[{}]/g,"").split(",").map(e=>e.trim()).filter(Boolean).forEach(t=>e.get(p)?.add(t))}else if(o.startsWith("* as")){const e=o.match(/\*\s+as\s+(\w+)/);if(e){const t=e[1];r.has(p)||r.set(p,new Set),r.get(p)?.add(t)}}else{const e=l?n:i;e.has(p)||e.set(p,new Set),e.get(p)?.add(o.trim())}}const a=[];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(", ");a.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(", ");a.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(", ");a.push(`import ${t} from "${e}";`)}}for(const[e,t]of n)if(!i.has(e)&&t.size>0){const s=Array.from(t).join(", ");a.push(`import type ${s} from "${e}";`)}for(const[e,t]of r)if(t.size>0){const s=Array.from(t).join(", ");a.push(`import * as ${s} from "${e}";`)}return a.sort()}function esmExportRemoveHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0);return{file:t,content:transformFunction(e=>{const{factory:t}=e,s=i=>{if(!utilities.isInsideNamespace(i)&&(ts.isFunctionDeclaration(i)||ts.isClassDeclaration(i)||ts.isInterfaceDeclaration(i)||ts.isTypeAliasDeclaration(i)||ts.isEnumDeclaration(i)||ts.isVariableStatement(i))){const e=i.modifiers?.filter(e=>e.kind!==ts.SyntaxKind.ExportKeyword&&e.kind!==ts.SyntaxKind.DefaultKeyword);if(e?.length!==i.modifiers?.length){if(ts.isFunctionDeclaration(i))return t.updateFunctionDeclaration(i,e,i.asteriskToken,i.name,i.typeParameters,i.parameters,i.type,i.body);if(ts.isClassDeclaration(i))return t.updateClassDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts.isInterfaceDeclaration(i))return t.updateInterfaceDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts.isTypeAliasDeclaration(i))return t.updateTypeAliasDeclaration(i,e,i.name,i.typeParameters,i.type);if(ts.isEnumDeclaration(i))return t.updateEnumDeclaration(i,e,i.name,i.members);if(ts.isVariableStatement(i))return t.updateVariableStatement(i,e,i.declarationList)}}if(ts.isExportDeclaration(i))return t.createEmptyStatement();if(ts.isExportAssignment(i)){const e=i.expression;if(ts.isIdentifier(e))return t.createEmptyStatement()}return ts.visitEachChild(i,s,e)};return e=>ts.visitNode(e,s)},n,e),...i}}}let properties=[];const typeObj={},typesNames=[];function findProperty(e){const t=[];return ts.isPropertyAccessExpression(e)&&ts.isIdentifier(e.expression)&&t.push(e.expression.text),e.forEachChild(e=>findProperty(e)),t}function importAllRemoveHandler(e,t){return({file:s,content:i,...n})=>{const r=ts.createSourceFile(s,i,ts.ScriptTarget.Latest,!0),a=new Set;for(const e of r.statements)if(ts.isImportEqualsDeclaration(e)&&e.isTypeOnly){const t=e.moduleReference;ts.isExternalModuleReference(t)&&ts.isStringLiteral(t.expression)&&a.add(e.name.text)}const o=transformFunction(t=>{const{factory:i}=t,n=o=>{properties=[...properties,...findProperty(o)];const c={isNamespace:!1,isTypeOnly:!1,isTypeNamespace:!1,source:"",importedString:void 0,importedObject:void 0};if(ts.isTypeReferenceNode(o)&&ts.isQualifiedName(o.typeName)&&ts.isIdentifier(o.typeName.left)&&ts.isIdentifier(o.typeName.right)){const e=o.typeName.left.text,t=o.typeName.right.text;if(typesNames.push(e),e in typeObj?typeObj[e]?.push(t):typeObj[e]=[t],utilities.checkModuleType(r,s).isCommonJs&&"ts"!==e&&!a.has(e))return i.updateTypeReferenceNode(o,i.createIdentifier(t),void 0)}if(ts.isImportDeclaration(o)){const t=o.getText(r);return e.push(t),i.createEmptyStatement()}if(ts.isImportEqualsDeclaration(o)){const t=o.name.text,s=o.moduleReference;let n;if(o.isTypeOnly&&(c.isTypeOnly=!0),c.importedString=t,c.isTypeOnly||properties.includes(t)&&(c.isNamespace=!0),ts.isExternalModuleReference(s)&&ts.isStringLiteral(s.expression)&&(c.source=s.expression.text),c.importedString&&!c.importedObject&&(n=c.isTypeOnly?a.has(c.importedString)?`import type * as ${c.importedString} from "${c.source}";`:typesNames.includes(c.importedString)?`import type { ${typeObj[c.importedString]?.join(",")} } from "${c.source}";`:`import type ${c.importedString} from "${c.source}";`:c.isNamespace&&c.source&&"typescript"!==c.source?`import * as ${c.importedString} from "${c.source}";`:`import ${c.importedString} from "${c.source}";`),!c.importedString&&c.importedObject&&(n=`import { ${c.importedObject.join(", ")} } from "${c.source}";`),n)return e.push(n),i.createEmptyStatement()}if(ts.isVariableStatement(o)){const t=o.declarationList.declarations;if(1===t.length){const s=t[0];if(s.initializer&&ts.isCallExpression(s.initializer)&&ts.isIdentifier(s.initializer.expression)&&"require"===s.initializer.expression.escapedText){const t=s.initializer.arguments[0];if(ts.isStringLiteral(t)&&(c.source=t.text),ts.isIdentifier(s.name)){const e=s.name.text;c.importedString=e,properties.includes(e)&&(c.isNamespace=!0)}else if(ts.isObjectBindingPattern(s.name)){const e=[];for(const t of s.name.elements)ts.isIdentifier(t.name)&&e.push(t.name.text);e.length>0&&(c.importedObject=e)}let n;if(c.importedString&&!c.importedObject&&(n=c.isNamespace?`import * as ${c.importedString} from "${c.source}";`:`import ${c.importedString} from "${c.source}";`),!c.importedString&&c.importedObject&&(n=`import { ${c.importedObject.join(", ")} } from "${c.source}";`),n)return e.push(n),i.createEmptyStatement()}}}return ts.visitEachChild(o,n,t)};return e=>ts.visitNode(e,n)},r,t);return{file:s,content:o,...n}}}const removeHandlers=async(e,t)=>{const s=resolves([[importAllRemoveHandler,e,t],[esmExportRemoveHandler,t]]);return await s.series()};function collectBindingNames(e,t){ts.isIdentifier(e)?t.push(e.text):(ts.isObjectBindingPattern(e)||ts.isArrayBindingPattern(e))&&e.elements.forEach(e=>{ts.isBindingElement(e)&&e.name&&collectBindingNames(e.name,t)})}function clearUnusedCode(e,t,s,i={treatExportsAsUsed:!0}){const n=ts.createSourceFile(t,e,ts.ScriptTarget.Latest,!0),r=new Map,a=new Set,o=(e,t=!1)=>{const s=r.get(e);r.set(e,{exported:!!s?.exported||t})},c=e=>{if(ts.isImportDeclaration(e)&&e.importClause){const t=e.importClause;t.name&&ts.isIdentifier(t.name)&&o(t.name.text,!1),t.namedBindings&&(ts.isNamedImports(t.namedBindings)?t.namedBindings.elements.forEach(e=>{ts.isImportSpecifier(e)&&ts.isIdentifier(e.name)&&o(e.name.text,!1)}):ts.isNamespaceImport(t.namedBindings)&&ts.isIdentifier(t.namedBindings.name)&&o(t.namedBindings.name.text,!1))}else if(ts.isImportEqualsDeclaration(e)&&ts.isIdentifier(e.name))o(e.name.text,!1);else if(ts.isVariableStatement(e)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;e.declarationList.declarations.forEach(e=>{collectBindingNames(e.name,[]);const s=[];collectBindingNames(e.name,s),s.forEach(e=>o(e,t))})}else if(ts.isFunctionDeclaration(e)&&e.name&&ts.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;o(e.name.text,t)}else if(ts.isClassDeclaration(e)&&e.name&&ts.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;o(e.name.text,t)}if(ts.isIdentifier(e)){const t=e.parent;ts.isVariableDeclaration(t)&&t.name===e||ts.isFunctionDeclaration(t)&&t.name===e||ts.isClassDeclaration(t)&&t.name===e||ts.isImportClause(t)&&t.name===e||ts.isImportSpecifier(t)&&t.name===e||ts.isNamespaceImport(t)&&t.name===e||ts.isBindingElement(t)&&t.name===e||ts.isParameter(t)&&t.name===e||a.add(e.text)}ts.forEachChild(e,c)};c(n);const l=new Set;r.forEach((e,t)=>{a.has(t)||i.treatExportsAsUsed&&e.exported||l.add(t)});return transformFunction(e=>{const t=s=>{if(ts.isImportDeclaration(s)&&s.importClause){const e=s.importClause,t=e.name&&ts.isIdentifier(e.name)?e.name.text:void 0;let i;const n=[];e.namedBindings&&(ts.isNamedImports(e.namedBindings)?e.namedBindings.elements.forEach(e=>{ts.isImportSpecifier(e)&&ts.isIdentifier(e.name)&&n.push(e)}):ts.isNamespaceImport(e.namedBindings)&&ts.isIdentifier(e.namedBindings.name)&&(i=e.namedBindings.name.text));const r=!!t&&!l.has(t),a=!!i&&!l.has(i),o=n.filter(e=>!l.has(e.name.text));if(!r&&!a&&0===o.length)return ts.factory.createNotEmittedStatement(s);if(!r&&!!e.name||void 0!==i&&!a||o.length!==n.length){let e;e=o.length>0?ts.factory.createNamedImports(o):a&&i?ts.factory.createNamespaceImport(ts.factory.createIdentifier(i)):void 0;const n=r&&t?ts.factory.createIdentifier(t):void 0,c=ts.factory.createImportClause(!1,n,e);return ts.factory.updateImportDeclaration(s,s.modifiers,c,s.moduleSpecifier,s.assertClause)}return s}if((ts.isFunctionDeclaration(s)||ts.isClassDeclaration(s))&&s.name&&ts.isIdentifier(s.name))return l.has(s.name.text)?ts.factory.createNotEmittedStatement(s):s;if(ts.isVariableStatement(s)){const e=[];s.declarationList.declarations.forEach(t=>collectBindingNames(t.name,e));return e.some(e=>!l.has(e))?s:ts.factory.createNotEmittedStatement(s)}return ts.visitEachChild(s,t,e)};return e=>ts.visitNode(e,t)},n,s)}async function preProcessPluginParser(e,t,s){if(e.length)for(const i of e){const e="function"==typeof i?i():i;"pre-process"===e.type&&(t=e.async?await e.func(t,s):e.func(t,s))}return t}async function preProcessHooksParser(e,t){if(preProcessHooks.length)for(const s of preProcessHooks)e=s.async?await s.func(e,t):s.func(e,t);return e}async function bundler(e){const t="."===e.exportPath?"Main":utilities.splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor.cyan("Bundled")} -> ${tcolor.brightCyan(t)} ${tcolor.cyan("export path")}`);let s=e.depFiles;const i=e.rename,n=e.tsOptions.default,r=e.plugins;let a=[];s=await anonymousHandler(s,n);const o=await removeHandlers(a,n);s=s.map(o[0]);const c=s.slice(0,-1).map(o[1]),l=s.slice(-1),p=/["']((?!\.\/|\.\.\/)[^"']+)["']/;a=a.filter(e=>p.test(e)),a=mergeImportsStatement(a);let m=`${a.join("\n").trim()}\n${c.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}\n${l.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}`;return m=m.replace(/^s*;\s*$/gm,"").trim(),i&&(m=duplicates(m,e.fileName,n)),m=clearUnusedCode(m,e.fileName,n),m=await preProcessPluginParser(r,m),await utilities.wait(1e3),m=await preProcessHooksParser(m),await utilities.wait(1e3),console.timeEnd(`${tcolor.cyan("Bundled")} -> ${tcolor.brightCyan(t)} ${tcolor.cyan("export path")}`),{bundledContent:m,...e}}async function bundle(e){const t=[];for(const s of e.points){const e=await bundler(s);t.push(e)}return{points:t,allowUpdatePackageJson:e.allowUpdatePackageJson}}function createHost(e,t){const s={},i={getSourceFile:(s,i)=>{if(s===t)return ts.createSourceFile(s,e,i)},writeFile:(e,t)=>{s[e]=t},getDefaultLibFileName:e=>ts.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}}const isCjs=e=>e.commonjs&&e.commonjsTypes,isEsm=e=>e.esm&&e.esmTypes;function getExports(e,t){return isCjs(e)&&isEsm(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)}`}}}:isCjs(e)&&!isEsm(e)?{[t]:{require:{types:`./${path.relative(process.cwd(),e.commonjsTypes)}`,default:`./${path.relative(process.cwd(),e.commonjs)}`}}}:!isCjs(e)&&isEsm(e)?{[t]:{import:{types:`./${path.relative(process.cwd(),e.esmTypes)}`,default:`./${path.relative(process.cwd(),e.esm)}`}}}:{}}async function writePackage(e,t){let s=!0;"."!==t&&(s=!1);const i=ts.sys.resolvePath("package.json"),n=fs.readFileSync(i,"utf8"),r=JSON.parse(n);let{name:a,version:o,description:c,main:l,module:p,type:m,types:f,exports:d,...u}=r;await utilities.wait(500),m="module";let y={},g={},h={},x={};if(s)y=e.main?{main:path.relative(process.cwd(),e.main)}:{},g=e.module?{module:path.relative(process.cwd(),e.module)}:{},h=e.types?{types:path.relative(process.cwd(),e.types)}:{},x={exports:{...getExports(e,t)}};else{y=l?{main:l}:{},g=p?{module:p}:{},h=f?{types:f}:{};x={exports:{...d&&"object"==typeof d&&!Array.isArray(d)?{...d}:{},...getExports(e,t)}}}await utilities.wait(1e3);const w={name:a,version:o,description:c,type:m,...y,...h,...g,...x,...u};utilities.writeCompileFile(i,JSON.stringify(w,null,2))}class Compiler{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}}_isUpdate(){return this.object.allowUpdatePackageJson}async _commonjs(e){const t="."===e.exportPath,s=t?"Main":utilities.splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor.cyan("Compiled CJS")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`);const i=e.fileName,n=e.bundledContent,r=e.format,a=e.plugins,o=e.tsOptions.cjs,c=createHost(n,i),l=c.createdFiles,p=c.host;ts.createProgram([i],o,p).emit(),Object.entries(l).map(async([e,s])=>{if(".js"===path.extname(e)&&a.length)for(let t of a)t="function"==typeof t?t():t,"post-process"===t.type&&(s=t.async?await t.func(s,e):t.func(s,e));this._isUpdate()&&(e.match(/.js/g)&&(this.files.commonjs=e.replace(/.js/g,".cjs")),e.match(/.d.ts/g)&&(this.files.commonjsTypes=e.replace(/.d.ts/g,".d.cts")),!t||"both"!==r&&"commonjs"!==r||(this.files.commonjs&&(this.files.main=this.files.commonjs),this.files.commonjsTypes&&(this.files.types=this.files.commonjsTypes))),e=(e=(e=e.replace(/.js/g,".cjs")).replace(/.map.js/g,".map.cjs")).replace(/.d.ts/g,".d.cts"),await utilities.wait(500),"commonjs"===r&&await utilities.clearFolder(path.dirname(e)),await utilities.writeCompileFile(e,s)}),console.timeEnd(`${tcolor.cyan("Compiled CJS")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`)}async _esm(e){const t="."===e.exportPath,s=t?"Main":utilities.splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor.cyan("Compiled ESM")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`);const i=e.fileName,n=e.bundledContent,r=e.format,a=e.plugins,o=e.tsOptions.esm,c=createHost(n,i),l=c.createdFiles,p=c.host;ts.createProgram([i],o,p).emit(),Object.entries(l).map(async([e,s])=>{if(".js"===path.extname(e)&&a.length)for(let t of a)t="function"==typeof t?t():t,"post-process"===t.type&&(s=t.async?await t.func(s,e):t.func(s,e));this._isUpdate()&&(e.match(/.js/g)&&(this.files.esm=e.replace(/.js/g,".mjs")),e.match(/.d.ts/g)&&(this.files.esmTypes=e.replace(/.d.ts/g,".d.mts")),t&&"both"===r&&this.files.esm&&(this.files.module=this.files.esm)),e=(e=(e=e.replace(/.js/g,".mjs")).replace(/.map.js/g,".map.mjs")).replace(/.d.ts/g,".d.mts"),await utilities.wait(500),"commonjs"!==r&&await utilities.clearFolder(path.dirname(e)),await utilities.writeCompileFile(e,s)}),console.timeEnd(`${tcolor.cyan("Compiled ESM")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`)}async compile(){for(const e of this.object.points){switch(await utilities.wait(500),e.format){case"commonjs":await this._commonjs(e),this._isUpdate()&&await writePackage(this.files,e.exportPath);break;case"esm":await this._esm(e),this._isUpdate()&&await writePackage(this.files,e.exportPath);break;case"both":await this._esm(e),await utilities.wait(1e3),await this._commonjs(e),this._isUpdate()&&await writePackage(this.files,e.exportPath)}await utilities.wait(500)}}}async function susee(){console.info(`${tcolor.cyan("Susee Started")} : `),console.time(`${tcolor.cyan("Susee Done")}`);const e=await initializer();await utilities.wait(1e3);const t=await bundle(e);await utilities.wait(1e3);const s=new Compiler(t);await s.compile(),console.timeEnd(`${tcolor.cyan("Susee Done")}`)}export{susee};
8
+ import TsConfig from"@suseejs/tsconfig";import fs from"node:fs";import mhaehko from"mhaehko";import path from"node:path";import process from"node:process";import resolves from"@suseejs/resolves";import tcolor from"@suseejs/tcolor";import transformFunction from"@suseejs/transformer";import ts from"typescript";import utils from"@suseejs/utils";import{Buffer}from"node:buffer";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, 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 , 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))}async function finalSuseeConfig(){const e=getConfigPath();void 0===e&&(console.error(tcolor.magenta('No susee.config file ("susee.config.ts", "susee.config.js", "susee.config.mjs") found')),ts.sys.exit(1));const t=(await import(e)).default,s=resolves([[checkEntries,t.entryPoints]]);await s.series();const i=t.outDir??"dist",n=[];for(const e of t.entryPoints){const t={entry:e.entry,exportPath:e.exportPath,format:e.format??["esm"],tsconfigFilePath:e.tsconfigFilePath??void 0,renameDuplicates:e.renameDuplicates??!0,outDirPath:"."===e.exportPath?i:`${i}${e.exportPath.slice(1)}`};n.push(t)}return{points:n,plugins:t.plugins??[],allowUpdatePackageJson:t.allowUpdatePackageJson??!1,outDir:i}}class CompilerOptions{constructor(e){this._point=e,this._options={}}__init(){const e=new TsConfig(this._point.tsconfigFilePath);e.removeCompilerOption("rootDir"),e.removeCompilerOption("module"),e.editCompilerOptions({moduleResolution:ts.ModuleResolutionKind.NodeNext,outDir:this._point.outDirPath,allowJs:!0}),this._options=e.getCompilerOptions()}__init2(){this.__init();let{types:e,lib:t,...s}=this._options;return e?e.includes("node")||(e=["node",...e]):e=["node"],t=t?[...new Set(["ESNext",...t])]:["ESNext"],{types:e,lib:t,...s}}get commonjs(){const e=this.__init2(),{module:t,...s}=e;return{module:ts.ModuleKind.CommonJS,...s}}get esm(){const e=this.__init2(),{module:t,...s}=e;return{module:ts.ModuleKind.ES2020,...s}}get default(){return this.__init2()}}function compilerOptions(e){return new CompilerOptions(e)}async function fileSizes(e){const t=await fs.promises.stat(e);return{logical:t.size,allocated:null!==t.blocks?512*t.blocks:null}}const checkExport=(e,t)=>!!(e.match(/export default .*/gm)||e.match(/export = .*/gm)&&t.match(/.cts/g));function isJsxContent(e){const t=ts.createSourceFile("file.tsx",e,ts.ScriptTarget.Latest,!0,ts.ScriptKind.TSX);let s=!1;return function e(t){ts.isJsxElement(t)||ts.isJsxSelfClosingElement(t)||ts.isJsxFragment(t)?s=!0:ts.forEachChild(t,e)}(t),s}async function generateDependencies(e){const t=(await mhaehko(e)).sort(),s=[];for(const e of t){const t=ts.sys.resolvePath(e),i=await fs.promises.readFile(t,"utf8"),n=path.extname(t),r=await fileSizes(t),a=i.length,o=checkExport(i,t),c=ts.createSourceFile(t,i,ts.ScriptTarget.Latest,!0),l=utils.check.moduleType(c,t).isCommonJs?"cjs":"esm",p={file:t,content:i,length:a,includeDefExport:o,size:{logical:r.logical,allocated:r.allocated,utf8:(new TextEncoder).encode(i).length,buffBytes:Buffer.byteLength(i,"utf8")},moduleType:l,fileExt:n,isJsx:isJsxContent(i)};s.push(p)}return s}function _typesCheck(e,t){if(!t.noCheck){const s=e.map(e=>e.file);let i=!1;const n=ts.createProgram(s,t);for(const e of s){const t=n.getSourceFile(e);t||(console.error(tcolor.magenta(`File not found: ${e}`)),ts.sys.exit(1));const s=[...n.getSyntacticDiagnostics(t),...n.getSemanticDiagnostics(t),...n.getDeclarationDiagnostics(t)];if(s.length>0){const e={getCurrentDirectory:()=>process.cwd(),getCanonicalFileName:e=>e,getNewLine:()=>ts.sys.newLine};console.error(ts.formatDiagnosticsWithColorAndContext(s,e)),i=!0}}if(!i)return!0;ts.sys.exit(1)}}async function typeCheck(e,t){const s=resolves([[_typesCheck,e,t]]);return(await s.series())[0]}async function depPluginParser(e,t,s){if(t.length)for(const i of t){const t="function"==typeof i?i():i;"dependency"===t.type&&(e=t.async?await t.func(e,s):t.func(e,s))}return e}async function initializer(){const e=await finalSuseeConfig(),t=e.points,s=e.plugins,i=[];for(const e of t){const t=compilerOptions(e);let n=await generateDependencies(e.entry);await typeCheck(n,t.esm)||ts.sys.exit(1),n=await depPluginParser(n,s,t.default);const r={fileName:e.entry,exportPath:e.exportPath,format:e.format,rename:e.renameDuplicates,outDir:e.outDirPath,tsOptions:{cjs:t.commonjs,esm:t.esm,default:t.default},depFiles:n,plugins:s};i.push(r)}return{points:i,allowUpdatePackageJson:e.allowUpdatePackageJson}}const exportDefaultExportNameMap=[],exportDefaultImportNameMap=[],prefixKey="AnonymousName",createAnonymousNameGenerator=()=>utils.uniqueName().setPrefix({key:prefixKey,value:"__anonymous__"});let genName=createAnonymousNameGenerator();const resetAnonymousState=()=>{exportDefaultExportNameMap.length=0,exportDefaultImportNameMap.length=0,genName=createAnonymousNameGenerator()};function anonymousCallExpressionHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=n=>{if(ts.isCallExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateCallExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts.isPropertyAccessExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updatePropertyAccessExpression(n,s.createIdentifier(i.newName),n.name)}}else if(ts.isNewExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateNewExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts.isExportSpecifier(n)&&ts.isIdentifier(n.name)){const e=n.name.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateExportSpecifier(n,n.isTypeOnly,n.propertyName,s.createIdentifier(i.newName))}return ts.visitEachChild(n,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}function anonymousExportHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=r=>{const a=path.basename(t).split(".")[0];if((ts.isFunctionDeclaration(r)||ts.isClassDeclaration(r))&&void 0===r.name){let e=!1,t=!1;if(r.modifiers?.forEach(s=>{s.kind===ts.SyntaxKind.ExportKeyword&&(e=!0),s.kind===ts.SyntaxKind.DefaultKeyword&&(t=!0)}),e&&t){const e=genName.getName(prefixKey,a);if(exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),ts.isFunctionDeclaration(r))return s.updateFunctionDeclaration(r,r.modifiers,r.asteriskToken,s.createIdentifier(e),r.typeParameters,r.parameters,r.type,r.body);if(ts.isClassDeclaration(r))return s.updateClassDeclaration(r,r.modifiers,s.createIdentifier(e),r.typeParameters,r.heritageClauses,r.members)}}else if(ts.isExportAssignment(r)&&!r.name&&!r.isExportEquals){if(ts.isArrowFunction(r.expression)){const e=genName.getName(prefixKey,a),t=s.createArrowFunction(r.expression.modifiers,r.expression.typeParameters,r.expression.parameters,r.expression.type,r.expression.equalsGreaterThanToken,r.expression.body),i=s.createVariableDeclaration(s.createIdentifier(e),r.expression.exclamationToken,r.expression.type,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(r.expression.modifiers,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isObjectLiteralExpression(r.expression)){const e=genName.getName(prefixKey,a),t=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,r.expression),i=s.createVariableDeclarationList([t],ts.NodeFlags.Const),o=s.createVariableStatement(void 0,i),c=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[o,c],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isArrayLiteralExpression(r.expression)){const e=genName.getName(prefixKey,a),t=s.createArrayLiteralExpression(r.expression.elements,!0),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isStringLiteral(r.expression)){const e=genName.getName(prefixKey,a),t=s.createStringLiteral(r.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isNumericLiteral(r.expression)){const e=genName.getName(prefixKey,a),t=s.createNumericLiteral(r.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}}return ts.visitEachChild(r,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}function anonymousImportHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=r=>{if(ts.isImportDeclaration(r)){const e=r.moduleSpecifier.getText(n),i=path.basename(e).split(".")[0].trim();if(r.importClause?.name&&ts.isIdentifier(r.importClause.name)){const e=r.importClause.name.text.trim(),n=exportDefaultExportNameMap.find(e=>e.file===i);if(n){exportDefaultImportNameMap.push({base:e,file:t,newName:n.newName,isEd:!0});const i=s.updateImportClause(r.importClause,r.importClause.phaseModifier,s.createIdentifier(n.newName),r.importClause.namedBindings);return s.updateImportDeclaration(r,r.modifiers,i,r.moduleSpecifier,r.attributes)}}}return ts.visitEachChild(r,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}const anonymousHandler=async(e,t)=>{resetAnonymousState();const s=resolves([[anonymousExportHandler,t],[anonymousImportHandler,t],[anonymousCallExpressionHandler,t]]),i=await s.concurrent();for(const t of i)e=e.map(t);return e},namesMap=new Map,callNameMap=[],importNameMap=[],exportNameMap=[];function __uniqueName(){const e=new Map;return{setPrefix({key:t,value:s}){const i=[];let n;if(e.has(t))throw console.warn(`${t} already exist`),new Error;return n=s,e.set(t,s),{getName:function(e){const t=i.length,s=n?`${n}${e}_${t+1}`:`$nyein${e}_${t+1}`;return i.push(s),s}}},getPrefix(t){if(e.has(t))return e.get(t)}}}let dupName=__uniqueName().setPrefix({key:"DuplicatesNames",value:"__duplicatesNames__"});const resetDuplicateState=()=>{namesMap.clear(),callNameMap.length=0,importNameMap.length=0,exportNameMap.length=0,dupName=__uniqueName().setPrefix({key:"DuplicatesNames",value:"__duplicatesNames__"})},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=ts.isStringLiteral(e)?e.text:e.getText(t).replace(/^['"]|['"]$/g,""),i.startsWith(".")||i.startsWith("/")){const e=path.dirname(s);return normalizePathKey(path.resolve(e,i))}return i},callExpression=e=>({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=e=>{const s=callNameMap.find(s=>s.base===e&&s.file===t),i=importNameMap.find(s=>s.base===e&&s.file===t);return s?s.newName:i?i.newName:null},n=t=>{if(ts.isCallExpression(t)){if(ts.isIdentifier(t.expression)){const e=i(t.expression.text);if(e)return s.updateCallExpression(t,s.createIdentifier(e),t.typeArguments,t.arguments)}}else if(ts.isPropertyAccessExpression(t)){if(ts.isIdentifier(t.expression)){const e=i(t.expression.text);if(e)return s.updatePropertyAccessExpression(t,s.createIdentifier(e),t.name)}}else if(ts.isNewExpression(t)){if(ts.isIdentifier(t.expression)){const e=i(t.expression.text);if(e)return s.updateNewExpression(t,s.createIdentifier(e),t.typeArguments,t.arguments)}}else if(ts.isIdentifier(t)&&!(e=>{const t=e.parent;return!!(t&&(ts.isVariableDeclaration(t)&&t.name===e||(ts.isFunctionDeclaration(t)||ts.isClassDeclaration(t)||ts.isInterfaceDeclaration(t)||ts.isTypeAliasDeclaration(t)||ts.isEnumDeclaration(t)||ts.isParameter(t)||ts.isBindingElement(t)||ts.isImportClause(t)||ts.isNamespaceImport(t)||ts.isImportSpecifier(t)||ts.isExportSpecifier(t)||ts.isTypeParameterDeclaration(t))&&t.name===e||(ts.isPropertyDeclaration(t)||ts.isMethodDeclaration(t))&&t.name===e))})(t)){if(ts.isPropertyAccessExpression(t.parent)&&t.parent.name===t)return t;if(ts.isPropertyAssignment(t.parent)&&t.parent.name===t)return t;const e=i(t.text);if(e)return ts.isShorthandPropertyAssignment(t.parent)&&t.parent.name===t?s.createPropertyAssignment(s.createIdentifier(t.text),s.createIdentifier(e)):s.createIdentifier(e)}return ts.visitEachChild(t,n,e)};return e=>ts.visitNode(e,n)},n,e);return{file:t,content:r,...i}},exportExpression=e=>({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=n=>{if(ts.isExportSpecifier(n)){if(ts.isIdentifier(n.name)){const e=n.name.text;let i=null;const r=callNameMap.find(s=>s.base===e&&s.file===t),a=importNameMap.find(s=>s.base===e&&s.file===t);if(r?(exportNameMap.push({base:e,file:getFileKey(t),newName:r.newName}),i=r.newName):a&&(i=a.newName),i)return s.updateExportSpecifier(n,n.isTypeOnly,n.propertyName,s.createIdentifier(i))}}else if(ts.isExportAssignment(n)){const e=n.expression;if(ts.isIdentifier(e)){const i=e.text;let r=null;const a=callNameMap.find(e=>e.base===i&&e.file===t),o=importNameMap.find(e=>e.base===i&&e.file===t);if(a?(exportNameMap.push({base:i,file:getFileKey(t),newName:a.newName}),r=a.newName):o&&(r=o.newName),r)return s.updateExportAssignment(n,n.modifiers,s.createIdentifier(r))}}return ts.visitEachChild(n,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}},importExpression=e=>({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=r=>{if(ts.isImportDeclaration(r)){const e=getModuleKeyFromSpecifier(r.moduleSpecifier,n,t);let i=[];if(r.importClause?.namedBindings&&ts.isNamedImports(r.importClause.namedBindings)&&(i=r.importClause.namedBindings.elements.map(e=>e.name.text.trim())),r.importClause?.name&&ts.isIdentifier(r.importClause.name)){const i=r.importClause.name.text.trim(),n=exportNameMap.find(t=>t.base===i&&t.file===e);if(n){importNameMap.push({base:n.base,file:t,newName:n.newName});const e=s.updateImportClause(r.importClause,r.importClause.phaseModifier,s.createIdentifier(n.newName),r.importClause.namedBindings);return s.updateImportDeclaration(r,r.modifiers,e,r.moduleSpecifier,r.attributes)}}if(i.length>0&&r.importClause&&r.importClause.namedBindings&&ts.isNamedImports(r.importClause.namedBindings)){const i=r.importClause.namedBindings.elements.map(i=>{const n=exportNameMap.find(t=>t.base===i.name.text.trim()&&t.file===e);return n?(importNameMap.push({base:n.base,file:t,newName:n.newName}),s.updateImportSpecifier(i,i.isTypeOnly,i.propertyName,s.createIdentifier(n.newName))):i}),n=s.updateNamedImports(r.importClause.namedBindings,i),a=s.updateImportClause(r.importClause,r.importClause.phaseModifier,r.importClause.name,n);return s.updateImportDeclaration(r,r.modifiers,a,r.moduleSpecifier,r.attributes)}}return ts.visitEachChild(r,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}},collector=e=>({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{function s(i,n=!0){if(n)if(ts.isVariableStatement(i))i.declarationList.declarations.forEach(e=>{if(ts.isIdentifier(e.name)){const s=e.name.text;namesMap.has(s)?namesMap.get(s).add({file:t}):namesMap.set(s,new Set([{file:t}]))}});else if(ts.isFunctionDeclaration(i)||ts.isClassDeclaration(i)||ts.isEnumDeclaration(i)||ts.isInterfaceDeclaration(i)||ts.isTypeAliasDeclaration(i)){const e=i.name?.text;e&&(namesMap.has(e)?namesMap.get(e).add({file:t}):namesMap.set(e,new Set([{file:t}])))}return ts.isBlock(i)||ts.isFunctionDeclaration(i)||ts.isFunctionExpression(i)||ts.isArrowFunction(i)||ts.isMethodDeclaration(i)||ts.isClassDeclaration(i)?(ts.isBlock(i)?ts.visitNodes(i.statements,e=>s(e,!1)):ts.forEachChild(i,e=>{s(e,!1)}),i):ts.visitEachChild(i,e=>s(e,n),e)}return e=>s(e,!0)},n,e);return{file:t,content:r,...i}},updater=e=>({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=n=>{if(ts.isVariableStatement(n)){const e=n.declarationList.declarations.map(e=>{if(ts.isIdentifier(e.name)){const i=e.name.text;if(namesMap.has(i)&&namesMap.get(i).size>1){const n=dupName.getName(i);return callNameMap.push({base:i,file:t,newName:n}),s.updateVariableDeclaration(e,s.createIdentifier(n),e.exclamationToken,e.type,e.initializer)}}return e}),i=s.updateVariableDeclarationList(n.declarationList,e);return s.updateVariableStatement(n,n.modifiers,i)}if(ts.isFunctionDeclaration(n)){if(n.name&&ts.isIdentifier(n.name)){const e=n.name.text;if(namesMap.has(e)&&namesMap.get(e).size>1){const i=dupName.getName(e);return callNameMap.push({base:e,file:t,newName:i}),s.updateFunctionDeclaration(n,n.modifiers,n.asteriskToken,s.createIdentifier(i),n.typeParameters,n.parameters,n.type,n.body)}}}else if(ts.isClassDeclaration(n)&&n.name&&ts.isIdentifier(n.name)){const e=n.name.text;if(namesMap.has(e)&&namesMap.get(e).size>1){const i=dupName.getName(e);return callNameMap.push({base:e,file:t,newName:i}),s.updateClassDeclaration(n,n.modifiers,s.createIdentifier(i),n.typeParameters,n.heritageClauses,n.members)}}return ts.visitEachChild(n,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}},duplicateHandlers={renamed:async(e,t)=>{resetDuplicateState();const s=resolves([[collector,t],[updater,t],[callExpression,t],[exportExpression,t],[importExpression,t],[callExpression,t],[exportExpression,t]]),i=await s.concurrent();for(const t of i)e=e.map(t);return e},notRenamed:async(e,t)=>{resetDuplicateState();let s=!1;const i=resolves([[collector,namesMap,t]]),n=await i.concurrent();return e.map(n[0]),await utils.wait(1e3),namesMap.forEach((e,t)=>{e.size>1&&(s=!0,console.warn(`Name -> ${t} declared in multiple files :`),e.forEach(e=>console.warn(` - ${e.file}`)))}),await utils.wait(500),s&&process.exit(1),e}};function mergeImportsStatement(e){const t=new Map,s=new Map,i=new Map,n=new Map,r=new Map;for(const a of e){const e=a.match(/import\s+(?:type\s+)?(?:(.*?)\s+from\s+)?["']([^"']+)["'];?/);if(!e)continue;const[,o,c]=e,l=a.includes("import type"),p=c;if(!o){const e=a.match(/import\s+(?:type\s+)?(\w+)/);if(e){const t=e[1],s=l?n:i;s.has(p)||s.set(p,new Set),s.get(p)?.add(t)}continue}if(o.startsWith("{")){const e=l?s:t;e.has(p)||e.set(p,new Set);o.replace(/[{}]/g,"").split(",").map(e=>e.trim()).filter(Boolean).forEach(t=>e.get(p)?.add(t))}else if(o.startsWith("* as")){const e=o.match(/\*\s+as\s+(\w+)/);if(e){const t=e[1];r.has(p)||r.set(p,new Set),r.get(p)?.add(t)}}else{const e=l?n:i;e.has(p)||e.set(p,new Set),e.get(p)?.add(o.trim())}}const a=[];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(", ");a.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(", ");a.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(", ");a.push(`import ${t} from "${e}";`)}}for(const[e,t]of n)if(!i.has(e)&&t.size>0){const s=Array.from(t).join(", ");a.push(`import type ${s} from "${e}";`)}for(const[e,t]of r)if(t.size>0){const s=Array.from(t).join(", ");a.push(`import * as ${s} from "${e}";`)}return a.sort()}function esmExportRemoveHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0);return{file:t,content:transformFunction(e=>{const{factory:t}=e,s=i=>{if(!utils.check.isInsideNamespace(i)&&(ts.isFunctionDeclaration(i)||ts.isClassDeclaration(i)||ts.isInterfaceDeclaration(i)||ts.isTypeAliasDeclaration(i)||ts.isEnumDeclaration(i)||ts.isVariableStatement(i))){const e=i.modifiers?.filter(e=>e.kind!==ts.SyntaxKind.ExportKeyword&&e.kind!==ts.SyntaxKind.DefaultKeyword);if(e?.length!==i.modifiers?.length){if(ts.isFunctionDeclaration(i))return t.updateFunctionDeclaration(i,e,i.asteriskToken,i.name,i.typeParameters,i.parameters,i.type,i.body);if(ts.isClassDeclaration(i))return t.updateClassDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts.isInterfaceDeclaration(i))return t.updateInterfaceDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts.isTypeAliasDeclaration(i))return t.updateTypeAliasDeclaration(i,e,i.name,i.typeParameters,i.type);if(ts.isEnumDeclaration(i))return t.updateEnumDeclaration(i,e,i.name,i.members);if(ts.isVariableStatement(i))return t.updateVariableStatement(i,e,i.declarationList)}}if(ts.isExportDeclaration(i))return t.createEmptyStatement();if(ts.isExportAssignment(i)){const e=i.expression;if(ts.isIdentifier(e))return t.createEmptyStatement()}return ts.visitEachChild(i,s,e)};return e=>ts.visitNode(e,s)},n,e),...i}}}let properties=[];const typeObj={},typesNames=[];function findProperty(e){const t=[];return ts.isPropertyAccessExpression(e)&&ts.isIdentifier(e.expression)&&t.push(e.expression.text),e.forEachChild(e=>findProperty(e)),t}function importAllRemoveHandler(e,t){return({file:s,content:i,...n})=>{const r=ts.createSourceFile(s,i,ts.ScriptTarget.Latest,!0),a=new Set;for(const e of r.statements)if(ts.isImportEqualsDeclaration(e)&&e.isTypeOnly){const t=e.moduleReference;ts.isExternalModuleReference(t)&&ts.isStringLiteral(t.expression)&&a.add(e.name.text)}const o=transformFunction(t=>{const{factory:i}=t,n=o=>{properties=[...properties,...findProperty(o)];const c={isNamespace:!1,isTypeOnly:!1,isTypeNamespace:!1,source:"",importedString:void 0,importedObject:void 0};if(ts.isTypeReferenceNode(o)&&ts.isQualifiedName(o.typeName)&&ts.isIdentifier(o.typeName.left)&&ts.isIdentifier(o.typeName.right)){const e=o.typeName.left.text,t=o.typeName.right.text;if(typesNames.push(e),e in typeObj?typeObj[e]?.push(t):typeObj[e]=[t],utils.check.moduleType(r,s).isCommonJs&&"ts"!==e&&!a.has(e))return i.updateTypeReferenceNode(o,i.createIdentifier(t),void 0)}if(ts.isImportDeclaration(o)){const t=o.getText(r);return e.push(t),i.createEmptyStatement()}if(ts.isImportEqualsDeclaration(o)){const t=o.name.text,s=o.moduleReference;let n;if(o.isTypeOnly&&(c.isTypeOnly=!0),c.importedString=t,c.isTypeOnly||properties.includes(t)&&(c.isNamespace=!0),ts.isExternalModuleReference(s)&&ts.isStringLiteral(s.expression)&&(c.source=s.expression.text),c.importedString&&!c.importedObject&&(n=c.isTypeOnly?a.has(c.importedString)?`import type * as ${c.importedString} from "${c.source}";`:typesNames.includes(c.importedString)?`import type { ${typeObj[c.importedString]?.join(",")} } from "${c.source}";`:`import type ${c.importedString} from "${c.source}";`:c.isNamespace&&c.source&&"typescript"!==c.source?`import * as ${c.importedString} from "${c.source}";`:`import ${c.importedString} from "${c.source}";`),!c.importedString&&c.importedObject&&(n=`import { ${c.importedObject.join(", ")} } from "${c.source}";`),n)return e.push(n),i.createEmptyStatement()}if(ts.isVariableStatement(o)){const t=o.declarationList.declarations;if(1===t.length){const s=t[0];if(s.initializer&&ts.isCallExpression(s.initializer)&&ts.isIdentifier(s.initializer.expression)&&"require"===s.initializer.expression.escapedText){const t=s.initializer.arguments[0];if(ts.isStringLiteral(t)&&(c.source=t.text),ts.isIdentifier(s.name)){const e=s.name.text;c.importedString=e,properties.includes(e)&&(c.isNamespace=!0)}else if(ts.isObjectBindingPattern(s.name)){const e=[];for(const t of s.name.elements)ts.isIdentifier(t.name)&&e.push(t.name.text);e.length>0&&(c.importedObject=e)}let n;if(c.importedString&&!c.importedObject&&(n=c.isNamespace?`import * as ${c.importedString} from "${c.source}";`:`import ${c.importedString} from "${c.source}";`),!c.importedString&&c.importedObject&&(n=`import { ${c.importedObject.join(", ")} } from "${c.source}";`),n)return e.push(n),i.createEmptyStatement()}}}return ts.visitEachChild(o,n,t)};return e=>ts.visitNode(e,n)},r,t);return{file:s,content:o,...n}}}const removeHandlers=async(e,t)=>{const s=resolves([[importAllRemoveHandler,e,t],[esmExportRemoveHandler,t]]);return await s.series()};function collectBindingNames(e,t){ts.isIdentifier(e)?t.push(e.text):(ts.isObjectBindingPattern(e)||ts.isArrayBindingPattern(e))&&e.elements.forEach(e=>{ts.isBindingElement(e)&&e.name&&collectBindingNames(e.name,t)})}function clearUnusedCode(e,t,s,i={treatExportsAsUsed:!0}){const n=ts.createSourceFile(t,e,ts.ScriptTarget.Latest,!0),r=new Map,a=new Set,o=(e,t=!1)=>{const s=r.get(e);r.set(e,{exported:!!s?.exported||t})},c=e=>{if(ts.isImportDeclaration(e)&&e.importClause){const t=e.importClause;t.name&&ts.isIdentifier(t.name)&&o(t.name.text,!1),t.namedBindings&&(ts.isNamedImports(t.namedBindings)?t.namedBindings.elements.forEach(e=>{ts.isImportSpecifier(e)&&ts.isIdentifier(e.name)&&o(e.name.text,!1)}):ts.isNamespaceImport(t.namedBindings)&&ts.isIdentifier(t.namedBindings.name)&&o(t.namedBindings.name.text,!1))}else if(ts.isImportEqualsDeclaration(e)&&ts.isIdentifier(e.name))o(e.name.text,!1);else if(ts.isVariableStatement(e)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;e.declarationList.declarations.forEach(e=>{collectBindingNames(e.name,[]);const s=[];collectBindingNames(e.name,s),s.forEach(e=>o(e,t))})}else if(ts.isFunctionDeclaration(e)&&e.name&&ts.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;o(e.name.text,t)}else if(ts.isClassDeclaration(e)&&e.name&&ts.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;o(e.name.text,t)}if(ts.isIdentifier(e)){const t=e.parent;ts.isVariableDeclaration(t)&&t.name===e||ts.isFunctionDeclaration(t)&&t.name===e||ts.isClassDeclaration(t)&&t.name===e||ts.isImportClause(t)&&t.name===e||ts.isImportSpecifier(t)&&t.name===e||ts.isNamespaceImport(t)&&t.name===e||ts.isBindingElement(t)&&t.name===e||ts.isParameter(t)&&t.name===e||a.add(e.text)}ts.forEachChild(e,c)};c(n);const l=new Set;r.forEach((e,t)=>{a.has(t)||i.treatExportsAsUsed&&e.exported||l.add(t)});return transformFunction(e=>{const t=s=>{if(ts.isImportDeclaration(s)&&s.importClause){const e=s.importClause,t=e.name&&ts.isIdentifier(e.name)?e.name.text:void 0;let i;const n=[];e.namedBindings&&(ts.isNamedImports(e.namedBindings)?e.namedBindings.elements.forEach(e=>{ts.isImportSpecifier(e)&&ts.isIdentifier(e.name)&&n.push(e)}):ts.isNamespaceImport(e.namedBindings)&&ts.isIdentifier(e.namedBindings.name)&&(i=e.namedBindings.name.text));const r=!!t&&!l.has(t),a=!!i&&!l.has(i),o=n.filter(e=>!l.has(e.name.text));if(!r&&!a&&0===o.length)return ts.factory.createNotEmittedStatement(s);if(!r&&!!e.name||void 0!==i&&!a||o.length!==n.length){let e;e=o.length>0?ts.factory.createNamedImports(o):a&&i?ts.factory.createNamespaceImport(ts.factory.createIdentifier(i)):void 0;const n=r&&t?ts.factory.createIdentifier(t):void 0,c=ts.factory.createImportClause(!1,n,e);return ts.factory.updateImportDeclaration(s,s.modifiers,c,s.moduleSpecifier,s.assertClause)}return s}if((ts.isFunctionDeclaration(s)||ts.isClassDeclaration(s))&&s.name&&ts.isIdentifier(s.name))return l.has(s.name.text)?ts.factory.createNotEmittedStatement(s):s;if(ts.isVariableStatement(s)){const e=[];s.declarationList.declarations.forEach(t=>collectBindingNames(t.name,e));return e.some(e=>!l.has(e))?s:ts.factory.createNotEmittedStatement(s)}return ts.visitEachChild(s,t,e)};return e=>ts.visitNode(e,t)},n,s)}async function preProcessPluginParser(e,t,s){if(e.length)for(const i of e){const e="function"==typeof i?i():i;"pre-process"===e.type&&(t=e.async?await e.func(t,s):e.func(t,s))}return t}async function bundler(e){"."===e.exportPath||utils.str.splitCamelCase(e.exportPath.slice(2));console.time(` > ${tcolor.cyan("Bundled")} -> ${tcolor.cyan(`export path(${tcolor.magenta(`"${e.exportPath}"`)})`)} `);let t=e.depFiles;const s=e.rename,i=e.tsOptions.default,n=e.plugins;let r=[];t=await anonymousHandler(t,i),t=s?await duplicateHandlers.renamed(t,i):await duplicateHandlers.notRenamed(t,i);const a=await removeHandlers(r,i);t=t.map(a[0]);const o=t.slice(0,-1).map(a[1]),c=t.slice(-1),l=/["']((?!\.\/|\.\.\/)[^"']+)["']/;r=r.filter(e=>l.test(e)),r=mergeImportsStatement(r);let p=`${r.join("\n").trim()}\n${o.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}\n${c.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}`;return p=p.replace(/^s*;\s*$/gm,"").trim(),p=clearUnusedCode(p,e.fileName,i),p=await preProcessPluginParser(n,p),console.timeEnd(` > ${tcolor.cyan("Bundled")} -> ${tcolor.cyan(`export path(${tcolor.magenta(`"${e.exportPath}"`)})`)} `),{bundledContent:p,...e}}async function bundle(e){const t=[];for(const s of e.points){const e=await bundler(s);t.push(e)}return{points:t,allowUpdatePackageJson:e.allowUpdatePackageJson}}function createHost(e,t){const s={},i={getSourceFile:(s,i)=>{if(s===t)return ts.createSourceFile(s,e,i)},writeFile:(e,t)=>{s[e]=t},getDefaultLibFileName:e=>ts.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}}const isCjs=e=>e.commonjs&&e.commonjsTypes,isEsm=e=>e.esm&&e.esmTypes;function getExports(e,t){return isCjs(e)&&isEsm(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)}`}}}:isCjs(e)&&!isEsm(e)?{[t]:{require:{types:`./${path.relative(process.cwd(),e.commonjsTypes)}`,default:`./${path.relative(process.cwd(),e.commonjs)}`}}}:!isCjs(e)&&isEsm(e)?{[t]:{import:{types:`./${path.relative(process.cwd(),e.esmTypes)}`,default:`./${path.relative(process.cwd(),e.esm)}`}}}:{}}async function writePackage(e,t){let s=!0;"."!==t&&(s=!1);const i=ts.sys.resolvePath("package.json"),n=fs.readFileSync(i,"utf8"),r=JSON.parse(n);let{name:a,version:o,description:c,main:l,module:p,type:m,types:f,exports:u,...d}=r;m="module";let y={},g={},h={},x={};if(s)y=e.main?{main:path.relative(process.cwd(),e.main)}:{},g=e.module?{module:path.relative(process.cwd(),e.module)}:{},h=e.types?{types:path.relative(process.cwd(),e.types)}:{},x={exports:{...getExports(e,t)}};else{y=l?{main:l}:{},g=p?{module:p}:{},h=f?{types:f}:{};x={exports:{...u&&"object"==typeof u&&!Array.isArray(u)?{...u}:{},...getExports(e,t)}}}const N={name:a,version:o,description:c,type:m,...y,...h,...g,...x,...d};await utils.file.writeFile(i,JSON.stringify(N,null,2))}const resolveSourceMappingURL=(e,t,s)=>{const i=path.extname(e),n=path.basename(e).split(".")[0],r=new RegExp(`${n}.js.map`,"gm"),a=new RegExp(`${n}.d.ts.map`,"gm"),o="cjs"===s?`${n}.cjs.map`:`${n}.mjs.map`,c="cjs"===s?`${n}.d.cts.map`:`${n}.d.mts.map`;return".js"===i?t.replace(r,o):t.replace(a,c)},postProcessPluginParser=async(e,t,s)=>{if(".js"===path.extname(s)&&e.length)for(let i of e)i="function"==typeof i?i():i,"post-process"===i.type&&(t=i.async?await i.func(t,s):i.func(t,s));return t};class Compiler{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}}_isUpdate(){return this.object.allowUpdatePackageJson}async _commonjs(e){const t="."===e.exportPath;console.time(` ${tcolor.cyan("Compiled commonjs")} -> ${tcolor.cyan(`export path(${tcolor.magenta(`"${e.exportPath}"`)})`)} `);const s=e.fileName,i=e.bundledContent,n=[...new Set(e.format)],r=e.tsOptions.cjs,a=createHost(i,s),o=a.createdFiles,c=a.host;ts.createProgram([s],r,c).emit(),Object.entries(o).map(async([s,i])=>{i=await postProcessPluginParser(e.plugins,i,s),i=resolveSourceMappingURL(s,i,"cjs"),this._isUpdate()&&(s.match(/.js/g)&&(this.files.commonjs=s.replace(/.js/g,".cjs")),s.match(/.d.ts/g)&&(this.files.commonjsTypes=s.replace(/.d.ts/g,".d.cts")),t&&n.includes("commonjs")&&(this.files.commonjs&&(this.files.main=this.files.commonjs),this.files.commonjsTypes&&(this.files.types=this.files.commonjsTypes))),s=(s=(s=s.replace(/.js/g,".cjs")).replace(/.map.js/g,".map.cjs")).replace(/.d.ts/g,".d.cts"),n.includes("commonjs")&&!n.includes("esm")&&await utils.file.clearFolder(path.dirname(s)),await utils.file.writeFile(s,i)}),console.timeEnd(` ${tcolor.cyan("Compiled commonjs")} -> ${tcolor.cyan(`export path(${tcolor.magenta(`"${e.exportPath}"`)})`)} `)}async _esm(e){const t="."===e.exportPath;console.time(` ${tcolor.cyan("Compiled esm")} -> ${tcolor.cyan(`export path(${tcolor.magenta(`"${e.exportPath}"`)})`)} `);const s=e.fileName,i=e.bundledContent,n=e.tsOptions.esm,r=createHost(i,s),a=r.createdFiles,o=r.host;ts.createProgram([s],n,o).emit(),Object.entries(a).map(async([s,i])=>{i=resolveSourceMappingURL(s,i,"esm"),i=await postProcessPluginParser(e.plugins,i,s),this._isUpdate()&&(s.match(/.js/g)&&(this.files.esm=s.replace(/.js/g,".mjs")),s.match(/.d.ts/g)&&(this.files.esmTypes=s.replace(/.d.ts/g,".d.mts")),t&&this.files.esm&&(this.files.module=this.files.esm)),s=(s=(s=s.replace(/.js/g,".mjs")).replace(/.map.js/g,".map.mjs")).replace(/.d.ts/g,".d.mts"),await utils.file.clearFolder(path.dirname(s)),await utils.file.writeFile(s,i)}),console.timeEnd(` ${tcolor.cyan("Compiled esm")} -> ${tcolor.cyan(`export path(${tcolor.magenta(`"${e.exportPath}"`)})`)} `)}async compile(){for(const e of this.object.points){const t=[...new Set(e.format)];for(const s of t)switch(s){case"commonjs":await this._commonjs(e),this._isUpdate()&&await writePackage(this.files,e.exportPath);break;case"esm":await this._esm(e),this._isUpdate()&&await writePackage(this.files,e.exportPath)}}}}const finalCheck=e=>{const t=e.points;for(const e of t)for(const t of e.depFiles)"cjs"===t.moduleType||".cjs"===t.fileExt?(console.error(`> ${tcolor.cyan(`Unsupported CommonJS dependency: ${tcolor.magenta(t.file)}\n To resolve that, recommend to use @suseejs/plugin-commonjs`)}`),ts.sys.exit(1)):(t.isJsx||".jsx"===t.fileExt||".tsx"===t.fileExt)&&(console.error(`> ${tcolor.cyan(`Unsupported JSX/TSX dependency: ${tcolor.magenta(t.file)}\n That will be fix in future versions`)}`),ts.sys.exit(1))},getPagInfo=()=>{const e=fs.readFileSync(path.resolve(process.cwd(),"package.json"),"utf8"),t=JSON.parse(e),s=t.name??"",i=t.version??"";let n="";return n=""!==s&&""!==i?`${s}@${i}`:""!==s&&""===i?`${s}`:""===s&&""!==i?`the project@${i}`:"the project",n};async function susee(){console.time(`susee > ${tcolor.cyan("Done in")}`);const e=getPagInfo();console.time(`susee > ${tcolor.cyan(`Initialized ${tcolor.magenta(e)}`)} `);const t=await initializer();finalCheck(t),console.timeEnd(`susee > ${tcolor.cyan(`Initialized ${tcolor.magenta(e)}`)} `);const s=await bundle(t),i=new Compiler(s);await i.compile(),console.timeEnd(`susee > ${tcolor.cyan("Done in")}`)}export{susee};