@@ -403,29 +403,45 @@ export interface IdentifierInfo {
403403 variables : string [ ] ;
404404 isError : boolean ;
405405}
406+
407+ // Extracted function to sanitize, wrap, parse code, and call ancestorWalk, now with caching
408+ const sanitizedWrappedAncestorWalkCache = new Map < string , NodeList > ( ) ;
409+
410+ function getSanitizedWrappedAncestorWalk (
411+ code : string ,
412+ evaluationVersion : number ,
413+ ) : NodeList {
414+ const cacheKey = `${ evaluationVersion } ::${ code } ` ;
415+
416+ if ( sanitizedWrappedAncestorWalkCache . has ( cacheKey ) ) {
417+ return sanitizedWrappedAncestorWalkCache . get ( cacheKey ) ! ;
418+ }
419+
420+ const sanitizedScript = sanitizeScript ( code , evaluationVersion ) ;
421+ // We sanitize and wrap the code because all code/script gets wrapped with a function during evaluation.
422+ // Some syntax won't be valid unless they're at the RHS of a statement.
423+ // Since we're assigning all code/script to RHS during evaluation, we do the same here.
424+ // So that during ast parse, those errors are neglected.
425+ // e.g. IIFE without braces:
426+ // function() { return 123; }() -> is invalid
427+ // let result = function() { return 123; }() -> is valid
428+ const wrappedCode = wrapCode ( sanitizedScript ) ;
429+ const ast = getAST ( wrappedCode ) ;
430+ const result = ancestorWalk ( ast ) ;
431+
432+ sanitizedWrappedAncestorWalkCache . set ( cacheKey , result ) ;
433+
434+ return result ;
435+ }
436+
406437export const extractIdentifierInfoFromCode = (
407438 code : string ,
408439 evaluationVersion : number ,
409440 invalidIdentifiers ?: Record < string , unknown > ,
410441) : IdentifierInfo => {
411- let ast : Node = { end : 0 , start : 0 , type : "" } ;
412-
413442 try {
414- const sanitizedScript = sanitizeScript ( code , evaluationVersion ) ;
415- /* wrapCode - Wrapping code in a function, since all code/script get wrapped with a function during evaluation.
416- Some syntax won't be valid unless they're at the RHS of a statement.
417- Since we're assigning all code/script to RHS during evaluation, we do the same here.
418- So that during ast parse, those errors are neglected.
419- */
420- /* e.g. IIFE without braces
421- function() { return 123; }() -> is invalid
422- let result = function() { return 123; }() -> is valid
423- */
424- const wrappedCode = wrapCode ( sanitizedScript ) ;
425-
426- ast = getAST ( wrappedCode ) ;
427443 const { functionalParams, references, variableDeclarations } : NodeList =
428- ancestorWalk ( ast ) ;
444+ getSanitizedWrappedAncestorWalk ( code , evaluationVersion ) ;
429445 const referencesArr = Array . from ( references ) . filter ( ( reference ) => {
430446 // To remove references derived from declared variables and function params,
431447 // We extract the topLevelIdentifier Eg. Api1.name => Api1
0 commit comments