pkgroll
Version:
Zero-config rollup bundler
33 lines (32 loc) • 38.6 kB
JavaScript
var ce=Object.defineProperty;var m=(n,e)=>ce(n,"name",{value:e,configurable:!0});import{createRequire as le}from"node:module";const pe=le(import.meta.url);import*as x from"node:path";import i from"typescript";import{createRequire as fe}from"node:module";import j from"magic-string";function me(n){return{...n,compilerOptions:n.compilerOptions??{},respectExternal:n.respectExternal??!1,includeExternal:n.includeExternal??[]}}m(me,"resolveDefaultOptions");const k=/\.d\.(c|m)?tsx?$/,_=/\.json$/,X=/((\.d)?\.(c|m)?(t|j)sx?|\.json)$/;function z(n){return n.replace(X,"")}m(z,"trimExtension");function J(n){return n.replace(X,".d.ts")}m(J,"getDeclarationId");function L(n,e){return i.createSourceFile(n,e,i.ScriptTarget.Latest,!0)}m(L,"parse");const V={getCurrentDirectory:m(()=>i.sys.getCurrentDirectory(),"getCurrentDirectory"),getNewLine:m(()=>i.sys.newLine,"getNewLine"),getCanonicalFileName:i.sys.useCaseSensitiveFileNames?n=>n:n=>n.toLowerCase()},ue={declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!0,target:i.ScriptTarget.ESNext,resolveJsonModule:!0},K=new Map,R=m((...n)=>process.env.DTS_LOG_CACHE?console.log("[cache]",...n):null,"logCache");function Q([n,e],t){for(R(n),K.set(n,t);n!==e&&n!==x.dirname(n);){if(n=x.dirname(n),R("up",n),K.has(n))return R("has",n);K.set(n,t)}}m(Q,"cacheConfig");function U(n,e,t){const s={...ue,...e};let r=x.dirname(n),a=[];const c=t||r;if(K.has(c))R("HIT",c);else{R("miss",c);const f=t?x.resolve(process.cwd(),t):i.findConfigFile(r,i.sys.fileExists);if(!f)return{dtsFiles:a,dirName:r,compilerOptions:s};const h=r;r=x.dirname(f);const{config:T,error:D}=i.readConfigFile(f,i.sys.readFile);if(D)return console.error(i.formatDiagnostic(D,V)),{dtsFiles:a,dirName:r,compilerOptions:s};R("tsconfig",T);const I=i.parseJsonConfigFileContent(T,i.sys,r);Q(t?[t,t]:[h,r],I)}const{fileNames:p,options:u,errors:l}=K.get(c);return a=p.filter(f=>k.test(f)),l.length?(console.error(i.formatDiagnostics(l,V)),{dtsFiles:a,dirName:r,compilerOptions:s}):{dtsFiles:a,dirName:r,compilerOptions:{...u,...s}}}m(U,"getCompilerOptions");function de(n,e,t){const{dtsFiles:s,compilerOptions:r}=U(n,e,t);return i.createProgram([n].concat(Array.from(s)),r,i.createCompilerHost(r,!0))}m(de,"createProgram$1");function he(n,e,t){const s=[],r=new Set;let a=[],c="",p={};for(let u of n){if(k.test(u))continue;u=x.resolve(u);const l=U(u,e,t);if(l.dtsFiles.forEach(r.add,r),!a.length){a.push(u),{dirName:c,compilerOptions:p}=l;continue}if(l.dirName===c)a.push(u);else{const f=i.createCompilerHost(p,!0),h=i.createProgram(a.concat(Array.from(r)),p,f);s.push(h),a=[u],{dirName:c,compilerOptions:p}=l}}if(a.length){const u=i.createCompilerHost(p,!0),l=i.createProgram(a.concat(Array.from(r)),p,u);s.push(l)}return s}m(he,"createPrograms");function ye(){let n;try{return{codeFrameColumns:n}=pe("@babel/code-frame"),n}catch{try{return{codeFrameColumns:n}=fe(import.meta.url)("@babel/code-frame"),n}catch{}}}m(ye,"getCodeFrame");function ge(n){const e=n.getSourceFile(),t=e.getLineAndCharacterOfPosition(n.getStart()),s=e.getLineAndCharacterOfPosition(n.getEnd());return{start:{line:t.line+1,column:t.character+1},end:{line:s.line+1,column:s.character+1}}}m(ge,"getLocation");function xe(n){const e=ye(),s=n.getSourceFile().getFullText(),r=ge(n);return e?`
`+e(s,r,{highlightCode:!0}):`
${r.start.line}:${r.start.column}: \`${n.getFullText().trim()}\``}m(xe,"frameNode");class g extends Error{static{m(this,"UnsupportedSyntaxError")}constructor(e,t="Syntax not yet supported"){super(`${t}
${xe(e)}`)}}class Se{static{m(this,"NamespaceFixer")}constructor(e){this.sourceFile=e}findNamespaces(){const e=[],t={};for(const s of this.sourceFile.statements){const r={start:s.getStart(),end:s.getEnd()};if(i.isEmptyStatement(s)){e.unshift({name:"",exports:[],location:r});continue}if((i.isImportDeclaration(s)||i.isExportDeclaration(s))&&s.moduleSpecifier&&i.isStringLiteral(s.moduleSpecifier)){const{text:f}=s.moduleSpecifier;if(f.startsWith(".")&&(f.endsWith(".d.ts")||f.endsWith(".d.cts")||f.endsWith(".d.mts"))){const h=s.moduleSpecifier.getStart()+1,T=s.moduleSpecifier.getEnd()-1;e.unshift({name:"",exports:[],location:{start:h,end:T},textBeforeCodeAfter:f.replace(/\.d\.ts$/,".js").replace(/\.d\.cts$/,".cjs").replace(/\.d\.mts$/,".mjs")})}}if(i.isModuleDeclaration(s)&&s.body&&i.isModuleBlock(s.body)){for(const f of s.body.statements)if(i.isExportDeclaration(f)&&f.exportClause){if(i.isNamespaceExport(f.exportClause))continue;for(const h of f.exportClause.elements)h.propertyName&&h.propertyName.getText()==h.name.getText()&&e.unshift({name:"",exports:[],location:{start:h.propertyName.getEnd(),end:h.name.getEnd()}})}}if(i.isClassDeclaration(s)?t[s.name.getText()]={type:"class",generics:s.typeParameters}:i.isFunctionDeclaration(s)?t[s.name.getText()]={type:"function"}:i.isInterfaceDeclaration(s)?t[s.name.getText()]={type:"interface",generics:s.typeParameters}:i.isTypeAliasDeclaration(s)?t[s.name.getText()]={type:"type",generics:s.typeParameters}:i.isModuleDeclaration(s)&&i.isIdentifier(s.name)?t[s.name.getText()]={type:"namespace"}:i.isEnumDeclaration(s)&&(t[s.name.getText()]={type:"enum"}),!i.isVariableStatement(s))continue;const{declarations:a}=s.declarationList;if(a.length!==1)continue;const c=a[0],p=c.name.getText();if(!c.initializer||!i.isCallExpression(c.initializer)){t[p]={type:"var"};continue}const u=c.initializer.arguments[0];if(!c.initializer.expression.getFullText().includes("/*#__PURE__*/Object.freeze")||!i.isObjectLiteralExpression(u))continue;const l=[];for(const f of u.properties){if(!i.isPropertyAssignment(f)||!(i.isIdentifier(f.name)||i.isStringLiteral(f.name))||f.name.text!=="__proto__"&&!i.isIdentifier(f.initializer))throw new g(f,"Expected a property assignment");f.name.text!=="__proto__"&&l.push({exportedName:f.name.text,localName:f.initializer.getText()})}e.unshift({name:p,exports:l,location:r})}return{namespaces:e,itemTypes:t}}fix(){let e=this.sourceFile.getFullText();const{namespaces:t,itemTypes:s}=this.findNamespaces();for(const r of t){const a=e.slice(r.location.end);e=e.slice(0,r.location.start);for(const{exportedName:c,localName:p}of r.exports)if(c===p){const{type:u,generics:l}=s[p]||{};if(u==="interface"||u==="type"){const f=Y(l);e+=`type ${r.name}_${c}${f.in} = ${p}${f.out};
`}else if(u==="enum"||u==="class"){const f=Y(l);e+=`type ${r.name}_${c}${f.in} = ${p}${f.out};
`,e+=`declare const ${r.name}_${c}: typeof ${p};
`}else u==="namespace"?e+=`import ${r.name}_${c} = ${p};
`:e+=`declare const ${r.name}_${c}: typeof ${p};
`}if(r.name){e+=`declare namespace ${r.name} {
`,e+=` export {
`;for(const{exportedName:c,localName:p}of r.exports)c===p?e+=` ${r.name}_${c} as ${c},
`:e+=` ${p} as ${c},
`;e+=` };
`,e+="}"}e+=r.textBeforeCodeAfter??"",e+=a}return e}}function Y(n){return!n||!n.length?{in:"",out:""}:{in:`<${n.map(e=>e.getText()).join(", ")}>`,out:`<${n.map(e=>e.name.getText()).join(", ")}>`}}m(Y,"renderTypeParams");let Z=1;function Ee(n){return E({type:"Program",sourceType:"module",body:[]},{start:n.getFullStart(),end:n.getEnd()})}m(Ee,"createProgram");function ve(n){const e={type:"Identifier",name:String(Z++)};return{ident:e,expr:{type:"AssignmentPattern",left:e,right:n}}}m(ve,"createReference");function v(n){return E({type:"Identifier",name:n.getText()},n)}m(v,"createIdentifier");function Te(n){const e=E({type:"FunctionExpression",id:null,params:[],body:{type:"BlockStatement",body:[]}},n),t=E({type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:String(Z++)},arguments:[e],optional:!1}},n);return{fn:e,iife:t}}m(Te,"createIIFE");function Ne(){const n={type:"ArrayExpression",elements:[]};return{expr:n,stmt:{type:"ReturnStatement",argument:n}}}m(Ne,"createReturn");function De(n,e){return E({type:"FunctionDeclaration",id:E({type:"Identifier",name:i.idText(n)},n),params:[],body:{type:"BlockStatement",body:[]}},e)}m(De,"createDeclaration");function w(n){if(i.isLiteralExpression(n))return{type:"Literal",value:n.text};if(i.isPropertyAccessExpression(n)){if(i.isPrivateIdentifier(n.name))throw new g(n.name);return E({type:"MemberExpression",computed:!1,optional:!1,object:w(n.expression),property:w(n.name)},{start:n.expression.getStart(),end:n.name.getEnd()})}if(i.isObjectLiteralExpression(n))return E({type:"ObjectExpression",properties:n.properties.map(e=>{if(i.isPropertyAssignment(e))return E({type:"Property",key:i.isIdentifier(e.name)?v(e.name):w(e.name),value:w(e.initializer),kind:"init",method:!1,shorthand:!1,computed:i.isComputedPropertyName(e.name)},e);if(i.isShorthandPropertyAssignment(e))return E({type:"Property",key:v(e.name),value:v(e.name),kind:"init",method:!1,shorthand:!0,computed:!1},e);throw new g(e,"Unsupported property type in object literal")})},n);if(i.isArrayLiteralExpression(n))return E({type:"ArrayExpression",elements:n.elements.map(e=>{if(i.isExpression(e))return w(e);throw new g(e,"Unsupported element type in array literal")})},n);if(i.isIdentifier(n))return v(n);if(n.kind==i.SyntaxKind.NullKeyword)return{type:"Literal",value:null};throw new g(n)}m(w,"convertExpression");function E(n,e){const t="start"in e?e:{start:e.getStart(),end:e.getEnd()};return Object.assign(n,t)}m(E,"withStartEnd");function B(n,e){return(i.getCombinedModifierFlags(n)&e)===e}m(B,"matchesModifier");class Ie{static{m(this,"LanguageService")}constructor(e){this.fileName="index.d.ts";const t={getCompilationSettings:m(()=>({noEmit:!0,noResolve:!0,skipLibCheck:!0,declaration:!1,checkJs:!1,declarationMap:!1,target:i.ScriptTarget.ESNext}),"getCompilationSettings"),getScriptFileNames:m(()=>[this.fileName],"getScriptFileNames"),getScriptVersion:m(()=>"1","getScriptVersion"),getScriptSnapshot:m(s=>s===this.fileName?i.ScriptSnapshot.fromString(e):void 0,"getScriptSnapshot"),getCurrentDirectory:m(()=>"","getCurrentDirectory"),getDefaultLibFileName:m(()=>"","getDefaultLibFileName"),fileExists:m(s=>s===this.fileName,"fileExists"),readFile:m(s=>s===this.fileName?e:void 0,"readFile")};this.service=i.createLanguageService(t,i.createDocumentRegistry(void 0,""),i.LanguageServiceMode.PartialSemantic)}findReferenceCount(e){const t=this.service.findReferences(this.fileName,e.getStart());return t?.length?t.reduce((s,r)=>s+r.references.length,0):0}}class be{static{m(this,"TypeOnlyFixer")}constructor(e,t){this.DEBUG=!!process.env.DTS_EXPORTS_FIXER_DEBUG,this.types=new Set,this.values=new Set,this.typeHints=new Map,this.reExportTypeHints=new Map,this.importNodes=[],this.exportNodes=[],this.rawCode=t,this.source=L(e,t),this.code=new j(t)}fix(){return this.analyze(this.source.statements),(this.typeHints.size||this.reExportTypeHints.size)&&(this.service=new Ie(this.rawCode),this.importNodes.forEach(e=>this.fixTypeOnlyImport(e))),this.types.size&&this.exportNodes.forEach(e=>this.fixTypeOnlyExport(e)),this.types.size?{magicCode:this.code}:{code:this.rawCode,map:null}}fixTypeOnlyImport(e){let t=!1;const s=[],r=[],a=e.moduleSpecifier.getText(),c=e.importClause.name,p=e.importClause.namedBindings;if(c){const u=c.text;this.isTypeOnly(u)?this.isUselessImport(c)?t=!0:s.push(`import type ${u} from ${a};`):r.push(`import ${u} from ${a};`)}if(p&&i.isNamespaceImport(p)){const u=p.name.text;this.isTypeOnly(u)?this.isUselessImport(p.name)?t=!0:s.push(`import type * as ${u} from ${a};`):r.push(`import * as ${u} from ${a};`)}if(p&&i.isNamedImports(p)){const u=[],l=[];for(const f of p.elements)this.isTypeOnly(f.name.text)?this.isUselessImport(f.name)?t=!0:u.push(f.getText()):l.push(f.getText());u.length&&s.push(`import type { ${u.join(", ")} } from ${a};`),l.length&&r.push(`import { ${l.join(", ")} } from ${a};`)}(s.length||t)&&this.code.overwrite(e.getStart(),e.getEnd(),[...r,...s].join(`
${ee(e)}`))}fixTypeOnlyExport(e){const t=[],s=[],r=e.moduleSpecifier?.getText();if(i.isNamespaceExport(e.exportClause)){const a=e.exportClause.name.text;this.isReExportTypeOnly(a)?t.push(`export type * as ${a} from ${r};`):s.push(`export * as ${a} from ${r};`)}if(i.isNamedExports(e.exportClause)){const a=[],c=[];for(const p of e.exportClause.elements){const u=p.propertyName?.text||p.name.text;(e.moduleSpecifier?this.isReExportTypeOnly(p.name.text):this.isTypeOnly(u))?a.push(p.getText()):c.push(p.getText())}a.length&&t.push(`export type { ${a.join(", ")} }${r?` from ${r}`:""};`),c.length&&s.push(`export { ${c.join(", ")} }${r?` from ${r}`:""};`)}t.length&&this.code.overwrite(e.getStart(),e.getEnd(),[...s,...t].join(`
${ee(e)}`))}analyze(e){for(const t of e){if(this.DEBUG&&console.log(t.getText(),t.kind),i.isImportDeclaration(t)&&t.importClause){this.importNodes.push(t);continue}if(i.isExportDeclaration(t)&&t.exportClause){this.exportNodes.push(t);continue}if(i.isInterfaceDeclaration(t)){this.DEBUG&&console.log(`${t.name.getFullText()} is a type`),this.types.add(t.name.text);continue}if(i.isTypeAliasDeclaration(t)){const s=t.name.text;this.DEBUG&&console.log(`${t.name.getFullText()} is a type`),this.types.add(s);continue}if(i.isEnumDeclaration(t)||i.isFunctionDeclaration(t)||i.isClassDeclaration(t)||i.isVariableStatement(t)){if(i.isVariableStatement(t))for(const s of t.declarationList.declarations)i.isIdentifier(s.name)&&(this.DEBUG&&console.log(`${s.name.getFullText()} is a value (from var statement)`),this.values.add(s.name.text));else t.name&&(this.DEBUG&&console.log(`${t.name.getFullText()} is a value (from declaration)`),this.values.add(t.name.text));continue}if(i.isModuleBlock(t)){this.analyze(t.statements);continue}if(i.isModuleDeclaration(t)){t.name&&i.isIdentifier(t.name)&&(this.DEBUG&&console.log(`${t.name.getFullText()} is a value (from module declaration)`),this.values.add(t.name.text)),this.analyze(t.getChildren());continue}this.DEBUG&&console.log("unhandled statement",t.getFullText(),t.kind)}}isUselessImport(e){const t=this.service.findReferenceCount(e),s=this.typeHints.get(e.text);return s&&s+1>=t}isTypeOnly(e){return this.typeHints.has(e)||this.types.has(e)&&!this.values.has(e)}isReExportTypeOnly(e){return this.reExportTypeHints.has(e)}}function ee(n){const e=n.getFullText().match(/^(?:\n*)([ ]*)/);return" ".repeat(e?.[1]?.length||0)}m(ee,"getNodeIndent");function te(n,e,t){for(const s of n.statements)G(e,s),i.isModuleDeclaration(s)&&ie(e,s),i.isModuleDeclaration(s)&&s.body&&i.isModuleBlock(s.body)&&te(s.body,e)}m(te,"preProcessNamespaceBody");function Ce({sourceFile:n,isEntry:e,isJSON:t}){const s=new j(n.getFullText()),r=!e&&we(n),a=new Set,c=new Set;let p="";const u=new Map,l=new Map;for(const o of n.statements){if(i.isEmptyStatement(o)){s.remove(o.getStart(),o.getEnd());continue}if(i.isImportDeclaration(o)){if(!o.importClause)continue;o.importClause.name&&a.add(o.importClause.name.text),o.importClause.namedBindings&&(i.isNamespaceImport(o.importClause.namedBindings)?a.add(o.importClause.namedBindings.name.text):o.importClause.namedBindings.elements.forEach(d=>a.add(d.name.text)))}else if(i.isEnumDeclaration(o)||i.isFunctionDeclaration(o)||i.isInterfaceDeclaration(o)||i.isClassDeclaration(o)||i.isTypeAliasDeclaration(o)||i.isModuleDeclaration(o)){if(o.name){const d=o.name.getText();a.add(d),B(o,i.ModifierFlags.ExportDefault)?p=d:(r&&i.isIdentifier(o.name)||B(o,i.ModifierFlags.Export))&&c.add(d),o.flags&i.NodeFlags.GlobalAugmentation||O(d,[H(o),se(o)])}i.isModuleDeclaration(o)&&(o.body&&i.isModuleBlock(o.body)&&te(o.body,s),ie(s,o)),G(s,o)}else if(i.isVariableStatement(o)){const{declarations:d}=o.declarationList,S=B(o,i.ModifierFlags.Export);for(const N of o.declarationList.declarations)if(i.isIdentifier(N.name)){const C=N.name.getText();a.add(C),(r||S)&&c.add(C)}if(G(s,o),d.length===1){const N=d[0];i.isIdentifier(N.name)&&O(N.name.getText(),[H(o),se(o)])}else{const N=d.slice(),C=N.shift();O(C.name.getText(),[H(o),C.getEnd()]);for(const M of N)i.isIdentifier(M.name)&&O(M.name.getText(),[M.getFullStart(),M.getEnd()])}const{flags:y}=o.declarationList,P=`declare ${y&i.NodeFlags.Let?"let":y&i.NodeFlags.Const?"const":"var"} `,A=o.declarationList.getChildren().find(N=>N.kind===i.SyntaxKind.SyntaxList).getChildren();let F=0;for(const N of A)if(N.kind===i.SyntaxKind.CommaToken)F=N.getStart(),s.remove(F,N.getEnd());else if(F){s.appendLeft(F,`;
`);const C=N.getFullStart(),M=s.slice(C,N.getStart()),W=M.length-M.trimStart().length;W?s.overwrite(C,C+W,P):s.appendLeft(C,P)}}}for(const o of n.statements){if(D(o),i.isExportAssignment(o)&&!o.isExportEquals&&(i.isObjectLiteralExpression(o.expression)||i.isArrayLiteralExpression(o.expression))){p||(p=b("export_default")),s.overwrite(o.getStart(),o.expression.getStart(),`declare var ${p} = `);continue}if(B(o,i.ModifierFlags.ExportDefault)&&(i.isFunctionDeclaration(o)||i.isClassDeclaration(o))){if(o.name)continue;p||(p=b("export_default"));const d=o.getChildren(),S=d.findIndex(A=>A.kind===i.SyntaxKind.ClassKeyword||A.kind===i.SyntaxKind.FunctionKeyword),y=d[S],$=d[S+1];if($.kind>=i.SyntaxKind.FirstPunctuation&&$.kind<=i.SyntaxKind.LastPunctuation){const A=s.slice(y.getEnd(),$.getStart())!=" ";s.appendLeft($.getStart(),`${A?" ":""}${p}`)}else s.appendRight(y.getEnd(),` ${p}`)}}for(const o of l.values()){const S=o.pop()[0];for(const y of o)s.move(y[0],y[1],S)}p&&s.append(`
export default ${p};
`),c.size&&s.append(`
export { ${[...c].join(", ")} };
`),t&&c.size&&(p=b("export_default"),s.append([`
declare const ${p}: {`,[...c].map(o=>` ${o}: typeof ${o};`).join(`
`),"};",`export default ${p};
`].join(`
`)));for(const[o,d]of u.entries())s.prepend(`import * as ${d} from "${o}";
`);const f=n.getLineStarts(),h=new Set;for(const o of n.typeReferenceDirectives){h.add(o.fileName);const{line:d}=n.getLineAndCharacterOfPosition(o.pos),S=f[d];let y=n.getLineEndOfPosition(o.pos);s.slice(y,y+1)===`
`&&(y+=1),s.remove(S,y)}const T=new Set;for(const o of n.referencedFiles){T.add(o.fileName);const{line:d}=n.getLineAndCharacterOfPosition(o.pos),S=f[d];let y=n.getLineEndOfPosition(o.pos);s.slice(y,y+1)===`
`&&(y+=1),s.remove(S,y)}return{code:s,typeReferences:h,fileReferences:T};function D(o){if(i.forEachChild(o,D),i.isImportTypeNode(o)){if(!i.isLiteralTypeNode(o.argument)||!i.isStringLiteral(o.argument.literal))throw new g(o,"inline imports should have a literal argument");const d=o.argument.literal.text,S=o.getChildren(),y=S.find(F=>F.kind===i.SyntaxKind.ImportKeyword).getStart();let $=o.getEnd();const P=S.find(F=>F.kind===i.SyntaxKind.DotToken||F.kind===i.SyntaxKind.LessThanToken);P&&($=P.getStart());const A=I(d);s.overwrite(y,$,A)}}function I(o){let d=u.get(o);return d||(d=b(Fe(o)),u.set(o,d)),d}function b(o){let d=o;for(;a.has(d);)d=`_${d}`;return a.add(d),d}function O(o,d){let S=l.get(o);if(!S)S=[d],l.set(o,S);else{const y=S[S.length-1];y[1]===d[0]?y[1]=d[1]:S.push(d)}}}m(Ce,"preProcess");function we(n){let e=!1;for(const t of n.statements){if(i.isExportDeclaration(t)||i.isExportAssignment(t))return!1;(e||i.isImportDeclaration(t)||B(t,i.ModifierFlags.Export))&&(e=!0)}return e}m(we,"isGlobalModule");function G(n,e){if(!i.canHaveModifiers(e))return;if(e.parent.kind===i.SyntaxKind.SourceFile){let s=!1;const r=i.isEnumDeclaration(e)||i.isClassDeclaration(e)||i.isFunctionDeclaration(e)||i.isModuleDeclaration(e)||i.isVariableStatement(e);for(const a of e.modifiers??[])switch(a.kind){case i.SyntaxKind.ExportKeyword:case i.SyntaxKind.DefaultKeyword:n.remove(a.getStart(),a.getEnd()+1);break;case i.SyntaxKind.DeclareKeyword:s=!0}r&&!s&&n.appendRight(e.getStart(),"declare ")}else if(i.isModuleDeclaration(e)){const s=e.modifiers?.find(r=>r.kind===i.SyntaxKind.ExportKeyword);s&&n.remove(s.getStart(),s.getEnd()+1)}}m(G,"fixModifiers");function ie(n,e){if(!(!e.body||!i.isModuleBlock(e.body))){for(const t of e.body.statements)if(i.isExportDeclaration(t)&&t.exportClause){if(i.isNamespaceExport(t.exportClause))continue;for(const s of t.exportClause.elements)s.propertyName||n.appendLeft(s.name.getEnd(),` as ${s.name.getText()}`)}}}m(ie,"duplicateExports");function Fe(n){return n.replace(/[^a-zA-Z0-9_$]/g,()=>"_")}m(Fe,"getSafeName");function H(n){const e=n.getFullStart();return e+(re(n,e)?1:0)}m(H,"getStart");function se(n){const e=n.getEnd();return e+(re(n,e)?1:0)}m(se,"getEnd");function re(n,e){return n.getSourceFile().getFullText()[e]===`
`}m(re,"newlineAt");const $e=new Set([i.SyntaxKind.LiteralType,i.SyntaxKind.VoidKeyword,i.SyntaxKind.UnknownKeyword,i.SyntaxKind.AnyKeyword,i.SyntaxKind.BooleanKeyword,i.SyntaxKind.NumberKeyword,i.SyntaxKind.StringKeyword,i.SyntaxKind.ObjectKeyword,i.SyntaxKind.NullKeyword,i.SyntaxKind.UndefinedKeyword,i.SyntaxKind.SymbolKeyword,i.SyntaxKind.NeverKeyword,i.SyntaxKind.ThisKeyword,i.SyntaxKind.ThisType,i.SyntaxKind.BigIntKeyword]);class ne{static{m(this,"DeclarationScope")}constructor({id:e,range:t}){if(this.scopes=[],e)this.declaration=De(e,t);else{const{iife:r,fn:a}=Te(t);this.iife=r,this.declaration=a}const s=Ne();this.declaration.body.body.push(s.stmt),this.returnExpr=s.expr}pushScope(){this.scopes.push(new Set)}popScope(e=1){for(let t=0;t<e;t++)this.scopes.pop()}pushTypeVariable(e){const t=e.getText();this.scopes[this.scopes.length-1]?.add(t)}pushReference(e){let t;if(e.type==="Identifier"?t=e.name:e.type==="MemberExpression"&&e.object.type==="Identifier"&&(t=e.object.name),t){for(const a of this.scopes)if(a.has(t))return}if(t==="this")return;const{ident:s,expr:r}=ve(e);this.declaration.params.push(r),this.returnExpr.elements.push(s)}pushIdentifierReference(e){this.pushReference(v(e))}convertEntityName(e){return i.isIdentifier(e)?v(e):E({type:"MemberExpression",computed:!1,optional:!1,object:this.convertEntityName(e.left),property:v(e.right)},e)}convertPropertyAccess(e){if(!i.isIdentifier(e.expression)&&!i.isPropertyAccessExpression(e.expression))throw new g(e.expression);if(i.isPrivateIdentifier(e.name))throw new g(e.name);const t=i.isIdentifier(e.expression)?v(e.expression):this.convertPropertyAccess(e.expression);return E({type:"MemberExpression",computed:!1,optional:!1,object:t,property:v(e.name)},e)}convertComputedPropertyName(e){if(!e.name||!i.isComputedPropertyName(e.name))return;const{expression:t}=e.name;if(!(i.isLiteralExpression(t)||i.isPrefixUnaryExpression(t))){if(i.isIdentifier(t))return this.pushReference(v(t));if(i.isPropertyAccessExpression(t))return this.pushReference(this.convertPropertyAccess(t));throw new g(t)}}convertParametersAndType(e){this.convertComputedPropertyName(e);const t=this.convertTypeParameters(e.typeParameters);for(const s of e.parameters)this.convertTypeNode(s.type);this.convertTypeNode(e.type),this.popScope(t)}convertHeritageClauses(e){for(const t of e.heritageClauses||[])for(const s of t.types)this.pushReference(w(s.expression)),this.convertTypeArguments(s)}convertTypeArguments(e){if(e.typeArguments)for(const t of e.typeArguments)this.convertTypeNode(t)}convertMembers(e){for(const t of e){if(i.isPropertyDeclaration(t)||i.isPropertySignature(t)||i.isIndexSignatureDeclaration(t)){i.isPropertyDeclaration(t)&&t.initializer&&i.isPropertyAccessExpression(t.initializer)&&this.pushReference(this.convertPropertyAccess(t.initializer)),this.convertComputedPropertyName(t),this.convertTypeNode(t.type);continue}if(i.isMethodDeclaration(t)||i.isMethodSignature(t)||i.isConstructorDeclaration(t)||i.isConstructSignatureDeclaration(t)||i.isCallSignatureDeclaration(t)||i.isGetAccessorDeclaration(t)||i.isSetAccessorDeclaration(t))this.convertParametersAndType(t);else throw new g(t)}}convertTypeParameters(e){if(!e)return 0;for(const t of e)this.convertTypeNode(t.constraint),this.convertTypeNode(t.default),this.pushScope(),this.pushTypeVariable(t.name);return e.length}convertTypeNode(e){if(e&&!$e.has(e.kind)){if(i.isTypeReferenceNode(e)){this.pushReference(this.convertEntityName(e.typeName)),this.convertTypeArguments(e);return}if(i.isTypeLiteralNode(e)){this.convertMembers(e.members);return}if(i.isArrayTypeNode(e)){this.convertTypeNode(e.elementType);return}if(i.isTupleTypeNode(e)){for(const t of e.elements)this.convertTypeNode(t);return}if(i.isNamedTupleMember(e)||i.isParenthesizedTypeNode(e)||i.isTypeOperatorNode(e)||i.isTypePredicateNode(e)){this.convertTypeNode(e.type);return}if(i.isUnionTypeNode(e)||i.isIntersectionTypeNode(e)){for(const t of e.types)this.convertTypeNode(t);return}if(i.isMappedTypeNode(e)){const{typeParameter:t,type:s,nameType:r}=e;this.convertTypeNode(t.constraint),this.pushScope(),this.pushTypeVariable(t.name),this.convertTypeNode(s),r&&this.convertTypeNode(r),this.popScope();return}if(i.isConditionalTypeNode(e)){this.convertTypeNode(e.checkType),this.pushScope(),this.convertTypeNode(e.extendsType),this.convertTypeNode(e.trueType),this.convertTypeNode(e.falseType),this.popScope();return}if(i.isIndexedAccessTypeNode(e)){this.convertTypeNode(e.objectType),this.convertTypeNode(e.indexType);return}if(i.isFunctionOrConstructorTypeNode(e)){this.convertParametersAndType(e);return}if(i.isTypeQueryNode(e)){const t=this.convertEntityName(e.exprName);this.pushReference(t),this.convertTypeArguments(e);return}if(i.isRestTypeNode(e)){this.convertTypeNode(e.type);return}if(i.isOptionalTypeNode(e)){this.convertTypeNode(e.type);return}if(i.isTemplateLiteralTypeNode(e)){for(const t of e.templateSpans)this.convertTypeNode(t.type);return}if(i.isInferTypeNode(e)){const{typeParameter:t}=e;this.convertTypeNode(t.constraint),this.pushTypeVariable(t.name);return}else throw new g(e)}}convertNamespace(e,t=!1){if(this.pushScope(),t&&e.body&&i.isModuleDeclaration(e.body)){this.convertNamespace(e.body,!0);return}if(!e.body||!i.isModuleBlock(e.body))throw new g(e,'namespace must have a "ModuleBlock" body.');const{statements:s}=e.body;for(const r of s){if(i.isEnumDeclaration(r)||i.isFunctionDeclaration(r)||i.isClassDeclaration(r)||i.isInterfaceDeclaration(r)||i.isTypeAliasDeclaration(r)||i.isModuleDeclaration(r)){if(r.name&&i.isIdentifier(r.name))this.pushTypeVariable(r.name);else throw new g(r,"non-Identifier name not supported");continue}if(i.isVariableStatement(r)){for(const a of r.declarationList.declarations)if(i.isIdentifier(a.name))this.pushTypeVariable(a.name);else throw new g(a,"non-Identifier name not supported");continue}if(i.isImportDeclaration(r)){if(r.importClause&&(r.importClause.name&&this.pushTypeVariable(r.importClause.name),r.importClause.namedBindings))if(i.isNamespaceImport(r.importClause.namedBindings))this.pushTypeVariable(r.importClause.namedBindings.name);else for(const a of r.importClause.namedBindings.elements)this.pushTypeVariable(a.name);continue}if(i.isImportEqualsDeclaration(r)){this.pushTypeVariable(r.name);continue}if(!i.isExportDeclaration(r))throw new g(r,"namespace child (hoisting) not supported yet")}for(const r of s){if(i.isVariableStatement(r)){for(const a of r.declarationList.declarations)a.type&&this.convertTypeNode(a.type);continue}if(i.isFunctionDeclaration(r)){this.convertParametersAndType(r);continue}if(i.isInterfaceDeclaration(r)||i.isClassDeclaration(r)){const a=this.convertTypeParameters(r.typeParameters);this.convertHeritageClauses(r),this.convertMembers(r.members),this.popScope(a);continue}if(i.isTypeAliasDeclaration(r)){const a=this.convertTypeParameters(r.typeParameters);this.convertTypeNode(r.type),this.popScope(a);continue}if(i.isModuleDeclaration(r)){this.convertNamespace(r,t);continue}if(!i.isEnumDeclaration(r)&&!i.isImportDeclaration(r)){if(i.isImportEqualsDeclaration(r)){i.isEntityName(r.moduleReference)&&this.pushReference(this.convertEntityName(r.moduleReference));continue}if(i.isExportDeclaration(r)){if(r.exportClause){if(i.isNamespaceExport(r.exportClause))throw new g(r.exportClause);for(const a of r.exportClause.elements){const c=a.propertyName||a.name;this.pushIdentifierReference(c)}}}else throw new g(r,"namespace child (walking) not supported yet")}}this.popScope()}}function Ae({sourceFile:n}){return new Me(n).transform()}m(Ae,"convert");class Me{static{m(this,"Transformer")}constructor(e){this.sourceFile=e,this.declarations=new Map,this.ast=Ee(e);for(const t of e.statements)this.convertStatement(t)}transform(){return{ast:this.ast}}pushStatement(e){this.ast.body.push(e)}createDeclaration(e,t){const s={start:e.getFullStart(),end:e.getEnd()};if(!t){const p=new ne({range:s});return this.pushStatement(p.iife),p}const r=t.getText(),a=new ne({id:t,range:s}),c=this.declarations.get(r);if(c){c.pushIdentifierReference(t),c.declaration.end=s.end;const p=this.ast.body.findIndex(u=>u==c.declaration);for(let u=p+1;u<this.ast.body.length;u++){const l=this.ast.body[u];l.start=l.end=s.end}}else this.pushStatement(a.declaration),this.declarations.set(r,a);return c||a}convertStatement(e){if(i.isEnumDeclaration(e))return this.convertEnumDeclaration(e);if(i.isFunctionDeclaration(e))return this.convertFunctionDeclaration(e);if(i.isInterfaceDeclaration(e)||i.isClassDeclaration(e))return this.convertClassOrInterfaceDeclaration(e);if(i.isTypeAliasDeclaration(e))return this.convertTypeAliasDeclaration(e);if(i.isVariableStatement(e))return this.convertVariableStatement(e);if(i.isExportDeclaration(e)||i.isExportAssignment(e))return this.convertExportDeclaration(e);if(i.isModuleDeclaration(e))return this.convertNamespaceDeclaration(e);if(e.kind===i.SyntaxKind.NamespaceExportDeclaration)return this.removeStatement(e);if(i.isImportDeclaration(e)||i.isImportEqualsDeclaration(e))return this.convertImportDeclaration(e);throw new g(e)}removeStatement(e){this.pushStatement(E({type:"ExpressionStatement",expression:{type:"Literal",value:"pls remove me"}},e))}convertNamespaceDeclaration(e){if(e.flags&i.NodeFlags.GlobalAugmentation||!i.isIdentifier(e.name)){this.createDeclaration(e).convertNamespace(e,!0);return}const s=this.createDeclaration(e,e.name);s.pushIdentifierReference(e.name),s.convertNamespace(e)}convertEnumDeclaration(e){this.createDeclaration(e,e.name).pushIdentifierReference(e.name)}convertFunctionDeclaration(e){if(!e.name)throw new g(e,"FunctionDeclaration should have a name");const t=this.createDeclaration(e,e.name);t.pushIdentifierReference(e.name),t.convertParametersAndType(e)}convertClassOrInterfaceDeclaration(e){if(!e.name)throw new g(e,"ClassDeclaration / InterfaceDeclaration should have a name");const t=this.createDeclaration(e,e.name),s=t.convertTypeParameters(e.typeParameters);t.convertHeritageClauses(e),t.convertMembers(e.members),t.popScope(s)}convertTypeAliasDeclaration(e){const t=this.createDeclaration(e,e.name),s=t.convertTypeParameters(e.typeParameters);t.convertTypeNode(e.type),t.popScope(s)}convertVariableStatement(e){const{declarations:t}=e.declarationList;if(t.length!==1)throw new g(e,"VariableStatement with more than one declaration not yet supported");for(const s of t){if(!i.isIdentifier(s.name))throw new g(e,"VariableDeclaration must have a name");const r=this.createDeclaration(e,s.name);r.convertTypeNode(s.type),s.initializer&&this.trackExpressionReferences(s.initializer,r)}}trackExpressionReferences(e,t){if(i.isIdentifier(e))t.pushIdentifierReference(e);else if(i.isObjectLiteralExpression(e))for(const s of e.properties)i.isShorthandPropertyAssignment(s)?t.pushIdentifierReference(s.name):i.isPropertyAssignment(s)&&this.trackExpressionReferences(s.initializer,t);else if(i.isArrayLiteralExpression(e))for(const s of e.elements)i.isExpression(s)&&this.trackExpressionReferences(s,t);else i.isPropertyAccessExpression(e)&&this.trackExpressionReferences(e.expression,t)}convertExportDeclaration(e){if(i.isExportAssignment(e)){this.pushStatement(E({type:"ExportDefaultDeclaration",declaration:w(e.expression)},e));return}const t=e.moduleSpecifier?w(e.moduleSpecifier):void 0;if(!e.exportClause)this.pushStatement(E({type:"ExportAllDeclaration",source:t,exported:null,attributes:[]},e));else if(i.isNamespaceExport(e.exportClause))this.pushStatement(E({type:"ExportAllDeclaration",source:t,exported:v(e.exportClause.name),attributes:[]},e));else{const s=[];for(const r of e.exportClause.elements)s.push(this.convertExportSpecifier(r));this.pushStatement(E({type:"ExportNamedDeclaration",declaration:null,specifiers:s,source:t,attributes:[]},e))}}convertImportDeclaration(e){if(i.isImportEqualsDeclaration(e)){if(i.isEntityName(e.moduleReference)){const r=this.createDeclaration(e,e.name);r.pushReference(r.convertEntityName(e.moduleReference));return}if(!i.isExternalModuleReference(e.moduleReference))throw new g(e,"ImportEquals should have a literal source.");this.pushStatement(E({type:"ImportDeclaration",specifiers:[{type:"ImportDefaultSpecifier",local:v(e.name)}],source:w(e.moduleReference.expression),attributes:[]},e));return}const t=w(e.moduleSpecifier),s=e.importClause&&e.importClause.namedBindings?this.convertNamedImportBindings(e.importClause.namedBindings):[];e.importClause&&e.importClause.name&&s.push({type:"ImportDefaultSpecifier",local:v(e.importClause.name)}),this.pushStatement(E({type:"ImportDeclaration",specifiers:s,source:t,attributes:[]},e))}convertNamedImportBindings(e){return i.isNamedImports(e)?e.elements.map(t=>{const s=v(t.name),r=t.propertyName?v(t.propertyName):s;return{type:"ImportSpecifier",local:s,imported:r}}):[{type:"ImportNamespaceSpecifier",local:v(e.name)}]}convertExportSpecifier(e){const t=v(e.name);return{type:"ExportSpecifier",exported:t,local:e.propertyName?v(e.propertyName):t}}}class Oe{static{m(this,"RelativeModuleDeclarationFixer")}constructor(e,t,s,r){this.sourcemap=s,this.DEBUG=!!process.env.DTS_EXPORTS_FIXER_DEBUG,this.relativeModuleDeclarations=[],this.source=L(e,t.toString()),this.code=t,this.name=r||"./index"}fix(){this.analyze(this.source.statements);for(const e of this.relativeModuleDeclarations){const t=e.getStart(),s=e.getEnd(),r=e.name.kind===i.SyntaxKind.StringLiteral&&"singleQuote"in e.name&&e.name.singleQuote?"'":'"',a=`declare module ${r}${this.name}${r} ${e.body.getText()}`;this.code.overwrite(t,s,a)}return{code:this.code.toString(),map:this.relativeModuleDeclarations.length&&this.sourcemap?this.code.generateMap():null}}analyze(e){for(const t of e)i.isModuleDeclaration(t)&&t.body&&i.isModuleBlock(t.body)&&/^\.\.?\//.test(t.name.text)&&(this.DEBUG&&console.log(`Found relative module declaration: ${t.name.text} in ${this.source.fileName}`),this.relativeModuleDeclarations.push(t))}}const Pe=m(()=>{const n=new Map,e=new Map;return{name:"dts-transform",options({onLog:t,...s}){return{...s,onLog(r,a,c){r==="warn"&&a.code==="CIRCULAR_DEPENDENCY"||(t?t(r,a,c):c(r,a))},treeshake:{moduleSideEffects:"no-external",propertyReadSideEffects:!0,unknownGlobalSideEffects:!1}}},outputOptions(t){return{...t,chunkFileNames:t.chunkFileNames||"[name]-[hash].d.ts",entryFileNames:t.entryFileNames||"[name].d.ts",format:"es",exports:"named",compact:!1,freeze:!0,interop:"esModule",generatedCode:Object.assign({symbols:!1},t.generatedCode),strict:!1}},transform(t,s){const r=z(s),a=this.getModuleIds(),c=Array.from(a).find(T=>z(T)===r),p=!!(c&&this.getModuleInfo(c)?.isEntry),u=!!(c&&_.test(c));let l=L(s,t);const f=Ce({sourceFile:l,isEntry:p,isJSON:u});n.set(l.fileName,f.typeReferences),e.set(l.fileName,f.fileReferences),t=f.code.toString(),l=L(s,t);const h=Ae({sourceFile:l});return process.env.DTS_DUMP_AST&&(console.log(s),console.log(t),console.log(JSON.stringify(h.ast.body,void 0,2))),{code:t,ast:h.ast,map:f.code.generateMap()}},renderChunk(t,s,r){const a=L(s.fileName,t),c=new Se(a),p=new Set,u=new Set;for(const D of Object.keys(s.modules)){for(const I of n.get(D.split("\\").join("/"))||[])p.add(I);for(const I of e.get(D.split("\\").join("/"))||[])if(I.startsWith(".")){const b=x.join(x.dirname(D),I),O=r.file&&x.dirname(r.file)||s.facadeModuleId&&x.dirname(s.facadeModuleId)||".";let o=x.relative(O,b).split("\\").join("/");o[0]!=="."&&(o="./"+o),u.add(o)}else u.add(I)}let l=oe(Array.from(u,D=>`/// <reference path="${D}" />`));l+=oe(Array.from(p,D=>`/// <reference types="${D}" />`)),l+=c.fix(),l||(l+=`
export { };`);const h=new be(s.fileName,l).fix();return new Oe(s.fileName,"magicCode"in h&&h.magicCode?h.magicCode:new j(l),!!r.sourcemap,"./"+(r.file&&r.file!=="-"?x.basename(r.file,".d.ts"):"index")).fix()}}},"transform");function oe(n){return n.length?n.join(`
`)+`
`:""}m(oe,"writeBlock");const Re=/\.([cm]ts|[tj]sx?)$/;function q({entries:n,programs:e,resolvedOptions:t},s,r){const{compilerOptions:a,tsconfig:c}=t;if(!e.length&&k.test(s))return{code:r};const p=n.includes(s),u=e.find(l=>{if(p)return l.getRootFileNames().includes(s);{const f=l.getSourceFile(s);return f&&l.isSourceFileFromExternalLibrary(f)?!1:!!f}});if(u){const l=u.getSourceFile(s);return{code:l?.getFullText(),source:l,program:u}}else if(i.sys.fileExists(s)){if(e.length>0&&k.test(s)&&(t.includeExternal.length>0||t.respectExternal))return{code:r};const l=de(s,a,c);e.push(l);const f=l.getSourceFile(s);return{code:f?.getFullText(),source:f,program:l}}else return null}m(q,"getModule");const ae=m((n={})=>{const e=Pe(),t={entries:[],programs:[],resolvedOptions:me(n)};return{name:"dts",outputOptions:e.outputOptions,renderChunk:e.renderChunk,options(s){let{input:r=[]}=s;if(!Array.isArray(r))r=typeof r=="string"?[r]:Object.values(r);else if(r.length>1){s.input={};for(const a of r){let c=z(a);x.isAbsolute(a)?c=x.basename(c):c=x.normalize(c),s.input[c]=a}}return t.programs=he(Object.values(r),t.resolvedOptions.compilerOptions,t.resolvedOptions.tsconfig),e.options.call(this,s)},transform(s,r){if(!Re.test(r)&&!_.test(r))return null;const a=m(l=>{if(l.program){const f=x.dirname(r);l.program.getSourceFiles().map(T=>T.fileName).filter(T=>T.startsWith(f)).forEach(this.addWatchFile)}},"watchFiles"),c=m(()=>{const l=q(t,r,s);return l?(a(l),e.transform.call(this,l.code,r)):null},"handleDtsFile"),p=m(()=>{const l=J(r),f=q(t,l,s);return f?(a(f),e.transform.call(this,f.code,l)):null},"treatTsAsDts"),u=m(()=>{const l=q(t,r,s);if(!l||!l.source||!l.program)return null;a(l);const f=J(r);let h;const{emitSkipped:T,diagnostics:D}=l.program.emit(l.source,(I,b)=>{h=e.transform.call(this,b,f)},void 0,!0,void 0,!0);if(T){const I=D.filter(b=>b.category===i.DiagnosticCategory.Error);I.length&&(console.error(i.formatDiagnostics(I,V)),this.error("Failed to compile. Check the logs above."))}return h},"generateDts");return k.test(r)?c():_.test(r)?u():p()??u()},resolveId(s,r){if(!r){t.entries.push(x.resolve(s));return}r=r.split("\\").join("/");let a=t.resolvedOptions.compilerOptions;if(t.resolvedOptions.tsconfig){const p=s.startsWith(".")?x.resolve(x.dirname(r),s):s;a=U(p,t.resolvedOptions.compilerOptions,t.resolvedOptions.tsconfig).compilerOptions}const{resolvedModule:c}=i.resolveModuleName(s,r,a,i.sys);if(c)return c.isExternalLibraryImport&&c.packageId&&t.resolvedOptions.includeExternal.includes(c.packageId.name)?{id:x.resolve(c.resolvedFileName)}:!t.resolvedOptions.respectExternal&&c.isExternalLibraryImport?{id:s,external:!0}:{id:x.resolve(c.resolvedFileName)}}}},"plugin");export{ae as default,ae as dts};