@@ -6,7 +6,6 @@ let fs = require('fs');
66let util = require ( 'util' ) ;
77let writeFile = util . promisify ( fs . writeFile ) ;
88let ts = require ( 'typescript' ) ;
9- let moduleDefinition = require ( 'module-definition' ) ;
109let getTSDefinition = require ( '../src/getTSDefinition' ) ;
1110const _axios = require ( 'axios' ) ;
1211const axios = _axios . default ? _axios . default . create ( ) : _axios . create ( ) ;
@@ -72,12 +71,47 @@ async function runSingle(schemaTs) {
7271async function writeIndexJs ( schemaJsPath ) {
7372 const schema = path . basename ( schemaJsPath ) ;
7473 const indexJs = path . join ( path . dirname ( schemaJsPath ) , '/index' + path . extname ( schemaJsPath ) ) ;
75- if ( moduleDefinition . sync ( schemaJsPath ) === 'commonjs' )
74+ if ( detectModuleFormat ( schemaJsPath ) === 'commonjs' )
7675 await writeFile ( indexJs , `module.exports = require('./${ schema } ');` ) ;
7776 else
7877 await writeFile ( indexJs , `export {default} from './${ schema } ';` ) ;
7978}
8079
80+ function detectModuleFormat ( filePath ) {
81+ const extension = path . extname ( filePath ) ;
82+ if ( extension === '.mjs' )
83+ return 'module' ;
84+ if ( extension === '.cjs' )
85+ return 'commonjs' ;
86+
87+ const pkg = findClosestPackageJson ( path . dirname ( filePath ) ) ;
88+ if ( pkg && pkg . type === 'module' )
89+ return 'module' ;
90+
91+ return 'commonjs' ;
92+ }
93+
94+ function findClosestPackageJson ( startDir ) {
95+ let currentDir = startDir ;
96+ while ( currentDir ) {
97+ const packageJsonPath = path . join ( currentDir , 'package.json' ) ;
98+ if ( fs . existsSync ( packageJsonPath ) ) {
99+ try {
100+ return JSON . parse ( fs . readFileSync ( packageJsonPath , 'utf8' ) ) ;
101+ }
102+ catch ( e ) {
103+ return null ;
104+ }
105+ }
106+
107+ const parentDir = path . dirname ( currentDir ) ;
108+ if ( parentDir === currentDir )
109+ return null ;
110+ currentDir = parentDir ;
111+ }
112+ return null ;
113+ }
114+
81115async function findSchemaJs ( cwd ) {
82116 let ignoredDirNames = {
83117 node_modules : true ,
0 commit comments