pkgroll 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -10
- package/dist/cli.js +2 -2
- package/dist/rollup-plugin-dts-93eb415d.js +25 -0
- package/package.json +1 -1
- package/dist/rollup-plugin-dts-eb7b5c98.js +0 -24
package/README.md
CHANGED
|
@@ -1,14 +1,10 @@
|
|
|
1
1
|
# 📦 🍣 pkgroll
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node.js packages already define entry-points in `package.json`, so why re-define them in our bundler configuration?
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
- **Export & Import maps** Uses export and import maps to configure endpoints and aliases
|
|
9
|
-
- **TypeScript friendly** Transform TS and emit `.d.ts` files (Supports `.cts`/`.mts` too!)
|
|
10
|
-
- **Node.js ESM ⇄ CJS friendly** Preserves named exports from ESM to CJS
|
|
11
|
-
- **Fast** Transformations powered by [esbuild](https://esbuild.github.io/)
|
|
5
|
+
Pkgroll is a smart package bundler that infers how to build your package from entry-points defined in `package.json`.
|
|
6
|
+
|
|
7
|
+
Write your code in TypeScript/ESM and run `pkgroll` to get ESM/CommonJS/DTS outputs!
|
|
12
8
|
|
|
13
9
|
## Install
|
|
14
10
|
```sh
|
|
@@ -32,14 +28,14 @@ npm install --save-dev pkgroll
|
|
|
32
28
|
// "type": "module",
|
|
33
29
|
|
|
34
30
|
// Define the output files
|
|
35
|
-
"main": "./dist/file.
|
|
31
|
+
"main": "./dist/file.cjs",
|
|
36
32
|
"module": "./dist/file.mjs",
|
|
37
33
|
"types": "./dist/file.d.ts",
|
|
38
34
|
|
|
39
35
|
// Define output files for Node.js export maps (https://nodejs.org/api/packages.html#exports)
|
|
40
36
|
"exports": {
|
|
41
37
|
"types": "./dist/file.d.ts",
|
|
42
|
-
"require": "./dist/file.
|
|
38
|
+
"require": "./dist/file.cjs",
|
|
43
39
|
"import": "./dist/file.mjs"
|
|
44
40
|
},
|
|
45
41
|
|
package/dist/cli.js
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
`:"")+(t?this.indentText({text:this.render(t),spaces:D}):"")}
|
|
20
20
|
`}table({tableData:e,tableOptions:t,tableBreakpoints:D}){return me(e.map(n=>n.map(r=>this.render(r))),D?ye(D):t)}flagParameter(e){return e===Boolean?"":e===String?"<string>":e===Number?"<number>":Array.isArray(e)?this.flagParameter(e[0]):"<value>"}flagOperator(e){return" "}flagName(e){const{flag:t,flagFormatted:D,aliasesEnabled:n,aliasFormatted:r}=e;let o="";if(r?o+=`${r}, `:n&&(o+=" "),o+=D,"placeholder"in t&&typeof t.placeholder=="string")o+=`${this.flagOperator(e)}${t.placeholder}`;else{const i=this.flagParameter("type"in t?t.type:t);i&&(o+=`${this.flagOperator(e)}${i}`)}return o}flagDefault(e){return JSON.stringify(e)}flagDescription({flag:e}){var D;let t="description"in e&&(D=e.description)!=null?D:"";if("default"in e){let{default:n}=e;typeof n=="function"&&(n=n()),n&&(t+=` (default: ${this.flagDefault(n)})`)}return t}render(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>this.render(t)).join(`
|
|
21
21
|
`);if("type"in e&&this[e.type]){const t=this[e.type];if(typeof t=="function")return t.call(this,e.data)}throw new Error(`Invalid node type: ${JSON.stringify(e)}`)}}const Ru=/^[\w.-]+$/,{stringify:x}=JSON,Ie=/[|\\{}()[\]^$+*?.]/;function ou(u){const e=[];let t,D;for(const n of u){if(D)throw new Error(`Invalid parameter: Spread parameter ${x(D)} must be last`);const r=n[0],o=n[n.length-1];let i;if(r==="<"&&o===">"&&(i=!0,t))throw new Error(`Invalid parameter: Required parameter ${x(n)} cannot come after optional parameter ${x(t)}`);if(r==="["&&o==="]"&&(i=!1,t=n),i===void 0)throw new Error(`Invalid parameter: ${x(n)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let a=n.slice(1,-1);const s=a.slice(-3)==="...";s&&(D=n,a=a.slice(0,-3));const F=a.match(Ie);if(F)throw new Error(`Invalid parameter: ${x(n)}. Invalid character found ${x(F[0])}`);e.push({name:a,required:i,spread:s})}return e}function iu(u,e,t,D){for(let n=0;n<e.length;n+=1){const{name:r,required:o,spread:i}=e[n],a=ve(r);if(a in u)throw new Error(`Invalid parameter: ${x(r)} is used more than once.`);const s=i?t.slice(n):t[n];if(i&&(n=e.length),o&&(!s||i&&s.length===0))return console.error(`Error: Missing required parameter ${x(r)}
|
|
22
|
-
`),D(),process.exit(1);u[a]=s}}function Le(u){return u===void 0||u!==!1}function Mu(u,e,t,D){const n={...e.flags},r=e.version;r&&(n.version={type:Boolean,description:"Show version"});const{help:o}=e,i=Le(o);i&&!("help"in n)&&(n.help={type:Boolean,alias:"h",description:"Show help"});const a=qD(n,D,{ignore:e.ignoreArgv}),s=()=>{console.log(e.version)};if(r&&a.flags.version===!0)return s(),process.exit(0);const F=new Me,l=i&&(o==null?void 0:o.render)?o.render:d=>F.render(d),C=d=>{const g=Ne({...e,...d?{help:d}:{},flags:n});console.log(l(g,F))};if(i&&a.flags.help===!0)return C(),process.exit(0);if(e.parameters){let{parameters:d}=e,g=a._;const A=d.indexOf("--"),B=d.slice(A+1),E=Object.create(null);if(A>-1&&B.length>0){d=d.slice(0,A);const c=a._["--"];g=g.slice(0,-c.length||void 0),iu(E,ou(d),g,C),iu(E,ou(B),c,C)}else iu(E,ou(d),g,C);Object.assign(a._,E)}const f={...a,showVersion:s,showHelp:C};return typeof t=="function"&&t(f),{command:u,...f}}function We(u,e){const t=new Map;for(const D of e){const n=[D.options.name],{alias:r}=D.options;r&&(Array.isArray(r)?n.push(...r):n.push(r));for(const o of n){if(t.has(o))throw new Error(`Duplicate command name found: ${x(o)}`);t.set(o,D)}}return t.get(u)}function qe(u,e,t=process.argv.slice(2)){if(!u)throw new Error("Options is required");if("name"in u&&(!u.name||!Ru.test(u.name)))throw new Error(`Invalid script name: ${x(u.name)}`);const D=t[0];if(u.commands&&Ru.test(D)){const n=We(D,u.commands);if(n)return Mu(n.options.name,{...n.options,parent:u},n.callback,t.slice(1))}return Mu(void 0,u,e,t)}var Ue="1.
|
|
22
|
+
`),D(),process.exit(1);u[a]=s}}function Le(u){return u===void 0||u!==!1}function Mu(u,e,t,D){const n={...e.flags},r=e.version;r&&(n.version={type:Boolean,description:"Show version"});const{help:o}=e,i=Le(o);i&&!("help"in n)&&(n.help={type:Boolean,alias:"h",description:"Show help"});const a=qD(n,D,{ignore:e.ignoreArgv}),s=()=>{console.log(e.version)};if(r&&a.flags.version===!0)return s(),process.exit(0);const F=new Me,l=i&&(o==null?void 0:o.render)?o.render:d=>F.render(d),C=d=>{const g=Ne({...e,...d?{help:d}:{},flags:n});console.log(l(g,F))};if(i&&a.flags.help===!0)return C(),process.exit(0);if(e.parameters){let{parameters:d}=e,g=a._;const A=d.indexOf("--"),B=d.slice(A+1),E=Object.create(null);if(A>-1&&B.length>0){d=d.slice(0,A);const c=a._["--"];g=g.slice(0,-c.length||void 0),iu(E,ou(d),g,C),iu(E,ou(B),c,C)}else iu(E,ou(d),g,C);Object.assign(a._,E)}const f={...a,showVersion:s,showHelp:C};return typeof t=="function"&&t(f),{command:u,...f}}function We(u,e){const t=new Map;for(const D of e){const n=[D.options.name],{alias:r}=D.options;r&&(Array.isArray(r)?n.push(...r):n.push(r));for(const o of n){if(t.has(o))throw new Error(`Duplicate command name found: ${x(o)}`);t.set(o,D)}}return t.get(u)}function qe(u,e,t=process.argv.slice(2)){if(!u)throw new Error("Options is required");if("name"in u&&(!u.name||!Ru.test(u.name)))throw new Error(`Invalid script name: ${x(u.name)}`);const D=t[0];if(u.commands&&Ru.test(D)){const n=We(D,u.commands);if(n)return Mu(n.options.name,{...n.options,parent:u},n.callback,t.slice(1))}return Mu(void 0,u,e,t)}var Ue="1.6.0";const Iu=u=>j.default.promises.access(u).then(()=>!0,()=>!1),Ve=async u=>{const e=p.default.join(u,"package.json");if(!await Iu(e))throw new Error(`package.json not found at: ${e}`);const D=await j.default.promises.readFile(e,"utf8");try{return JSON.parse(D)}catch(n){throw new Error(`Cannot parse package.json: ${n.message}`)}},ze=/^[/.]/,Y=(u,e)=>(!p.default.isAbsolute(u)&&!ze.test(u)&&(u=`./${u}`),e&&!u.endsWith("/")&&(u+="/"),u),k=u=>{if(u.endsWith(".mjs"))return"module";if(u.endsWith(".cjs"))return"commonjs"},Lu=u=>u.startsWith(".");function au(u,e,t="exports"){if(u){if(typeof u=="string")return Lu(u)?[{outputPath:u,type:k(u)||e,from:t}]:[];if(Array.isArray(u))return u.flatMap((D,n)=>{const r=`${t}[${n}]`;return typeof D=="string"?Lu(D)?{outputPath:D,type:k(D)||e,from:r}:[]:au(D,e,r)});if(typeof u=="object")return Object.entries(u).flatMap(([D,n])=>{if(typeof n=="string"){const r={outputPath:n,from:`${t}.${D}`};if(D==="require")return{...r,type:"commonjs"};if(D==="import")return{...r,type:k(n)||e};if(D==="types")return{...r,type:"types"};if(D==="node")return{...r,type:k(n)||e,platform:"node"};if(D==="default")return{...r,type:k(n)||e}}return au(n,e,`${t}.${D}`)})}return[]}function P(u,e){e.outputPath=Y(e.outputPath);const{outputPath:t,type:D,platform:n}=e,r=u[t];if(r){if(r.type!==D)throw new Error(`Conflicting export types "${r.type}" & "${D}" found for ${t}`);if(r.platform!==n)throw new Error(`Conflicting export platforms "${r.platform}" & "${n}" found for ${t}`);Object.assign(r,e)}else u[t]=e}const Ge=u=>{var e,t,D,n;const r={},o=(e=u.type)!=null?e:"commonjs";if(u.main){const i=u.main;P(r,{outputPath:i,type:(t=k(i))!=null?t:o,from:"main"})}if(u.module&&P(r,{outputPath:u.module,type:"module",from:"module"}),u.types&&P(r,{outputPath:u.types,type:"types",from:"types"}),u.bin){const{bin:i}=u;if(typeof i=="string")P(r,{outputPath:i,type:(D=k(i))!=null?D:o,isExecutable:!0,from:"bin"});else for(const[a,s]of Object.entries(i))P(r,{outputPath:s,type:(n=k(s))!=null?n:o,isExecutable:!0,from:`bin.${a}`})}if(u.exports){const i=au(u.exports,o);for(const a of i)P(r,a)}return Object.values(r)},Ze=["peerDependencies","dependencies","optionalDependencies"],Je=u=>{const e=[];for(const t of Ze){const D=u[t];D&&e.push(...Object.keys(D))}return e},Ye=({imports:u},e)=>{const t={};if(u)for(const D in u){if(D.startsWith("#"))continue;const n=u[D];typeof n=="string"&&(t[D]=p.default.join(e,n))}return t},{stringify:He}=JSON;async function Ke(u,e){for(const t of e){const D=u+t;if(await Iu(D))return D}}const Wu={".d.ts":[".d.ts",".ts",".mts",".cts"],".js":[".js",".ts",".tsx",".mts",".cts"],".mjs":[".mjs",".js",".cjs",".mts",".cts",".ts"],".cjs":[".cjs",".js",".mjs",".mts",".cts",".ts"]};async function Qe(u,e,t){const D=e+u.outputPath.slice(t.length);for(const n of Object.keys(Wu))if(u.outputPath.endsWith(n)){const r=await Ke(D.slice(0,-n.length),Wu[n]);if(r)return r}throw new Error(`Could not find matching source file for export path ${He(u.outputPath)}`)}const su="pkgroll:create-require",qu=`IS_ESM${Math.random().toString(36).slice(2)}`,Xe=()=>({...mD.default({require:su}),name:"create-require",resolveId:u=>u===su?u:null,load(u){return u!==su?null:`
|
|
23
23
|
import { createRequire } from 'module';
|
|
24
24
|
|
|
25
25
|
export default (
|
|
@@ -30,4 +30,4 @@
|
|
|
30
30
|
`}}),ut=u=>({name:"create-require-insert-format",renderChunk:pu.default({[qu]:u}).renderChunk});function H(u){const e=/^\\\\\?\\/.test(u),t=/[^\u0000-\u0080]+/.test(u);return e||t?u:u.replace(/\\/g,"/")}function lu(u,e){for(;;){const t=p.default.join(u,e);if(j.default.existsSync(t))return H(t);const D=p.default.dirname(u);if(D===u)return;u=D}}function Dt(u,e){e===void 0&&(e=!1);var t=u.length,D=0,n="",r=0,o=16,i=0,a=0,s=0,F=0,l=0;function C(c,b){for(var w=0,y=0;w<c||!b;){var m=u.charCodeAt(D);if(m>=48&&m<=57)y=y*16+m-48;else if(m>=65&&m<=70)y=y*16+m-65+10;else if(m>=97&&m<=102)y=y*16+m-97+10;else break;D++,w++}return w<c&&(y=-1),y}function f(c){D=c,n="",r=0,o=16,l=0}function d(){var c=D;if(u.charCodeAt(D)===48)D++;else for(D++;D<u.length&&_(u.charCodeAt(D));)D++;if(D<u.length&&u.charCodeAt(D)===46)if(D++,D<u.length&&_(u.charCodeAt(D)))for(D++;D<u.length&&_(u.charCodeAt(D));)D++;else return l=3,u.substring(c,D);var b=D;if(D<u.length&&(u.charCodeAt(D)===69||u.charCodeAt(D)===101))if(D++,(D<u.length&&u.charCodeAt(D)===43||u.charCodeAt(D)===45)&&D++,D<u.length&&_(u.charCodeAt(D))){for(D++;D<u.length&&_(u.charCodeAt(D));)D++;b=D}else l=3;return u.substring(c,b)}function g(){for(var c="",b=D;;){if(D>=t){c+=u.substring(b,D),l=2;break}var w=u.charCodeAt(D);if(w===34){c+=u.substring(b,D),D++;break}if(w===92){if(c+=u.substring(b,D),D++,D>=t){l=2;break}var y=u.charCodeAt(D++);switch(y){case 34:c+='"';break;case 92:c+="\\";break;case 47:c+="/";break;case 98:c+="\b";break;case 102:c+="\f";break;case 110:c+=`
|
|
31
31
|
`;break;case 114:c+="\r";break;case 116:c+=" ";break;case 117:var m=C(4,!0);m>=0?c+=String.fromCharCode(m):l=4;break;default:l=5}b=D;continue}if(w>=0&&w<=31)if(L(w)){c+=u.substring(b,D),l=2;break}else l=6;D++}return c}function A(){if(n="",l=0,r=D,a=i,F=s,D>=t)return r=t,o=17;var c=u.charCodeAt(D);if(Fu(c)){do D++,n+=String.fromCharCode(c),c=u.charCodeAt(D);while(Fu(c));return o=15}if(L(c))return D++,n+=String.fromCharCode(c),c===13&&u.charCodeAt(D)===10&&(D++,n+=`
|
|
32
32
|
`),i++,s=D,o=14;switch(c){case 123:return D++,o=1;case 125:return D++,o=2;case 91:return D++,o=3;case 93:return D++,o=4;case 58:return D++,o=6;case 44:return D++,o=5;case 34:return D++,n=g(),o=10;case 47:var b=D-1;if(u.charCodeAt(D+1)===47){for(D+=2;D<t&&!L(u.charCodeAt(D));)D++;return n=u.substring(b,D),o=12}if(u.charCodeAt(D+1)===42){D+=2;for(var w=t-1,y=!1;D<w;){var m=u.charCodeAt(D);if(m===42&&u.charCodeAt(D+1)===47){D+=2,y=!0;break}D++,L(m)&&(m===13&&u.charCodeAt(D)===10&&D++,i++,s=D)}return y||(D++,l=1),n=u.substring(b,D),o=13}return n+=String.fromCharCode(c),D++,o=16;case 45:if(n+=String.fromCharCode(c),D++,D===t||!_(u.charCodeAt(D)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return n+=d(),o=11;default:for(;D<t&&B(c);)D++,c=u.charCodeAt(D);if(r!==D){switch(n=u.substring(r,D),n){case"true":return o=8;case"false":return o=9;case"null":return o=7}return o=16}return n+=String.fromCharCode(c),D++,o=16}}function B(c){if(Fu(c)||L(c))return!1;switch(c){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function E(){var c;do c=A();while(c>=12&&c<=15);return c}return{setPosition:f,getPosition:function(){return D},scan:e?E:A,getToken:function(){return o},getTokenValue:function(){return n},getTokenOffset:function(){return r},getTokenLength:function(){return D-r},getTokenStartLine:function(){return a},getTokenStartCharacter:function(){return r-F},getTokenError:function(){return l}}}function Fu(u){return u===32||u===9||u===11||u===12||u===160||u===5760||u>=8192&&u<=8203||u===8239||u===8287||u===12288||u===65279}function L(u){return u===10||u===13||u===8232||u===8233}function _(u){return u>=48&&u<=57}var K;(function(u){u.DEFAULT={allowTrailingComma:!1}})(K||(K={}));function et(u,e,t){e===void 0&&(e=[]),t===void 0&&(t=K.DEFAULT);var D=null,n=[],r=[];function o(a){Array.isArray(n)?n.push(a):D!==null&&(n[D]=a)}var i={onObjectBegin:function(){var a={};o(a),r.push(n),n=a,D=null},onObjectProperty:function(a){D=a},onObjectEnd:function(){n=r.pop()},onArrayBegin:function(){var a=[];o(a),r.push(n),n=a,D=null},onArrayEnd:function(){n=r.pop()},onLiteralValue:o,onError:function(a,s,F){e.push({error:a,offset:s,length:F})}};return tt(u,i,t),n[0]}function tt(u,e,t){t===void 0&&(t=K.DEFAULT);var D=Dt(u,!1);function n(h){return h?function(){return h(D.getTokenOffset(),D.getTokenLength(),D.getTokenStartLine(),D.getTokenStartCharacter())}:function(){return!0}}function r(h){return h?function($){return h($,D.getTokenOffset(),D.getTokenLength(),D.getTokenStartLine(),D.getTokenStartCharacter())}:function(){return!0}}var o=n(e.onObjectBegin),i=r(e.onObjectProperty),a=n(e.onObjectEnd),s=n(e.onArrayBegin),F=n(e.onArrayEnd),l=r(e.onLiteralValue),C=r(e.onSeparator),f=n(e.onComment),d=r(e.onError),g=t&&t.disallowComments,A=t&&t.allowTrailingComma;function B(){for(;;){var h=D.scan();switch(D.getTokenError()){case 4:E(14);break;case 5:E(15);break;case 3:E(13);break;case 1:g||E(11);break;case 2:E(12);break;case 6:E(16);break}switch(h){case 12:case 13:g?E(10):f();break;case 16:E(1);break;case 15:case 14:break;default:return h}}}function E(h,$,U){if($===void 0&&($=[]),U===void 0&&(U=[]),d(h),$.length+U.length>0)for(var V=D.getToken();V!==17;){if($.indexOf(V)!==-1){B();break}else if(U.indexOf(V)!==-1)break;V=B()}}function c(h){var $=D.getTokenValue();return h?l($):i($),B(),!0}function b(){switch(D.getToken()){case 11:var h=D.getTokenValue(),$=Number(h);isNaN($)&&(E(2),$=0),l($);break;case 7:l(null);break;case 8:l(!0);break;case 9:l(!1);break;default:return!1}return B(),!0}function w(){return D.getToken()!==10?(E(3,[],[2,5]),!1):(c(!1),D.getToken()===6?(C(":"),B(),uu()||E(4,[],[2,5])):E(5,[],[2,5]),!0)}function y(){o(),B();for(var h=!1;D.getToken()!==2&&D.getToken()!==17;){if(D.getToken()===5){if(h||E(4,[],[]),C(","),B(),D.getToken()===2&&A)break}else h&&E(6,[],[]);w()||E(4,[],[2,5]),h=!0}return a(),D.getToken()!==2?E(7,[2],[]):B(),!0}function m(){s(),B();for(var h=!1;D.getToken()!==4&&D.getToken()!==17;){if(D.getToken()===5){if(h||E(4,[],[]),C(","),B(),D.getToken()===4&&A)break}else h&&E(6,[],[]);uu()||E(4,[],[4,5]),h=!0}return F(),D.getToken()!==4?E(8,[4],[]):B(),!0}function uu(){switch(D.getToken()){case 3:return m();case 1:return y();case 10:return c(!0);default:return b()}}return B(),D.getToken()===17?t.allowEmptyContent?!0:(E(4,[],[]),!1):uu()?(D.getToken()!==17&&E(9,[],[]),!0):(E(4,[],[]),!1)}var nt=et;const rt=/^\.{1,2}(\/.*)?$/,cu=u=>H(rt.test(u)?u:`./${u}`),{existsSync:W}=j.default,ot=u=>{try{return JSON.parse(u)}catch{}},it=()=>{const{findPnpApi:u}=AD.default;return u&&u(process.cwd())};function Uu(u){const e=ot(j.default.readFileSync(u,"utf8"));return p.default.join(u,"..",e&&"tsconfig"in e?e.tsconfig:"tsconfig.json")}function at(u,e){let t=u;if(t===".."&&(t+="/tsconfig.json"),t.startsWith(".")){let r=p.default.resolve(e,t);if(W(r)&&j.default.statSync(r).isFile()||!r.endsWith(".json")&&(r+=".json",W(r)))return r;throw new Error(`File '${u}' not found.`)}const D=it();if(D){const{resolveRequest:r}=D,[o,i]=u.split("/"),a=o.startsWith("@")?`${o}/${i}`:o;try{if(a===u){const s=r(p.default.join(a,"package.json"),e);if(s){const F=Uu(s);if(W(F))return F}}else try{return r(u,e,{extensions:[".json"]})}catch{return r(p.default.join(u,"tsconfig.json"),e)}}catch{}}let n=lu(e,p.default.join("node_modules",t));if(n){if(j.default.statSync(n).isDirectory()){const r=p.default.join(n,"package.json");if(W(r)?n=Uu(r):n=p.default.join(n,"tsconfig.json"),W(n))return n}else if(n.endsWith(".json"))return n}if(!t.endsWith(".json")&&(t+=".json",n=lu(e,p.default.join("node_modules",t)),n))return n;throw new Error(`File '${u}' not found.`)}var st=Object.defineProperty,lt=Object.defineProperties,Ft=Object.getOwnPropertyDescriptors,Vu=Object.getOwnPropertySymbols,ct=Object.prototype.hasOwnProperty,Ct=Object.prototype.propertyIsEnumerable,zu=(u,e,t)=>e in u?st(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t,N=(u,e)=>{for(var t in e||(e={}))ct.call(e,t)&&zu(u,t,e[t]);if(Vu)for(var t of Vu(e))Ct.call(e,t)&&zu(u,t,e[t]);return u},ft=(u,e)=>lt(u,Ft(e));function Gu(u){var e;let t;try{t=j.default.realpathSync(u)}catch{throw new Error(`Cannot resolve tsconfig at path: ${u}`)}const D=p.default.dirname(t),n=j.default.readFileSync(t,"utf8").trim();let r={};if(n&&(r=nt(n),!r||typeof r!="object"))throw new SyntaxError(`Failed to parse tsconfig at: ${u}`);if(r.extends){const o=at(r.extends,D),i=Gu(o);if(delete i.references,(e=i.compilerOptions)!=null&&e.baseUrl){const{compilerOptions:s}=i;s.baseUrl=p.default.relative(D,p.default.join(p.default.dirname(o),s.baseUrl))||"./"}i.files&&(i.files=i.files.map(s=>p.default.relative(D,p.default.join(p.default.dirname(o),s)))),i.include&&(i.include=i.include.map(s=>p.default.relative(D,p.default.join(p.default.dirname(o),s)))),delete r.extends;const a=ft(N(N({},i),r),{compilerOptions:N(N({},i.compilerOptions),r.compilerOptions)});i.watchOptions&&(a.watchOptions=N(N({},i.watchOptions),r.watchOptions)),r=a}if(r.compilerOptions){const{compilerOptions:o}=r;o.baseUrl&&(o.baseUrl=cu(o.baseUrl)),o.outDir&&(Array.isArray(r.exclude)||(r.exclude=[]),r.exclude.push(o.outDir),o.outDir=cu(o.outDir))}if(r.files&&(r.files=r.files.map(cu)),r.include&&(r.include=r.include.map(H)),r.watchOptions){const{watchOptions:o}=r;o.excludeDirectories&&(o.excludeDirectories=o.excludeDirectories.map(i=>H(p.default.resolve(D,i))))}return r}function Et(u=process.cwd(),e="tsconfig.json"){const t=lu(u,e);if(!t)return null;const D=Gu(t);return{path:t,config:D}}const Zu=Et();function dt(u){const e=fD.createFilter(/\.([cm]?ts|[jt]sx)$/);return{name:"esbuild-transform",async transform(t,D){var n;if(!e(D))return null;const r=await Eu.transform(t,{...u,loader:"default",sourcefile:D.replace(/\.[cm]ts/,".ts"),tsconfigRaw:(n=Zu)==null?void 0:n.config});return{code:r.code,map:r.map||null}}}}const pt=u=>{if(u==="es")return"esm";if(u==="cjs"||u==="iife")return u};function gt(u){return{name:"esbuild-minify",async renderChunk(e,t,D){const n=await Eu.transform(e,{...u,format:pt(D.format),minify:!0});return{code:n.code,map:n.map||null}}}}const Cu=(u,e)=>u[0]-e[0]||u[1]-e[1]||u[2]-e[2],Ju=({target:u})=>{const e=u.some(t=>{var D,n;if(t=t.trim(),!t.startsWith("node"))return;const r=t.slice(4).split(".").map(Number),o=[r[0],(D=r[1])!=null?D:0,(n=r[2])!=null?n:0];return!(Cu(o,[12,20,0])>=0&&Cu(o,[13,0,0])<0||Cu(o,[14,13,1])>=0)});return{name:"externalize-node-builtins",resolveId:t=>{const D=t.startsWith("node:");if(e&&D&&(t=t.slice(5)),du.builtinModules.includes(t)||D)return{id:t,external:!0}}}},ht=u=>({name:"patch-binary",renderChunk(e,t,D){if(!t.isEntry||!t.facadeModuleId)return;const n=D.entryFileNames,r=`./${p.default.join(D.dir,n(t))}`;if(u.includes(r)){const o=new bD.default(e);return o.prepend(`#!/usr/bin/env node
|
|
33
|
-
`),{code:o.toString(),map:D.sourcemap?o.generateMap({hires:!0}):void 0}}},async writeBundle(e,t){const D=e.entryFileNames,n=Object.values(t).map(async r=>{const o=r;if(o.isEntry&&o.facadeModuleId){const i=p.default.join(e.dir,D(o));await j.default.promises.chmod(i,493)}});await Promise.all(n)}});function Yu(){const u=/\.(?:
|
|
33
|
+
`),{code:o.toString(),map:D.sourcemap?o.generateMap({hires:!0}):void 0}}},async writeBundle(e,t){const D=e.entryFileNames,n=Object.values(t).map(async r=>{const o=r;if(o.isEntry&&o.facadeModuleId){const i=p.default.join(e.dir,D(o));await j.default.promises.chmod(i,493)}});await Promise.all(n)}});function Yu(){const u=/\.(?:[mc]?js|jsx)$/,e=/\.(?:mts|cts)$/;return{name:"resolve-typescript-mjs-cjs",resolveId(t,D,n){return u.test(t)&&D&&e.test(D)?this.resolve(t.replace(/js(x?)$/,"ts$1"),D,n):null}}}const Hu=u=>u.split("?")[0],Ku={async type(u){const e=await Promise.resolve().then(function(){return require("./rollup-plugin-dts-93eb415d.js")});return{input:[],preserveEntrySignatures:"strict",plugins:[Ju(u),Yu(),e.default({respectExternal:!0})],output:[],external:[]}},app(u,e,t,D){const n={target:u.target};return{input:[],preserveEntrySignatures:"strict",plugins:[Ju(u),Yu(),BD.default({entries:e}),pD.default({extensions:[".mjs",".js",".ts",".jsx",".tsx",".json"],exportConditions:u.exportCondition}),...Object.keys(t).length>0?[pu.default({preventAssignment:!0,objectGuards:!0,values:t})]:[],gD.default(),hD.default(),dt(n),Xe(),...u.minify?[gt(n)]:[],ht(D)],output:[],external:[]}}};async function Bt(u,e,t,D,n,r){const o=t.filter(({exportEntry:s})=>s.isExecutable).map(({exportEntry:s})=>s.outputPath),i=Object.create(null),a=Object.fromEntries(D.env.map(({key:s,value:F})=>[`process.env.${s}`,JSON.stringify(F)]));for(const{input:s,exportEntry:F}of t){if(F.type==="types"){let g=i.type;g||(g=await Ku.type(D),g.external=r,i.type=g),g.input.push(s);const A=".d.ts";g.output=[{dir:e,entryFileNames:B=>j.default.realpathSync.native(Hu(B.facadeModuleId)).slice(u.length).replace(/(:?\.d)?\.\w+$/,A),exports:"auto",format:"esm"}];continue}let l=i.app;l||(l=Ku.app(D,n,a,o),l.external=r,i.app=l),l.input.includes(s)||l.input.push(s);const C=l.output,f=p.default.extname(F.outputPath),d=`${F.type}-${f}`;if(!C[d]){const g={dir:e,exports:"auto",format:F.type,chunkFileNames:`[name]-[hash]${f}`,plugins:[ut(F.type==="module")],entryFileNames:A=>j.default.realpathSync.native(Hu(A.facadeModuleId)).slice(u.length).replace(/\.\w+$/,f)};C.push(g),C[d]=g}}return i}let T=!0;const R=typeof self!="undefined"?self:typeof window!="undefined"?window:typeof global!="undefined"?global:{};let Qu=0;if(R.process&&R.process.env&&R.process.stdout){const{FORCE_COLOR:u,NODE_DISABLE_COLORS:e,TERM:t}=R.process.env;e||u==="0"?T=!1:u==="1"?T=!0:t==="dumb"?T=!1:"CI"in R.process.env&&["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(D=>D in R.process.env)?T=!0:T=process.stdout.isTTY,T&&(Qu=t&&t.endsWith("-256color")?2:1)}let Xu={enabled:T,supportLevel:Qu};function mt(u,e,t=1){const D=`\x1B[${u}m`,n=`\x1B[${e}m`,r=new RegExp(`\\x1b\\[${e}m`,"g");return o=>Xu.enabled&&Xu.supportLevel>=t?D+(""+o).replace(r,D)+n:""+o}const At=mt(90,39),bt=()=>new Date().toLocaleTimeString(),Q=(...u)=>console.log(`[${At(bt())}]`,...u);var uD,DD;const q=qe({name:"pkgroll",version:Ue,flags:{src:{type:String,description:"Source directory",default:"./src"},dist:{type:String,description:"Distribution directory",default:"./dist"},minify:{type:Boolean,description:"Minify output",alias:"m",default:!1},target:{type:[String],default:[`node${process.versions.node}`],description:"Environments to support. `target` in tsconfig.json is automatically added. Defaults to the current Node.js version.",alias:"t"},watch:{type:Boolean,description:"Watch mode",alias:"w",default:!1},env:{type:[function(e){const[t,D]=e.split("=");return{key:t,value:D}}],description:"Compile-time environment variables (eg. --env.NODE_ENV=production)"},exportCondition:{type:[String],description:"Export conditions for resolving dependency export and import maps (eg. --export-condition=node)"}},help:{description:"Minimalistic package bundler",render(u,e){return e.flagOperator=t=>t.name==="env"?".key=":" ",e.render(u)}}}),eD=process.cwd(),{stringify:yt}=JSON,tD=Y(q.flags.src,!0),X=Y(q.flags.dist,!0),nD=(DD=(uD=Zu)==null?void 0:uD.config.compilerOptions)==null?void 0:DD.target;nD&&q.flags.target.push(nD),(async()=>{const u=await Ve(eD);let e=Ge(u);if(e=e.filter(o=>{const i=o.outputPath.startsWith(X);return i||console.warn(`Ignoring entry outside of ${X} directory: package.json#${o.from}=${yt(o.outputPath)}`),i}),e.length===0)throw new Error("No export entries found in package.json");const t=await Promise.all(e.map(async o=>({input:await Qe(o,tD,X),exportEntry:o}))),D=Ye(u,eD),n=Je(u).filter(o=>!(o in D)).flatMap(o=>[o,new RegExp(`^${o}/`)]),r=await Bt(Y(j.default.realpathSync.native(tD),!0),X,t,q.flags,D,n);q.flags.watch?(Q("Watch initialized"),Object.values(r).map(async o=>{fu.watch(o).on("event",async a=>{a.code==="BUNDLE_START"&&Q("Building",...Array.isArray(a.input)?a.input:[a.input]),a.code==="BUNDLE_END"&&(await Promise.all(o.output.map(s=>a.result.write(s))),Q("Built",...Array.isArray(a.input)?a.input:[a.input])),a.code==="ERROR"&&Q("Error:",a.error.message)})})):await Promise.all(Object.values(r).map(async o=>{const i=await fu.rollup(o);return Promise.all(o.output.map(a=>i.write(a)))}))})().catch(u=>{console.error(u),process.exit(1)});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";var W=require("module"),G=require("path"),J=require("magic-string");function Y(i){return i&&typeof i=="object"&&"default"in i?i:{default:i}}function Q(i){if(i&&i.__esModule)return i;var e=Object.create(null);return i&&Object.keys(i).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(i,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return i[r]}})}}),e.default=i,Object.freeze(e)}var T=Q(G),Z=Y(J),K=require;function X(){const i=process.cwd();try{return K.resolve("typescript",{paths:[i]})}catch{throw new Error(`Could not find \`typescript\` in ${i}`)}}var t=K(X());const A=".d.ts",M={getCurrentDirectory:()=>t.sys.getCurrentDirectory(),getNewLine:()=>t.sys.newLine,getCanonicalFileName:t.sys.useCaseSensitiveFileNames?i=>i:i=>i.toLowerCase()},ee={declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!0,target:t.ScriptTarget.ESNext};function j(i,e){const r={...ee,...e};let n=T.dirname(i),s=[];const o=t.findConfigFile(n,t.sys.fileExists);if(!o)return{dtsFiles:s,dirName:n,compilerOptions:r};n=T.dirname(o);const{config:p,error:c}=t.readConfigFile(o,t.sys.readFile);if(c)return console.error(t.formatDiagnostic(c,M)),{dtsFiles:s,dirName:n,compilerOptions:r};const{fileNames:l,options:m,errors:f}=t.parseJsonConfigFileContent(p,t.sys,n);return s=l.filter(d=>d.endsWith(A)),f.length?(console.error(t.formatDiagnostics(f,M)),{dtsFiles:s,dirName:n,compilerOptions:r}):{dtsFiles:s,dirName:n,compilerOptions:{...m,...r}}}function te(i,e){const{dtsFiles:r,compilerOptions:n}=j(i,e);return t.createProgram([i].concat(Array.from(r)),n,t.createCompilerHost(n,!0))}function re(i,e){const r=[];let n=[],s=new Set,o="",p={};for(let c of i){if(c.endsWith(A))continue;c=T.resolve(c);const l=j(c,e);if(l.dtsFiles.forEach(s.add,s),!n.length){n.push(c),{dirName:o,compilerOptions:p}=l;continue}if(l.dirName===o)n.push(c);else{const m=t.createCompilerHost(p,!0),f=t.createProgram(n.concat(Array.from(s)),p,m);r.push(f),n=[c],{dirName:o,compilerOptions:p}=l}}if(n.length){const c=t.createCompilerHost(p,!0),l=t.createProgram(n.concat(Array.from(s)),p,c);r.push(l)}return r}function ne(){let i;try{return{codeFrameColumns:i}=K("@babel/code-frame"),i}catch{try{return{codeFrameColumns:i}=W.createRequire(typeof document=="undefined"?new(require("url")).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("rollup-plugin-dts-93eb415d.js",document.baseURI).href)("@babel/code-frame"),i}catch{}}}function ie(i){const e=i.getSourceFile(),r=e.getLineAndCharacterOfPosition(i.getStart()),n=e.getLineAndCharacterOfPosition(i.getEnd());return{start:{line:r.line+1,column:r.character+1},end:{line:n.line+1,column:n.character+1}}}function se(i){const e=ne(),n=i.getSourceFile().getFullText(),s=ie(i);return e?`
|
|
2
|
+
`+e(n,s,{highlightCode:!0}):`
|
|
3
|
+
${s.start.line}:${s.start.column}: \`${i.getFullText().trim()}\``}class h extends Error{constructor(e,r="Syntax not yet supported"){super(`${r}
|
|
4
|
+
${se(e)}`)}}class ae{constructor(e){this.sourceFile=e}findNamespaces(){const e=[],r={};for(const n of this.sourceFile.statements){const s={start:n.getStart(),end:n.getEnd()};if(t.isEmptyStatement(n)){e.unshift({name:"",exports:[],location:s});continue}if((t.isImportDeclaration(n)||t.isExportDeclaration(n))&&n.moduleSpecifier&&t.isStringLiteral(n.moduleSpecifier)){let{text:f}=n.moduleSpecifier;if(f.startsWith(".")&&(f.endsWith(".d.ts")||f.endsWith(".d.cts")||f.endsWith(".d.mts"))){let d=n.moduleSpecifier.getStart()+1,b=n.moduleSpecifier.getEnd()-1;e.unshift({name:"",exports:[],location:{start:d,end:b},textBeforeCodeAfter:f.replace(/\.d\.ts$/,".js").replace(/\.d\.cts$/,".cjs").replace(/\.d\.mts$/,".mjs")})}}if(t.isModuleDeclaration(n)&&n.body&&t.isModuleBlock(n.body)){for(const f of n.body.statements)if(t.isExportDeclaration(f)&&f.exportClause){if(t.isNamespaceExport(f.exportClause))continue;for(const d of f.exportClause.elements)d.propertyName&&d.propertyName.getText()==d.name.getText()&&e.unshift({name:"",exports:[],location:{start:d.propertyName.getEnd(),end:d.name.getEnd()}})}}if(t.isClassDeclaration(n)?r[n.name.getText()]={type:"class",generics:n.typeParameters}:t.isFunctionDeclaration(n)?r[n.name.getText()]={type:"function"}:t.isInterfaceDeclaration(n)?r[n.name.getText()]={type:"interface",generics:n.typeParameters}:t.isTypeAliasDeclaration(n)?r[n.name.getText()]={type:"type",generics:n.typeParameters}:t.isModuleDeclaration(n)&&t.isIdentifier(n.name)?r[n.name.getText()]={type:"namespace"}:t.isEnumDeclaration(n)&&(r[n.name.getText()]={type:"enum"}),!t.isVariableStatement(n))continue;const{declarations:o}=n.declarationList;if(o.length!==1)continue;const p=o[0],c=p.name.getText();if(!p.initializer||!t.isCallExpression(p.initializer)){r[c]={type:"var"};continue}const l=p.initializer.arguments[0];if(!p.initializer.expression.getFullText().includes("/*#__PURE__*/Object.freeze")||!t.isObjectLiteralExpression(l))continue;const m=[];for(const f of l.properties){if(!t.isPropertyAssignment(f)||!(t.isIdentifier(f.name)||t.isStringLiteral(f.name))||f.name.text!=="__proto__"&&!t.isIdentifier(f.initializer))throw new h(f,"Expected a property assignment");f.name.text!=="__proto__"&&m.push({exportedName:f.name.text,localName:f.initializer.getText()})}e.unshift({name:c,exports:m,location:s})}return{namespaces:e,itemTypes:r}}fix(){var s;let e=this.sourceFile.getFullText();const{namespaces:r,itemTypes:n}=this.findNamespaces();for(const o of r){const p=e.slice(o.location.end);e=e.slice(0,o.location.start);for(const{exportedName:c,localName:l}of o.exports)if(c===l){const{type:m,generics:f}=n[l]||{};if(m==="interface"||m==="type"){const d=O(f);e+=`type ${o.name}_${c}${d.in} = ${l}${d.out};
|
|
5
|
+
`}else if(m==="enum"||m==="class"){const d=O(f);e+=`type ${o.name}_${c}${d.in} = ${l}${d.out};
|
|
6
|
+
`,e+=`declare const ${o.name}_${c}: typeof ${l};
|
|
7
|
+
`}else e+=`declare const ${o.name}_${c}: typeof ${l};
|
|
8
|
+
`}if(o.name){e+=`declare namespace ${o.name} {
|
|
9
|
+
`,e+=` export {
|
|
10
|
+
`;for(const{exportedName:c,localName:l}of o.exports)c===l?e+=` ${o.name}_${c} as ${c},
|
|
11
|
+
`:e+=` ${l} as ${c},
|
|
12
|
+
`;e+=` };
|
|
13
|
+
`,e+="}"}e+=(s=o.textBeforeCodeAfter)!=null?s:"",e+=p}return e}}function O(i){return!i||!i.length?{in:"",out:""}:{in:`<${i.map(e=>e.getText()).join(", ")}>`,out:`<${i.map(e=>e.name.getText()).join(", ")}>`}}let _=1;function oe(i){return S({type:"Program",sourceType:"module",body:[]},{start:i.getFullStart(),end:i.getEnd()})}function ce(i){const e={type:"Identifier",name:String(_++)};return{ident:e,expr:{type:"AssignmentPattern",left:e,right:i}}}function v(i){return S({type:"Identifier",name:i.getText()},i)}function le(i){const e=S({type:"FunctionExpression",id:null,params:[],body:{type:"BlockStatement",body:[]}},i),r=S({type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:String(_++)},arguments:[e],optional:!1}},i);return{fn:e,iife:r}}function pe(){const i={type:"ArrayExpression",elements:[]};return{expr:i,stmt:{type:"ReturnStatement",argument:i}}}function fe(i,e){return S({type:"FunctionDeclaration",id:S({type:"Identifier",name:t.idText(i)},i),params:[],body:{type:"BlockStatement",body:[]}},e)}function I(i){if(t.isLiteralExpression(i))return{type:"Literal",value:i.text};if(t.isPropertyAccessExpression(i)){if(t.isPrivateIdentifier(i.name))throw new h(i.name);return S({type:"MemberExpression",computed:!1,optional:!1,object:I(i.expression),property:I(i.name)},{start:i.expression.getStart(),end:i.name.getEnd()})}if(t.isIdentifier(i))return v(i);if(i.kind==t.SyntaxKind.NullKeyword)return{type:"Literal",value:null};throw new h(i)}function S(i,e){let r="start"in e?e:{start:e.getStart(),end:e.getEnd()};return Object.assign(i,r)}function L(i,e){return(t.getCombinedModifierFlags(i)&e)===e}function ue({sourceFile:i}){const e=new Z.default(i.getFullText()),r=new Set,n=new Set;let s="";const o=new Map,p=new Map;for(const a of i.statements){if(t.isEmptyStatement(a)){e.remove(a.getStart(),a.getEnd());continue}if(t.isEnumDeclaration(a)||t.isFunctionDeclaration(a)||t.isInterfaceDeclaration(a)||t.isClassDeclaration(a)||t.isTypeAliasDeclaration(a)||t.isModuleDeclaration(a)){if(a.name){const u=a.name.getText();r.add(u),L(a,t.ModifierFlags.ExportDefault)?s=u:L(a,t.ModifierFlags.Export)&&n.add(u),a.flags&t.NodeFlags.GlobalAugmentation||N(u,[R(a),z(a)])}t.isModuleDeclaration(a)&&me(e,a),V(e,a)}else if(t.isVariableStatement(a)){const{declarations:u}=a.declarationList,g=L(a,t.ModifierFlags.Export);for(const x of a.declarationList.declarations)if(t.isIdentifier(x.name)){const D=x.name.getText();r.add(D),g&&n.add(D)}if(V(e,a),u.length==1){const x=u[0];t.isIdentifier(x.name)&&N(x.name.getText(),[R(a),z(a)])}else{const x=u.slice(),D=x.shift();N(D.name.getText(),[R(a),D.getEnd()]);for(const C of x)t.isIdentifier(C.name)&&N(C.name.getText(),[C.getFullStart(),C.getEnd()])}const{flags:y}=a.declarationList,P=`declare ${y&t.NodeFlags.Let?"let":y&t.NodeFlags.Const?"const":"var"} `,F=a.declarationList.getChildren().find(x=>x.kind===t.SyntaxKind.SyntaxList).getChildren();let E=0;for(const x of F)if(x.kind===t.SyntaxKind.CommaToken)E=x.getStart(),e.remove(E,x.getEnd());else if(E){e.appendLeft(E,`;
|
|
14
|
+
`);const D=x.getFullStart(),C=e.slice(D,x.getStart());let k=C.length-C.trimStart().length;k?e.overwrite(D,D+k,P):e.appendLeft(D,P)}}}for(const a of i.statements)if(f(a),!!L(a,t.ModifierFlags.ExportDefault)&&(t.isFunctionDeclaration(a)||t.isClassDeclaration(a))){if(a.name)continue;s||(s=b("export_default"));const u=a.getChildren(),g=u.findIndex(F=>F.kind===t.SyntaxKind.ClassKeyword||F.kind===t.SyntaxKind.FunctionKeyword),y=u[g],w=u[g+1];w.kind>=t.SyntaxKind.FirstPunctuation&&w.kind<=t.SyntaxKind.LastPunctuation?e.appendLeft(w.getStart(),s):e.appendRight(y.getEnd(),` ${s}`)}for(const a of p.values()){const g=a.pop()[0];for(const y of a)e.move(y[0],y[1],g)}s&&e.append(`
|
|
15
|
+
export default ${s};
|
|
16
|
+
`),n.size&&e.append(`
|
|
17
|
+
export { ${[...n].join(", ")} };
|
|
18
|
+
`);for(const[a,u]of o.entries())e.prepend(`import * as ${u} from "${a}";
|
|
19
|
+
`);const c=i.getLineStarts(),l=new Set;for(const a of i.typeReferenceDirectives){l.add(a.fileName);const{line:u}=i.getLineAndCharacterOfPosition(a.pos),g=c[u];let y=i.getLineEndOfPosition(a.pos);e.slice(y,y+1)==`
|
|
20
|
+
`&&(y+=1),e.remove(g,y)}const m=new Set;for(const a of i.referencedFiles){m.add(a.fileName);const{line:u}=i.getLineAndCharacterOfPosition(a.pos),g=c[u];let y=i.getLineEndOfPosition(a.pos);e.slice(y,y+1)==`
|
|
21
|
+
`&&(y+=1),e.remove(g,y)}return{code:e,typeReferences:l,fileReferences:m};function f(a){if(t.forEachChild(a,f),t.isImportTypeNode(a)){if(!t.isLiteralTypeNode(a.argument)||!t.isStringLiteral(a.argument.literal))throw new h(a,"inline imports should have a literal argument");const u=a.argument.literal.text,g=a.getChildren(),y=g.find(E=>E.kind===t.SyntaxKind.ImportKeyword).getStart();let w=a.getEnd();const P=g.find(E=>E.kind===t.SyntaxKind.DotToken||E.kind===t.SyntaxKind.LessThanToken);P&&(w=P.getStart());const F=d(u);e.overwrite(y,w,F)}}function d(a){let u=o.get(a);return u||(u=b(a.replace(/[^a-zA-Z0-9_$]/g,()=>"_")),o.set(a,u)),u}function b(a){let u=a;for(;r.has(u);)u=`_${u}`;return r.add(u),u}function N(a,u){let g=p.get(a);if(!g)g=[u],p.set(a,g);else{const y=g[g.length-1];y[1]===u[0]?y[1]=u[1]:g.push(u)}}}function V(i,e){var s;let r=!1;const n=t.isClassDeclaration(e)||t.isFunctionDeclaration(e)||t.isModuleDeclaration(e)||t.isVariableStatement(e);for(const o of(s=e.modifiers)!=null?s:[])switch(o.kind){case t.SyntaxKind.ExportKeyword:case t.SyntaxKind.DefaultKeyword:i.remove(o.getStart(),o.getEnd()+1);break;case t.SyntaxKind.DeclareKeyword:r=!0}n&&!r&&i.appendRight(e.getStart(),"declare ")}function me(i,e){if(!(!e.body||!t.isModuleBlock(e.body))){for(const r of e.body.statements)if(t.isExportDeclaration(r)&&r.exportClause){if(t.isNamespaceExport(r.exportClause))continue;for(const n of r.exportClause.elements)n.propertyName||i.appendLeft(n.name.getEnd(),` as ${n.name.getText()}`)}}}function R(i){const e=i.getFullStart();return e+(q(i,e)?1:0)}function z(i){const e=i.getEnd();return e+(q(i,e)?1:0)}function q(i,e){return i.getSourceFile().getFullText()[e]==`
|
|
22
|
+
`}const de=new Set([t.SyntaxKind.LiteralType,t.SyntaxKind.VoidKeyword,t.SyntaxKind.UnknownKeyword,t.SyntaxKind.AnyKeyword,t.SyntaxKind.BooleanKeyword,t.SyntaxKind.NumberKeyword,t.SyntaxKind.StringKeyword,t.SyntaxKind.ObjectKeyword,t.SyntaxKind.NullKeyword,t.SyntaxKind.UndefinedKeyword,t.SyntaxKind.SymbolKeyword,t.SyntaxKind.NeverKeyword,t.SyntaxKind.ThisKeyword,t.SyntaxKind.ThisType,t.SyntaxKind.BigIntKeyword]);class U{constructor({id:e,range:r}){if(this.scopes=[],e)this.declaration=fe(e,r);else{const{iife:s,fn:o}=le(r);this.iife=s,this.declaration=o}const n=pe();this.declaration.body.body.push(n.stmt),this.returnExpr=n.expr}pushScope(){this.scopes.push(new Set)}popScope(e=1){for(let r=0;r<e;r++)this.scopes.pop()}pushTypeVariable(e){var n;const r=e.getText();(n=this.scopes[this.scopes.length-1])==null||n.add(r)}pushReference(e){let r;if(e.type==="Identifier"?r=e.name:e.type==="MemberExpression"&&e.object.type==="Identifier"&&(r=e.object.name),r){for(const o of this.scopes)if(o.has(r))return}const{ident:n,expr:s}=ce(e);this.declaration.params.push(s),this.returnExpr.elements.push(n)}pushIdentifierReference(e){this.pushReference(v(e))}convertEntityName(e){return t.isIdentifier(e)?v(e):S({type:"MemberExpression",computed:!1,optional:!1,object:this.convertEntityName(e.left),property:v(e.right)},e)}convertPropertyAccess(e){if(!t.isIdentifier(e.expression)&&!t.isPropertyAccessExpression(e.expression))throw new h(e.expression);if(t.isPrivateIdentifier(e.name))throw new h(e.name);let r=t.isIdentifier(e.expression)?v(e.expression):this.convertPropertyAccess(e.expression);return S({type:"MemberExpression",computed:!1,optional:!1,object:r,property:v(e.name)},e)}convertComputedPropertyName(e){if(!e.name||!t.isComputedPropertyName(e.name))return;const{expression:r}=e.name;if(!(t.isLiteralExpression(r)||t.isPrefixUnaryExpression(r))){if(t.isIdentifier(r))return this.pushReference(v(r));if(t.isPropertyAccessExpression(r))return this.pushReference(this.convertPropertyAccess(r));throw new h(r)}}convertParametersAndType(e){this.convertComputedPropertyName(e);const r=this.convertTypeParameters(e.typeParameters);for(const n of e.parameters)this.convertTypeNode(n.type);this.convertTypeNode(e.type),this.popScope(r)}convertHeritageClauses(e){for(const r of e.heritageClauses||[])for(const n of r.types)this.pushReference(I(n.expression)),this.convertTypeArguments(n)}convertTypeArguments(e){if(!!e.typeArguments)for(const r of e.typeArguments)this.convertTypeNode(r)}convertMembers(e){for(const r of e){if(t.isPropertyDeclaration(r)||t.isPropertySignature(r)||t.isIndexSignatureDeclaration(r)){t.isPropertyDeclaration(r)&&r.initializer&&t.isPropertyAccessExpression(r.initializer)&&this.pushReference(this.convertPropertyAccess(r.initializer)),this.convertComputedPropertyName(r),this.convertTypeNode(r.type);continue}if(t.isMethodDeclaration(r)||t.isMethodSignature(r)||t.isConstructorDeclaration(r)||t.isConstructSignatureDeclaration(r)||t.isCallSignatureDeclaration(r)||t.isGetAccessorDeclaration(r)||t.isSetAccessorDeclaration(r))this.convertParametersAndType(r);else throw new h(r)}}convertTypeParameters(e){if(!e)return 0;for(const r of e)this.convertTypeNode(r.constraint),this.convertTypeNode(r.default),this.pushScope(),this.pushTypeVariable(r.name);return e.length}convertTypeNode(e){if(!!e&&!de.has(e.kind)){if(t.isTypeReferenceNode(e)){this.pushReference(this.convertEntityName(e.typeName)),this.convertTypeArguments(e);return}if(t.isTypeLiteralNode(e))return this.convertMembers(e.members);if(t.isArrayTypeNode(e))return this.convertTypeNode(e.elementType);if(t.isTupleTypeNode(e)){for(const r of e.elements)this.convertTypeNode(r);return}if(t.isNamedTupleMember(e)||t.isParenthesizedTypeNode(e)||t.isTypeOperatorNode(e)||t.isTypePredicateNode(e))return this.convertTypeNode(e.type);if(t.isUnionTypeNode(e)||t.isIntersectionTypeNode(e)){for(const r of e.types)this.convertTypeNode(r);return}if(t.isMappedTypeNode(e)){const{typeParameter:r,type:n,nameType:s}=e;this.convertTypeNode(r.constraint),this.pushScope(),this.pushTypeVariable(r.name),this.convertTypeNode(n),s&&this.convertTypeNode(s),this.popScope();return}if(t.isConditionalTypeNode(e)){this.convertTypeNode(e.checkType),this.pushScope(),this.convertTypeNode(e.extendsType),this.convertTypeNode(e.trueType),this.convertTypeNode(e.falseType),this.popScope();return}if(t.isIndexedAccessTypeNode(e)){this.convertTypeNode(e.objectType),this.convertTypeNode(e.indexType);return}if(t.isFunctionOrConstructorTypeNode(e)){this.convertParametersAndType(e);return}if(t.isTypeQueryNode(e)){this.pushReference(this.convertEntityName(e.exprName));return}if(t.isRestTypeNode(e)){this.convertTypeNode(e.type);return}if(t.isOptionalTypeNode(e)){this.convertTypeNode(e.type);return}if(t.isTemplateLiteralTypeNode(e)){for(const r of e.templateSpans)this.convertTypeNode(r.type);return}if(t.isInferTypeNode(e)){const{typeParameter:r}=e;this.convertTypeNode(r.constraint),this.pushTypeVariable(r.name);return}else throw new h(e)}}convertNamespace(e,r=!1){if(this.pushScope(),r&&e.body&&t.isModuleDeclaration(e.body)){this.convertNamespace(e.body,!0);return}if(!e.body||!t.isModuleBlock(e.body))throw new h(e,'namespace must have a "ModuleBlock" body.');const{statements:n}=e.body;for(const s of n){if(t.isEnumDeclaration(s)||t.isFunctionDeclaration(s)||t.isClassDeclaration(s)||t.isInterfaceDeclaration(s)||t.isTypeAliasDeclaration(s)||t.isModuleDeclaration(s)){if(s.name&&t.isIdentifier(s.name))this.pushTypeVariable(s.name);else throw new h(s,"non-Identifier name not supported");continue}if(t.isVariableStatement(s)){for(const o of s.declarationList.declarations)if(t.isIdentifier(o.name))this.pushTypeVariable(o.name);else throw new h(o,"non-Identifier name not supported");continue}if(!t.isExportDeclaration(s))throw new h(s,"namespace child (hoisting) not supported yet")}for(const s of n){if(t.isVariableStatement(s)){for(const o of s.declarationList.declarations)o.type&&this.convertTypeNode(o.type);continue}if(t.isFunctionDeclaration(s)){this.convertParametersAndType(s);continue}if(t.isInterfaceDeclaration(s)||t.isClassDeclaration(s)){const o=this.convertTypeParameters(s.typeParameters);this.convertHeritageClauses(s),this.convertMembers(s.members),this.popScope(o);continue}if(t.isTypeAliasDeclaration(s)){const o=this.convertTypeParameters(s.typeParameters);this.convertTypeNode(s.type),this.popScope(o);continue}if(t.isModuleDeclaration(s)){this.convertNamespace(s,r);continue}if(!t.isEnumDeclaration(s))if(t.isExportDeclaration(s)){if(s.exportClause){if(t.isNamespaceExport(s.exportClause))throw new h(s.exportClause);for(const o of s.exportClause.elements){const p=o.propertyName||o.name;this.pushIdentifierReference(p)}}}else throw new h(s,"namespace child (walking) not supported yet")}this.popScope()}}function ye({sourceFile:i}){return new he(i).transform()}class he{constructor(e){this.sourceFile=e,this.declarations=new Map,this.ast=oe(e);for(const r of e.statements)this.convertStatement(r)}transform(){return{ast:this.ast}}pushStatement(e){this.ast.body.push(e)}createDeclaration(e,r){const n={start:e.getFullStart(),end:e.getEnd()};if(!r){const c=new U({range:n});return this.pushStatement(c.iife),c}const s=r.getText(),o=new U({id:r,range:n}),p=this.declarations.get(s);if(p){p.pushIdentifierReference(r),p.declaration.end=n.end;let c=this.ast.body.findIndex(l=>l==p.declaration);for(let l=c+1;l<this.ast.body.length;l++){const m=this.ast.body[l];m.start=m.end=n.end}}else this.pushStatement(o.declaration),this.declarations.set(s,o);return p||o}convertStatement(e){if(t.isEnumDeclaration(e))return this.convertEnumDeclaration(e);if(t.isFunctionDeclaration(e))return this.convertFunctionDeclaration(e);if(t.isInterfaceDeclaration(e)||t.isClassDeclaration(e))return this.convertClassOrInterfaceDeclaration(e);if(t.isTypeAliasDeclaration(e))return this.convertTypeAliasDeclaration(e);if(t.isVariableStatement(e))return this.convertVariableStatement(e);if(t.isExportDeclaration(e)||t.isExportAssignment(e))return this.convertExportDeclaration(e);if(t.isModuleDeclaration(e))return this.convertNamespaceDeclaration(e);if(e.kind==t.SyntaxKind.NamespaceExportDeclaration)return this.removeStatement(e);if(t.isImportDeclaration(e)||t.isImportEqualsDeclaration(e))return this.convertImportDeclaration(e);throw new h(e)}removeStatement(e){this.pushStatement(S({type:"ExpressionStatement",expression:{type:"Literal",value:"pls remove me"}},e))}convertNamespaceDeclaration(e){if(e.flags&t.NodeFlags.GlobalAugmentation||!t.isIdentifier(e.name)){this.createDeclaration(e).convertNamespace(e,!0);return}const n=this.createDeclaration(e,e.name);n.pushIdentifierReference(e.name),n.convertNamespace(e)}convertEnumDeclaration(e){this.createDeclaration(e,e.name).pushIdentifierReference(e.name)}convertFunctionDeclaration(e){if(!e.name)throw new h(e,"FunctionDeclaration should have a name");const r=this.createDeclaration(e,e.name);r.pushIdentifierReference(e.name),r.convertParametersAndType(e)}convertClassOrInterfaceDeclaration(e){if(!e.name)throw new h(e,"ClassDeclaration / InterfaceDeclaration should have a name");const r=this.createDeclaration(e,e.name),n=r.convertTypeParameters(e.typeParameters);r.convertHeritageClauses(e),r.convertMembers(e.members),r.popScope(n)}convertTypeAliasDeclaration(e){const r=this.createDeclaration(e,e.name),n=r.convertTypeParameters(e.typeParameters);r.convertTypeNode(e.type),r.popScope(n)}convertVariableStatement(e){const{declarations:r}=e.declarationList;if(r.length!==1)throw new h(e,"VariableStatement with more than one declaration not yet supported");for(const n of r){if(!t.isIdentifier(n.name))throw new h(e,"VariableDeclaration must have a name");this.createDeclaration(e,n.name).convertTypeNode(n.type)}}convertExportDeclaration(e){if(t.isExportAssignment(e)){this.pushStatement(S({type:"ExportDefaultDeclaration",declaration:I(e.expression)},e));return}const r=e.moduleSpecifier?I(e.moduleSpecifier):void 0;if(!e.exportClause)this.pushStatement(S({type:"ExportAllDeclaration",source:r,exported:null},e));else if(t.isNamespaceExport(e.exportClause))this.pushStatement(S({type:"ExportAllDeclaration",source:r,exported:v(e.exportClause.name)},e));else{const n=[];for(const s of e.exportClause.elements)n.push(this.convertExportSpecifier(s));this.pushStatement(S({type:"ExportNamedDeclaration",declaration:null,specifiers:n,source:r},e))}}convertImportDeclaration(e){if(t.isImportEqualsDeclaration(e)){if(!t.isExternalModuleReference(e.moduleReference))throw new h(e,"ImportEquals should have a literal source.");this.pushStatement(S({type:"ImportDeclaration",specifiers:[{type:"ImportDefaultSpecifier",local:v(e.name)}],source:I(e.moduleReference.expression)},e));return}const r=I(e.moduleSpecifier),n=e.importClause&&e.importClause.namedBindings?this.convertNamedImportBindings(e.importClause.namedBindings):[];e.importClause&&e.importClause.name&&n.push({type:"ImportDefaultSpecifier",local:v(e.importClause.name)}),this.pushStatement(S({type:"ImportDeclaration",specifiers:n,source:r},e))}convertNamedImportBindings(e){return t.isNamedImports(e)?e.elements.map(r=>{const n=v(r.name),s=r.propertyName?v(r.propertyName):n;return{type:"ImportSpecifier",local:n,imported:s}}):[{type:"ImportNamespaceSpecifier",local:v(e.name)}]}convertExportSpecifier(e){const r=v(e.name);return{type:"ExportSpecifier",exported:r,local:e.propertyName?v(e.propertyName):r}}}function $(i,e){return t.createSourceFile(i,e,t.ScriptTarget.Latest,!0)}const ge=()=>{const i=new Map,e=new Map;return{name:"dts-transform",options(r){const{onwarn:n}=r;return{...r,onwarn(s,o){s.code!="CIRCULAR_DEPENDENCY"&&(n?n(s,o):o(s))},treeshake:{moduleSideEffects:"no-external",propertyReadSideEffects:!0,unknownGlobalSideEffects:!1}}},outputOptions(r){return{...r,chunkFileNames:r.chunkFileNames||"[name]-[hash].d.ts",entryFileNames:r.entryFileNames||"[name].d.ts",format:"es",exports:"named",compact:!1,freeze:!0,interop:"esModule",generatedCode:Object.assign({symbols:!1},r.generatedCode),strict:!1}},transform(r,n){let s=$(n,r);const o=ue({sourceFile:s});i.set(s.fileName,o.typeReferences),e.set(s.fileName,o.fileReferences),r=o.code.toString(),s=$(n,r);const p=ye({sourceFile:s});return process.env.DTS_DUMP_AST&&(console.log(n),console.log(r),console.log(JSON.stringify(p.ast.body,void 0,2))),{code:r,ast:p.ast,map:o.code.generateMap()}},renderChunk(r,n,s){const o=$(n.fileName,r),p=new ae(o),c=new Set,l=new Set;for(const m of Object.keys(n.modules)){for(const f of i.get(m.split("\\").join("/"))||[])c.add(f);for(const f of e.get(m.split("\\").join("/"))||[])if(f.startsWith(".")){const d=T.join(T.dirname(m),f),b=s.file&&T.dirname(s.file)||n.facadeModuleId&&T.dirname(n.facadeModuleId)||".";let N=T.relative(b,d).split("\\").join("/");N[0]!=="."&&(N="./"+N),l.add(N)}else l.add(f)}return r=B(Array.from(l,m=>`/// <reference path="${m}" />`)),r+=B(Array.from(c,m=>`/// <reference types="${m}" />`)),r+=p.fix(),r||(r+=`
|
|
23
|
+
export { }`),{code:r,map:{mappings:""}}}}};function B(i){return i.length?i.join(`
|
|
24
|
+
`)+`
|
|
25
|
+
`:""}const H=/\.([cm]ts|[tj]sx?)$/,xe=(i={})=>{const e=ge(),{respectExternal:r=!1,compilerOptions:n={}}=i;let s=[];function o(p){let c,l;return!s.length&&p.endsWith(A)?c=!0:(l=s.find(m=>c=m.getSourceFile(p)),!l&&t.sys.fileExists(p)&&(s.push(l=te(p,n)),c=l.getSourceFile(p))),{source:c,program:l}}return{name:"dts",options(p){let{input:c=[]}=p;if(!Array.isArray(c))c=typeof c=="string"?[c]:Object.values(c);else if(c.length>1){p.input={};for(const l of c){let m=l.replace(/((\.d)?\.(t|j)sx?)$/,"");T.isAbsolute(l)?m=T.basename(m):m=T.normalize(m),p.input[m]=l}}return s=re(Object.values(c),n),e.options.call(this,p)},outputOptions:e.outputOptions,transform(p,c){const l=(a,u)=>(typeof a=="object"&&(p=a.getFullText()),e.transform.call(this,p,u));if(!H.test(c))return null;if(c.endsWith(A)){const{source:a}=o(c);return a?l(a,c):null}const m=c.replace(H,A);let f=o(m);if(f.source)return l(f.source,m);if(f=o(c),typeof f.source!="object"||!f.program)return null;let d;const{emitSkipped:b,diagnostics:N}=f.program.emit(f.source,(a,u)=>{p=u,d=l(!0,m)},void 0,!0);if(b){const a=N.filter(u=>u.category===t.DiagnosticCategory.Error);a.length&&(console.error(t.formatDiagnostics(a,M)),this.error("Failed to compile. Check the logs above."))}return d},resolveId(p,c){if(!c)return;c=c.split("\\").join("/");const{resolvedModule:l}=t.nodeModuleNameResolver(p,c,n,t.sys);if(!!l)return!r&&l.isExternalLibraryImport?{id:p,external:!0}:{id:T.resolve(l.resolvedFileName)}},renderChunk:e.renderChunk}};exports.default=xe;
|
package/package.json
CHANGED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
"use strict";var W=require("module"),G=require("path"),J=require("magic-string");function Y(i){return i&&typeof i=="object"&&"default"in i?i:{default:i}}function Q(i){if(i&&i.__esModule)return i;var e=Object.create(null);return i&&Object.keys(i).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(i,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return i[r]}})}}),e.default=i,Object.freeze(e)}var T=Q(G),Z=Y(J),K=require;function X(){const i=process.cwd();try{return K.resolve("typescript",{paths:[i]})}catch{throw new Error(`Could not find \`typescript\` in ${i}`)}}var t=K(X());const A=".d.ts",M={getCurrentDirectory:()=>t.sys.getCurrentDirectory(),getNewLine:()=>t.sys.newLine,getCanonicalFileName:t.sys.useCaseSensitiveFileNames?i=>i:i=>i.toLowerCase()},ee={declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!0,target:t.ScriptTarget.ESNext};function k(i,e){const r={...ee,...e};let n=T.dirname(i),s=[];const o=t.findConfigFile(n,t.sys.fileExists);if(!o)return{dtsFiles:s,dirName:n,compilerOptions:r};n=T.dirname(o);const{config:p,error:c}=t.readConfigFile(o,t.sys.readFile);if(c)return console.error(t.formatDiagnostic(c,M)),{dtsFiles:s,dirName:n,compilerOptions:r};const{fileNames:l,options:m,errors:f}=t.parseJsonConfigFileContent(p,t.sys,n);return s=l.filter(d=>d.endsWith(A)),f.length?(console.error(t.formatDiagnostics(f,M)),{dtsFiles:s,dirName:n,compilerOptions:r}):{dtsFiles:s,dirName:n,compilerOptions:{...m,...r}}}function te(i,e){const{dtsFiles:r,compilerOptions:n}=k(i,e);return t.createProgram([i].concat(Array.from(r)),n,t.createCompilerHost(n,!0))}function re(i,e){const r=[];let n=[],s=new Set,o="",p={};for(let c of i){if(c.endsWith(A))continue;c=T.resolve(c);const l=k(c,e);if(l.dtsFiles.forEach(s.add,s),!n.length){n.push(c),{dirName:o,compilerOptions:p}=l;continue}if(l.dirName===o)n.push(c);else{const m=t.createCompilerHost(p,!0),f=t.createProgram(n.concat(Array.from(s)),p,m);r.push(f),n=[c],{dirName:o,compilerOptions:p}=l}}if(n.length){const c=t.createCompilerHost(p,!0),l=t.createProgram(n.concat(Array.from(s)),p,c);r.push(l)}return r}function ne(){let i;try{return{codeFrameColumns:i}=K("@babel/code-frame"),i}catch{try{return{codeFrameColumns:i}=W.createRequire(typeof document=="undefined"?new(require("url")).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("rollup-plugin-dts-eb7b5c98.js",document.baseURI).href)("@babel/code-frame"),i}catch{}}}function ie(i){const e=i.getSourceFile(),r=e.getLineAndCharacterOfPosition(i.getStart()),n=e.getLineAndCharacterOfPosition(i.getEnd());return{start:{line:r.line+1,column:r.character+1},end:{line:n.line+1,column:n.character+1}}}function se(i){const e=ne(),n=i.getSourceFile().getFullText(),s=ie(i);return e?`
|
|
2
|
-
`+e(n,s,{highlightCode:!0}):`
|
|
3
|
-
${s.start.line}:${s.start.column}: \`${i.getFullText().trim()}\``}class h extends Error{constructor(e,r="Syntax not yet supported"){super(`${r}
|
|
4
|
-
${se(e)}`)}}class ae{constructor(e){this.sourceFile=e}findNamespaces(){const e=[],r={};for(const n of this.sourceFile.statements){const s={start:n.getStart(),end:n.getEnd()};if(t.isEmptyStatement(n)){e.unshift({name:"",exports:[],location:s});continue}if((t.isImportDeclaration(n)||t.isExportDeclaration(n))&&n.moduleSpecifier&&t.isStringLiteral(n.moduleSpecifier)){let{text:f}=n.moduleSpecifier;if(f.startsWith(".")&&(f.endsWith(".d.ts")||f.endsWith(".d.cts")||f.endsWith(".d.mts"))){let d=n.moduleSpecifier.getStart()+1,b=n.moduleSpecifier.getEnd()-1;e.unshift({name:"",exports:[],location:{start:d,end:b},textBeforeCodeAfter:f.replace(/\.d\.ts$/,".js").replace(/\.d\.cts$/,".cjs").replace(/\.d\.mts$/,".mjs")})}}if(t.isModuleDeclaration(n)&&n.body&&t.isModuleBlock(n.body)){for(const f of n.body.statements)if(t.isExportDeclaration(f)&&f.exportClause){if(t.isNamespaceExport(f.exportClause))continue;for(const d of f.exportClause.elements)d.propertyName&&d.propertyName.getText()==d.name.getText()&&e.unshift({name:"",exports:[],location:{start:d.propertyName.getEnd(),end:d.name.getEnd()}})}}if(t.isClassDeclaration(n)?r[n.name.getText()]={type:"class",generics:n.typeParameters}:t.isFunctionDeclaration(n)?r[n.name.getText()]={type:"function"}:t.isInterfaceDeclaration(n)?r[n.name.getText()]={type:"interface",generics:n.typeParameters}:t.isTypeAliasDeclaration(n)?r[n.name.getText()]={type:"type",generics:n.typeParameters}:t.isModuleDeclaration(n)&&t.isIdentifier(n.name)?r[n.name.getText()]={type:"namespace"}:t.isEnumDeclaration(n)&&(r[n.name.getText()]={type:"enum"}),!t.isVariableStatement(n))continue;const{declarations:o}=n.declarationList;if(o.length!==1)continue;const p=o[0],c=p.name.getText();if(!p.initializer||!t.isCallExpression(p.initializer)){r[c]={type:"var"};continue}const l=p.initializer.arguments[0];if(!p.initializer.expression.getFullText().includes("/*#__PURE__*/Object.freeze")||!t.isObjectLiteralExpression(l))continue;const m=[];for(const f of l.properties){if(!t.isPropertyAssignment(f)||!(t.isIdentifier(f.name)||t.isStringLiteral(f.name))||f.name.text!=="__proto__"&&!t.isIdentifier(f.initializer))throw new h(f,"Expected a property assignment");f.name.text!=="__proto__"&&m.push({exportedName:f.name.text,localName:f.initializer.getText()})}e.unshift({name:c,exports:m,location:s})}return{namespaces:e,itemTypes:r}}fix(){var e;let r=this.sourceFile.getFullText();const{namespaces:n,itemTypes:s}=this.findNamespaces();for(const o of n){const p=r.slice(o.location.end);r=r.slice(0,o.location.start);for(const{exportedName:c,localName:l}of o.exports)if(c===l){const{type:m,generics:f}=s[l]||{};if(m==="interface"||m==="type"){const d=j(f);r+=`type ${o.name}_${c}${d.in} = ${l}${d.out};
|
|
5
|
-
`}else if(m==="enum"||m==="class"){const d=j(f);r+=`type ${o.name}_${c}${d.in} = ${l}${d.out};
|
|
6
|
-
`,r+=`declare const ${o.name}_${c}: typeof ${l};
|
|
7
|
-
`}else r+=`declare const ${o.name}_${c}: typeof ${l};
|
|
8
|
-
`}if(o.name){r+=`declare namespace ${o.name} {
|
|
9
|
-
`,r+=` export {
|
|
10
|
-
`;for(const{exportedName:c,localName:l}of o.exports)c===l?r+=` ${o.name}_${c} as ${c},
|
|
11
|
-
`:r+=` ${l} as ${c},
|
|
12
|
-
`;r+=` };
|
|
13
|
-
`,r+="}"}r+=(e=o.textBeforeCodeAfter)!==null&&e!==void 0?e:"",r+=p}return r}}function j(i){return!i||!i.length?{in:"",out:""}:{in:`<${i.map(e=>e.getText()).join(", ")}>`,out:`<${i.map(e=>e.name.getText()).join(", ")}>`}}let O=1;function oe(i){return S({type:"Program",sourceType:"module",body:[]},{start:i.getFullStart(),end:i.getEnd()})}function ce(i){const e={type:"Identifier",name:String(O++)};return{ident:e,expr:{type:"AssignmentPattern",left:e,right:i}}}function v(i){return S({type:"Identifier",name:i.getText()},i)}function le(i){const e=S({type:"FunctionExpression",id:null,params:[],body:{type:"BlockStatement",body:[]}},i),r=S({type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:String(O++)},arguments:[e],optional:!1}},i);return{fn:e,iife:r}}function pe(){const i={type:"ArrayExpression",elements:[]};return{expr:i,stmt:{type:"ReturnStatement",argument:i}}}function fe(i,e){return S({type:"FunctionDeclaration",id:S({type:"Identifier",name:t.idText(i)},i),params:[],body:{type:"BlockStatement",body:[]}},e)}function I(i){if(t.isLiteralExpression(i))return{type:"Literal",value:i.text};if(t.isPropertyAccessExpression(i)){if(t.isPrivateIdentifier(i.name))throw new h(i.name);return S({type:"MemberExpression",computed:!1,optional:!1,object:I(i.expression),property:I(i.name)},{start:i.expression.getStart(),end:i.name.getEnd()})}if(t.isIdentifier(i))return v(i);if(i.kind==t.SyntaxKind.NullKeyword)return{type:"Literal",value:null};throw new h(i)}function S(i,e){let r="start"in e?e:{start:e.getStart(),end:e.getEnd()};return Object.assign(i,r)}function L(i,e){return(t.getCombinedModifierFlags(i)&e)===e}function ue({sourceFile:i}){const e=new Z.default(i.getFullText()),r=new Set,n=new Set;let s="";const o=new Map,p=new Map;for(const a of i.statements){if(t.isEmptyStatement(a)){e.remove(a.getStart(),a.getEnd());continue}if(t.isEnumDeclaration(a)||t.isFunctionDeclaration(a)||t.isInterfaceDeclaration(a)||t.isClassDeclaration(a)||t.isTypeAliasDeclaration(a)||t.isModuleDeclaration(a)){if(a.name){const u=a.name.getText();r.add(u),L(a,t.ModifierFlags.ExportDefault)?s=u:L(a,t.ModifierFlags.Export)&&n.add(u),a.flags&t.NodeFlags.GlobalAugmentation||N(u,[R(a),z(a)])}t.isModuleDeclaration(a)&&me(e,a),V(e,a)}else if(t.isVariableStatement(a)){const{declarations:u}=a.declarationList,g=L(a,t.ModifierFlags.Export);for(const x of a.declarationList.declarations)if(t.isIdentifier(x.name)){const D=x.name.getText();r.add(D),g&&n.add(D)}if(V(e,a),u.length==1){const x=u[0];t.isIdentifier(x.name)&&N(x.name.getText(),[R(a),z(a)])}else{const x=u.slice(),D=x.shift();N(D.name.getText(),[R(a),D.getEnd()]);for(const C of x)t.isIdentifier(C.name)&&N(C.name.getText(),[C.getFullStart(),C.getEnd()])}const{flags:y}=a.declarationList,P=`declare ${y&t.NodeFlags.Let?"let":y&t.NodeFlags.Const?"const":"var"} `,F=a.declarationList.getChildren().find(x=>x.kind===t.SyntaxKind.SyntaxList).getChildren();let E=0;for(const x of F)if(x.kind===t.SyntaxKind.CommaToken)E=x.getStart(),e.remove(E,x.getEnd());else if(E){e.appendLeft(E,`;
|
|
14
|
-
`);const D=x.getFullStart(),C=e.slice(D,x.getStart());let _=C.length-C.trimStart().length;_?e.overwrite(D,D+_,P):e.appendLeft(D,P)}}}for(const a of i.statements)if(f(a),!!L(a,t.ModifierFlags.ExportDefault)&&(t.isFunctionDeclaration(a)||t.isClassDeclaration(a))){if(a.name)continue;s||(s=b("export_default"));const u=a.getChildren(),g=u.findIndex(F=>F.kind===t.SyntaxKind.ClassKeyword||F.kind===t.SyntaxKind.FunctionKeyword),y=u[g],w=u[g+1];w.kind>=t.SyntaxKind.FirstPunctuation&&w.kind<=t.SyntaxKind.LastPunctuation?e.appendLeft(w.getStart(),s):e.appendRight(y.getEnd(),` ${s}`)}for(const a of p.values()){const g=a.pop()[0];for(const y of a)e.move(y[0],y[1],g)}s&&e.append(`
|
|
15
|
-
export default ${s};
|
|
16
|
-
`),n.size&&e.append(`
|
|
17
|
-
export { ${[...n].join(", ")} };
|
|
18
|
-
`);for(const[a,u]of o.entries())e.prepend(`import * as ${u} from "${a}";
|
|
19
|
-
`);const c=i.getLineStarts(),l=new Set;for(const a of i.typeReferenceDirectives){l.add(a.fileName);const{line:u}=i.getLineAndCharacterOfPosition(a.pos),g=c[u];let y=i.getLineEndOfPosition(a.pos);e.slice(y,y+1)==`
|
|
20
|
-
`&&(y+=1),e.remove(g,y)}const m=new Set;for(const a of i.referencedFiles){m.add(a.fileName);const{line:u}=i.getLineAndCharacterOfPosition(a.pos),g=c[u];let y=i.getLineEndOfPosition(a.pos);e.slice(y,y+1)==`
|
|
21
|
-
`&&(y+=1),e.remove(g,y)}return{code:e,typeReferences:l,fileReferences:m};function f(a){if(t.forEachChild(a,f),t.isImportTypeNode(a)){if(!t.isLiteralTypeNode(a.argument)||!t.isStringLiteral(a.argument.literal))throw new h(a,"inline imports should have a literal argument");const u=a.argument.literal.text,g=a.getChildren(),y=g.find(E=>E.kind===t.SyntaxKind.ImportKeyword).getStart();let w=a.getEnd();const P=g.find(E=>E.kind===t.SyntaxKind.DotToken||E.kind===t.SyntaxKind.LessThanToken);P&&(w=P.getStart());const F=d(u);e.overwrite(y,w,F)}}function d(a){let u=o.get(a);return u||(u=b(a.replace(/[^a-zA-Z0-9_$]/g,()=>"_")),o.set(a,u)),u}function b(a){let u=a;for(;r.has(u);)u=`_${u}`;return r.add(u),u}function N(a,u){let g=p.get(a);if(!g)g=[u],p.set(a,g);else{const y=g[g.length-1];y[1]===u[0]?y[1]=u[1]:g.push(u)}}}function V(i,e){var r;let n=!1;const s=t.isClassDeclaration(e)||t.isFunctionDeclaration(e)||t.isModuleDeclaration(e)||t.isVariableStatement(e);for(const o of(r=e.modifiers)!==null&&r!==void 0?r:[])switch(o.kind){case t.SyntaxKind.ExportKeyword:case t.SyntaxKind.DefaultKeyword:i.remove(o.getStart(),o.getEnd()+1);break;case t.SyntaxKind.DeclareKeyword:n=!0}s&&!n&&i.appendRight(e.getStart(),"declare ")}function me(i,e){if(!(!e.body||!t.isModuleBlock(e.body))){for(const r of e.body.statements)if(t.isExportDeclaration(r)&&r.exportClause){if(t.isNamespaceExport(r.exportClause))continue;for(const n of r.exportClause.elements)n.propertyName||i.appendLeft(n.name.getEnd(),` as ${n.name.getText()}`)}}}function R(i){const e=i.getFullStart();return e+(q(i,e)?1:0)}function z(i){const e=i.getEnd();return e+(q(i,e)?1:0)}function q(i,e){return i.getSourceFile().getFullText()[e]==`
|
|
22
|
-
`}const de=new Set([t.SyntaxKind.LiteralType,t.SyntaxKind.VoidKeyword,t.SyntaxKind.UnknownKeyword,t.SyntaxKind.AnyKeyword,t.SyntaxKind.BooleanKeyword,t.SyntaxKind.NumberKeyword,t.SyntaxKind.StringKeyword,t.SyntaxKind.ObjectKeyword,t.SyntaxKind.NullKeyword,t.SyntaxKind.UndefinedKeyword,t.SyntaxKind.SymbolKeyword,t.SyntaxKind.NeverKeyword,t.SyntaxKind.ThisKeyword,t.SyntaxKind.ThisType,t.SyntaxKind.BigIntKeyword]);class U{constructor({id:e,range:r}){if(this.scopes=[],e)this.declaration=fe(e,r);else{const{iife:s,fn:o}=le(r);this.iife=s,this.declaration=o}const n=pe();this.declaration.body.body.push(n.stmt),this.returnExpr=n.expr}pushScope(){this.scopes.push(new Set)}popScope(e=1){for(let r=0;r<e;r++)this.scopes.pop()}pushTypeVariable(e){var r;const n=e.getText();(r=this.scopes[this.scopes.length-1])===null||r===void 0||r.add(n)}pushReference(e){let r;if(e.type==="Identifier"?r=e.name:e.type==="MemberExpression"&&e.object.type==="Identifier"&&(r=e.object.name),r){for(const o of this.scopes)if(o.has(r))return}const{ident:n,expr:s}=ce(e);this.declaration.params.push(s),this.returnExpr.elements.push(n)}pushIdentifierReference(e){this.pushReference(v(e))}convertEntityName(e){return t.isIdentifier(e)?v(e):S({type:"MemberExpression",computed:!1,optional:!1,object:this.convertEntityName(e.left),property:v(e.right)},e)}convertPropertyAccess(e){if(!t.isIdentifier(e.expression)&&!t.isPropertyAccessExpression(e.expression))throw new h(e.expression);if(t.isPrivateIdentifier(e.name))throw new h(e.name);let r=t.isIdentifier(e.expression)?v(e.expression):this.convertPropertyAccess(e.expression);return S({type:"MemberExpression",computed:!1,optional:!1,object:r,property:v(e.name)},e)}convertComputedPropertyName(e){if(!e.name||!t.isComputedPropertyName(e.name))return;const{expression:r}=e.name;if(!(t.isLiteralExpression(r)||t.isPrefixUnaryExpression(r))){if(t.isIdentifier(r))return this.pushReference(v(r));if(t.isPropertyAccessExpression(r))return this.pushReference(this.convertPropertyAccess(r));throw new h(r)}}convertParametersAndType(e){this.convertComputedPropertyName(e);const r=this.convertTypeParameters(e.typeParameters);for(const n of e.parameters)this.convertTypeNode(n.type);this.convertTypeNode(e.type),this.popScope(r)}convertHeritageClauses(e){for(const r of e.heritageClauses||[])for(const n of r.types)this.pushReference(I(n.expression)),this.convertTypeArguments(n)}convertTypeArguments(e){if(!!e.typeArguments)for(const r of e.typeArguments)this.convertTypeNode(r)}convertMembers(e){for(const r of e){if(t.isPropertyDeclaration(r)||t.isPropertySignature(r)||t.isIndexSignatureDeclaration(r)){t.isPropertyDeclaration(r)&&r.initializer&&t.isPropertyAccessExpression(r.initializer)&&this.pushReference(this.convertPropertyAccess(r.initializer)),this.convertComputedPropertyName(r),this.convertTypeNode(r.type);continue}if(t.isMethodDeclaration(r)||t.isMethodSignature(r)||t.isConstructorDeclaration(r)||t.isConstructSignatureDeclaration(r)||t.isCallSignatureDeclaration(r)||t.isGetAccessorDeclaration(r)||t.isSetAccessorDeclaration(r))this.convertParametersAndType(r);else throw new h(r)}}convertTypeParameters(e){if(!e)return 0;for(const r of e)this.convertTypeNode(r.constraint),this.convertTypeNode(r.default),this.pushScope(),this.pushTypeVariable(r.name);return e.length}convertTypeNode(e){if(!!e&&!de.has(e.kind)){if(t.isTypeReferenceNode(e)){this.pushReference(this.convertEntityName(e.typeName)),this.convertTypeArguments(e);return}if(t.isTypeLiteralNode(e))return this.convertMembers(e.members);if(t.isArrayTypeNode(e))return this.convertTypeNode(e.elementType);if(t.isTupleTypeNode(e)){for(const r of e.elements)this.convertTypeNode(r);return}if(t.isNamedTupleMember(e)||t.isParenthesizedTypeNode(e)||t.isTypeOperatorNode(e)||t.isTypePredicateNode(e))return this.convertTypeNode(e.type);if(t.isUnionTypeNode(e)||t.isIntersectionTypeNode(e)){for(const r of e.types)this.convertTypeNode(r);return}if(t.isMappedTypeNode(e)){const{typeParameter:r,type:n,nameType:s}=e;this.convertTypeNode(r.constraint),this.pushScope(),this.pushTypeVariable(r.name),this.convertTypeNode(n),s&&this.convertTypeNode(s),this.popScope();return}if(t.isConditionalTypeNode(e)){this.convertTypeNode(e.checkType),this.pushScope(),this.convertTypeNode(e.extendsType),this.convertTypeNode(e.trueType),this.convertTypeNode(e.falseType),this.popScope();return}if(t.isIndexedAccessTypeNode(e)){this.convertTypeNode(e.objectType),this.convertTypeNode(e.indexType);return}if(t.isFunctionOrConstructorTypeNode(e)){this.convertParametersAndType(e);return}if(t.isTypeQueryNode(e)){this.pushReference(this.convertEntityName(e.exprName));return}if(t.isRestTypeNode(e)){this.convertTypeNode(e.type);return}if(t.isOptionalTypeNode(e)){this.convertTypeNode(e.type);return}if(t.isTemplateLiteralTypeNode(e)){for(const r of e.templateSpans)this.convertTypeNode(r.type);return}if(t.isInferTypeNode(e)){const{typeParameter:r}=e;this.convertTypeNode(r.constraint),this.pushTypeVariable(r.name);return}else throw new h(e)}}convertNamespace(e,r=!1){if(this.pushScope(),r&&e.body&&t.isModuleDeclaration(e.body)){this.convertNamespace(e.body,!0);return}if(!e.body||!t.isModuleBlock(e.body))throw new h(e,'namespace must have a "ModuleBlock" body.');const{statements:n}=e.body;for(const s of n){if(t.isEnumDeclaration(s)||t.isFunctionDeclaration(s)||t.isClassDeclaration(s)||t.isInterfaceDeclaration(s)||t.isTypeAliasDeclaration(s)||t.isModuleDeclaration(s)){if(s.name&&t.isIdentifier(s.name))this.pushTypeVariable(s.name);else throw new h(s,"non-Identifier name not supported");continue}if(t.isVariableStatement(s)){for(const o of s.declarationList.declarations)if(t.isIdentifier(o.name))this.pushTypeVariable(o.name);else throw new h(o,"non-Identifier name not supported");continue}if(!t.isExportDeclaration(s))throw new h(s,"namespace child (hoisting) not supported yet")}for(const s of n){if(t.isVariableStatement(s)){for(const o of s.declarationList.declarations)o.type&&this.convertTypeNode(o.type);continue}if(t.isFunctionDeclaration(s)){this.convertParametersAndType(s);continue}if(t.isInterfaceDeclaration(s)||t.isClassDeclaration(s)){const o=this.convertTypeParameters(s.typeParameters);this.convertHeritageClauses(s),this.convertMembers(s.members),this.popScope(o);continue}if(t.isTypeAliasDeclaration(s)){const o=this.convertTypeParameters(s.typeParameters);this.convertTypeNode(s.type),this.popScope(o);continue}if(t.isModuleDeclaration(s)){this.convertNamespace(s,r);continue}if(!t.isEnumDeclaration(s))if(t.isExportDeclaration(s)){if(s.exportClause){if(t.isNamespaceExport(s.exportClause))throw new h(s.exportClause);for(const o of s.exportClause.elements){const p=o.propertyName||o.name;this.pushIdentifierReference(p)}}}else throw new h(s,"namespace child (walking) not supported yet")}this.popScope()}}function ye({sourceFile:i}){return new he(i).transform()}class he{constructor(e){this.sourceFile=e,this.declarations=new Map,this.ast=oe(e);for(const r of e.statements)this.convertStatement(r)}transform(){return{ast:this.ast}}pushStatement(e){this.ast.body.push(e)}createDeclaration(e,r){const n={start:e.getFullStart(),end:e.getEnd()};if(!r){const c=new U({range:n});return this.pushStatement(c.iife),c}const s=r.getText(),o=new U({id:r,range:n}),p=this.declarations.get(s);if(p){p.pushIdentifierReference(r),p.declaration.end=n.end;let c=this.ast.body.findIndex(l=>l==p.declaration);for(let l=c+1;l<this.ast.body.length;l++){const m=this.ast.body[l];m.start=m.end=n.end}}else this.pushStatement(o.declaration),this.declarations.set(s,o);return p||o}convertStatement(e){if(t.isEnumDeclaration(e))return this.convertEnumDeclaration(e);if(t.isFunctionDeclaration(e))return this.convertFunctionDeclaration(e);if(t.isInterfaceDeclaration(e)||t.isClassDeclaration(e))return this.convertClassOrInterfaceDeclaration(e);if(t.isTypeAliasDeclaration(e))return this.convertTypeAliasDeclaration(e);if(t.isVariableStatement(e))return this.convertVariableStatement(e);if(t.isExportDeclaration(e)||t.isExportAssignment(e))return this.convertExportDeclaration(e);if(t.isModuleDeclaration(e))return this.convertNamespaceDeclaration(e);if(e.kind==t.SyntaxKind.NamespaceExportDeclaration)return this.removeStatement(e);if(t.isImportDeclaration(e)||t.isImportEqualsDeclaration(e))return this.convertImportDeclaration(e);throw new h(e)}removeStatement(e){this.pushStatement(S({type:"ExpressionStatement",expression:{type:"Literal",value:"pls remove me"}},e))}convertNamespaceDeclaration(e){if(e.flags&t.NodeFlags.GlobalAugmentation||!t.isIdentifier(e.name)){this.createDeclaration(e).convertNamespace(e,!0);return}const n=this.createDeclaration(e,e.name);n.pushIdentifierReference(e.name),n.convertNamespace(e)}convertEnumDeclaration(e){this.createDeclaration(e,e.name).pushIdentifierReference(e.name)}convertFunctionDeclaration(e){if(!e.name)throw new h(e,"FunctionDeclaration should have a name");const r=this.createDeclaration(e,e.name);r.pushIdentifierReference(e.name),r.convertParametersAndType(e)}convertClassOrInterfaceDeclaration(e){if(!e.name)throw new h(e,"ClassDeclaration / InterfaceDeclaration should have a name");const r=this.createDeclaration(e,e.name),n=r.convertTypeParameters(e.typeParameters);r.convertHeritageClauses(e),r.convertMembers(e.members),r.popScope(n)}convertTypeAliasDeclaration(e){const r=this.createDeclaration(e,e.name),n=r.convertTypeParameters(e.typeParameters);r.convertTypeNode(e.type),r.popScope(n)}convertVariableStatement(e){const{declarations:r}=e.declarationList;if(r.length!==1)throw new h(e,"VariableStatement with more than one declaration not yet supported");for(const n of r){if(!t.isIdentifier(n.name))throw new h(e,"VariableDeclaration must have a name");this.createDeclaration(e,n.name).convertTypeNode(n.type)}}convertExportDeclaration(e){if(t.isExportAssignment(e)){this.pushStatement(S({type:"ExportDefaultDeclaration",declaration:I(e.expression)},e));return}const r=e.moduleSpecifier?I(e.moduleSpecifier):void 0;if(!e.exportClause)this.pushStatement(S({type:"ExportAllDeclaration",source:r,exported:null},e));else if(t.isNamespaceExport(e.exportClause))this.pushStatement(S({type:"ExportAllDeclaration",source:r,exported:v(e.exportClause.name)},e));else{const n=[];for(const s of e.exportClause.elements)n.push(this.convertExportSpecifier(s));this.pushStatement(S({type:"ExportNamedDeclaration",declaration:null,specifiers:n,source:r},e))}}convertImportDeclaration(e){if(t.isImportEqualsDeclaration(e)){if(!t.isExternalModuleReference(e.moduleReference))throw new h(e,"ImportEquals should have a literal source.");this.pushStatement(S({type:"ImportDeclaration",specifiers:[{type:"ImportDefaultSpecifier",local:v(e.name)}],source:I(e.moduleReference.expression)},e));return}const r=I(e.moduleSpecifier),n=e.importClause&&e.importClause.namedBindings?this.convertNamedImportBindings(e.importClause.namedBindings):[];e.importClause&&e.importClause.name&&n.push({type:"ImportDefaultSpecifier",local:v(e.importClause.name)}),this.pushStatement(S({type:"ImportDeclaration",specifiers:n,source:r},e))}convertNamedImportBindings(e){return t.isNamedImports(e)?e.elements.map(r=>{const n=v(r.name),s=r.propertyName?v(r.propertyName):n;return{type:"ImportSpecifier",local:n,imported:s}}):[{type:"ImportNamespaceSpecifier",local:v(e.name)}]}convertExportSpecifier(e){const r=v(e.name);return{type:"ExportSpecifier",exported:r,local:e.propertyName?v(e.propertyName):r}}}function $(i,e){return t.createSourceFile(i,e,t.ScriptTarget.Latest,!0)}const ge=()=>{const i=new Map,e=new Map;return{name:"dts-transform",options(r){const{onwarn:n}=r;return{...r,onwarn(s,o){s.code!="CIRCULAR_DEPENDENCY"&&(n?n(s,o):o(s))},treeshake:{moduleSideEffects:"no-external",propertyReadSideEffects:!0,unknownGlobalSideEffects:!1}}},outputOptions(r){return{...r,chunkFileNames:r.chunkFileNames||"[name]-[hash].d.ts",entryFileNames:r.entryFileNames||"[name].d.ts",format:"es",exports:"named",compact:!1,freeze:!0,interop:!1,namespaceToStringTag:!1,strict:!1}},transform(r,n){let s=$(n,r);const o=ue({sourceFile:s});i.set(s.fileName,o.typeReferences),e.set(s.fileName,o.fileReferences),r=o.code.toString(),s=$(n,r);const p=ye({sourceFile:s});return process.env.DTS_DUMP_AST&&(console.log(n),console.log(r),console.log(JSON.stringify(p.ast.body,void 0,2))),{code:r,ast:p.ast,map:o.code.generateMap()}},renderChunk(r,n,s){const o=$(n.fileName,r),p=new ae(o),c=new Set,l=new Set;for(const m of Object.keys(n.modules)){for(const f of i.get(m.split("\\").join("/"))||[])c.add(f);for(const f of e.get(m.split("\\").join("/"))||[])if(f.startsWith(".")){const d=T.join(T.dirname(m),f),b=s.file&&T.dirname(s.file)||n.facadeModuleId&&T.dirname(n.facadeModuleId)||".";let N=T.relative(b,d).split("\\").join("/");N[0]!=="."&&(N="./"+N),l.add(N)}else l.add(f)}return r=B(Array.from(l,m=>`/// <reference path="${m}" />`)),r+=B(Array.from(c,m=>`/// <reference types="${m}" />`)),r+=p.fix(),{code:r,map:{mappings:""}}}}};function B(i){return i.length?i.join(`
|
|
23
|
-
`)+`
|
|
24
|
-
`:""}const H=/\.(t|j)sx?$/,xe=(i={})=>{const e=ge(),{respectExternal:r=!1,compilerOptions:n={}}=i;let s=[];function o(p){let c,l;return!s.length&&p.endsWith(A)?c=!0:(l=s.find(m=>c=m.getSourceFile(p)),!l&&t.sys.fileExists(p)&&(s.push(l=te(p,n)),c=l.getSourceFile(p))),{source:c,program:l}}return{name:"dts",options(p){let{input:c=[]}=p;if(!Array.isArray(c))c=typeof c=="string"?[c]:Object.values(c);else if(c.length>1){p.input={};for(const l of c){let m=l.replace(/((\.d)?\.(t|j)sx?)$/,"");T.isAbsolute(l)?m=T.basename(m):m=T.normalize(m),p.input[m]=l}}return s=re(Object.values(c),n),e.options.call(this,p)},outputOptions:e.outputOptions,transform(p,c){const l=(a,u)=>(typeof a=="object"&&(p=a.getFullText()),e.transform.call(this,p,u));if(!H.test(c))return null;if(c.endsWith(A)){const{source:a}=o(c);return a?l(a,c):null}const m=c.replace(H,A);let f=o(m);if(f.source)return l(f.source,m);if(f=o(c),typeof f.source!="object"||!f.program)return null;let d;const{emitSkipped:b,diagnostics:N}=f.program.emit(f.source,(a,u)=>{p=u,d=l(!0,m)},void 0,!0);if(b){const a=N.filter(u=>u.category===t.DiagnosticCategory.Error);a.length&&(console.error(t.formatDiagnostics(a,M)),this.error("Failed to compile. Check the logs above."))}return d},resolveId(p,c){if(!c)return;c=c.split("\\").join("/");const{resolvedModule:l}=t.nodeModuleNameResolver(p,c,n,t.sys);if(!!l)return!r&&l.isExternalLibraryImport?{id:p,external:!0}:{id:T.resolve(l.resolvedFileName)}},renderChunk:e.renderChunk}};exports.default=xe;
|