import { readFileSync, writeFileSync, readdirSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { dirname, join, relative } from 'node:path' import ts2json from './ts2json.mjs' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) const buildDir = join(__dirname, '..', 'build') const files = (await readdirSync(buildDir, { recursive: true })) .filter(file => file.endsWith('.js')) .map(file => join(buildDir, file)) for (const file of files) { reflectType5(file, { debug: true }) } function reflectType5(srcFile, options = { debug: false }) { log(`=========Reflecting file "${relative(__dirname, srcFile)}"`) const defFile = srcFile.replace(/.js$/, '.d.ts') const src = String(readFileSync(srcFile)) const defs = String(readFileSync(defFile)) const parsedDefs = ts2json(defFile) console.log('Defs from', defFile, 'are', parsedDefs) const typeDefMatches = defs.matchAll(/: ({(?:(?!\n}).)+\n}) & (?:(?!ReflectedTypeInfo).)+ReflectedTypeInfo/gs) if (!typeDefMatches) { log('No ReflectedTypeInfo found.') return } const typeDefs = Array.from(typeDefMatches).map(def => def[1]) log(` ${typeDefs.length} ReflectedTypeInfo found`) let index = 0 let srcReflected = src.replaceAll(/(\s*)\.ship\(\)/g, () => { const def = typeDefs[index] index++ return `.ship({ reflectedType5: \`${def}\` })` }) log(` ReflectedTypeInfo injected in ${index} occurrences of .ship()`) if (index !== typeDefs.length) { log(' WARNING: not all ReflectedTypeInfo occurrences could be injected') } for (const id in parsedDefs) { if (id.includes('interface')) continue srcReflected += `\n${id}._reflectedType6 = ${JSON.stringify(parsedDefs[id])}\n` } writeFileSync(srcFile, srcReflected) function log(...args) { if (options.debug) { console.log(...args) } } }