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 | // src/indexer/RuntimeExtractor.ts import * as cp from 'child_process'; import * as path from 'path'; import * as vscode from 'vscode'; import type { CacheManager } from '../cache/CacheManager'; import type { ExtensionConfig, RouteDefinition, ColumnDefinition, ModelDefinition, RuntimePayload, } from '../types'; // ─── Runtime Extractor ──────────────────────────────────────────────────── export class RuntimeExtractor implements vscode.Disposable { private readonly workspaceRoot: string; private readonly cache: CacheManager; private readonly config: ExtensionConfig; private extractionTimer: ReturnType<typeof setTimeout> | null = null; private lastExtractionMs = 0; private readonly MIN_INTERVAL_MS = 30_000; // throttle: max once per 30s constructor(workspaceRoot: string, cache: CacheManager, config: ExtensionConfig) { this.workspaceRoot = workspaceRoot; this.cache = cache; this.config = config; } // ─── Public API ─────────────────────────────────────────────────────── /** * Run the PHP extractor. Debounced internally; safe to call frequently. */ async extract(): Promise<void> { const now = Date.now(); if (now - this.lastExtractionMs < this.MIN_INTERVAL_MS) { return; // Throttle } this.lastExtractionMs = now; try { const payload = await this.runPhpExtractor(); this.mergePayload(payload); } catch (err) { console.error('[Maestro] Runtime extraction failed:', err); } } /** Schedule an extraction with a delay (avoids hammering on save). */ scheduleExtraction(delayMs = 2000): void { if (this.extractionTimer) { clearTimeout(this.extractionTimer); } this.extractionTimer = setTimeout(() => { void this.extract(); }, delayMs); } // ─── PHP Child Process ──────────────────────────────────────────────── private async runPhpExtractor(): Promise<RuntimePayload> { const scriptPath = path.join(__dirname, '..', 'php-worker', 'extract.php'); const php = this.config.phpExecutable; const timeout = this.config.runtimeExtractionTimeout; return new Promise<RuntimePayload>((resolve, reject) => { let stdout = ''; let stderr = ''; const child = cp.execFile( php, [scriptPath, this.workspaceRoot], { cwd: this.workspaceRoot, timeout, maxBuffer: 10 * 1024 * 1024, // 10 MB env: { ...process.env, VSCODE_LARAVEL_INDEXING: 'true', // Prevent Laravel from opening browser / running migrations APP_ENV: 'local', }, }, (error, out, err) => { stdout = out; stderr = err; if (error) { // Timeout if ((error as NodeJS.ErrnoException).code === 'ETIMEDOUT') { reject(new Error(`[Maestro] PHP extractor timed out after ${timeout}ms`)); return; } // Non-zero exit - still try to parse stdout if (!stdout.trim()) { reject(new Error(`[Maestro] PHP extractor failed: ${stderr.slice(0, 500)}`)); return; } } try { const parsed = JSON.parse(stdout) as RuntimePayload; resolve(parsed); } catch (parseErr) { reject(new Error(`[Maestro] Failed to parse extractor JSON: ${String(parseErr)}`)); } } ); // Hard-kill the process if it somehow survives the timeout const killTimer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error('[Maestro] PHP extractor killed (SIGKILL) after hard timeout')); }, timeout + 2000); child.on('close', () => clearTimeout(killTimer)); }); } // ─── Payload Merging ────────────────────────────────────────────────── private mergePayload(payload: RuntimePayload): void { this.mergeRoutes(payload.routes ?? []); // IMPORTANT: mergeModels MUST run before mergeSchema so that // model.tableName is corrected from runtime data before we // attempt to match schema columns by table name. this.mergeModels((payload as RuntimePayloadExtended).models ?? {}); this.mergeSchema(payload.schema ?? {}); this.mergeConfig(payload.config ?? {}); this.mergeViews(payload.views ?? []); console.log( `[Maestro] Runtime merge: ${Object.keys(payload.routes ?? {}).length} routes, ` + `${Object.keys(payload.schema ?? {}).length} tables` ); } private mergeRoutes(routes: RuntimePayload['routes']): void { const index = this.cache.getIndex(); const routeMap = new Map<string, RouteDefinition>(index.routes); for (const r of routes) { if (!r.name) { continue; } // skip anonymous routes const parts = r.action.split('@'); const controllerClass = parts[0]; const controllerMethod = parts[1]; const existing = routeMap.get(r.name); const params = this.parseRouteParameters(r.uri); routeMap.set(r.name, { name: r.name, uri: r.uri, methods: r.methods, action: r.action, controllerClass: controllerClass ?? existing?.controllerClass, controllerMethod: controllerMethod ?? existing?.controllerMethod, middleware: r.middleware ?? [], parameters: params, filePath: existing?.filePath, lineNumber: existing?.lineNumber, }); } this.cache.updateIndex({ routes: routeMap }); } private mergeSchema(schema: Record<string, RuntimePayload['schema'][string]>): void { const index = this.cache.getIndex(); const dbSchema = new Map<string, ColumnDefinition[]>(index.dbSchema); const updatedModels = new Map<string, ModelDefinition>(index.models); for (const [table, cols] of Object.entries(schema)) { const columns: ColumnDefinition[] = cols.map((c) => ({ name: c.name, type: c.type, nullable: c.nullable, default: c.default ?? undefined, length: c.length ?? undefined, })); dbSchema.set(table, columns); // Attach columns to models that reference this table for (const [fqn, model] of updatedModels.entries()) { if (model.tableName === table) { updatedModels.set(fqn, { ...model, columns }); } } } this.cache.updateIndex({ dbSchema, models: updatedModels }); } private mergeConfig(config: Record<string, unknown>): void { const index = this.cache.getIndex(); const configMap = new Map(index.configs); for (const [key, value] of Object.entries(config)) { configMap.set(key, { key, value }); } this.cache.updateIndex({ configs: configMap }); } private mergeViews(views: string[]): void { const index = this.cache.getIndex(); const viewMap = new Map(index.views); for (const v of views) { if (!viewMap.has(v)) { viewMap.set(v, ''); // path unknown from runtime; filled by AST indexer } } this.cache.updateIndex({ views: viewMap }); } private mergeModels(models: Record<string, RuntimeModelData>): void { const index = this.cache.getIndex(); const updatedModels = new Map<string, ModelDefinition>(index.models); for (const [fqn, data] of Object.entries(models)) { const existing = updatedModels.get(fqn); if (existing) { updatedModels.set(fqn, { ...existing, tableName: data.table ?? existing.tableName, fillable: data.fillable ?? existing.fillable, guarded: data.guarded ?? existing.guarded, hidden: data.hidden ?? existing.hidden, casts: data.casts ?? existing.casts, primaryKey: data.primaryKey ?? existing.primaryKey, timestamps: data.timestamps ?? existing.timestamps, }); } } this.cache.updateIndex({ models: updatedModels }); } // ─── Helpers ────────────────────────────────────────────────────────── private parseRouteParameters(uri: string): RouteDefinition['parameters'] { const params: RouteDefinition['parameters'] = []; // Laravel syntax: {param} = required, {param?} = optional (trailing ?) const pattern = /\{([^}]+)\}/g; let match: RegExpExecArray | null; while ((match = pattern.exec(uri)) !== null) { const raw = match[1]; const isOptional = raw.endsWith('?'); const name = raw.replace(/\?$/, ''); params.push({ name, required: !isOptional }); } return params; } dispose(): void { if (this.extractionTimer) { clearTimeout(this.extractionTimer); } } } // ─── Extended Payload Type (internal) ──────────────────────────────────── interface RuntimeModelData { table: string; fillable: string[]; guarded: string[]; hidden: string[]; casts: Record<string, string>; primaryKey: string; timestamps: boolean; } interface RuntimePayloadExtended extends RuntimePayload { models?: Record<string, RuntimeModelData>; } |