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 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 | // src/providers/EcosystemProviders.ts // Pennant indexer, nWidart modules indexer, Gate name completions, // Twig view support, Composer.json scripts, Event→Listener nav, toResource nav import * as vscode from 'vscode'; import * as path from 'path'; import * as fs from 'fs'; import type { CacheManager } from '../cache/CacheManager'; import type { ModelDefinition, ColumnDefinition } from '../types'; import type { PennantFeature } from '../types'; // ─── Pennant Feature Indexer ────────────────────────────────────────────── export class PennantIndexer { static index(workspaceRoot: string): PennantFeature[] { const features: PennantFeature[] = []; // Scan AppServiceProvider and all service providers for Feature::define() const providerDirs = [ path.join(workspaceRoot, 'app', 'Providers'), path.join(workspaceRoot, 'app', 'Features'), ]; for (const dir of providerDirs) { if (!fs.existsSync(dir)) { continue; } for (const file of fs.readdirSync(dir)) { if (!file.endsWith('.php')) { continue; } const fullPath = path.join(dir, file); try { const source = fs.readFileSync(fullPath, 'utf8'); // Feature::define('feature-name', fn() => ...) const defineRe = /Feature::define\s*\(\s*['"]([^'"]+)['"]/g; let m: RegExpExecArray | null; while ((m = defineRe.exec(source)) !== null) { features.push({ name: m[1], isClassBased: false, filePath: fullPath }); } // Class-based features: class FeatureName { ... } if (source.includes('Illuminate\\Foundation\\HasFeatures') || source.includes('extends Feature')) { const classMatch = /class\s+(\w+)(?:\s+extends\s+\w+)?/.exec(source); if (classMatch) { const kebab = classMatch[1].replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, ''); features.push({ name: kebab, isClassBased: true, className: classMatch[1], filePath: fullPath }); } } } catch { /* skip */ } } } return features; } } // ─── nWidart Modules Indexer ────────────────────────────────────────────── export class NWidartModulesIndexer { static index(workspaceRoot: string, modulesPath = 'Modules'): Set<string> { const modules = new Set<string>(); const modulesDir = path.join(workspaceRoot, modulesPath); if (!fs.existsSync(modulesDir)) { return modules; } try { for (const entry of fs.readdirSync(modulesDir, { withFileTypes: true })) { if (entry.isDirectory()) { // Verify it's a proper module (has module.json or src/) const hasModuleJson = fs.existsSync(path.join(modulesDir, entry.name, 'module.json')); const hasSrc = fs.existsSync(path.join(modulesDir, entry.name, 'src')); if (hasModuleJson || hasSrc) { modules.add(entry.name); } } } } catch { /* skip */ } return modules; } } // ─── Gate Name Completion Provider ─────────────────────────────────────── export class GateNameProvider implements vscode.CompletionItemProvider { constructor(private readonly cache: CacheManager) {} provideCompletionItems( document: vscode.TextDocument, position: vscode.Position ): vscode.CompletionItem[] { const lineText = document.lineAt(position).text; const textBefore = lineText.substring(0, position.character); // gate('|'), Gate::allows('|'), Gate::denies('|'), $user->can('|'), @can('|') const isGate = /\bgate\s*\(\s*['"][^'"]*$/.test(textBefore) || /\bGate::\w+\s*\(\s*['"][^'"]*$/.test(textBefore) || /\$(?:user|this)\s*->\s*can\s*\(\s*['"][^'"]*$/.test(textBefore) || /@can\s*\(\s*['"][^'"]*$/.test(textBefore) || /@cannot\s*\(\s*['"][^'"]*$/.test(textBefore) || /\$request\s*->\s*user\s*\(\s*\)\s*->\s*can\s*\(\s*['"][^'"]*$/.test(textBefore); if (!isGate) { return []; } const index = this.cache.getIndex(); const items: vscode.CompletionItem[] = []; const seenGates = new Set<string>(); // Extract gate names from all PHP files (Gate::define() in service providers) for (const [, cls] of index.classes) { if (!cls.name.includes('Provider') && !cls.name.includes('Auth')) { continue; } try { const source = fs.readFileSync(cls.filePath, 'utf8'); const gateRe = /Gate::define\s*\(\s*['"]([^'"]+)['"]/g; let m: RegExpExecArray | null; while ((m = gateRe.exec(source)) !== null) { seenGates.add(m[1]); } } catch { /* skip */ } } // Gates derived from Policy methods for (const [, model] of index.models) { const policyPath = path.join( path.dirname(model.filePath), '..', '..', 'Policies', `${model.className}Policy.php` ); if (!fs.existsSync(policyPath)) { continue; } try { const source = fs.readFileSync(policyPath, 'utf8'); const methodRe = /public\s+function\s+(\w+)\s*\(User/g; let m: RegExpExecArray | null; while ((m = methodRe.exec(source)) !== null) { const gateName = `${model.className.toLowerCase()}.${m[1]}`; seenGates.add(gateName); } } catch { /* skip */ } } for (const gate of seenGates) { const item = new vscode.CompletionItem(gate, vscode.CompletionItemKind.Value); item.detail = 'Gate / Policy ability'; item.documentation = new vscode.MarkdownString(`**Gate ability:** \`${gate}\``); items.push(item); } return items; } } // ─── Twig View Support ──────────────────────────────────────────────────── export class TwigViewProvider implements vscode.CompletionItemProvider { constructor(_cache: CacheManager, private readonly workspaceRoot: string) {} provideCompletionItems( document: vscode.TextDocument, position: vscode.Position ): vscode.CompletionItem[] { const lineText = document.lineAt(position).text; const textBefore = lineText.substring(0, position.character); // view('file.twig'), view('file.html.twig') if (!/\bview\s*\(\s*['"][^'"]*$/.test(textBefore)) { return []; } const items: vscode.CompletionItem[] = []; const twigDirs = [ path.join(this.workspaceRoot, 'resources', 'views'), path.join(this.workspaceRoot, 'templates'), ]; for (const dir of twigDirs) { if (!fs.existsSync(dir)) { continue; } this.scanTwigFiles(dir, dir, items); } return items; } private scanTwigFiles(dir: string, root: string, items: vscode.CompletionItem[], prefix = ''): void { try { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const fullPath = path.join(dir, entry.name); if (entry.isDirectory()) { this.scanTwigFiles(fullPath, root, items, prefix ? `${prefix}/${entry.name}` : entry.name); } else if (entry.name.endsWith('.twig') || entry.name.endsWith('.html.twig')) { const viewName = (prefix ? `${prefix}/${entry.name}` : entry.name) .replace(/\.html\.twig$/, '') .replace(/\.twig$/, ''); const item = new vscode.CompletionItem(viewName, vscode.CompletionItemKind.File); item.detail = 'Twig view'; item.documentation = new vscode.MarkdownString(`**Twig View:** \`${fullPath.replace(root + path.sep, '')}\``); items.push(item); } } } catch { /* skip */ } } } // ─── Composer.json Scripts Completion ──────────────────────────────────── export class ComposerScriptsProvider implements vscode.CompletionItemProvider { constructor(_workspaceRoot: string) {} provideCompletionItems( document: vscode.TextDocument, position: vscode.Position ): vscode.CompletionItem[] { // Only in terminal-like contexts or composer.json itself if (document.languageId !== 'json' && document.languageId !== 'jsonc') { return []; } if (!document.fileName.endsWith('composer.json')) { return []; } // Inside "scripts" section if (!/"scripts"\s*:\s*\{/.test(document.getText().substring(0, document.offsetAt(position)))) { return []; } // Suggest @php, @composer, common script patterns const suggestions = [ { label: '@php artisan', detail: 'Run an Artisan command' }, { label: '@composer', detail: 'Run a Composer command' }, { label: 'php artisan optimize', detail: 'Cache routes, config, views' }, { label: 'php artisan migrate --force', detail: 'Run migrations in production' }, { label: 'php artisan config:cache', detail: 'Cache config' }, { label: 'php artisan route:cache', detail: 'Cache routes' }, { label: 'php artisan view:cache', detail: 'Compile Blade views' }, { label: 'php artisan queue:restart', detail: 'Restart queue workers' }, { label: '@php -r "opcache_reset();"', detail: 'Reset OPcache' }, ]; return suggestions.map(({ label, detail }) => { const item = new vscode.CompletionItem(label, vscode.CompletionItemKind.Event); item.detail = detail; return item; }); } } // ─── Event → Listener Navigation Provider ──────────────────────────────── export class EventListenerNavigationProvider implements vscode.CodeLensProvider { constructor( _cache: CacheManager, private readonly workspaceRoot: string ) {} provideCodeLenses(document: vscode.TextDocument): vscode.CodeLens[] { if (!document.fileName.endsWith('.php')) { return []; } const text = document.getText(); // Check if this is an Event class if (!text.includes('use Dispatchable') && !text.includes('extends Event')) { return []; } const classMatch = /^class\s+(\w+)/m.exec(text); if (!classMatch) { return []; } const eventClass = classMatch[1]; const listeners = this.findListenersForEvent(eventClass); if (listeners.length === 0) { return []; } const line = (text.slice(0, text.indexOf(classMatch[0])).match(/\n/g) ?? []).length; return listeners.map((listener) => new vscode.CodeLens( new vscode.Range(line, 0, line, 0), { title: `👂 ${listener.name}`, command: 'laravelMaestro.navigateToListener', arguments: [listener.filePath], tooltip: `Go to listener: ${listener.filePath}`, } ) ); } private findListenersForEvent(eventClass: string): Array<{ name: string; filePath: string }> { const listeners: Array<{ name: string; filePath: string }> = []; // Scan EventServiceProvider for $listen map const espPath = path.join(this.workspaceRoot, 'app', 'Providers', 'EventServiceProvider.php'); if (!fs.existsSync(espPath)) { return listeners; } try { const source = fs.readFileSync(espPath, 'utf8'); // Find the event in the $listen array const eventSection = new RegExp(`${eventClass}::class\\s*=>\\s*\\[([^\\]]+)\\]`, 's').exec(source); if (!eventSection) { return listeners; } const listenerSection = eventSection[1]; const listenerRe = /(\w+)::class/g; let m: RegExpExecArray | null; while ((m = listenerRe.exec(listenerSection)) !== null) { const listenerName = m[1]; const listenerPath = this.resolveListenerPath(listenerName); if (listenerPath) { listeners.push({ name: listenerName, filePath: listenerPath }); } } } catch { /* skip */ } return listeners; } private resolveListenerPath(listenerName: string): string | undefined { const candidates = [ path.join(this.workspaceRoot, 'app', 'Listeners', `${listenerName}.php`), ]; return candidates.find((c) => fs.existsSync(c)); } } // ─── toResource / toResourceCollection Navigation ───────────────────────── export class ResourceNavigationProvider implements vscode.DefinitionProvider { constructor( private readonly cache: CacheManager, private readonly workspaceRoot: string ) {} async provideDefinition( document: vscode.TextDocument, position: vscode.Position ): Promise<vscode.Location | undefined> { const lineText = document.lineAt(position).text; // Check for ->toResource() or ->toResourceCollection() if (!lineText.includes('toResource') && !lineText.includes('toCollection')) { return undefined; } const wordRange = document.getWordRangeAtPosition(position, /\bto(?:Resource|Collection)\b/); if (!wordRange) { return undefined; } // Try to infer model from the expression before -> const textBefore = lineText.substring(0, document.offsetAt(wordRange.start)); const varMatch = /\$(\w+)\s*->$/.exec(textBefore); if (!varMatch) { return undefined; } const varName = varMatch[1]; const index = this.cache.getIndex(); // Find model by variable name via backward scan for (let l = position.line; l >= Math.max(0, position.line - 30); l--) { const t = document.lineAt(l).text; const assign = new RegExp(`(\\w+)\\s+\\$${varName}`).exec(t); if (!assign) { continue; } const modelName = assign[1]; for (const [, model] of index.models) { if (model.className !== modelName) { continue; } // Find the resource file const resourcePath = path.join( this.workspaceRoot, 'app', 'Http', 'Resources', `${modelName}Resource.php` ); if (fs.existsSync(resourcePath)) { return new vscode.Location(vscode.Uri.file(resourcePath), new vscode.Position(0, 0)); } } } return undefined; } } // ─── Artisan Migration Runner ───────────────────────────────────────────── export class MigrationRunner { static async run(workspaceRoot: string, phpExecutable: string): Promise<void> { const action = await vscode.window.showQuickPick([ { label: '▶ migrate', cmd: 'migrate', detail: 'Run pending migrations' }, { label: '▶ migrate:fresh --seed', cmd: 'migrate:fresh --seed', detail: 'Drop all tables, re-migrate, seed' }, { label: '▶ migrate:rollback', cmd: 'migrate:rollback', detail: 'Rollback the last batch' }, { label: '▶ migrate:refresh', cmd: 'migrate:refresh', detail: 'Rollback all and re-run' }, { label: '▶ migrate:status', cmd: 'migrate:status', detail: 'Show migration status' }, { label: '▶ db:seed', cmd: 'db:seed', detail: 'Run database seeders' }, { label: '▶ db:wipe', cmd: 'db:wipe', detail: 'Drop all tables, views, types' }, ], { placeHolder: 'Select migration action' }); if (!action) { return; } const terminal = vscode.window.createTerminal({ name: `Artisan: ${action.label}`, cwd: workspaceRoot, }); terminal.show(); terminal.sendText(`${phpExecutable} artisan ${action.cmd}`); } } // ─── Nova Resource Generator ───────────────────────────────────────────── export class NovaResourceGenerator { constructor( private readonly workspaceRoot: string, private readonly cache: CacheManager ) {} async generateResource(): Promise<void> { const index = this.cache.getIndex(); const models = Array.from(index.models.values()); let modelName: string | undefined; if (models.length > 0) { const picked = await vscode.window.showQuickPick( models.map((m) => ({ label: m.className, description: m.namespace })), { placeHolder: 'Select model for Nova resource' } ); modelName = picked?.label; } if (!modelName) { modelName = await vscode.window.showInputBox({ prompt: 'Model class name', placeHolder: 'User', validateInput: (v) => v.trim() ? null : 'Required', }); } if (!modelName) { return; } const model = models.find((m) => m.className === modelName); const modelNs = model?.namespace ?? 'App\\Models'; const fields = this.inferNovaFields(model); const content = `<?php namespace App\\Nova; use ${modelNs}\\${modelName}; use Laravel\\Nova\\Fields\\ID; use Laravel\\Nova\\Fields\\Text; use Laravel\\Nova\\Fields\\DateTime; use Laravel\\Nova\\Http\\Requests\\NovaRequest; class ${modelName} extends Resource { /** * The model the resource corresponds to. * * @var class-string<\\${modelNs}\\${modelName}> */ public static $model = ${modelName}::class; /** * The single value that should be used to represent the resource when being displayed. * * @var string */ public static $title = '${model?.columns.find((c) => ['name', 'title', 'email'].includes(c.name))?.name ?? 'id'}'; /** * The columns that should be searched. * * @var array */ public static $search = [ '${model?.columns.find((c) => ['name', 'email', 'title'].includes(c.name))?.name ?? 'id'}', ]; /** * Get the fields displayed by the resource. */ public function fields(NovaRequest $request): array { return [ ${fields} ]; } /** * Get the filters available for the resource. */ public function filters(NovaRequest $request): array { return []; } /** * Get the lenses available for the resource. */ public function lenses(NovaRequest $request): array { return []; } /** * Get the actions available for the resource. */ public function actions(NovaRequest $request): array { return []; } } `; const dir = path.join(this.workspaceRoot, 'app', 'Nova'); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } const filePath = path.join(dir, `${modelName}.php`); const uri = vscode.Uri.file(filePath); const edit = new vscode.WorkspaceEdit(); edit.createFile(uri, { overwrite: true }); edit.insert(uri, new vscode.Position(0, 0), content); await vscode.workspace.applyEdit(edit); const doc = await vscode.workspace.openTextDocument(uri); await vscode.window.showTextDocument(doc); vscode.window.showInformationMessage(`✅ Created Nova resource: ${modelName}`); } private inferNovaFields(model: ModelDefinition | undefined): string { if (!model || model.columns.length === 0) { return ` ID::make()->sortable(),\n Text::make('Name'),\n`; } const excluded = new Set(['password', 'remember_token']); return model.columns .filter((c) => !excluded.has(c.name)) .slice(0, 8) .map((col: ColumnDefinition) => { const field = this.columnToNovaField(col.name, col.type); return ` ${field},`; }) .join('\n') + '\n'; } private columnToNovaField(name: string, type: string): string { const label = name.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()); if (name === 'id') { return `ID::make()->sortable()`; } if (name.includes('email')) { return `Text::make('${label}', '${name}')->sortable()->rules('email')`; } if (name.includes('_at') || type.includes('timestamp') || type.includes('datetime')) { return `DateTime::make('${label}', '${name}')->sortable()`; } if (type.includes('bool')) { return `Boolean::make('${label}', '${name}')`; } if (type.includes('int') || type.includes('decimal')) { return `Number::make('${label}', '${name}')->sortable()`; } if (name.includes('description') || name.includes('body') || name.includes('content')) { return `Textarea::make('${label}', '${name}')`; } if (name.includes('image') || name.includes('avatar') || name.includes('photo')) { return `Image::make('${label}', '${name}')`; } if (name.endsWith('_id')) { const rel = label.replace(/ Id$/, ''); return `BelongsTo::make('${rel}')`; } return `Text::make('${label}', '${name}')->sortable()`; } } // ─── Dusk Test Generator ────────────────────────────────────────────────── export class DuskTestGenerator { constructor(private readonly workspaceRoot: string) {} async generate(): Promise<void> { const type = await vscode.window.showQuickPick([ { label: 'Browser Test', value: 'test', description: 'Test extending DuskTestCase' }, { label: 'Page Object', value: 'page', description: 'Encapsulate page interactions' }, { label: 'Component Object', value: 'component', description: 'Reusable component selectors' }, ], { placeHolder: 'Dusk artifact type' }); if (!type) { return; } const name = await vscode.window.showInputBox({ prompt: `${type.label} name (e.g. LoginTest / LoginPage / DatePicker)`, validateInput: (v) => v.trim() ? null : 'Required', }); if (!name) { return; } let filePath: string; let content: string; if (type.value === 'test') { filePath = path.join(this.workspaceRoot, 'tests', 'Browser', `${name}.php`); content = `<?php\n\nnamespace Tests\\Browser;\n\nuse Illuminate\\Foundation\\Testing\\DatabaseMigrations;\nuse Laravel\\Dusk\\Browser;\nuse Tests\\DuskTestCase;\n\nclass ${name} extends DuskTestCase\n{\n use DatabaseMigrations;\n\n /**\n * A basic browser test.\n */\n public function test_basic_example(): void\n {\n $this->browse(function (Browser $browser) {\n $browser->visit('/')\n ->assertSee('Laravel');\n });\n }\n}\n`; } else if (type.value === 'page') { filePath = path.join(this.workspaceRoot, 'tests', 'Browser', 'Pages', `${name}.php`); content = `<?php\n\nnamespace Tests\\Browser\\Pages;\n\nuse Laravel\\Dusk\\Browser;\n\nclass ${name} extends Page\n{\n /**\n * Get the URL for the page.\n */\n public function url(): string\n {\n return '/';\n }\n\n /**\n * Assert that the browser is on the page.\n */\n public function assert(Browser $browser): void\n {\n $browser->assertPathIs($this->url());\n }\n\n /**\n * Get the element shortcuts for the page.\n *\n * @return array<string, string>\n */\n public function elements(): array\n {\n return [\n '@element' => '#selector',\n ];\n }\n}\n`; } else { filePath = path.join(this.workspaceRoot, 'tests', 'Browser', 'Components', `${name}.php`); content = `<?php\n\nnamespace Tests\\Browser\\Components;\n\nuse Laravel\\Dusk\\Browser;\nuse Laravel\\Dusk\\Component;\n\nclass ${name} extends Component\n{\n /**\n * Get the root selector for the component.\n */\n public function selector(): string\n {\n return '.${name.toLowerCase()}';\n }\n\n /**\n * Assert that the browser page contains the component.\n */\n public function assert(Browser $browser): void\n {\n $browser->assertVisible($this->selector());\n }\n\n /**\n * Get the element shortcuts for the component.\n *\n * @return array<string, string>\n */\n public function elements(): array\n {\n return [];\n }\n}\n`; } const dir = path.dirname(filePath); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } const uri = vscode.Uri.file(filePath); const edit = new vscode.WorkspaceEdit(); edit.createFile(uri, { overwrite: false }); edit.insert(uri, new vscode.Position(0, 0), content); await vscode.workspace.applyEdit(edit); const doc = await vscode.workspace.openTextDocument(uri); await vscode.window.showTextDocument(doc); vscode.window.showInformationMessage(`✅ Created Dusk ${type.label}: ${name}`); } } // ─── Blade Component Smart Rename ────────────────────────────────────────── export class BladeComponentRenameHandler implements vscode.Disposable { private readonly disposables: vscode.Disposable[] = []; constructor( _cache: import('../cache/CacheManager').CacheManager, private readonly workspaceRoot: string ) { this.disposables.push( vscode.workspace.onDidRenameFiles((e) => void this.handleRename(e)) ); } private async handleRename(e: vscode.FileRenameEvent): Promise<void> { for (const { oldUri, newUri } of e.files) { const oldPath = oldUri.fsPath; const newPath = newUri.fsPath; if (!oldPath.endsWith('.blade.php')) { continue; } const componentRoot = path.join(this.workspaceRoot, 'resources', 'views', 'components'); if (!oldPath.startsWith(componentRoot)) { continue; } const oldTag = path.relative(componentRoot, oldPath).replace(/\.blade\.php$/, '').replace(/[\/\\]/g, '-').toLowerCase(); const newTag = path.relative(componentRoot, newPath).replace(/\.blade\.php$/, '').replace(/[\/\\]/g, '-').toLowerCase(); if (oldTag === newTag) { continue; } const bladeFiles = await vscode.workspace.findFiles( new vscode.RelativePattern(this.workspaceRoot, '**/*.blade.php'), '{vendor/**,node_modules/**}' ); const edit = new vscode.WorkspaceEdit(); let count = 0; for (const fileUri of bladeFiles) { if (fileUri.fsPath === newPath) { continue; } try { const doc = await vscode.workspace.openTextDocument(fileUri); const text = doc.getText(); const escaped = oldTag.replace(/[-.]/g, (c: string) => `\\${c}`); const re = new RegExp(`(</?x-)(${escaped})(\\b)`, 'g'); let m: RegExpExecArray | null; while ((m = re.exec(text)) !== null) { const s = doc.positionAt(m.index + m[1].length); const e2 = doc.positionAt(m.index + m[1].length + oldTag.length); edit.replace(fileUri, new vscode.Range(s, e2), newTag); count++; } } catch { /* skip */ } } if (count > 0) { await vscode.workspace.applyEdit(edit); vscode.window.showInformationMessage(`[Maestro] Renamed x-${oldTag} → x-${newTag} (${count} usages)`); } } } dispose(): void { for (const d of this.disposables) { d.dispose(); } } } |