loopable / web /jsx_contract.py
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
8145bee verified
Raw History Blame Contribute Delete
1.29 kB
"""Read complete JSX nodes, including nested children and arrow-valued attributes."""
import json
from pathlib import Path
import subprocess
WEB = Path(__file__).resolve().parent
PARSER = r"""
const ts = require('typescript');
const fs = require('fs');
const input = JSON.parse(fs.readFileSync(0, 'utf8'));
const source = ts.createSourceFile('contract.tsx', input.source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const nodes = [];
function visit(node) {
const opening = ts.isJsxElement(node) ? node.openingElement : ts.isJsxSelfClosingElement(node) ? node : null;
if (opening && opening.tagName.getText(source) === input.tag) {
nodes.push({start: node.getStart(source), end: node.end, text: node.getText(source),
opening: opening.getText(source), props: opening.attributes.properties.map(p => p.name?.getText(source) ?? '...')});
}
ts.forEachChild(node, visit);
}
visit(source);
process.stdout.write(JSON.stringify(nodes));
"""
def jsx_elements(source: str, tag: str) -> list[dict]:
result = subprocess.run(["node", "-e", PARSER], cwd=WEB,
input=json.dumps({"source": source, "tag": tag}),
capture_output=True, text=True, encoding="utf-8", timeout=20, check=True)
return json.loads(result.stdout)