@@ -10,7 +10,6 @@ import { parent } from '../../utils/ipc/client.js';
10
10
import type { Message } from '../types.js' ;
11
11
import { fileMatcher } from '../../utils/tsconfig.js' ;
12
12
import { isJsonPattern , tsExtensionsPattern } from '../../utils/path-utils.js' ;
13
- import { parseEsm } from '../../utils/es-module-lexer.js' ;
14
13
import { getNamespace } from './utils.js' ;
15
14
import { data } from './initialize.js' ;
16
15
@@ -69,20 +68,35 @@ export const load: LoadHook = async (
69
68
loaded . format === 'commonjs'
70
69
&& isFeatureSupported ( esmLoadReadFile )
71
70
&& loaded . responseURL ?. startsWith ( 'file:' ) // Could be data:
71
+ && ! filePath . endsWith ( '.cjs' ) // CJS syntax doesn't need to be transformed for interop
72
72
) {
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' ,
85
88
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 ( ) } ` ;
86
100
return loaded ;
87
101
}
88
102
0 commit comments