All files check_test.js

70.54% Statements 103/146
62.69% Branches 79/126
64.7% Functions 11/17
71.12% Lines 101/142

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471    3x 3x 3x 3x                     3x   3x   3x       3x 3x       3x 3x   3x 3x 1x 1x         2x   2x 2x                                       2x                 2x 2x 14x 14x 14x 42x                     2x   2x                 2x         4x 4x   4x     5x 5x   5x       10x   10x 5x   5x         5x 5x   5x 10x 10x 10x 10x   10x 5x   5x 5x 5x                         5x   1x                                                                         6x 6x 8x   1x   7x           7x     5x   2x                                   2x 3x 3x               2x   3x       2x 1x   1x 1x 1x                                                                           2x                                                                                                           11x 2x     9x                                 4x   4x 4x 4x 4x 1x       1x   1x         3x 3x 1x   1x         1x                     1x   1x     1x 1x                                               1x             2x 1x   1x   1x 1x         2x 2x                     3x       3x              
// checkOptionalChaining.js
 
const { existsSync, readFileSync, mkdirSync, appendFileSync } = require('fs');
const path = require('path');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
 
 
 
// Needed for __dirname in ESM
// import { fileURLToPath } from 'url';
// import { argv } from 'process';
 
 
function runOptionalChainingCheck() {
 
    try {
 
        console.log(`Script started...`);
 
        const STATIC_SAFE_CALLS = new Set();
 
 
 
        const relativePath = process.argv[2];
        Iif (!relativePath) {
            console.log(`No file argument provided.`);
            process.exit(0);
        }
        const file = path.resolve(process.cwd(), relativePath);
        console.log(`fileName`, file);
 
        const fileExists = existsSync(file);
        if (!file || !fileExists) {
            console.log(`No file provided or file doesn't exist.`);
            process.exit(0);
        }
 
 
 
        console.log(`Analyzing file: ${file}`);
 
        const code = readFileSync(file, 'utf8');
        let errorFound = false;
 
 
 
        // const astCommentCleaner = parser.parse(code, {
        //     sourceType: 'module',
        //     plugins: ['jsx', 'optionalChaining', ['optionalChainingAssign', { version: '2023-07' }]],
        //     comments: false,
        // });
 
        // const codeWithoutComments = babelGenerator.default(astCommentCleaner, { comments: false }).code;
 
        // Ensure 'log' folder exists
        // if (!fs.existsSync('log')) {
        //    fs.mkdirSync('log');
        // }
        // fs.writeFileSync('log/astCommentCleaner.json', JSON.stringify(astCommentCleaner, null, 2), 'utf8');
        // fs.writeFileSync('log/code.txt', JSON.stringify(code, null, 2), 'utf8');
 
        // ❌ Regex pre-checks for invalid optional chaining use
        const invalidChainingPatterns = [
            /\+\+\s*[a-zA-Z_$][\w$]*\?\.\w+/,         // ++user?.count
            /[a-zA-Z_$][\w$]*\?\.\w+\s*\+\+/,         // user?.count++
            /[a-zA-Z_$][\w$]*\?\.\w+\s*=(?!=|>)/      // user?.name = "x" but NOT ===, ==, =>
        ];
 
 
 
        // const lines = codeWithoutComments.split('\n');
        const lines = code.split('\n');
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i];
            Iif (/^\s*(import|export)\s/.test(line)) continue;
            for (const pattern of invalidChainingPatterns) {
                Iif (pattern.test(line)) {
                    // console.log(`❌ [Invalid Pattern] ${file}:${i + 1}`);
                    // console.log(`   ↪ ${line.trim()}`);
                    // console.log(`   🚫 Optional chaining cannot be used on the left-hand side of assignment, delete, or increment/decrement.`);
                    console.log(`\n${file}:${i + 1} error optional-chaining-misuse optional chaining used in invalid assignment/delete/increment\n`);
 
                    process.exit(1);
                }
            }
        }
 
        console.log(`Regex pre-checks completed`);
 
        const ast = parser.parse(code, {
            sourceType: 'module',
            plugins: [['optionalChainingAssign', { version: '2023-07' }], 'optionalChaining', 'jsx'],
            comments: true
        });
 
        // fs.writeFileSync('log/ast.json', JSON.stringify(ast, null, 2), 'utf8');
        // fs.writeFileSync('log/codeWithoutComments.txt', JSON.stringify(codeWithoutComments, null, 2), 'utf8');
 
        const localIdentifiers = new Set();
 
 
        // 🧠 Get root identifier from any nested chain
        function getBaseIdentifierName(node) {
            while (node && (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression')) {
                node = node.object;
            }
            return node?.type === 'Identifier' ? node.name : null;
        }
        function checkOptionalChainSafety(path) {
            const chainLinks = [];
            let node = path.node;
            // Walk down the callee/member chain and collect links
            while (
                node.type === 'CallExpression' || node.type === 'OptionalCallExpression' ||
                node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression'
            ) {
                chainLinks.push(node);
                // Move to the next link: callee of calls, object of member access
                if (node.type === 'CallExpression' || node.type === 'OptionalCallExpression') {
                    node = node.callee;
                } else {
                    node = node.object;
                }
            }
 
            // Now analyze the chain from base to top
            let chainActive = false;
            let unsafe = false;
            // Traverse from base object up to the final call
            for (let i = chainLinks.length - 1; i >= 0; i--) {
                const link = chainLinks[i];
                const isFinalLink = i === 0;
                const isCall = link.type === 'CallExpression' || link.type === 'OptionalCallExpression';
                const isFunctionAtEnd = isFinalLink && isCall && path.parent.type !== 'MemberExpression';
 
                if (isFunctionAtEnd) {
                    continue; // Allow direct function call at the end
                }
                const isOptionalType = link.type === 'OptionalMemberExpression' || link.type === 'OptionalCallExpression';
                const hasOptionalOperator = isOptionalType && link.optional === true;
                Iif (chainActive && (!isOptionalType || link.optional === false)) {
                    // Chain already started, but this link has no optional operator
 
                    const line = path.node.loc?.start?.line || '?';
                    // console.log(`❌ [Unsafe Optional Call] ${file}:${line}`);
                    // console.log(`   ↪ ${path.toString()}`);
                    // console.log(`   🚫 Once optional chaining starts, all links and the final call must use '?.'`);
                    console.log(`\n${file}:${line} error: optional chaining starts but not all links use '?.' (optional-chaining-unsafe-call)\n`);
 
                    errorFound = true;
                    process.exit(1); // immediate stop
                    // break;
                }
                if (hasOptionalOperator) {
                    // This link has a ?. operator, so the optional chain is (or remains) active
                    chainActive = true;
                }
            }
 
            // if (unsafe) { // never executed due to this earlier block
            //     // Report or collect the error (here we just log for illustration)
            //     console.log(`Unsafe optional call at line ${ path.node.loc.start.line }: ${ path.toString() } `);
            // }
        }
 
 
        // function isFullyOptionalChain(path) {
        //     let node = path.node;
 
        //     // Check downward
        //     while (node && (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression')) {
        //         if (!node.optional) {
        //             return false; // 🛑 Found non-optional access
        //         }
        //         node = node.object;
        //     }
 
        //     // Check upward
        //     let parentPath = path.parentPath;
        //     while (parentPath && (parentPath.isMemberExpression() || parentPath.isOptionalMemberExpression())) {
        //         if (!parentPath.node.optional) {
        //             return false; // 🛑 Parent access is non-optional
        //         }
        //         parentPath = parentPath.parentPath;
        //     }
 
        //     return true; // ✅ All access are optional
        // }
 
        // Helper function to check if a member chain is fully optional
        function isFullyOptionalChain(path) {
            // Traverse down the chain from the current member expression
            let current = path;
            while (current && (current.isMemberExpression() || current.isOptionalMemberExpression())) {
                if (!current.isOptionalMemberExpression()) {
                    // This node is a normal MemberExpression (no optional chaining at this link)
                    return false;
                }
                Iif (current.isOptionalMemberExpression() && !current.node.optional) {
                    // This node is an OptionalMemberExpression, but `.optional` is false,
                    // meaning this particular access used a plain dot.
                    return false;
                }
                // Move to the next object in the chain (e.g., traverse from `obj?.foo.bar` to `obj?.foo`)
                current = current.get("object");
            }
            // If we exited the loop without finding a non-optional link, the chain is fully optional
            return true;
        }
        traverse(ast, {
            ImportDeclaration(path) {
                const importSource = path.node.source.value;
                const isLocalImport = importSource.startsWith('./') || importSource.startsWith('../');
 
                path.node.specifiers.forEach(spec => {
                    if (spec.local) {
                        const importedName = spec.local.name;
                        if (!isLocalImport) {
                            STATIC_SAFE_CALLS.add(importedName);
                        } else {
                            localIdentifiers.add(importedName);
                        }
                    }
                });
            }
        });
 
        const addToLocalIdentifiers = (name) => {
            Eif (!STATIC_SAFE_CALLS.has(name)) {
                localIdentifiers.add(name);
            }
        }
 
 
        // console.log(`STATIC_SAFE_CALLS populated`, [...STATIC_SAFE_CALLS]);
 
 
        traverse(ast, {
            VariableDeclarator(path) {
                if (path.node.id.type === 'Identifier') {
                    // if (!STATIC_SAFE_CALLS.has(path.node.id.name)) {
                    //     localIdentifiers.add(path.node.id.name);
                    // }
                    addToLocalIdentifiers(path.node.id.name);
                } else Eif (path.node.id.type === 'ObjectPattern') {
                    // ✅ Handle destructuring: { user } = this.props // Class based components
                    for (const property of path.node.id.properties) {
                        Eif (property.type === 'ObjectProperty' && property.key.type === 'Identifier') {
                            addToLocalIdentifiers(property.key.name);
                        }
                    }
                }
            },
            FunctionDeclaration(path) {
                if (path.node.id) {
                    // if (!STATIC_SAFE_CALLS.has(path.node.id.name)) {
                    //     localIdentifiers.add(path.node.id.name);
                    // }
                    addToLocalIdentifiers(path.node.id.name);
                }
            },
            ClassDeclaration(path) {
                if (path.node.id) {
                    // if (!STATIC_SAFE_CALLS.has(path.node.id.name)) {
                    //     localIdentifiers.add(path.node.id.name);
                    // }
                    getBaseIdentifierName(path.node.id.name);
                }
            },
            ImportDeclaration(path) {
                path.node.specifiers.forEach(spec => {
                    if (spec.local) {
                        // if (!STATIC_SAFE_CALLS.has(spec.local.name)) {
                        //     localIdentifiers.add(spec.local.name);
                        // }
                        getBaseIdentifierName(spec.local.name);
                    }
                });
            }
        });
 
        // console.log('localIdentifiers populated ', localIdentifiers);
 
        // console.log(JSON.stringify(ast, null, 2)); // 🌟 Full readable AST
 
        // ✅ Deep inspection for member, optional, and call expressions
        traverse(ast, {
            // MemberExpression(path) {
            //     const baseName = getBaseIdentifierName(path.node);
            //     const propertyName = path.node.property?.name;
 
            //     // ✅ Skip if it's assigning .propTypes to a local component
            //     if (
            //         propertyName === 'propTypes' &&
            //         localIdentifiers.has(baseName) &&
            //         path.parent?.type === 'AssignmentExpression' &&
            //         path.parent.left === path.node
            //     ) {
            //         return; // ✅ This is safe: MyComponent.propTypes = { ... }
            //     }
 
            //     if (localIdentifiers.has(baseName) && !isFullyOptionalChain(path)) {
            //         const line = path.node.loc?.start?.line || '?';
            //         console.log(`❌[Unsafe Access] ${ file }:${ line } `);
            //         console.log(`   ↪ ${ path.toString() } `);
            //         console.log(`   ⚠️ '${baseName}' is local, but some part of the chain is accessed unsafely after optional chaining.`);
            //         errorFound = true;
            //     }
            // },
 
            // OptionalMemberExpression(path) {
            //     const propertyName = path.node.property?.name;
            //     const baseName = getBaseIdentifierName(path.node);
 
            //     // ✅ Skip known safe pattern: MyComponent.propTypes = ...
            //     if (
            //         propertyName === 'propTypes' &&
            //         localIdentifiers.has(baseName) &&
            //         path.parent?.type === 'AssignmentExpression' &&
            //         path.parent.left === path.node
            //     ) {
            //         return;
            //     }
            //     if (localIdentifiers.has(baseName)) {
            //         const parent = path.parentPath;
            //         const line = path.node.loc?.start?.line || '?';
            //         if (
            //             parent.isAssignmentExpression() ||
            //             parent.isUpdateExpression()
            //         ) {
            //             console.log(`❌[Chaining Misuse] ${ file }:${ line } `);
            //             console.log(`   ↪ ${ path.toString() } `);
            //             console.log(`   🚫 Optional chaining misused with assignment / delete/increment.`);
            //             errorFound = true;
            //         }
            //     }
            // },
            // Handle both OptionalMemberExpression and MemberExpression nodes
            "MemberExpression|OptionalMemberExpression"(path) {
                // Only check the outermost member of a chain to avoid duplicate checks
                if (path.parentPath.isMemberExpression() || path.parentPath.isOptionalMemberExpression()) {
                    return;  // Skip if parent is also a property access (not the chain's end)
                }
                // Now `path` is the top of a member access chain
                Iif (path.node.type === 'OptionalMemberExpression' && !isFullyOptionalChain(path)) {
                    const { line } = path.node.loc.start;
                    const baseName = getBaseIdentifierName(path.node);
 
                    // You could collect this location or otherwise record the violation as needed
                    if (localIdentifiers.has(baseName)) {
                        // console.log(`❌ [Unsafe Access] ${file}:${line}`);
                        // console.log(`   ↪ ${path.toString()}`);
                        // console.log(`   ⚠️ '${baseName}' is local, but some part of the chain is accessed unsafely after optional chaining.`);
                        console.log(`\n${file}:${line} error optional-chaining-unsafe '${baseName}' accessed unsafely after optional chaining\n`);
 
                        errorFound = true;
                    }
                }
            },
            CallExpression(path) {
                //  if (path.node.type === 'CallExpression') {
                checkOptionalChainSafety(path);
                //  }
                const callee = path.node.callee;
                Eif (callee.type === 'MemberExpression' || callee.type === 'OptionalMemberExpression') {
                    const baseName = getBaseIdentifierName(callee);
                    if (localIdentifiers.has(baseName) && !isFullyOptionalChain(path.get('callee'))) {
                        const line = path.node.loc?.start?.line || '?';
                        // console.log(`❌ [Unsafe Call Access] ${file}:${line}`);
                        // console.log(`   ↪ ${path.toString()}`);
                        // console.log(`   ⚠️ '${baseName}' is local, but function/property call chain is not safely guarded.`);
                        console.log(`\n${file}:${line} error optional-chaining-unsafe-call '${baseName}' function/property call is not safely guarded\n`);
 
                        errorFound = true;
                    }
                }
            },
            VariableDeclarator(path) { // first 
                const line = path.node.loc?.start?.line || '?';
                if (path.node.id.type === 'ObjectPattern') {
                    const init = path.node.init;
                    const unsafe =
                        !init ||
                        init.type === 'Identifier' ||
                        init.type === 'NullLiteral' ||
                        (init.type === 'Literal' && init.value === null);
 
                    Iif (unsafe) {
                        // console.log(`❌ [Unguarded Destructuring] ${file}:${line}`);
                        // console.log(`   ↪ const { ... } = ${init?.name || 'null/undefined'}`);
                        // console.log(`   💡 Add fallback: const { name } = ${init?.name || 'obj'} ?? {}`);
                        console.log(`\n${file}:${line} error optional-chaining-unguarded-destructure destructuring without fallback\n`);
 
                        errorFound = true;
                    }
                }
            },
            UnaryExpression(path) {
                Iif (path.node.operator !== 'delete') return;
 
                const arg = path.node.argument;
 
                // ✅ If already optional (safe delete), ignore
                Eif (arg.type === 'OptionalMemberExpression') {
                    return;
                }
 
                // ❌ If non-optional, check if dangerous
                if (
                    arg.type === 'MemberExpression' &&
                    !arg.optional && // redundant, but safe
                    arg.object.type === 'Identifier'
                ) {
                    const base = arg.object.name;
                    if (localIdentifiers.has(base)) {
                        const line = path.node.loc?.start?.line || '?';
                        // console.log(`❌ [Unsafe Delete Access] ${file}:${line}`);
                        // console.log(`   ↪ ${path.toString()}`);
                        // console.log(`   ⚠️ '${base}' may be null/undefined. Use optional chaining: delete ${base}?.prop`);
                        console.log(`\n${file}:${line} error optional-chaining-unsafe-delete '${base}' may be undefined, use delete ${base}?.prop\n`);
 
                        errorFound = true;
 
                    }
                }
            },
            OptionalCallExpression(path) {
                // Handle optional calls separately
                checkOptionalChainSafety(path);
            }
 
 
 
        });
 
        if (errorFound) {
            console.log('FAIL');
 
            process.exit(1);
        } else {
            console.log('All checks passed.');
            console.log('PASS');
        }
 
    } catch (e) {
 
        Eif (e instanceof Error && e.message.startsWith('ProcessExit_')) {
            throw e; // Let Jest test catch this
        }
 
        console.log('Unexpected error during optional chaining analysis:', e);
        console.log('FAIL');
        process.exit(1); // fallback exit
 
 
    }
 
}
module.exports = { runOptionalChainingCheck }; // for mjs
// export { runOptionalChainingCheck };for esm
 
// ✅ Call runOptionalChainingCheck if run via `node checkOptionalChaining.js file.js`
Iif (require?.main === module) { // for mjs
    runOptionalChainingCheck();
}
 
// const currentFile = fileURLToPath(import.meta.url); // for esm
// if (argv[1] === currentFile) {
//     runOptionalChainingCheck();
// }