UNPKG

tsx

Version:

TypeScript Execute (tsx): Node.js enhanced with esbuild to run TypeScript & ESM files

3 lines (2 loc) 17.5 kB
var _e=Object.defineProperty;var i=(e,s)=>_e(e,"name",{value:s,configurable:!0});import T from"node:module";import{MessageChannel as $e}from"node:worker_threads";import{i as E,b as be,e as z,m as Je}from"./node-features-JeyyvQz6.mjs";import{l as se,t as re,g as Oe,a as Ne,d as O,b as d,e as D,f as S,h as L,j as V,k as Ae,m as h,n as Me,w as oe,o as ne,p as N,q as ae,s as I,u as Be}from"./register-HWZIKnmC.mjs";import{pathToFileURL as g,fileURLToPath as F}from"node:url";import{readFileSync as qe,existsSync as Qe}from"node:fs";import{readFile as He}from"node:fs/promises";import{p as Ge,i as ce,t as ie,a as A,b as me,c as Xe,r as ze}from"./index-CQhDiIsg.mjs";import{p as le}from"./client-D_mPDF5S.mjs";import R from"node:path";const De=i(()=>({active:!0,parsedTsconfig:void 0}),"createDefaultData"),de=i(e=>{const s={active:!0,namespace:e?.namespace,onImport:e?.onImport,parsedTsconfig:void 0,port:e?.port,tsconfig:e?.tsconfig};return e?.tsconfig!==!1&&(s.parsedTsconfig=se(e?.tsconfig??process.env.TSX_TSCONFIG_PATH)),s},"createData"),Ve=i(e=>async s=>{if(!s)throw new Error(`tsx must be loaded with --import instead of --loader The --loader flag was deprecated in Node v20.6.0 and v18.19.0`);Object.assign(e,de(s)),s.port&&s.port.on("message",t=>{t==="deactivate"&&(e.active=!1,s.port.postMessage({type:"deactivated"}))})},"createInitialize"),Ke=i(e=>()=>(e.parsedTsconfig=se(process.env.TSX_TSCONFIG_PATH),"process.setSourceMapsEnabled(true);"),"createGlobalPreload"),Ye=i(e=>{const{pathname:s}=new URL(e),t=R.extname(s);if(t===".mts"||t===".mjs")return"module";if(t===".cts"||t===".cjs")return"commonjs";if(t===".js"||re.includes(t))return Oe(e)},"getFormatFromFileUrl"),Ze=i(e=>{const{pathname:s}=new URL(e),t=R.extname(s);if(t===".mts"||t===".mjs")return"module";if(t===".cts"||t===".cjs")return"commonjs";if(t===".js"||re.includes(t))return Ne(e)},"getFormatFromFileUrlSync"),U="tsx-namespace=",M="tsx-commonjs-export-preparse",ue=`${M}=1`,C="tsx-commonjs-virtual-query",W=new Map,K=i((e,s)=>e.slice(1).split("&").filter(t=>t&&s.every(r=>!t.startsWith(r))).join("&"),"getQueryWithoutParameters"),B=i((e,s)=>{const t=K(e,s);return t?`?${t}`:""},"getSearchWithoutParameters"),ke=i(e=>e.replaceAll(/\/\*[\s\S]*?\*\/|\/\/[^\n\r]*/g,""),"stripComments"),xe=i(e=>{const s=ke(e);if(/^\s*export\s*\*/.test(s))return"named";if(/^\s*import\s*\*\s*as\s+[\w$]+/.test(s))return"namespace";const t=s.match(/\{([^}]*)\}/)?.[1];if(t)return t.split(",").some(r=>{const o=r.trim().split(/\s+as\s+/)[0];return!!(o&&o!=="default")})?"named":void 0},"getCommonJsImportBinding"),et=i((e,s,t)=>{const r=W.get(e);if(!r)return!1;try{const[o]=Ge(r);return o.some(a=>{if(a.d!==-1||a.n!==s)return!1;const m=xe(r.slice(a.ss,a.s));return m==="named"||t&&m==="namespace"})}catch{return!1}},"parentImportsCommonJsExports"),v=i(e=>{const s=e.indexOf(U);if(s===-1)return;const t=e[s-1];if(t!=="?"&&t!=="&")return;const r=s+U.length,o=e.indexOf("&",r);return o===-1?e.slice(r):e.slice(r,o)},"getNamespace"),fe=E(be)?"importAttributes":"importAssertions",pe=i(e=>e==="commonjs"||e==="commonjs-typescript","isCommonJsFormat"),he=i(e=>e==="module-typescript"||e==="typescript","isModuleTypeScriptFormat"),tt=E(z),st=[`${C}=`],q=[`${M}=`,`${C}=`],w=i((e,s)=>s.parsedTsconfig&&Ae(s.parsedTsconfig,e)?s.parsedTsconfig.config:void 0,"getTsconfigRaw"),rt=i(e=>{if(!e.searchParams.has(C))return;const{pathname:s}=e,t=s.toLowerCase().lastIndexOf("%3f");if(t===-1)return;const r=new URL(e);return r.pathname=s.slice(0,t),r.search="",F(r)},"getFilePathFromVirtualQuery"),Y=i(e=>{const s=e.startsWith(h)?new URL(e):void 0,t=s?F(s):e,r=s&&rt(s),o=r||t,a=s&&r?g(o).toString()+B(s.search,st):e;return{fileUrl:s,filePath:o,loadUrl:a}},"getFileLoadContext"),ge=i((e,s)=>{if(!s?.search)return e;const t=B(s.search,q);return t?g(e).toString()+t:e},"getTransformPath"),ye=i((e,s,t)=>{const r=[...s?K(s.search,[U,...q]).split("&").filter(Boolean):[],...t?[`namespace=${encodeURIComponent(t)}`]:[]].join("&");return r?`${e}?${r}`:e},"getFilePathWithQuery"),ot=new TextDecoder,Pe=i(e=>typeof e=="string"?e:ot.decode(e),"decodeSource"),nt=i((e,s)=>{const t=new URL(s),r=s.startsWith(h)?Y(s).filePath:void 0;t.searchParams.delete("tsx-namespace"),t.searchParams.delete(M),t.searchParams.delete(C),r&&(t.pathname=new URL(g(r)).pathname);const o=t.toString();return e.port&&e.port.postMessage({type:"load",url:o}),e.onImport?.(o),o},"notifyLoad"),Se=i((e,s)=>{if(!e.active)return!1;const t=v(s);if(e.namespace!==t)return!1;const r=nt(e,s);return le.send&&le.send({type:"dependency",path:r}),!0},"prepareLoad"),Re=i((e,s)=>{if(!Me.test(e))return s;const t=s[fe];return t?.type?s:{...s,[fe]:{...t,type:"json"}}},"prepareJsonAttributes"),Z=i(({conditions:e})=>e?.includes("require")===!0&&!e.includes("import"),"isCommonJsRequireContext$1"),at=i(e=>{const s=i(async(t,r,o)=>{if(!Se(e,t))return o(t,r);const a=v(t),{fileUrl:m,filePath:c,loadUrl:n}=Y(t),u=Re(n,r),l=await o(n,u);d(3,"loaded by next loader",{url:t,loadUrl:n,loaded:l});const y=m?.searchParams.has(M)===!0,P=l.format,j=m?new URL(g(c)):void 0;if(j&&m&&(j.search=B(m.search,q)),pe(P)&&m&&l.responseURL?.startsWith("file:")&&!c.endsWith(".cjs")){const f=await He(g(c),"utf8"),b=ce(f);if(P==="commonjs-typescript"||!c.endsWith(".js")||b){if(!tt){if(y&&b&&D.test(c)){const J=await ie(f,c,{define:{"import.meta.url":JSON.stringify(j.toString())},tsconfigRaw:w(c,e)});return W.set(t,J.code),{format:"module",source:S(J)}}return l}if(!a&&!y&&!c.endsWith(".cts"))return l;const ee=!!(a||y||B(m.search,q)),te=A(f,ge(c,m),{cjsBanner:ee?`require = require("node:module").createRequire(${JSON.stringify(g(c).toString())});`:void 0,tsconfigRaw:w(c,e)});if(l.format="commonjs",l.source=S(te),ee){const J=ye(c,m,a);l.responseURL=`data:text/javascript,${encodeURIComponent(te.code)}?filePath=${encodeURIComponent(J)}`}return d(3,"returning CJS export annotation",l),l}}if(!l.source)return l;const p=Pe(l.source),$=P==="json"&&!Z(r);if(P==="commonjs-typescript"){const f=A(p,c,{tsconfigRaw:w(c,e)});return{...l,format:"commonjs",source:S(f)}}if($||he(P)||L.test(t)){const f=await ie(p,c,{tsconfigRaw:w(c,e)});return W.set(t,f.code),{format:"module",source:S(f)}}if(l.format==="module"){const f=me(c,p);f?(l.source=S(f),W.set(t,f.code)):W.set(t,p)}return l},"load");return O?async(t,r,o)=>{d(2,"load",{url:t,context:r});const a=await s(t,r,o);return d(1,"loaded",{url:t,result:a}),a}:s},"createLoad"),ct=i(e=>{const s=i((t,r,o)=>{if(Z(r)&&V()||!Se(e,t))return o(t,r);const a=v(t),{fileUrl:m,filePath:c,loadUrl:n}=Y(t),u=Re(n,r),l=o(n,u);d(3,"loaded by next loader",{url:t,loadUrl:n,loaded:l});const y=l.format;if(pe(y)&&E(z)&&l.responseURL?.startsWith("file:")&&!c.endsWith(".cjs")){const p=qe(g(c),"utf8");if(y==="commonjs-typescript"||!c.endsWith(".js")||ce(p)){const $=A(p,ge(c,m),{tsconfigRaw:w(c,e)}),f=!a&&V(),b=ye(c,m,a);return l.format="commonjs",l.shouldBeReloadedByCJSLoader=f,l.source=S($),f||(l.responseURL=`data:text/javascript,${encodeURIComponent($.code)}?filePath=${encodeURIComponent(b)}`),d(3,"returning CJS export annotation",l),l}}if(!l.source)return l;const P=Pe(l.source),j=y==="json"&&!Z(r);if(y==="commonjs-typescript"){const p=A(P,c,{tsconfigRaw:w(c,e)});return{...l,format:"commonjs",shouldBeReloadedByCJSLoader:!1,source:S(p)}}if(j||he(y)||L.test(t)){const p=Xe(P,c,{tsconfigRaw:w(c,e)});return{format:"module",source:S(p)}}if(l.format==="module"){const p=me(c,P);p&&(l.source=S(p))}return l},"load");return O?(t,r,o)=>{d(2,"loadSync",{url:t,context:r});const a=s(t,r,o);return d(1,"loadedSync",{url:t,result:a}),a}:s},"createLoadSync"),it=E(z),mt=/^(?:[a-z][\d+.a-z-]*:\/\/|data:|file:|node:)/i,Ue=i(e=>!ne(e)&&!mt.test(e),"isTsconfigPathAliasSpecifier"),Q=i(e=>{if(e.url)return e.url;const s=e.message.match(/^Cannot find module '([^']+)'/);if(s){const[,r]=s;return r}const t=e.message.match(/^Cannot find package '([^']+)'/);if(t){const[,r]=t;if(!R.isAbsolute(r))return;const o=g(r);if(o.pathname.endsWith("/")&&(o.pathname+="package.json"),o.pathname.endsWith("/package.json")){const a=ze(o);if(a?.main)return new URL(a.main,o).toString()}else return o.toString()}},"getMissingPathFromNotFound"),H=i(e=>e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND","isModuleNotFound"),ve=i(e=>e.conditions.includes("require")&&!e.conditions.includes("import"),"isCommonJsRequireContext"),lt=i((e,s)=>{const[t]=e.split("?");try{if(t.startsWith(h))return F(t);if(R.isAbsolute(t))return t;if(I(t)&&s?.startsWith(h))return F(new URL(t,s))}catch{}},"getProbeFilePath"),we=i((e,s)=>{const t=lt(e,s);return t!==void 0&&!Qe(t)},"candidateDoesntExist"),G=i(async(e,s,t,r)=>{const o=ae(e);if(d(3,"resolveExtensions",{url:e,context:s,throwError:r,tryPaths:o}),!o)return;let a;for(const m of o)if(!we(m,s.parentURL))try{return await t(m,s)}catch(c){const{code:n}=c;if(!H(n)&&n!=="ERR_PACKAGE_PATH_NOT_EXPORTED")throw c;a=c}if(r){if(a===void 0)return t(o[0],s);throw a}},"resolveExtensions"),_=i((e,s,t,r)=>{const o=ae(e);if(d(3,"resolveExtensionsSync",{url:e,context:s,throwError:r,tryPaths:o}),!o)return;let a;for(const m of o)if(!we(m,s.parentURL))try{return t(m,s)}catch(c){const{code:n}=c;if(!H(n)&&n!=="ERR_PACKAGE_PATH_NOT_EXPORTED")throw c;a=c}if(r){if(a===void 0)return t(o[0],s);throw a}},"resolveExtensionsSync"),dt=i(async(e,s,t,r)=>{const o=r.parsedTsconfig?.config.compilerOptions?.allowJs??!1;if(d(3,"resolveBase",{specifier:e,context:s,specifierStartsWithFileUrl:e.startsWith(h),isRelativePath:I(e),tsExtensionsPattern:L.test(s.parentURL),allowJs:o}),(e.startsWith(h)||I(e))&&(L.test(s.parentURL)||o)){const a=await G(e,s,t);if(d(3,"resolveBase resolved",{specifier:e,context:s,resolved:a}),a)return a}try{return await t(e,s)}catch(a){if(d(3,"resolveBase error",{specifier:e,context:s,error:a}),a instanceof Error){const m=a;if(H(m.code)){const c=Q(m);if(c){const n=await G(c,s,t);if(n)return n}}}throw a}},"resolveBase"),k=i((e,s,t,r)=>{const o=r.parsedTsconfig?.config.compilerOptions?.allowJs??!1;if(d(3,"resolveBaseSync",{specifier:e,context:s,specifierStartsWithFileUrl:e.startsWith(h),isRelativePath:I(e),tsExtensionsPattern:L.test(s.parentURL),allowJs:o}),(e.startsWith(h)||I(e))&&(L.test(s.parentURL)||o)){const a=_(e,s,t);if(d(3,"resolveBaseSync resolved",{specifier:e,context:s,resolved:a}),a)return a}try{return t(e,s)}catch(a){if(d(3,"resolveBaseSync error",{specifier:e,context:s,error:a}),a instanceof Error){const m=a;if(H(m.code)){const c=Q(m);if(c){const n=_(c,s,t);if(n)return n}}}throw a}},"resolveBaseSync"),Te=i(async(e,s,t,r)=>{if(d(3,"resolveDirectory",{specifier:e,context:s,isDirectory:N.test(e)}),(e==="."||e===".."||e.endsWith("/.."))&&(e+="/"),N.test(e)){const o=new URL(e,s.parentURL);return o.pathname=R.join(o.pathname,"index"),await G(o.toString(),s,t,!0)}try{return await dt(e,s,t,r)}catch(o){if(o instanceof Error){d(3,"resolveDirectory error",{specifier:e,context:s,error:o});const a=o;if(a.code==="ERR_UNSUPPORTED_DIR_IMPORT"){const m=Q(a);if(m)try{return await G(`${m}/index`,s,t,!0)}catch(c){const n=c,{message:u}=n;throw n.message=n.message.replace(`${"/index".replace("/",R.sep)}'`,"'"),n.stack=n.stack.replace(u,n.message),n}}}throw o}},"resolveDirectory"),Le=i((e,s,t,r)=>{if(d(3,"resolveDirectorySync",{specifier:e,context:s,isDirectory:N.test(e)}),(e==="."||e===".."||e.endsWith("/.."))&&(e+="/"),N.test(e)){const o=ve(s);if(o&&!ne(e))return k(e,s,t,r);const a=new URL(e,s.parentURL);return a.pathname=R.join(a.pathname,"index"),o?_(F(a),s,t,!1)??k(e,s,t,r):_(a.toString(),s,t,!0)}try{return k(e,s,t,r)}catch(o){if(o instanceof Error){d(3,"resolveDirectorySync error",{specifier:e,context:s,error:o});const a=o;if(a.code==="ERR_UNSUPPORTED_DIR_IMPORT"){const m=Q(a);if(m)try{return _(`${m}/index`,s,t,!0)}catch(c){const n=c,{message:u}=n;throw n.message=n.message.replace(`${"/index".replace("/",R.sep)}'`,"'"),n.stack=n.stack.replace(u,n.message),n}}}throw o}},"resolveDirectorySync"),ut=i(async(e,s,t,r)=>{const o=Ue(e);if(d(3,"resolveTsPaths",{specifier:e,context:s,tsconfigPathAliasSpecifier:o,tsconfig:r.parsedTsconfig,fromNodeModules:s.parentURL?.includes("/node_modules/")}),o&&r.parsedTsconfig&&!s.parentURL?.includes("/node_modules/")){const a=oe(r.parsedTsconfig,e);d(3,"resolveTsPaths",{possiblePaths:a});for(const m of a)try{return await Te(g(m).toString(),s,t,r)}catch{}}return Te(e,s,t,r)},"resolveTsPaths"),ft=i((e,s,t,r)=>{const o=Ue(e);if(d(3,"resolveTsPathsSync",{specifier:e,context:s,tsconfigPathAliasSpecifier:o,tsconfig:r.parsedTsconfig,fromNodeModules:s.parentURL?.includes("/node_modules/")}),o&&r.parsedTsconfig&&!s.parentURL?.includes("/node_modules/")){const a=oe(r.parsedTsconfig,e);d(3,"resolveTsPathsSync",{possiblePaths:a});for(const m of a)try{return Le(g(m).toString(),s,t,r)}catch{}}return Le(e,s,t,r)},"resolveTsPathsSync"),X="tsx://",x=i((e,s)=>`${e}${e.includes("?")?"&":"?"}${s}`,"addQuery"),je=i((e,s,t)=>{if(s!=="commonjs"||!e.startsWith(h)||!D.test(e))return e;const r=new URL(e),o=[K(r.search,[U]),...t?[`namespace=${encodeURIComponent(t)}`]:[]].filter(Boolean).join("&");return o?(r.pathname+=`%3F${o}`,r.searchParams.set(C,"1"),r.toString()):e},"preserveCommonJsQueryIdentity"),pt=i(e=>{const s=i(async(t,r,o)=>{if(!e.active||t.startsWith("node:"))return o(t,r);let a=v(t)??(r.parentURL&&v(r.parentURL));if(e.namespace){let l;if(t.startsWith(X)){try{l=JSON.parse(t.slice(X.length))}catch{}l?.namespace&&(a=l.namespace)}if(e.namespace!==a)return o(t,r);l&&(t=l.specifier,r.parentURL=l.parentURL)}const[m,c]=t.split("?"),n=await ut(m,r,o,e);if(d(2,"nextResolve",{resolved:n}),n.format==="builtin")return n;n.url.startsWith(h)&&(n.format==="module-typescript"?n.format="module":n.format==="commonjs-typescript"?n.format="commonjs":n.format||(n.format=await Ye(n.url),d(2,"getFormatFromFileUrl",{resolved:n,format:n.format}))),c&&(n.url+=`?${c}`);const u=r.parentURL&&n.format==="commonjs"&&D.test(n.url)&&(r.parentURL.includes(ue)||et(r.parentURL,t,it));return a&&!n.url.includes(U)&&(n.url=x(n.url,`${U}${a}`)),u&&(n.url=x(n.url,ue)),(a||u)&&(n.url=je(n.url,n.format,a)),n},"resolve");return O?async(t,r,o)=>{d(2,"resolve",{specifier:t,context:r});const a=await s(t,r,o);return d(1,"resolved",{specifier:t,context:r,result:a}),a}:s},"createResolve"),ht=i(e=>{const s=i((t,r,o)=>{if(!e.active||t.startsWith("node:")||ve(r)&&V())return o(t,r);let a=v(t)??(r.parentURL&&v(r.parentURL));if(e.namespace){let u;if(t.startsWith(X)){try{u=JSON.parse(t.slice(X.length))}catch{}u?.namespace&&(a=u.namespace)}if(e.namespace!==a)return o(t,r);u&&(t=u.specifier,r.parentURL=u.parentURL)}const[m,c]=t.split("?"),n=ft(m,r,o,e);return d(2,"nextResolve",{resolved:n}),n.format==="builtin"||(n.url.startsWith(h)&&(n.format==="module-typescript"?n.format="module":n.format==="commonjs-typescript"?n.format="commonjs":n.format||(n.format=Ze(n.url),d(2,"getFormatFromFileUrlSync",{resolved:n,format:n.format}))),c&&(n.url+=`?${c}`),a&&!n.url.includes(U)&&(n.url=x(n.url,`${U}${a}`)),n.url=je(n.url,n.format,a)),n},"resolve");return O?(t,r,o)=>{d(2,"resolveSync",{specifier:t,context:r});const a=s(t,r,o);return d(1,"resolvedSync",{specifier:t,context:r,result:a}),a}:s},"createResolveSync"),Ee=i(e=>(s,t)=>{if(!t)throw new Error("The current file path (import.meta.url) must be provided in the second argument of tsImport()");const r=t.startsWith(h)?t:g(t).toString();return import(`tsx://${JSON.stringify({specifier:s,parentURL:r,namespace:e})}`)},"createScopedImport");let Ie=!1;const gt=i(e=>{const s=[];for(let t=0;t<e.length;t+=1){const r=e[t];if(r==="--import"){const o=e[t+1];o&&s.push(o),t+=1}else r.startsWith("--import=")&&s.push(r.slice(9))}return s},"collectImportSpecifiers"),yt=i(()=>[...(process.env.NODE_OPTIONS??"").matchAll(/(?:^|\s)--import(?:=|\s+)(\S+)/g)].map(([,e])=>e),"collectNodeOptionsImportSpecifiers"),Fe=[new URL("loader.mjs",import.meta.url).toString(),new URL("esm/index.mjs",import.meta.url).toString()],Pt=new Set(["tsx","tsx/esm",...Fe,...Fe.map(e=>decodeURI(new URL(e).pathname))]),St=i(e=>Pt.has(e),"isTsxImport"),Ce=i(e=>/\.(?:[cm]?ts|tsx)(?:[?#].*)?$/.test(e),"isTypeScriptImport"),Rt=i(()=>{const e=gt(process.execArgv),s=e.findIndex(St);return s>0&&e.slice(0,s).some(Ce)},"hasCliTypeScriptPreload"),Ut=yt().some(Ce)||Rt(),We=typeof T.registerHooks=="function"&&E(Je)&&!Ut,vt=i(e=>{if(!T.register&&!We)throw new Error(`This version of Node.js (${process.version}) does not support module.register(). Please upgrade to Node v18.19 or v20.6 and above.`);if(!Ie){const{_resolveFilename:c}=T;T._resolveFilename=(n,...u)=>c(Be(n),...u),Ie=!0}const{sourceMapsEnabled:s}=process;if(process.setSourceMapsEnabled(!0),We){const c=de({namespace:e?.namespace,onImport:e?.onImport,tsconfig:e?.tsconfig}),n=T.registerHooks({load:ct(c),resolve:ht(c)}),u=i(async()=>{c.active=!1,n.deregister(),s===!1&&process.setSourceMapsEnabled(!1)},"unregister2");return e?.namespace&&(u.import=Ee(e.namespace),u.unregister=u),u}const{port1:t,port2:r}=new $e;T.register(`./esm/index.mjs?${Date.now()}`,{parentURL:import.meta.url,data:{port:r,namespace:e?.namespace,tsconfig:e?.tsconfig},transferList:[r]});const o=e?.onImport,a=o&&(c=>{c.type==="load"&&o(c.url)});a&&(t.on("message",a),t.unref());const m=i(()=>(s===!1&&process.setSourceMapsEnabled(!1),a&&t.off("message",a),t.postMessage("deactivate"),new Promise(c=>{const n=i(u=>{u.type==="deactivated"&&(c(),t.off("message",n))},"onDeactivated");t.on("message",n)})),"unregister");return e?.namespace&&(m.import=Ee(e.namespace),m.unregister=m),m},"register");export{Ke as a,at as b,Ve as c,pt as d,De as e,vt as r};