File size: 2,375 Bytes
d9879cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import * as fs from 'fs';
import * as path from 'path';

function processDirectory(directory: string) {
    fs.readdirSync(directory).forEach(file => {
        const fullPath = path.join(directory, file);
        if (fs.statSync(fullPath).isDirectory()) {
            processDirectory(fullPath);
        } else if (fullPath.endsWith('.ts') && !fullPath.includes('node_modules') && !fullPath.includes('dist')) {
            processFile(fullPath);
        }
    });
}

function processFile(filePath: string) {
    let content = fs.readFileSync(filePath, 'utf-8');
    let original = content;

    // 1. Replace catch (e: unknown) with catch (error: unknown)
    content = content.replace(/catch\s*\(\s*([a-zA-Z0-9_]+)\s*:\s*any\s*\)/g, 'catch ($1: unknown)');

    // 2. Replace common (error instanceof Error ? (error instanceof Error ? error.message : String(error)) : String(error)) usages if they exist after a catch
    // Since we don't have full AST context, we replace (e instanceof Error ? (e instanceof Error ? e.message : String(e)) : String(e)) where 'e' matches the catch variable
    // This simple regex replaces generic .message calls with proper type checking.
    // It's a bit naive but works for standard setups. We'll specifically target common variable names:
    const errorVars = ['e', 'err', 'error'];
    for (const v of errorVars) {
        // (e instanceof Error ? (e instanceof Error ? e.message : String(e)) : String(e)) -> (e instanceof Error ? (e instanceof Error ? (e instanceof Error ? e.message : String(e)) : String(e)) : String(e))
        const regex = new RegExp(`\\b${v}\\.message\\b`, 'g');
        content = content.replace(regex, `(${v} instanceof Error ? ${v}.message : String(${v}))`);
    }

    // 3. Remove "as any" assertions in specific safe contexts if requested, 
    // but the prompt only asked for catch blocks and webhooks specifically.
    // Let's leave "as any" broadly for now and focus on catch blocks as requested.

    if (content !== original) {
        fs.writeFileSync(filePath, content, 'utf-8');
        console.log(`Updated: ${filePath}`);
    }
}

const targetDirs = [
    path.resolve(__dirname, '..'), // /Volumes/sms/edtech/apps/api/src
    path.resolve(__dirname, '../../../whatsapp-worker/src')
];

targetDirs.forEach(dir => processDirectory(dir));
console.log('Purge any in catch blocks completed!');