Files
tdir/parser.ts
Gregor Lohaus e900729c8f
All checks were successful
Publish npm package / publish (push) Successful in 24s
better errors, and/or support
2026-05-24 16:14:08 +02:00

128 lines
4.2 KiB
TypeScript

import { readdirSync, statSync, readFileSync } from "node:fs"
import { join, relative } from "node:path"
import { TextDecoder } from "node:util"
import { getDirectiveTokens, splitArgs } from "./scanner"
export type TemplateVariable = {
path: string
type: string
}
const VAR_RE = /<@var\(context\.(.+?)(?::(\w+))?\)>/g
const STRING_COMPARE_RE = /^(?:eq|neq)\(context\.(.+?),\s*"(.*)"\)$/
const PATH_RE = /^context\.(.+)$/
function extractCondition(expr: string | undefined, vars: TemplateVariable[]) {
if (!expr) throw new Error("Missing condition expression")
for (const operator of ["and", "or"]) {
const prefix = `${operator}(`
if (expr.startsWith(prefix) && expr.endsWith(")")) {
const args = splitArgs(expr.slice(prefix.length, -1))
if (args.length === 0) throw new Error(`Invalid condition expression: ${expr}`)
for (const arg of args) extractCondition(arg, vars)
return
}
}
const stringCompareMatch = expr.match(STRING_COMPARE_RE)
if (stringCompareMatch) {
vars.push({ path: stringCompareMatch[1]!, type: "string" })
return
}
const pathMatch = expr.match(PATH_RE)
if (pathMatch) {
vars.push({ path: pathMatch[1]!, type: "boolean" })
return
}
throw new Error(`Invalid condition expression: ${expr}`)
}
function extractFromString(text: string, vars: TemplateVariable[], source = "template") {
for (const token of getDirectiveTokens(text)) {
if (token.type === "if" || token.type === "elseif") {
try {
extractCondition(token.condition, vars)
} catch (error) {
if (error instanceof Error) throw new Error(`${source}: ${error.message}`)
throw error
}
}
}
for (const match of text.matchAll(VAR_RE)) {
vars.push({ path: match[1]!, type: match[2] ?? "string" })
}
}
function validateIfBlocks(content: string, vars: TemplateVariable[], source: string) {
const stack: { sawElse: boolean }[] = []
for (const token of getDirectiveTokens(content)) {
const directive = token.type
const condition = token.condition
if (directive === "if") {
extractCondition(condition!, vars)
stack.push({ sawElse: false })
} else if (directive === "elseif") {
const frame = stack[stack.length - 1]
if (!frame) throw new Error(`${source}: Unexpected <@elseif> without <@if>`)
if (frame.sawElse) throw new Error(`${source}: Unexpected <@elseif> after <@else>`)
extractCondition(condition!, vars)
} else if (directive === "else") {
const frame = stack[stack.length - 1]
if (!frame) throw new Error(`${source}: Unexpected <@else> without <@if>`)
if (frame.sawElse) throw new Error(`${source}: Unexpected duplicate <@else>`)
frame.sawElse = true
} else if (directive === "endif") {
if (stack.length === 0) throw new Error(`${source}: Unexpected <@endif> without <@if>`)
stack.pop()
}
}
if (stack.length > 0) {
throw new Error(`${source}: Unmatched <@if> without <@endif>`)
}
}
function isUtf8Text(buffer: Buffer): boolean {
if (buffer.indexOf(0) !== -1) return false
try {
new TextDecoder("utf-8", { fatal: true }).decode(buffer)
return true
} catch {
return false
}
}
function walkDir(dirPath: string, vars: TemplateVariable[], rootPath: string) {
const entries = readdirSync(dirPath).sort()
for (const entry of entries) {
const fullPath = join(dirPath, entry)
const relativePath = relative(rootPath, fullPath)
extractFromString(entry, vars, relativePath || entry)
const stat = statSync(fullPath)
if (stat.isDirectory()) {
walkDir(fullPath, vars, rootPath)
} else if (stat.isFile()) {
const content = readFileSync(fullPath)
if (isUtf8Text(content)) {
const text = content.toString("utf-8")
extractFromString(text, vars, relativePath || fullPath)
validateIfBlocks(text, vars, relativePath || fullPath)
}
}
}
}
export function parse(dirPath: string): TemplateVariable[] {
const vars: TemplateVariable[] = []
walkDir(dirPath, vars, dirPath)
const seen = new Set<string>()
return vars.filter(v => {
const key = `${v.path}:${v.type}`
if (seen.has(key)) return false
seen.add(key)
return true
})
}