MCPcopy Create free account
hub / github.com/Snapchat/Valdi / parseComponentFile

Function parseComponentFile

npm_modules/cli/src/preview/viewModelParser.ts:25–76  ·  view source on GitHub ↗
(filePath: string)

Source from the content-addressed store, hash-verified

23 * Uses regex — no TypeScript compiler dependency.
24 */
25export function parseComponentFile(filePath: string): ParsedViewModel {
26 const source = fs.readFileSync(filePath, 'utf8');
27
28 // 1. Find the exported component class and its ViewModel type parameter
29 const classMatch = source.match(
30 /export\s+class\s+(\w+)\s+extends\s+(?:Stateful)?Component<(\w+)/,
31 );
32 if (!classMatch) {
33 throw new Error(`Could not find an exported Component class in ${filePath}`);
34 }
35 const componentName = classMatch[1]!;
36 const viewModelName = classMatch[2]!;
37
38 // 2. Find the ViewModel interface body
39 // Match `interface ViewModelName {` through the closing `}`
40 const ifaceRegex = new RegExp(
41 `(?:export\\s+)?interface\\s+${escapeRegex(viewModelName)}\\s*\\{([^}]*)\\}`,
42 's',
43 );
44 const ifaceMatch = source.match(ifaceRegex);
45 if (!ifaceMatch) {
46 throw new Error(`Could not find interface ${viewModelName} in ${filePath}`);
47 }
48 const body = ifaceMatch[1]!;
49
50 // 3. Parse each property line
51 const props: ParsedProp[] = [];
52 // Match lines like: propName?: TypeExpression;
53 const propRegex = /^\s*(\w+)(\??):\s*(.+?)\s*;/gm;
54 let m: RegExpExecArray | null;
55 while ((m = propRegex.exec(body)) !== null) {
56 const name = m[1]!;
57 const optional = m[2] === '?';
58 const typeString = m[3]!.trim();
59
60 const isBoolean = typeString === 'boolean';
61 const isCallback = /=>/.test(typeString);
62 let callbackParamType: string | undefined;
63
64 if (isCallback) {
65 // Extract param type from patterns like (val: boolean) => void
66 const cbMatch = typeString.match(/\(\s*\w+\s*:\s*(\w+)\s*\)\s*=>/);
67 if (cbMatch) {
68 callbackParamType = cbMatch[1];
69 }
70 }
71
72 props.push({ name: name, typeString: typeString, optional, isBoolean, isCallback, callbackParamType });
73 }
74
75 return { componentName: componentName, viewModelName: viewModelName, props, extraImports: [] };
76}
77
78/**
79 * Detect interactive boolean pairs: a boolean prop + a callback that takes boolean.

Callers 2

valdiPreviewFunction · 0.90

Calls 6

escapeRegexFunction · 0.85
readFileSyncMethod · 0.80
matchMethod · 0.45
trimMethod · 0.45
testMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected