Glen Whitney
df339df94d
Co-authored-by: Jos de Jong <wjosdejong@gmail.com> Reviewed-on: #4 Co-authored-by: Glen Whitney <glen@studioinfinity.org> Co-committed-by: Glen Whitney <glen@studioinfinity.org>
63 lines
1.9 KiB
JavaScript
63 lines
1.9 KiB
JavaScript
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)
|
|
|
|
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
|
|
if (parsedDefs[id] === undefined) continue
|
|
log(` Tagging ${id} with type data`, parsedDefs[id])
|
|
srcReflected +=
|
|
`\n${id}._reflectedType5 = ${JSON.stringify(parsedDefs[id])}\n`
|
|
}
|
|
writeFileSync(srcFile, srcReflected)
|
|
|
|
function log(...args) {
|
|
if (options.debug) {
|
|
console.log(...args)
|
|
}
|
|
}
|
|
}
|