import { walk } from 'estree-walker' import recast from 'recast' //my thoughts on this code are: na na na nani the fuck export default function preprocess(opts) { return { name: "preprocess", transform: { order: 'pre', handler(code) { const state = { failedIf: false } const parse = this.parse const comments = [] const ast = recast.parse(code, { parser: this }) walk(ast, { //WALK CST FOR COMPTIME_VARS enter(node, parent, prop, index) { if (parent?.type === "MemberExpression" && parent?.property === node) { if (state.failedIf) { delete parent[prop] } return //ignore childs of objects ie console.log } else if (node.type === "Identifier") { if (opts.values) { for (const i in opts.values) { if (i === node.name) { console.log(`Found comp-time var ${i} with value ${opts.values[i]}`) const res = eval(`(${opts.values[i]})`) if (typeof res === "string") { parent[prop] = [ parse(`('${res}')`).body[0].expression ] } else { parent[prop] = [ parse(`(${res})`).body[0].expression ] } return } } } } else if (node.comments) { node.comments.forEach((cmt, cidx) => { for (const i in opts.transforms) { if (cmt.value.startsWith(i)) { console.log(`Found comp-time comment transformation ${i}`) opts.transforms[i](cmt, node, cidx) return } } if (cmt.value.toUpperCase().startsWith("#IF ")) { const vari = cmt.value.substring(4) node.comments = [] if (opts.values[vari] === undefined) { throw new Error("Cannot use undefined comp-time variable in #IF macro!") } else { const res = eval(`(${opts.values[vari]})`) if (!!res) { console.log("Broke into #IF macro") } else { console.log(`Unmet #IF for ${vari}`) state.failedIf = true } } } else if (cmt.value.toUpperCase().startsWith("#IFNOT ")) { const vari = cmt.value.substring(7) node.comments = [] if (opts.values[vari] === undefined) { throw new Error("Cannot use undefined comp-time variable in #IFNOT macro!") } else { const res = eval(`(${opts.values[vari]})`) if (!res) { console.log("Broke into #IFNOT macro") } else { console.log(`Unmet #IFNOT for ${vari} at Line ${cmt.loc.start.line}:${cmt.loc.start.column}`) state.failedIf = true } } } else if (cmt.value.toUpperCase().startsWith("#END")) { console.log("Broke out of macro") node.comments = [] state.failedIf = false } }) } else { if (state.failedIf) { delete parent[prop] } } } }) return { code: recast.print(ast).code } } } } }