@d1g1tal/tsnode 0.1.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ type TsconfigOptions = false | string;
2
+
3
+ export type RegisterOptions = {
4
+ namespace?: string;
5
+ onImport?: (url: string) => void;
6
+ tsconfig?: TsconfigOptions;
7
+ };
8
+
9
+ export type Unregister = () => Promise<void>;
10
+
11
+ type ScopedImport = (specifier: string, parent: string) => Promise<any>;
12
+
13
+ export type RegisterHandle = {
14
+ unregister: Unregister;
15
+ import?: ScopedImport;
16
+ };
17
+
18
+ export type NamespacedUnregister = RegisterHandle & {
19
+ import: ScopedImport;
20
+ };
21
+
22
+ type RequiredProperty<Type, Keys extends keyof Type> = Type & {
23
+ [P in Keys]-?: Type[P];
24
+ };
25
+
26
+ export type Register = {
27
+ (options: RequiredProperty<RegisterOptions, 'namespace'>): NamespacedUnregister;
28
+ (options?: RegisterOptions): RegisterHandle;
29
+ };
30
+
31
+ type Options = {
32
+ parentURL: string;
33
+ onImport?: (url: string) => void;
34
+ tsconfig?: TsconfigOptions;
35
+ };
36
+
37
+ export declare function register(options: RequiredProperty<RegisterOptions, 'namespace'>): NamespacedUnregister;
38
+
39
+ export declare function register(options?: RegisterOptions): RegisterHandle;
40
+
41
+ export declare const tsImport: (specifier: string, options: string | Options) => Promise<any>;
@@ -0,0 +1,3 @@
1
+ import{a as $,g as G,h as q}from"../chunk-G3UY36AV.js";import{a as D}from"../chunk-QZ6GOFQ4.js";import{a as B,b as z}from"../chunk-UY7ICRUU.js";import{a as C,b as S,c as m,f as I,g,h as j,i as U,j as W}from"../chunk-CWI5WFAA.js";import er from"node:module";import T from"node:path";import Ut from"node:fs";var d=class{static parse(e){return JSON.parse(e)}static serialize(e){return JSON.stringify(e)}};var P=t=>{try{return d.parse(Ut.readFileSync(t,"utf8"))}catch{}};var V=Symbol("missing-tsconfig"),Q=new Map,Dt=t=>{let e=P(t);if(!e)return;let{compilerOptions:{baseUrl:r,paths:s={},allowJs:n=!1}={}}=e;return{compilerOptions:{allowJs:n,baseUrl:T.resolve(T.dirname(t),r||"."),paths:s}}},X=(t,e)=>{let r=[],{baseUrl:s,paths:n}=t.compilerOptions;for(let[o,i]of Object.entries(n)){let a=o.indexOf("*");if(a===-1&&e!==o)continue;let c=a===-1?"":void 0;if(a!==-1){let p=o.slice(0,a),f=o.slice(a+1);if(!e.startsWith(p)||!e.endsWith(f))continue;c=e.slice(p.length,e.length-f.length)}for(let p of i)r.push(T.resolve(s,p.replaceAll("*",c)))}return r};var K=(t="tsconfig.json")=>T.resolve(t),Y=(t="tsconfig.json")=>{let e=T.resolve(t),r=Q.get(e);if(r!==void 0)return r===V?void 0:r;let s=Dt(e);return Q.set(e,s??V),s};var R=t=>{if(t.tsconfig===!1){t.hasLoadedTsconfig=!0;return}return t.hasLoadedTsconfig||(t.parsedTsconfig=Y(t.tsconfig??process.env?.TSNODE_TSCONFIG_PATH),t.hasLoadedTsconfig=!0),t.parsedTsconfig},Z=t=>({active:!0,hasLoadedTsconfig:!1,namespace:t?.namespace,onImport:t?.onImport,parsedTsconfig:void 0,virtualSources:t?.virtualSources,tsconfig:t?.tsconfig});import{fileURLToPath as Te}from"node:url";import{writeSync as Lt}from"node:fs";import{createRequire as _t}from"node:module";var h=Number(process.env.TSNODE_DEBUG);h&&$(!0);var tt,Mt=()=>(tt??=_t(import.meta.url)("node:util").inspect,tt),Ft=t=>(e,...r)=>{if(!h||e>h)return;let s=Mt(),n=r.map(o=>typeof o=="string"?o:s(o,{colors:!0})).join(" ");Lt(1,`${`${q(` tsnode P${process.pid} `)} ${t}`} ${n}
2
+ `)},y=Ft(G(" ESM "));import{createRequire as re,stripTypeScriptTypes as se}from"node:module";import ne from"node:path";import L from"node:path";import{mkdirSync as Ht,readFileSync as Jt,writeFileSync as kt}from"node:fs";import{unlink as _,mkdir as At,readdir as It,rm as jt,writeFile as Wt,stat as et,readFile as $t}from"node:fs/promises";var b=()=>{},Gt=64,qt=2e3,Bt=10080*60*1e3,zt=1440*60*1e3,rt=".last-sweep",M=class{#e=new Map;#t=B;#l=z;#a=0;#r=new Map;#n=!1;#c=!1;#p;#s;#u=!1;get(e){return this.#d(e)??this.#f(e,this.#T(e))}async getAsync(e){return this.#d(e)??this.#f(e,await this.#R(e))}set(e,r){return this.#i(e,r),r&&this.#a<qt&&(this.#a+=1,this.#r.set(e,r),this.#E()),this}has(e){return this.#e.has(e)||this.#r.has(e)}clear(){this.#e.clear(),this.#r.clear()}async#g(){let e=L.join(this.#t,rt);try{let{mtimeMs:r}=await et(e);if(Date.now()-r<zt)return!1}catch{}try{await this.#y(),await Wt(e,"")}catch{return!1}return!0}#h(){this.#u||(this.#u=!0,setImmediate(async()=>{try{if(!await this.#g())return;await this.#P(),await this.#w()}catch{}}))}#o(e){return L.join(this.#t,e)}#y(){return this.#s!==this.#t&&(this.#s=this.#t,this.#p=At(this.#t,{recursive:!0}).then(b)),this.#p}#S(){this.#s!==this.#t&&(Ht(this.#t,{recursive:!0}),this.#s=this.#t)}#i(e,r){if(!this.#e.has(e)&&this.#e.size>=Gt){let s=this.#e.keys().next().value;s!==void 0&&this.#e.delete(s)}this.#e.set(e,r)}#d(e){let r=this.#e.get(e);if(r)return r;let s=this.#r.get(e);if(s)return this.#i(e,s),s}#f(e,r){if(r)return this.#i(e,r),this.#h(),r}#T(e){let r=this.#o(e);try{return d.parse(Jt(r,"utf8"))}catch(s){s.code!=="ENOENT"&&_(r).catch(b);return}}async#R(e){let r=this.#o(e);try{return d.parse(await $t(r,"utf8"))}catch(s){s.code!=="ENOENT"&&_(r).catch(b);return}}#E(){this.#O(),!this.#n&&(this.#n=!0,setImmediate(()=>{this.#n=!1,this.#x()}))}#O(){this.#c||(this.#c=!0,process.once("exit",()=>this.#m()))}#x(){return this.#m(),Promise.resolve()}#m(){if(this.#r.size===0)return;let e=[...this.#r];this.#r.clear();try{this.#S()}catch{return}for(let[r,s]of e)try{kt(this.#o(r),JSON.stringify(s))}catch{}}async#P(){let e;try{e=await It(this.#t)}catch{return}let r=Date.now()-Bt;await Promise.all(e.map(async s=>{if(s===rt)return;let n=L.join(this.#t,s);try{(await et(n)).mtimeMs<r&&await _(n)}catch{}}))}async#b(e){return jt(e,{recursive:!0,force:!0}).catch(b)}async#w(){await Promise.all(this.#l.map(this.#b))}},E=process.env.TSNODE_DISABLE_CACHE?new Map:new M;import Vt from"node:path";var Qt=Object.freeze({target:`node${process.versions.node}`,loader:"default"}),Xt=/^--inspect(?:-brk|-port|-publish-uid|-wait)?(?:=|$)/,Kt=/^--enable-source-maps(?:=|$)/,st=process.execArgv.some(t=>Xt.test(t)),Yt=process.execArgv.some(t=>Kt.test(t)),nt=!!process.env.NODE_V8_COVERAGE,Zt=process.env.TSNODE_SOURCE_MAPS==="1",te=st||Yt||nt||Zt,F={...Qt,sourcemap:te,sourcesContent:nt||st,minifyWhitespace:!0,keepNames:!0},ee=t=>{let e=t.indexOf("?");return e===-1?t:t.slice(0,e)},ot=t=>{let e=t.sourcefile;return e&&Vt.extname(ee(e)).length===0&&(t.sourcefile+=".js"),e},it=(t,e,r)=>{let s;return t.map&&(e!==r&&(t.map=t.map.replace(d.serialize(e),d.serialize(r))),s=d.parse(t.map)),{code:t.code,map:s}};var pt=re(import.meta.url),oe=`-${pt("esbuild/package.json").version}`,at,ie=()=>at??(at=pt("esbuild")),ae=t=>{throw t.name="TransformError",delete t.errors,delete t.warnings,t},ct=new WeakMap,H=t=>{if(t&&typeof t=="object"){let e=ct.get(t);return e!==void 0||(e=JSON.stringify(t),ct.set(t,e)),e}return JSON.stringify(t)??""},u=(t,e)=>{let r=t;for(let s=0,n=e.length;s<n;s+=1)r=Math.imul(r^e.charCodeAt(s),16777619);return r},O="\0",ce=(t,e)=>{let r=2166136261;return r=u(r,t),r=u(r,O),r=u(r,e),(r>>>0).toString(16)},pe=(t,e,r,s,n)=>{let o=2166136261;return o=u(o,t),o=u(o,O),o=u(o,e),o=u(o,O),o=u(o,r),o=u(o,O),o=u(o,s),o=u(o,O),o=u(o,n),(o>>>0).toString(16)},ue=H({...F,format:"esm"}),de=`-strip-${process.versions.node}`,ut=t=>{let e=ce(t,de),r=E.get(e);return r||(r={code:se(t,{mode:"strip"})},E.set(e,r)),r},fe=t=>{if(!t)return!1;for(let e in t)if(e!=="sourcefile"&&e!=="tsconfigRaw"&&e!=="tsconfigHash"&&e!=="getTsconfigRaw")return!0;return!1},me=(t,e,r,s,n,o)=>pe(t,e,n,o??H(r.tsconfigRaw),s),le=t=>{let e=t.indexOf("?");return e===-1?t:t.slice(0,e)},ge=t=>t?ne.extname(le(t)).length===0:!1,dt=(t,e,r)=>{let{tsconfigHash:s,getTsconfigRaw:n,...o}=r??{},i={...F,format:"esm",sourcefile:e,...o},a=ge(i.sourcefile)?ot(i):i.sourcefile;n&&i.tsconfigRaw===void 0&&!s&&(i.tsconfigRaw=n());let c=fe(r)?H({...i,sourcefile:void 0,tsconfigRaw:void 0}):ue,p=me(t,e,i,oe,c,s),f=E.get(p);if(!f){n&&i.tsconfigRaw===void 0&&(i.tsconfigRaw=n());let v;try{v=ie().transformSync(t,i)}catch(Ct){throw ae(Ct)}f=i.sourcemap||a!==i.sourcefile?it(v,i.sourcefile,a):{code:v.code},E.set(p,f)}return f};var he=new Set(I),ft=t=>Se(t),ye=/\.ts($|\?)/,Se=t=>ye.test(t)&&!t.includes("/node_modules/"),mt=t=>{let e=t.indexOf("?"),r=t.indexOf("#");(e===-1||r!==-1&&r<e)&&(e=r),e===-1&&(e=t.length);let s=t.lastIndexOf(".",e-1);if(s>t.lastIndexOf("/",e-1)&&he.has(t.slice(s,e)))return"module"},l="tsnode-namespace=",x=t=>{let e=t.indexOf(l);if(e===-1)return;let r=t[e-1];if(r!=="?"&&r!=="&")return;let s=e+l.length,n=t.indexOf("&",s);return n===-1?t.slice(s):t.slice(s,n)};var Re=`
3
+ //# sourceMappingURL=data:application/json;base64,`,lt=({code:t,map:e})=>e?t+Re+Buffer.from(JSON.stringify(e),"utf8").toString("base64"):t,Ee=t=>t==="module-typescript"||t==="typescript",Oe=t=>R(t),xe=t=>t.tsconfig===!1?void 0:K(t.tsconfig??process.env.TSNODE_TSCONFIG_PATH),Pe=t=>t.startsWith(m)?Te(t):t,be=t=>typeof t=="string"?t:new TextDecoder().decode(t),we=/^\s*@/m,Ne=t=>t.includes("@")&&we.test(t),ve=/(?:^|[^\w$])(?:enum|namespace)\s+[\w$]/m,Ce=t=>(t.includes("enum")||t.includes("namespace"))&&ve.test(t),Ue=t=>{try{return ut(t)}catch(e){if(e.code==="ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX")return;throw e}},De=(t,e)=>{let r=e;if(e.includes(l)){let s=new URL(e);s.searchParams.delete("tsnode-namespace"),r=s.toString()}return t.onImport?.(r),r},Le=(t,e)=>{if(!j.test(t))return e;let r=e.importAttributes;return r?.type?e:{...e,importAttributes:{...r,type:"json"}}},gt=t=>{let e=(r,s,n)=>{if(!t.active||t.namespace!==x(r))return n(r,s);let o=t.virtualSources?.get(r);if(o!==void 0)return{format:"module",source:o,shortCircuit:!0};(t.onImport||D.send)&&D.send?.({type:"dependency",path:De(t,r)});let i=n(r,Le(r,s));if(y(3,"loaded by next loader",{url:r,loaded:i}),!i.source)return i;let a=Ee(i.format)||g.test(r),c=i.format==="json"&&s.conditions?.includes("import")===!0;if(!c&&!a)return i;let p=be(i.source);if(a&&ft(r)&&!Ne(p)&&!Ce(p)){let f=Ue(p);if(f)return{format:"module",source:lt(f)}}return c||a?{format:"module",source:lt(dt(p,Pe(r),{tsconfigHash:xe(t),getTsconfigRaw:()=>Oe(t)}))}:i};return h?(r,s,n)=>{y(2,"loadSync",{url:r,context:s});let o=e(r,s,n);return y(1,"loadedSync",{url:r,result:o}),o}:e};import{pathToFileURL as Tt}from"node:url";import{extname as _e,isAbsolute as Me,posix as Fe,sep as He}from"node:path";var Rt=[".js",".json"],Et=[".ts",".tsx",".jsx"],Je=[...Et,...Rt],ke=[...Rt,...Et],k=Object.create(null);k[".js"]=[".ts",".tsx",".js",".jsx"];k[".jsx"]=[".tsx",".ts",".jsx",".js"];var Ae=new Set([".ts",".tsx"]),Ie=t=>{let e=t.indexOf("?");return e===-1?[t,""]:[t.slice(0,e),t.slice(e)]},je=t=>{let[e,r]=Ie(t),s=_e(e);if(Ae.has(s))return;let n=[],o=p=>e.slice(0,-s.length)+p+r,i=k[s];if(i)return n.push(...i.map(o)),n;let a=p=>e+p+r,c=!(t.startsWith(m)||S(e))||e.includes(W)||e.includes("/node_modules/")?ke:Je;return n.push(...c.map(a)),n},We=/^(?:[a-z][\d+.a-z-]*:\/\/|data:|file:|node:)/i,$e=t=>!S(t)&&!We.test(t),Ot=t=>{if(t.url)return t.url;let e=t.message.match(/^Cannot find module '([^']+)'/);if(e){let[,s]=e;return s}let r=t.message.match(/^Cannot find package '([^']+)'/);if(r){let[,s]=r;if(!Me(s))return;let n=Tt(s);if(n.pathname.endsWith("/")&&(n.pathname+="package.json"),n.pathname.endsWith("/package.json")){let o=P(n);if(o?.main)return new URL(o.main,n).toString()}else return n.toString()}},A=t=>t==="ERR_MODULE_NOT_FOUND"||t==="MODULE_NOT_FOUND",N=(t,e,r,s)=>{let n=je(t);if(!n)return;let o;for(let i of n)try{return r(i,e)}catch(a){let{code:c}=a;if(!A(c)&&c!=="ERR_PACKAGE_PATH_NOT_EXPORTED")throw a;o=a}if(s){if(o===void 0)return r(n[0],e);throw o}},Ge=(t,e,r)=>g.test(t)?!1:(t.startsWith(m)||C(t))&&(g.test(e.parentURL)||(R(r)?.compilerOptions.allowJs??!1)),ht=(t,e,r,s)=>{if(Ge(t,e,s)){let n=N(t,e,r);if(n)return n}try{return r(t,e)}catch(n){if(n instanceof Error){let o=n;if(A(o.code)){let i=Ot(o);if(i){let a=N(i,e,r);if(a)return a}}}throw n}},qe=t=>t==="."||t===".."||t.endsWith("/..")?`${t}/`:t,yt=(t,e,r,s)=>{if(t=qe(t),U.test(t)){if(!S(t)&&!t.startsWith(m))return ht(t,e,r,s);let n=new URL(t,e.parentURL);return n.pathname=Fe.join(n.pathname,"index"),N(n.toString(),e,r,!0)}try{return ht(t,e,r,s)}catch(n){if(n instanceof Error){let o=n;if(o.code==="ERR_UNSUPPORTED_DIR_IMPORT"){let i=Ot(o);if(i)try{return N(`${i}/index`,e,r,!0)}catch(a){let c=a,{message:p}=c;throw c.message=c.message.replace(`${"/index".replace("/",He)}'`,"'"),c.stack=c.stack.replace(p,c.message),c}}}throw n}},xt=(t,e,r,s)=>{let n=R(s);if($e(t)&&n&&!e.parentURL?.includes("/node_modules/"))for(let o of X(n,t))try{return yt(Tt(o).toString(),e,r,s)}catch{}return yt(t,e,r,s)},J="tsnode://",Be=/\.(?:m?js|json)($|\?)/,St=(t,e)=>`${t}${t.includes("?")?"&":"?"}${e}`,ze=(t,e,{namespace:r})=>{let s=x(t)??(e.parentURL&&x(e.parentURL)),n=e.parentURL;if(r){let o;if(t.startsWith(J)){try{o=JSON.parse(t.slice(J.length))}catch{}o?.namespace&&(s=o.namespace)}if(r!==s)return;o&&(t=o.specifier,n=o.parentURL)}return{specifier:t,requestNamespace:s,parentURL:n}},Ve=(t,e,r)=>(e&&(t.url=St(t.url,e)),r&&!t.url.includes(l)&&(t.url=St(t.url,`${l}${r}`)),t),w=t=>((!t.format||t.format==="module-typescript")&&t.url.startsWith(m)&&(t.format=mt(t.url)),t),Pt=(t,e)=>!e.namespace&&!t.startsWith(J)&&!t.includes(l)&&!t.includes("?")&&!U.test(t)&&(t.startsWith(m)||C(t)||S(t)),Qe=(t,e)=>Pt(t,e)&&g.test(t),Xe=(t,e,r)=>Pt(t,r)&&Be.test(t)&&!g.test(e.parentURL??""),Ke=t=>((e,r,s)=>{if(!t.active||e.startsWith("node:"))return s(e,r);if(Qe(e,t))return w(s(e,r));if(Xe(e,r,t))try{return w(s(e,r))}catch(o){if(!A(o.code))throw o}let n=xt(e,r,s,t);return n.format==="builtin"?n:w(n)}),Ye=t=>((e,r,s)=>{if(!t.active||e.startsWith("node:"))return s(e,r);let n=ze(e,r,t);if(!n)return s(e,r);let o=n.parentURL&&n.parentURL!==r.parentURL?{...r,parentURL:n.parentURL}:r,[i,a]=n.specifier.split("?"),c=xt(i,o,s,t);return c.format==="builtin"?c:(w(c),Ve(c,a,n.requestNamespace))}),bt=t=>{let e=t.namespace?Ye(t):Ke(t);return h?(r,s,n)=>{y(2,"resolveSync",{specifier:r,context:s});let o=e(r,s,n);return y(1,"resolvedSync",{specifier:r,context:s,result:o}),o}:e};import{pathToFileURL as Ze}from"node:url";var tr=new Function("specifier","return import(specifier);"),wt=t=>(e,r)=>{if(!r)throw new Error("The current file path (import.meta.url) must be provided in the second argument of tsImport()");let s=r.startsWith(m)?r:Ze(r).toString();return tr(`tsnode://${JSON.stringify({specifier:e,parentURL:s,namespace:t})}`)};var rr=/^--enable-source-maps(?:=|$)/,sr=/^--inspect(?:-brk|-port|-publish-uid|-wait)?(?:=|$)/,nr=t=>rr.test(t),or=t=>sr.test(t),Nt=process.execArgv.some(nr)||process.execArgv.some(or)||!!process.env.NODE_V8_COVERAGE||process.env.TSNODE_SOURCE_MAPS==="1";function vt(t){Nt&&process.setSourceMapsEnabled(!0);let e=Z({namespace:t?.namespace,onImport:t?.onImport,tsconfig:t?.tsconfig}),r=er.registerHooks({load:gt(e),resolve:bt(e)}),s=async()=>{e.active=!1,r.deregister(),Nt&&process.sourceMapsEnabled===!1&&process.setSourceMapsEnabled(!1)};return t?.namespace?{import:wt(t.namespace),unregister:s}:{unregister:s}}var ps=(t,e)=>{if(!e||typeof e=="object"&&!e.parentURL)throw new Error("The current file path (import.meta.url) must be provided in the second argument of tsImport()");return typeof e=="string"&&(e={parentURL:e}),vt({...e,namespace:Date.now().toString()}).import(t,e.parentURL)};export{vt as register,ps as tsImport};
@@ -0,0 +1 @@
1
+ import{spawn as a}from"node:child_process";var c=n=>{for(let t of n)if(t!=="-i"&&t!=="--interactive")return!1;return!0},p=(n,t)=>{let i=["inherit","inherit","inherit"],e={...process.env};process.send&&i.push("ipc");let r=t?.signalRelay!==!1,o=!!t?.ipc||r;t&&(t.noCache&&(e.TSNODE_DISABLE_CACHE="1"),r||(e.TSNODE_SIGNAL_RELAY="0"),t.ipc&&(e.TSNODE_DEPENDENCY_REPORTING="1"),t.tsconfigPath&&(e.TSNODE_TSCONFIG_PATH=t.tsconfigPath)),o&&(e.TSNODE_IPC="1");let s=[...o?["--import",new URL("./preflight.js",import.meta.url).toString()]:[],...c(n)?["--import",new URL("./repl.js",import.meta.url).toString()]:[],"--import",new URL("./loader.js",import.meta.url).toString(),...n];return a(process.execPath,s,{stdio:i,env:e})};export{p as a};
@@ -0,0 +1 @@
1
+ import n from"node:path";import{statSync as l}from"node:fs";import{fileURLToPath as p}from"node:url";var f=t=>t[0]==="."&&(t[1]==="/"||t[1]==="."&&t[2]==="/"),P=t=>f(t)||n.isAbsolute(t);var a="file://",d=t=>{if(!t.startsWith(a))return t;try{return p(t)}catch{return t}},c=[".ts",".tsx",".jsx",".js",".json"],r=t=>{try{return l(t).isFile()?t:void 0}catch{return}},g=t=>{let x=d(t),s=n.resolve(x),i=r(s);if(i)return i;for(let o of c){let e=r(s+o);if(e)return e}for(let o of c){let e=r(n.join(s,`index${o}`));if(e)return e}},j=[".ts",".tsx",".jsx"],y=/\.(?:ts|[tj]sx)($|\?)/;var $=/\.json($|\?)/,F=/\/(?:$|\?)/;var E=`${n.sep}node_modules${n.sep}`;export{f as a,P as b,a as c,d,g as e,j as f,y as g,$ as h,F as i,E as j};
@@ -0,0 +1 @@
1
+ var r=process.stdout.isTTY&&process.env.NO_COLOR===void 0&&process.env.TERM!=="dumb",s=(e,t,n)=>r?`\x1B[${e}m${n}\x1B[${t}m`:n,o=(e,t)=>n=>s(e,t,n),c=e=>{r=e},l=o(90,39),p=o(96,39),a=o(95,39),b=o(92,39),u=o(33,39),g=o(44,49),i=o(100,49);export{c as a,l as b,p as c,a as d,b as e,u as f,g,i as h};
@@ -0,0 +1 @@
1
+ import{a as o,c as s,d as i}from"./chunk-UY7ICRUU.js";import{createServer as n}from"node:net";import{rmSync as f}from"node:fs";import{mkdir as c,rm as m}from"node:fs/promises";var p=r=>{let e=Buffer.alloc(0);return a=>{for(e=Buffer.concat([e,a]);e.length>4;){let t=e.readInt32BE(0);if(e.length>=4+t)r(e.subarray(4,4+t)),e=e.subarray(4+t);else break}}},v=async()=>{let r=n(a=>{a.on("data",p(t=>r.emit("data",JSON.parse(t.toString()))))}),e=i(process.pid);return await c(o,{recursive:!0}),await m(e,{force:!0}),await new Promise((a,t)=>{r.listen(e,a),r.on("error",t)}),r.unref(),process.on("exit",()=>{if(r.close(),!s)try{f(e)}catch{}}),r};export{v as a};
@@ -0,0 +1 @@
1
+ var d=n=>n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),a=(n,e)=>{if(e in n)return[e,n[e]];let t=d(e);return t in n?[t,n[t]]:void 0},u=(n,e)=>{for(let t in n){let s=n[t];if(s.alias===e)return[t,s]}},f=n=>{let e=n.indexOf("=");return e===-1?[n,void 0]:[n.slice(0,e),n.slice(e+1)]},c=n=>n.type!==Boolean,g=(n,e)=>{for(let t=0,s=e.length;t<s;t+=1){let i=e[t];if(i==="--")return t+1;if(i.startsWith("--")){let[o,l]=f(i.slice(2)),r=a(n,o);r&&l===void 0&&c(r[1])&&(t+=1);continue}if(i.startsWith("-")&&i.length===2){let[,o]=u(n,i[1])??[];o&&c(o)&&(t+=1);continue}if(!i.startsWith("-")||i==="-")return t}return-1},p=(n,e=process.argv.slice(2))=>{for(let t=0;t<e.length;){let s=e[t];if(s==="--"||!s.startsWith("-")||s==="-")break;let i=0;if(s.startsWith("--")){let[o,l]=f(s.slice(2)),[,r]=a(n,o)??[];r&&(i=l===void 0&&c(r)?2:1)}else if(s.length===2){let[,o]=u(n,s[1])??[];o&&(i=c(o)?2:1)}if(i>0){e.splice(t,i);continue}t+=1}return e};export{g as a,p as b};
@@ -0,0 +1 @@
1
+ import{d as c}from"./chunk-UY7ICRUU.js";import f from"node:net";var a=process.env.TSNODE_IPC==="1",t=process.env.TSNODE_DEPENDENCY_REPORTING==="1",o=[],p=()=>new Promise(e=>{let n=f.createConnection(c(process.ppid),()=>{e(i=>{let r=Buffer.from(JSON.stringify(i)),s=Buffer.alloc(4);s.writeInt32BE(r.length,0),n.write(Buffer.concat([s,r]))})});n.on("error",()=>e()),n.unref()}),d={send:t?e=>o.push(e):void 0},P=a&&process.env.TSNODE_SIGNAL_RELAY!=="0"?p():Promise.resolve();P.then(e=>{if(e&&t)for(let n of o)e(n);o=[],d.send=t?e:void 0},()=>{o=[],d.send=void 0});export{d as a,P as b};
@@ -0,0 +1 @@
1
+ import t from"node:path";import o from"node:os";var{geteuid:e}=process,p=e?e():o.userInfo().username,n=2,i=t.join(o.tmpdir(),`tsnode-v${n}-${p}`),f=[t.join(o.tmpdir(),"tsnode"),t.join(o.tmpdir(),`tsnode-${p}`)];import m from"node:path";var c=process.platform==="win32",$=s=>{let r=m.join(i,`${s}.pipe`);return c?`\\\\?\\pipe\\${r}`:r};export{i as a,f as b,c,$ as d};
package/dist/cli.js CHANGED
@@ -1,18 +1,5 @@
1
- #!/usr/bin/env node
2
- import process from 'node:process';
3
- import { pathToFileURL } from 'node:url';
4
- import { registerHooks } from 'node:module';
5
- import { resolve as resolvePath } from 'node:path';
6
- import { loaderLifecycle, load, resolve } from './hooks.js';
7
- // Use top-level await to ensure the loader is registered before importing the target.
8
- await using _loader = loaderLifecycle;
9
- // Register the TypeScript loader hooks synchronously before importing the target.
10
- registerHooks({ load, resolve });
11
- const entry = process.argv[2];
12
- if (entry === undefined) {
13
- process.stderr.write('Usage: tsnode <file.ts> [...args]\n');
14
- process.exit(1);
15
- }
16
- // Shift argv so the target file looks like the main script to the loaded module.
17
- process.argv.splice(1, 1);
18
- await import(entry.startsWith('file:') ? entry : pathToFileURL(resolvePath(entry)).href);
1
+ import{d as v,e as S}from"./chunk-CWI5WFAA.js";import{constants as g}from"node:os";import{enableCompileCache as h}from"node:module";if(typeof h=="function"&&process.env.NODE_DISABLE_COMPILE_CACHE!=="1")try{h()}catch{}var w=(o,i)=>{let a;i.on("data",s=>{s?.type==="signal"&&a&&a(s.signal)});let e=()=>{let s=new Promise(c=>{setTimeout(()=>c(void 0),30),a=c});return s.then(()=>a=void 0,()=>{}),s},t=async s=>{await e()!==s&&(o.kill(s),await e()!==s&&(o.on("exit",()=>{process.exit(128+g.signals[s])}),o.kill(g.signals.SIGKILL)))};process.on("SIGINT",t),process.on("SIGTERM",t)},C={noCache:{type:Boolean},tsconfig:{type:String}},I={...C,version:{type:Boolean,alias:"v"},help:{type:Boolean,alias:"h"}},T={...I,inputType:{type:String},test:{type:Boolean},eval:{type:String,alias:"e"},print:{type:String,alias:"p"}},A={"no-cache":{type:"boolean"},tsconfig:{type:"string"},version:{type:"boolean",short:"v"},help:{type:"boolean",short:"h"},"input-type":{type:"string"},test:{type:"boolean"},eval:{type:"string",short:"e"},print:{type:"string",short:"p"}},O=async o=>{let{parseArgs:i}=await import("node:util");return i({args:o,allowPositionals:!0,strict:!1,options:A}).values},F=o=>{for(let i of["print","eval"]){let a=o[i];if(a!==void 0)return{type:i,code:a}}},N=()=>{process.stdout.write(`Node.js runtime enhanced with esbuild for loading TypeScript & ESM
2
+ `),process.stdout.write(`Usage: tsnode [script path] [arguments]
3
+ `)},f=process.argv.slice(2);if(f[0]==="watch"){let{runWatchCommand:o}=await import("./watch-KRAOMOO6.js");await o(f.slice(1)),process.exitCode??=0}else{let{findFirstPositionalIndex:o}=await import("./remove-argv-flags-YKV2LNF2.js"),i=o(T,f),a=i===-1?f:f.slice(0,i),e=a.length===0?{}:await O(a);if(e.version){let{default:{version:n}}=await import("./package-H7Z52REB.js");process.stdout.write(`tsnode v${n}
4
+ node `)}else e.help&&(N(),console.log(`${"-".repeat(45)}
5
+ `));let t=(await import("./remove-argv-flags-YKV2LNF2.js")).removeArgvFlags({...C,eval:{type:String,alias:"e"},print:{type:String,alias:"p"}}),s=F(e);if(s){let n=(await import("esbuild")).transformSync(s.code,{loader:"ts",sourcefile:"/eval.ts",...s.type==="eval"?{format:"esm"}:{}});t.unshift(`--${s.type}`,n.code),s.type==="eval"&&e["input-type"]!=="module"&&t.unshift("--input-type=module")}e.test&&i===-1&&t.push("**/{test,test/**/*,test-*,*[.-_]test}.?(c|m)@(t|j)s");let{run:c}=await import("./run-J7WDXCNP.js"),[d]=t,r=d&&!d.startsWith("-")?v(d):d,u=r&&!r.startsWith("-")?S(r):void 0;r!==d&&r!==void 0&&(t[0]=r);let E=process.env.TSNODE_DISABLE_IN_PROCESS!=="1"&&!e.version&&!e.help&&!s&&!e.test&&i!==-1&&r!==void 0&&!r.startsWith("-")&&!process.send&&u!==void 0,P=process.env.TSNODE_DISABLE_IN_PROCESS!=="1"&&!e.version&&!e.help&&s?.type==="eval"&&!e.test&&!process.send&&!t.some(n=>n.startsWith("-"));if(E){e["no-cache"]&&(process.env.TSNODE_DISABLE_CACHE="1"),typeof e.tsconfig=="string"&&(process.env.TSNODE_TSCONFIG_PATH=e.tsconfig);let{runInProcess:n}=await import("./run-in-process-5OFAUP24.js");await n(t,u)}else if(P){let{runEvalInProcess:n}=await import("./run-eval-in-process-LFWU3AL6.js");await n(t.shift(),t)}else{let n=process.env.TSNODE_DISABLE_SIGNAL_RELAY!=="1"&&(process.env.TSNODE_FORCE_SIGNAL_RELAY==="1"||process.stdin.isTTY||process.stdout.isTTY||process.stderr.isTTY),y=n?await import("./server-TWLLBPU7.js").then(({createIpcServer:l})=>l()):void 0,p=c(t,{noCache:!!e["no-cache"],signalRelay:n,tsconfigPath:e.tsconfig});y&&w(p,y);let m=process.send;m!==void 0&&p.on("message",l=>m(l)),p.send&&process.on("message",l=>p.send(l)),p.on("close",l=>process.exit(l??g.signals[p.signalCode]+128))}}
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-QZ6GOFQ4.js";import"./chunk-UY7ICRUU.js";export{b as connectingToServer,a as parent};
@@ -0,0 +1 @@
1
+ export {};
package/dist/loader.js ADDED
@@ -0,0 +1 @@
1
+ import{enableCompileCache as e}from"node:module";if(process.env.NODE_DISABLE_COMPILE_CACHE!=="1")try{e()}catch{}await import("./suppress-warnings.js");(await import("./api/index.js")).register();
@@ -0,0 +1 @@
1
+ var s={name:"@d1g1tal/tsnode",version:"1.0.1",description:"ESM-only Node.js TypeScript runner \u2014 run .ts files directly with `tsnode foo.ts`. CommonJS support removed.",keywords:["cli","runtime","node","esm","typescript","typescript runner"],license:"MIT",repository:"D1g1talEntr0py/tsnode",author:"D1g1talEntr0py",contributors:[{name:"Hiroki Osame",email:"hiroki.osame@gmail.com",url:"https://github.com/privatenumber/tsx"}],files:["dist"],types:"./dist/loader.d.ts",type:"module",bin:{tsnode:"./dist/cli.js"},exports:{"./package.json":"./package.json",".":{types:"./dist/loader.d.ts",default:"./dist/loader.js"},"./api":{types:"./dist/api/index.d.ts",default:"./dist/api/index.js"},"./cli":"./dist/cli.js","./suppress-warnings":"./dist/suppress-warnings.js","./preflight":"./dist/preflight.js","./repl":"./dist/repl.js"},packageManager:"pnpm@11.17.0",scripts:{build:"pnpm type-check && node ./scripts/build/build-js.ts && node ./scripts/build/build-types.ts","run:import":"node --import ./dist/loader.js","run:import:build":"pnpm build && node --import ./dist/loader.js","run:import:no-relay":"TSNODE_DISABLE_SIGNAL_RELAY=1 node --import ./dist/loader.js",benchmark:"pnpm build && node ./dist/cli.js tests/benchmarks/index.ts","benchmark:hooks":"pnpm build && node ./dist/cli.js tests/benchmarks/hooks.ts","benchmark:compare":"pnpm build && node ./dist/cli.js tests/benchmarks/compare.ts","benchmark:memory":"pnpm build && node ./dist/cli.js tests/benchmarks/memory-profile.ts",lint:"eslint --flag unstable_native_nodejs_ts_config ./src","type-check":"tsc",test:"vitest run","test:coverage":"vitest run --coverage","test:watch":"vitest"},engines:{node:">=24.11.1"},dependencies:{"@d1g1tal/watchr":"^1.1.1",esbuild:"^0.28.1"},devDependencies:{"@eslint/js":"^10.0.1","@types/node":"^26.1.1","@typescript-eslint/eslint-plugin":"^8.65.0","@typescript-eslint/parser":"^8.65.0","@typescript/native":"npm:typescript@^7.0.2","@vitest/coverage-v8":"^4.1.10",eslint:"^10.8.0","eslint-plugin-jsdoc":"^63.3.1",execa:"^10.0.0","fs-fixture":"^2.14.0","get-node":"^15.0.4",mitata:"^1.0.34",typescript:"npm:@typescript/typescript6@^6.0.2","typescript-eslint":"^8.65.0",vitest:"^4.1.10"}};export{s as default};
@@ -0,0 +1 @@
1
+ import{enableCompileCache as r}from"node:module";import{constants as c}from"node:os";import{isMainThread as p}from"node:worker_threads";if(typeof r=="function"&&process.env.NODE_DISABLE_COMPILE_CACHE!=="1")try{r()}catch{}var S=(s,t)=>{let o=new Map;for(let e of s){let n=i=>{t(i),process.listenerCount(e)===0&&process.exit(128+c.signals[e])};process.on(e,n),o.set(e,n)}let{listenerCount:a,listeners:l}=process;process.listenerCount=function(e){let n=Reflect.apply(a,this,arguments);return s.includes(e)&&(n-=1),n},process.listeners=function(e){let n=Reflect.apply(l,this,arguments);return s.includes(e)?n.filter(i=>i!==o.get(e)):n}};await import("./suppress-warnings.js");var{connectingToServer:d}=await import("./client-MB4FJ7RP.js");p&&(async()=>{if(process.env.TSNODE_SIGNAL_RELAY==="0")return;let s=await d;s&&S(["SIGINT","SIGTERM"],t=>s({type:"signal",signal:t}))})();
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-QJLUIPZW.js";export{a as findFirstPositionalIndex,b as removeArgvFlags};
package/dist/repl.js ADDED
@@ -0,0 +1 @@
1
+ import{transform as p}from"esbuild";import e from"node:repl";var c=t=>{let{eval:s}=t,n=async function(r,o,a,i){let l={sourcefile:a,loader:"ts",tsconfigRaw:{compilerOptions:{preserveValueImports:!0}},define:{require:"global.require"}};try{({code:r}=await p(r,l))}catch{}return s.call(this,r,o,a,i)};return t.eval=n,t},{start:f}=e;e.start=function(){return c(Reflect.apply(f,this,arguments))};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-4VQTTHC7.js";export{a as run};
@@ -0,0 +1 @@
1
+ import t from"node:path";import{pathToFileURL as s}from"node:url";var p=async(a,o)=>{process.argv=[process.argv[0],...o],await import("./suppress-warnings.js");let r=s(t.join(process.cwd(),"[eval1]")).href;(await import("./api/index.js")).register({virtualSources:new Map([[r,a]])}),await import(r)};export{p as runEvalInProcess};
@@ -0,0 +1 @@
1
+ import{d as t}from"./chunk-CWI5WFAA.js";import{pathToFileURL as e}from"node:url";import p from"node:path";var g=async(o,i)=>{let[a,...s]=o,r=p.resolve(t(a));process.argv=[process.argv[0],r,...s],await import("./suppress-warnings.js"),(await import("./api/index.js")).register(),await import(e(i??r).href)};export{g as runInProcess};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-PXHSM7AZ.js";import"./chunk-UY7ICRUU.js";export{a as createIpcServer};
@@ -0,0 +1 @@
1
+ var a=new Set(["Custom ESM Loaders is an experimental feature. This feature could change at any time","Custom ESM Loaders is an experimental feature and might change at any time","Import assertions are not a stable feature of the JavaScript language. Avoid relying on their current behavior and syntax as those might change in a future version of Node.js.","stripTypeScriptTypes is an experimental feature and might change at any time"]),n=process.emit;process.emit=function(e,...t){return e==="warning"&&a.has(t[0].message)?!0:Reflect.apply(n,this,arguments)};
@@ -0,0 +1,4 @@
1
+ import{a as F}from"./chunk-PXHSM7AZ.js";import{b as I,c as b,d as C,e as M,f as l}from"./chunk-G3UY36AV.js";import"./chunk-UY7ICRUU.js";import{a as E}from"./chunk-4VQTTHC7.js";import{a as G,b as R}from"./chunk-QJLUIPZW.js";import{isAbsolute as m,join as B,relative as Q,matchesGlob as V}from"node:path";import{fileURLToPath as X}from"node:url";import{constants as Y}from"node:os";import{parseArgs as Z}from"node:util";import{Watchr as ee}from"@d1g1tal/watchr";var O=()=>new Date().toLocaleTimeString(),p=(...e)=>console.log(I(O()),b("[tsnode]"),...e),L="\x1Bc",N=(e,s)=>{let u;return function(){u&&clearTimeout(u),u=setTimeout(()=>Reflect.apply(e,this,arguments),s)}};var D={noCache:{type:Boolean},tsconfig:{type:String},clearScreen:{type:Boolean},include:{type:[String]},exclude:{type:[String]},help:{type:Boolean,alias:"h"}},te=e=>typeof e=="string",$=e=>e?Array.isArray(e)?e.filter(te):typeof e=="string"?[e]:[]:[],ne=()=>{process.stdout.write(`Run the script and watch for changes
2
+ `),process.stdout.write(`Usage: tsnode watch [options] <script path> [arguments]
3
+ `)},w=e=>e.replace(/\\/g,"/"),A=(e,s)=>{try{return V(e,s)}catch{return!1}},re=e=>e!==null&&typeof e=="object"&&"type"in e&&e.type==="dependency"&&"path"in e&&typeof e.path=="string",ye=async(e=process.argv.slice(3))=>{let s=G(D,e),u=s===-1?e:e.slice(0,s),{values:o}=Z({args:u,allowPositionals:!0,strict:!1,options:{"no-cache":{type:"boolean"},tsconfig:{type:"string"},"clear-screen":{type:"boolean"},include:{type:"string",multiple:!0},exclude:{type:"string",multiple:!0},help:{type:"boolean",short:"h"}}});if(o.help&&s===-1){ne();return}if(s===-1){process.stderr.write(`Error: Missing required parameter "script path"
4
+ `),process.exitCode=1;return}let y=process.cwd(),H=R(D,[...e]),J=t=>m(t)?t:B(y,t),d={noCache:!!o["no-cache"],tsconfigPath:typeof o.tsconfig=="string"?o.tsconfig:void 0,clearScreen:o["clear-screen"]??!0,include:$(o.include),exclude:$(o.exclude),ipc:!0},K=[e.slice(s)[0],...d.include].map(J),P=t=>{let n=w(t);if(n.split("/").some(r=>r.startsWith(".")&&r.length>1)||n.includes("/node_modules/")||n.includes("/bower_components/")||n.includes("/vendor/"))return!0;for(let r of d.exclude){let c=w(r),a=w(m(r)?r:B(y,r));if(A(n,c)||A(n,a))return!0}return!1},i,x=!1,S=new Set,f=()=>{},_=await F(),v=(t,n,r,c)=>{let a=c??r,h=Q(y,a);f(t,h.length>0&&!h.startsWith("..")?h:a)},T={ignoreInitial:!0,ignore:P,recursive:!0},j=new ee(K,T,v);_.on("data",t=>{if(re(t)){let n=t.path.startsWith("file:")?X(t.path):t.path;m(n)&&!S.has(n)&&!P(n)&&(S.add(n),j.watchPath(n,T,v))}});let z=()=>{if(!x)return E(H,d)},g=!1,W=async(t,n="SIGTERM",r=5e3)=>{let c=!1,a=setTimeout(()=>{c||(p(l(`Process didn't exit in ${Math.floor(r/1e3)}s. Force killing...`)),t.kill("SIGKILL"))},r),h=new Promise(U=>{t.once("exit",q=>{c=!0,g=!1,clearTimeout(a),U(q)})});return g=!0,t.kill(n),h};f=N(async(t,n)=>{let r=t?`${C(t)}${n?` in ${M(`./${n}`)}`:""}`:"";if(g){p(r,l("Process hasn't exited. Killing process...")),i.kill("SIGKILL");return}i&&(i.exitCode===null?(p(r,l("Restarting...")),await W(i)):p(r,l("Rerunning...")),d.clearScreen&&process.stdout.write(L)),i=z()},100),f();let k=t=>{x=!0,i?.exitCode===null?(g&&p(l("Previous process hasn't exited yet. Force killing...")),W(i,g?"SIGKILL":t).then(n=>process.exit(n??0),()=>{})):process.exit(Y.signals[t])};process.on("SIGINT",k),process.on("SIGTERM",k),process.stdin.on("data",()=>f("Return key"))};export{ye as runWatchCommand};
package/package.json CHANGED
@@ -1,68 +1,88 @@
1
1
  {
2
2
  "name": "@d1g1tal/tsnode",
3
- "author": "D1g1talEntr0py",
4
- "version": "0.1.0",
5
- "license": "MIT",
6
- "description": "Zero-flag Node.js TypeScript loader — run .ts files directly with `tsnode foo.ts`.",
3
+ "version": "1.0.1",
4
+ "description": "ESM-only Node.js TypeScript runner — run .ts files directly with `tsnode foo.ts`. CommonJS support removed.",
5
+ "keywords": [
6
+ "cli",
7
+ "runtime",
8
+ "node",
9
+ "esm",
10
+ "typescript",
11
+ "typescript runner"
12
+ ],
13
+ "license": "MIT",
7
14
  "repository": {
8
15
  "type": "git",
9
- "url": "git+https://github.com/D1g1talEntr0py/tsnode.git"
10
- },
11
- "bugs": {
12
- "url": "https://github.com/D1g1talEntr0py/tsnode/issues"
16
+ "url": "D1g1talEntr0py/tsnode"
13
17
  },
14
- "maintainers": [
18
+ "author": "D1g1talEntr0py",
19
+ "contributors": [
15
20
  {
16
- "name": "D1g1talEntr0py",
17
- "email": "jason.dimeo@gmail.com"
21
+ "name": "Hiroki Osame",
22
+ "email": "hiroki.osame@gmail.com",
23
+ "url": "https://github.com/privatenumber/tsx"
18
24
  }
19
25
  ],
20
- "engines": {
21
- "node": ">=22.15.0"
22
- },
23
- "packageManager": "pnpm@11.8.0",
24
- "publishConfig": {
25
- "registry": "https://registry.npmjs.org",
26
- "access": "public"
27
- },
28
- "type": "module",
29
- "exports": {
30
- ".": {
31
- "types": "./dist/hooks.d.ts",
32
- "default": "./dist/hooks.js"
33
- }
34
- },
35
26
  "files": [
36
- "dist",
37
- "README.md",
38
- "LICENSE"
27
+ "dist"
39
28
  ],
29
+ "types": "./dist/loader.d.ts",
30
+ "type": "module",
40
31
  "bin": {
41
32
  "tsnode": "./dist/cli.js"
42
33
  },
43
- "scripts": {
44
- "build": "tsc -p tsconfig.json && node -e \"import('node:fs').then(({chmodSync})=>chmodSync('./dist/cli.js',0o755))\"",
45
- "clean": "rm -rf dist",
46
- "prepack": "pnpm run clean && pnpm run build",
47
- "release:check": "pnpm run clean && pnpm run build && pnpm run test && pnpm run type-check && npm pack --dry-run",
48
- "test": "vitest run",
49
- "test:watch": "vitest",
50
- "type-check": "tsc -p tsconfig.json --noEmit"
34
+ "exports": {
35
+ "./package.json": "./package.json",
36
+ ".": {
37
+ "types": "./dist/loader.d.ts",
38
+ "default": "./dist/loader.js"
39
+ },
40
+ "./api": {
41
+ "types": "./dist/api/index.d.ts",
42
+ "default": "./dist/api/index.js"
43
+ },
44
+ "./cli": "./dist/cli.js",
45
+ "./suppress-warnings": "./dist/suppress-warnings.js",
46
+ "./preflight": "./dist/preflight.js",
47
+ "./repl": "./dist/repl.js"
48
+ },
49
+ "engines": {
50
+ "node": ">=24.11.1"
51
51
  },
52
52
  "dependencies": {
53
- "typescript": "^6.0.3"
53
+ "@d1g1tal/watchr": "^1.1.1",
54
+ "esbuild": "^0.28.1"
54
55
  },
55
56
  "devDependencies": {
56
- "@types/node": "^25.9.3",
57
- "vitest": "^4.1.8"
57
+ "@eslint/js": "^10.0.1",
58
+ "@types/node": "^26.1.1",
59
+ "@typescript-eslint/eslint-plugin": "^8.65.0",
60
+ "@typescript-eslint/parser": "^8.65.0",
61
+ "@typescript/native": "npm:typescript@^7.0.2",
62
+ "@vitest/coverage-v8": "^4.1.10",
63
+ "eslint": "^10.8.0",
64
+ "eslint-plugin-jsdoc": "^63.3.1",
65
+ "execa": "^10.0.0",
66
+ "fs-fixture": "^2.14.0",
67
+ "get-node": "^15.0.4",
68
+ "mitata": "^1.0.34",
69
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
70
+ "typescript-eslint": "^8.65.0",
71
+ "vitest": "^4.1.10"
58
72
  },
59
-
60
- "keywords": [
61
- "typescript",
62
- "node",
63
- "loader",
64
- "esm",
65
- "cli",
66
- "transpile"
67
- ]
68
- }
73
+ "scripts": {
74
+ "build": "pnpm type-check && node ./scripts/build/build-js.ts && node ./scripts/build/build-types.ts",
75
+ "run:import": "node --import ./dist/loader.js",
76
+ "run:import:build": "pnpm build && node --import ./dist/loader.js",
77
+ "run:import:no-relay": "TSNODE_DISABLE_SIGNAL_RELAY=1 node --import ./dist/loader.js",
78
+ "benchmark": "pnpm build && node ./dist/cli.js tests/benchmarks/index.ts",
79
+ "benchmark:hooks": "pnpm build && node ./dist/cli.js tests/benchmarks/hooks.ts",
80
+ "benchmark:compare": "pnpm build && node ./dist/cli.js tests/benchmarks/compare.ts",
81
+ "benchmark:memory": "pnpm build && node ./dist/cli.js tests/benchmarks/memory-profile.ts",
82
+ "lint": "eslint --flag unstable_native_nodejs_ts_config ./src",
83
+ "type-check": "tsc",
84
+ "test": "vitest run",
85
+ "test:coverage": "vitest run --coverage",
86
+ "test:watch": "vitest"
87
+ }
88
+ }
package/dist/cli.d.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/dist/hooks.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import type { ResolveHookSync, LoadHookSync } from 'node:module';
2
- export declare const loaderLifecycle: {
3
- [Symbol.dispose](): void;
4
- [Symbol.asyncDispose](): Promise<void>;
5
- };
6
- export declare const resolve: ResolveHookSync;
7
- export declare const load: LoadHookSync;
8
- export declare function disposeLoader(): Promise<void>;
package/dist/hooks.js DELETED
@@ -1,217 +0,0 @@
1
- import process from 'node:process';
2
- import { homedir } from 'node:os';
3
- import { createHash } from 'node:crypto';
4
- import { fileURLToPath, pathToFileURL } from 'node:url';
5
- import { dirname, resolve as resolvePath } from 'node:path';
6
- import { mkdirSync, readFileSync, statSync } from 'node:fs';
7
- import { rename, rm, writeFile } from 'node:fs/promises';
8
- import { transpileModule, ScriptTarget, ModuleKind, version as typescriptVersion } from 'typescript';
9
- const cacheDir = resolvePath(homedir(), '.cache', 'tsnode', typescriptVersion);
10
- mkdirSync(cacheDir, { recursive: true });
11
- const transpileTarget = ScriptTarget.ES2022;
12
- const loaderCacheVersion = 'target-es2022';
13
- const cachedEntries = new Set();
14
- const cacheVersion = `${process.versions.node}-${typescriptVersion}-${loaderCacheVersion}`;
15
- const resolveCache = new Map();
16
- const statCache = new Map();
17
- const pathHashCache = new Map();
18
- const projectRootCache = new Map();
19
- const pendingCacheWrites = new Map();
20
- let cacheWriteSequence = 0;
21
- function clearLoaderCaches() {
22
- cachedEntries.clear();
23
- resolveCache.clear();
24
- statCache.clear();
25
- pathHashCache.clear();
26
- projectRootCache.clear();
27
- }
28
- async function flushPendingCacheWrites() {
29
- const writes = [...pendingCacheWrites.values()];
30
- if (writes.length === 0) {
31
- return;
32
- }
33
- await Promise.allSettled(writes);
34
- }
35
- export const loaderLifecycle = {
36
- [Symbol.dispose]() {
37
- clearLoaderCaches();
38
- },
39
- async [Symbol.asyncDispose]() {
40
- await flushPendingCacheWrites();
41
- clearLoaderCaches();
42
- }
43
- };
44
- function hashPath(path) {
45
- const cached = pathHashCache.get(path);
46
- if (cached !== undefined) {
47
- return cached;
48
- }
49
- const hash = createHash('sha256').update(path).digest('hex').slice(0, 16);
50
- pathHashCache.set(path, hash);
51
- return hash;
52
- }
53
- function getStat(path) {
54
- const cached = statCache.get(path);
55
- if (cached !== undefined) {
56
- return cached;
57
- }
58
- const stat = statSync(path, { throwIfNoEntry: false });
59
- if (stat === undefined || !stat.isFile()) {
60
- return undefined;
61
- }
62
- const info = { mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, ino: stat.ino, size: stat.size };
63
- statCache.set(path, info);
64
- return info;
65
- }
66
- function fileExists(path) {
67
- return getStat(path) !== undefined;
68
- }
69
- function scheduleCacheWrite(cacheFileName, cachePath, source) {
70
- if (cachedEntries.has(cacheFileName) || pendingCacheWrites.has(cacheFileName)) {
71
- return;
72
- }
73
- const temporaryCachePath = cachePath + '.' + process.pid + '.' + cacheWriteSequence++ + '.tmp';
74
- const writePromise = writeFile(temporaryCachePath, source)
75
- .then(() => rename(temporaryCachePath, cachePath))
76
- .then(() => {
77
- cachedEntries.add(cacheFileName);
78
- })
79
- .catch(error => {
80
- rm(temporaryCachePath, { force: true }).catch(() => undefined);
81
- process.stderr.write('[tsnode] cache write failed: ' + String(error) + '\n');
82
- })
83
- .finally(() => {
84
- pendingCacheWrites.delete(cacheFileName);
85
- });
86
- pendingCacheWrites.set(cacheFileName, writePromise);
87
- }
88
- function directoryExists(path) {
89
- const stat = statSync(path, { throwIfNoEntry: false });
90
- return stat !== undefined && stat.isDirectory();
91
- }
92
- function readCachedSource(cacheFileName, cachePath) {
93
- try {
94
- const source = readFileSync(cachePath, 'utf8');
95
- cachedEntries.add(cacheFileName);
96
- return source;
97
- }
98
- catch (error) {
99
- const code = typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : undefined;
100
- cachedEntries.delete(cacheFileName);
101
- if (code !== 'ENOENT') {
102
- process.stderr.write('[tsnode] cache read failed: ' + String(error) + '\n');
103
- }
104
- return undefined;
105
- }
106
- }
107
- function findProjectRoot(startDirectory) {
108
- const cached = projectRootCache.get(startDirectory);
109
- if (cached !== undefined) {
110
- return cached;
111
- }
112
- let currentDirectory = startDirectory;
113
- for (;;) {
114
- if (fileExists(resolvePath(currentDirectory, 'tsconfig.json')) || fileExists(resolvePath(currentDirectory, 'package.json'))) {
115
- projectRootCache.set(startDirectory, currentDirectory);
116
- return currentDirectory;
117
- }
118
- const parentDirectory = dirname(currentDirectory);
119
- if (parentDirectory === currentDirectory) {
120
- const fallbackDirectory = process.cwd();
121
- projectRootCache.set(startDirectory, fallbackDirectory);
122
- return fallbackDirectory;
123
- }
124
- currentDirectory = parentDirectory;
125
- }
126
- }
127
- function resolveSrcRoot(parentURL) {
128
- if (parentURL !== undefined && parentURL.startsWith('file:')) {
129
- const parentDirectory = dirname(fileURLToPath(parentURL));
130
- const projectRoot = findProjectRoot(parentDirectory);
131
- const candidateSrcRoot = resolvePath(projectRoot, 'src');
132
- if (directoryExists(candidateSrcRoot)) {
133
- return candidateSrcRoot;
134
- }
135
- }
136
- return resolvePath(process.cwd(), 'src');
137
- }
138
- function resolveTsPath(absPath) {
139
- if (absPath.endsWith('.ts') && fileExists(absPath)) {
140
- return absPath;
141
- }
142
- if (absPath.endsWith('.js')) {
143
- const tsPath = absPath.slice(0, -3) + '.ts';
144
- if (fileExists(tsPath)) {
145
- return tsPath;
146
- }
147
- }
148
- const withTs = absPath + '.ts';
149
- if (fileExists(withTs)) {
150
- return withTs;
151
- }
152
- const indexTs = absPath + '/index.ts';
153
- return fileExists(indexTs) ? indexTs : null;
154
- }
155
- export const resolve = function (specifier, context, nextResolve) {
156
- const firstChar = specifier.charCodeAt(0);
157
- const isRelative = firstChar === 46 /* . */;
158
- const isSrcAlias = firstChar === 115 /* s */ && specifier.startsWith('src/');
159
- if (!isRelative && !isSrcAlias) {
160
- return nextResolve(specifier, context);
161
- }
162
- const cacheKey = context.parentURL !== undefined ? specifier + '\0' + context.parentURL : specifier;
163
- const cached = resolveCache.get(cacheKey);
164
- if (cached !== undefined) {
165
- return cached;
166
- }
167
- let absPath = null;
168
- if (isSrcAlias) {
169
- absPath = resolvePath(resolveSrcRoot(context.parentURL), specifier.slice(4));
170
- }
171
- else if (context.parentURL !== undefined && context.parentURL.startsWith('file:')) {
172
- absPath = resolvePath(dirname(fileURLToPath(context.parentURL)), specifier);
173
- }
174
- if (absPath !== null) {
175
- const tsPath = resolveTsPath(absPath);
176
- if (tsPath !== null) {
177
- const result = { url: pathToFileURL(tsPath).href, format: 'module', shortCircuit: true };
178
- resolveCache.set(cacheKey, result);
179
- return result;
180
- }
181
- }
182
- return nextResolve(specifier, context);
183
- };
184
- export const load = function (url, context, nextLoad) {
185
- if (!url.startsWith('file:') || !url.endsWith('.ts')) {
186
- return nextLoad(url, context);
187
- }
188
- const path = fileURLToPath(url);
189
- const info = getStat(path);
190
- if (info === undefined) {
191
- return nextLoad(url, context);
192
- }
193
- const cacheFileName = hashPath(path) + '-' + info.mtimeMs + '-' + info.ctimeMs + '-' + info.ino + '-' + info.size + '-' + cacheVersion + '.js';
194
- const cachePath = resolvePath(cacheDir, cacheFileName);
195
- let source = readCachedSource(cacheFileName, cachePath);
196
- if (source === undefined) {
197
- const sourceCode = readFileSync(path, 'utf8');
198
- const result = transpileModule(sourceCode, {
199
- compilerOptions: {
200
- // Downlevel stage 3 decorators because current Node still can't execute
201
- // the syntax directly even though TypeScript can parse and type-check it.
202
- target: transpileTarget,
203
- module: ModuleKind.ESNext,
204
- jsx: undefined,
205
- declaration: false,
206
- sourceMap: false
207
- },
208
- reportDiagnostics: true
209
- });
210
- source = result.outputText;
211
- scheduleCacheWrite(cacheFileName, cachePath, source);
212
- }
213
- return { format: 'module', source, shortCircuit: true };
214
- };
215
- export async function disposeLoader() {
216
- await loaderLifecycle[Symbol.asyncDispose]();
217
- }