log property access from function body for from/to

This commit is contained in:
Orion Reed 2024-12-02 17:14:51 -05:00
parent 7cedd6b82e
commit 7bf64b6586
2 changed files with 45 additions and 1 deletions

View File

@ -8,6 +8,7 @@
"preview": "vite build && vite preview"
},
"dependencies": {
"@babel/parser": "^7.26.2",
"leaflet": "^1.9.4",
"perfect-arrows": "^0.3.7",
"perfect-freehand": "^1.2.2"
@ -19,4 +20,4 @@
"typescript": "^5.7.2",
"vite": "^6.0.0"
}
}
}

View File

@ -1,5 +1,6 @@
import { css } from './common/tags.ts';
import { FolkRope } from './folk-rope.ts';
import * as parser from '@babel/parser';
const styles = new CSSStyleSheet();
styles.replaceSync(css`
@ -90,6 +91,8 @@ export class FolkEventPropagator extends FolkRope {
const functionBody = codeLines.join('\n');
try {
parseAst(functionBody);
this.#function = new Function('from', 'to', 'event', functionBody);
} catch (error) {
console.warn('Failed to parse expression:', error, functionBody);
@ -208,3 +211,43 @@ export class FolkEventPropagator extends FolkRope {
}
};
}
function parseAst(functionBody: string) {
const ast = parser.parse(functionBody, {
sourceType: 'script',
});
const toProps = new Set<string>();
const fromProps = new Set<string>();
function walkAst(node: any) {
if (!node || typeof node !== 'object') return;
if (node.type === 'MemberExpression' && node.object?.type === 'Identifier') {
const objName = node.object.name;
if (objName !== 'to' && objName !== 'from') return;
const propSet = objName === 'to' ? toProps : fromProps;
if (node.property?.type === 'Identifier') {
propSet.add(node.property.name);
} else if (node.property?.type === 'StringLiteral') {
propSet.add(node.property.value);
}
}
// Recursively walk through all properties
for (const key in node) {
if (Array.isArray(node[key])) {
node[key].forEach(walkAst);
} else if (node[key] && typeof node[key] === 'object') {
walkAst(node[key]);
}
}
}
walkAst(ast);
console.log('Properties accessed on to:', Array.from(toProps));
console.log('Properties accessed on from:', Array.from(fromProps));
}