@@ -10,7 +10,6 @@ import { parent } from '../../utils/ipc/client.js';
1010import type { Message } from '../types.js' ;
1111import { fileMatcher } from '../../utils/tsconfig.js' ;
1212import { isJsonPattern , tsExtensionsPattern } from '../../utils/path-utils.js' ;
13- import { parseEsm } from '../../utils/es-module-lexer.js' ;
1413import { getNamespace } from './utils.js' ;
1514import { data } from './initialize.js' ;
1615
@@ -69,20 +68,35 @@ export const load: LoadHook = async (
6968 loaded . format === 'commonjs'
7069 && isFeatureSupported ( esmLoadReadFile )
7170 && loaded . responseURL ?. startsWith ( 'file:' ) // Could be data:
71+ && ! filePath . endsWith ( '.cjs' ) // CJS syntax doesn't need to be transformed for interop
7272 ) {
73- const code = await readFile ( new URL ( url ) , 'utf8' ) ;
74- const [ , exports ] = parseEsm ( code ) ;
75- if ( exports . length > 0 ) {
76- const cjsExports = `module.exports={${
77- exports . map ( exported => exported . n ) . filter ( name => name !== 'default' ) . join ( ',' )
78- } }`;
79- const parameters = new URLSearchParams ( { filePath } ) ;
80- if ( urlNamespace ) {
81- parameters . set ( 'namespace' , urlNamespace ) ;
82- }
83- loaded . responseURL = `data:text/javascript,${ encodeURIComponent ( cjsExports ) } ?${ parameters . toString ( ) } ` ;
84- }
73+ /**
74+ * es or cjs module lexer unfortunately cannot be used because it doesn't support
75+ * typescript syntax
76+ *
77+ * While the full code is transformed, only the exports are used for parsing.
78+ * In fact, the code can't even run because imports cannot be resolved relative
79+ * from the data: URL.
80+ *
81+ * TODO: extract exports only
82+ */
83+ const transformed = await transform (
84+ await readFile ( new URL ( url ) , 'utf8' ) ,
85+ filePath ,
86+ {
87+ format : 'cjs' ,
8588
89+ // CJS Annotations for Node
90+ platform : 'node' ,
91+ // TODO: disable source maps
92+ } ,
93+ ) ;
94+
95+ const parameters = new URLSearchParams ( { filePath } ) ;
96+ if ( urlNamespace ) {
97+ parameters . set ( 'namespace' , urlNamespace ) ;
98+ }
99+ loaded . responseURL = `data:text/javascript,${ encodeURIComponent ( transformed . code ) } ?${ parameters . toString ( ) } ` ;
86100 return loaded ;
87101 }
88102
0 commit comments