diff --git a/README.md b/README.md index 5c7367b9..c401f7e9 100644 --- a/README.md +++ b/README.md @@ -86,16 +86,17 @@ See [Commands Reference](./docs/commands_reference.md) for the full command list ## Frontend Inspector -The MageForge Inspector lets you inspect Magento blocks, templates, and performance metrics directly in your browser. +MageForge includes a unified in-browser DevTools dock and panel (strictly CSS-isolated from storefront styles across Luma, Hyvä, and custom themes) for auditing pages and inspecting Magento blocks, templates, cache telemetry, and Web Vitals. **Features:** -- Template paths, block classes, and module names -- 1-click **Open in IDE** (PhpStorm, VS Code, Cursor, Zed, Sublime Text, or custom URL) with browser-saved Docker/DDEV host path mapping -- 1-click **Override & Open** directly into any editable `app/design/frontend` theme, including automatic cache cleaning -- PHP render times and cache status (lifetime, tags) -- Web Vitals: LCP, CLS, INP per element -- Accessibility checks: ARIA roles, contrast ratios, alt text +- **Unified DevTools Dock & Panel** — Switch between a floating popover and a docked right-hand sidebar drawer in Dark, Light, or Auto colour schemes +- **Interactive Element Inspector** — Compact non-intrusive Hover-HUD on storefront elements, interactive layout/DOM breadcrumbs, and `↑` / `↓` parent/child stepping +- **Page Block & Template Explorer** — Searchable, filterable tree of every rendered Magento block on the page (`All`, `Overrides`, `No Cache`, `Slow >50ms`) with live hover highlighting +- **Main-Thread & Core Web Vitals Profiler** — Live browser `PerformanceObserver` telemetry for TTFB & `Server-Timing` waterfalls, Google 4-phase `LCP` breakdown, `CLS` layout-shift culprits mapped to Magento `.phtml` blocks, runtime Magento AJAX/GraphQL/`customer-data` requests, Long Tasks (`>50 ms`) & `TBT`, Chromium `long-animation-frame` (LoAF) script/reflow attribution, render-blocking resources, and `INP` interactions +- **27 Automated Storefront Audits** — Accessibility (WCAG), SEO, Performance (including Main-Thread Blockers), HTML Quality, and Schema/JSON-LD checks with 1-click **Inspect** handoff from any finding straight to its `.phtml` template +- **1-Click Open in IDE & Template Override** — Open templates in PhpStorm, VS Code, Cursor, Zed, Sublime Text, or custom URLs (with automatic zero-config DDEV bind-mount / Mutagen host-path detection) or copy overrides into editable `app/design/frontend` themes +- **Unified Settings Hub** — Browser-persisted preferences for dock corner, panel layout, dock labels, default override target theme, and IDE path mappings ### Screenshot diff --git a/src/Block/Inspector.php b/src/Block/Inspector.php index 52f8999a..5b5c3d93 100644 --- a/src/Block/Inspector.php +++ b/src/Block/Inspector.php @@ -17,15 +17,24 @@ use OpenForgeProject\MageForge\Model\Config\Inspector as InspectorConfig; use OpenForgeProject\MageForge\Model\ThemeList; use OpenForgeProject\MageForge\Service\DeveloperAccessChecker; +use OpenForgeProject\MageForge\Service\Inspector\HostPathDetector; use OpenForgeProject\MageForge\Service\Inspector\OverrideTokenManager; /** * Block for MageForge Inspector * * Only renders inspector assets when in developer mode, enabled in config, and from allowed IP + * + * @phpstan-import-type DetectedHostPaths from HostPathDetector */ class Inspector extends Template { + /** + * @var array|null + * @phpstan-var DetectedHostPaths|null + */ + private ?array $detectedHostPaths = null; + /** * @param Context $context * @param State $state @@ -36,6 +45,7 @@ class Inspector extends Template * @param ComponentRegistrarInterface $componentRegistrar * @param DirectoryList $directoryList * @param DesignInterface $design + * @param HostPathDetector $hostPathDetector * @param array $data * @phpstan-param array $data */ @@ -49,6 +59,7 @@ public function __construct( private readonly ComponentRegistrarInterface $componentRegistrar, private readonly DirectoryList $directoryList, private readonly DesignInterface $design, + private readonly HostPathDetector $hostPathDetector, array $data = [], ) { parent::__construct($context, $data); @@ -236,6 +247,41 @@ public function getMagentoRoot(): string return rtrim(str_replace('\\', '/', $this->directoryList->getRoot()), '/'); } + /** + * Get auto-detected host Magento root path from DDEV/container mounts when available + * + * @return string + */ + public function getDetectedHostRoot(): string + { + return $this->getDetectedHostPaths()['hostRoot']; + } + + /** + * Get auto-detected external container=host bind-mount mappings when available + * + * @return string + */ + public function getDetectedExternalMappings(): string + { + return $this->getDetectedHostPaths()['externalMappings']; + } + + /** + * Memoize container mount path detection per block instance + * + * @return array + * @phpstan-return DetectedHostPaths + */ + private function getDetectedHostPaths(): array + { + if ($this->detectedHostPaths === null) { + $this->detectedHostPaths = $this->hostPathDetector->detect(); + } + + return $this->detectedHostPaths; + } + /** * Get currently active frontend theme code * diff --git a/src/Service/Inspector/HostPathDetector.php b/src/Service/Inspector/HostPathDetector.php new file mode 100644 index 00000000..ceea3827 --- /dev/null +++ b/src/Service/Inspector/HostPathDetector.php @@ -0,0 +1,414 @@ + + * @phpstan-return DetectedHostPaths + */ + public function detect( + string $ddevComposePath = self::DEFAULT_DDEV_COMPOSE_PATH, + ?string $envHostRoot = null, + ?string $ddevAppRoot = null, + ): array { + $magentoRoot = $this->normalizePath($this->directoryList->getRoot()); + $explicitHostRoot = $this->normalizePath($envHostRoot ?? $this->readEnvironmentVariable('MAGEFORGE_HOST_ROOT')); + + $bindMounts = $this->parseDdevMounts($ddevComposePath, $magentoRoot, $ddevAppRoot); + if ($bindMounts === []) { + return [ + 'hostRoot' => $explicitHostRoot, + 'externalMappings' => '', + ]; + } + + [$detectedRoot, $matchedContainerTarget] = $this->resolveMagentoHostRoot($magentoRoot, $bindMounts); + + $externalPairs = []; + foreach ($bindMounts as $target => $source) { + if ($target === $matchedContainerTarget) { + continue; + } + $externalPairs[] = $target . '=' . $source; + } + + return [ + 'hostRoot' => $explicitHostRoot !== '' ? $explicitHostRoot : $detectedRoot, + 'externalMappings' => implode(', ', $externalPairs), + ]; + } + + /** + * Parse bind mounts and DDEV approot fallback from `.ddev-docker-compose-full.yaml`. + * + * @param string $composePath + * @param string $magentoRoot + * @param string|null $ddevAppRoot + * @return array Container target => Host source + */ + private function parseDdevMounts(string $composePath, string $magentoRoot, ?string $ddevAppRoot): array + { + try { + if (!$this->fileDriver->isExists($composePath) || !$this->fileDriver->isReadable($composePath)) { + return []; + } + + $content = $this->fileDriver->fileGetContents($composePath); + } catch (FileSystemException) { + return []; + } + + if ($content === '') { + return []; + } + + $webSection = $this->extractWebServiceSection($content); + [$mounts, $namedVolumeTarget] = $this->extractVolumeEntries($webSection, $magentoRoot); + $approotHost = $this->extractDdevApprootLabel($webSection); + if ($approotHost === '') { + $approotHost = $this->extractDdevApprootLabel($content); + } + + if ($approotHost !== '') { + $fallbackRoot = $namedVolumeTarget !== '' ? $namedVolumeTarget : '/var/www/html'; + $appRootContainer = $this->normalizePath($ddevAppRoot ?? $fallbackRoot); + $canAddApproot = + $this->isAppContainerTarget($appRootContainer) + && $this->containsMagentoRoot($appRootContainer, $magentoRoot); + if ($canAddApproot && !isset($mounts[$appRootContainer])) { + $mounts[$appRootContainer] = $approotHost; + } + } + + return $mounts; + } + + /** + * Isolate the `services.web` block so mounts from `worker`/`db` services do not overwrite `web`. + * + * @param string $yamlContent + * @return string + */ + private function extractWebServiceSection(string $yamlContent): string + { + $lines = preg_split('/\R/', $yamlContent) ?: []; + $inServices = false; + $servicesIndent = 0; + $inWeb = false; + $webIndent = 0; + $collected = []; + + foreach ($lines as $line) { + if (preg_match('/^\s*(?:#.*)?$/', $line) === 1) { + if ($inWeb) { + $collected[] = $line; + } + continue; + } + + $indentMatch = null; + preg_match('/^(\s*)/', $line, $indentMatch); + $indent = strlen($indentMatch[1] ?? ''); + + if (!$inServices) { + if (preg_match('/^\s*services:\s*$/', $line) === 1) { + $inServices = true; + $servicesIndent = $indent; + } + continue; + } + + if ($indent <= $servicesIndent) { + break; + } + + if (!$inWeb) { + if (preg_match('/^\s*web:\s*$/', $line) === 1) { + $inWeb = true; + $webIndent = $indent; + $collected[] = $line; + } + continue; + } + + if ($indent <= $webIndent) { + break; + } + + $collected[] = $line; + } + + return $collected !== [] ? implode("\n", $collected) : $yamlContent; + } + + /** + * Extract `type: bind` mount pairs and the most specific named volume target containing Magento's root. + * + * @param string $yamlSection + * @param string $magentoRoot + * @return array{0: array, 1: string} + */ + private function extractVolumeEntries(string $yamlSection, string $magentoRoot): array + { + $lines = preg_split('/\R/', $yamlSection) ?: []; + $mounts = []; + $namedVolumeTarget = ''; + $inVolumeItem = false; + $itemIndent = 0; + $itemType = ''; + $itemSource = ''; + $itemTarget = ''; + + foreach ($lines as $line) { + $m = null; + if (preg_match('/^(\s*)-\s+type:\s*(.+)$/', $line, $m) === 1) { + $this->recordVolumeItem($mounts, $namedVolumeTarget, $itemType, $itemSource, $itemTarget, $magentoRoot); + $inVolumeItem = true; + $itemIndent = strlen($m[1]); + $itemType = $this->unquoteYamlScalar($m[2]); + $itemSource = ''; + $itemTarget = ''; + continue; + } + + if (!$inVolumeItem || preg_match('/^\s*(?:#.*)?$/', $line) === 1) { + continue; + } + + $indentMatch = null; + preg_match('/^(\s*)/', $line, $indentMatch); + $currentIndent = strlen($indentMatch[1] ?? ''); + if ($currentIndent <= $itemIndent) { + $this->recordVolumeItem($mounts, $namedVolumeTarget, $itemType, $itemSource, $itemTarget, $magentoRoot); + $inVolumeItem = false; + $itemType = ''; + $itemSource = ''; + $itemTarget = ''; + continue; + } + + if (preg_match('/^\s*source:\s*(.+)$/', $line, $m) === 1) { + $itemSource = $this->normalizePath($this->unquoteYamlScalar($m[1])); + } elseif (preg_match('/^\s*target:\s*(.+)$/', $line, $m) === 1) { + $itemTarget = $this->normalizePath($this->unquoteYamlScalar($m[1])); + } + } + + if ($inVolumeItem) { + $this->recordVolumeItem($mounts, $namedVolumeTarget, $itemType, $itemSource, $itemTarget, $magentoRoot); + } + + return [$mounts, $namedVolumeTarget]; + } + + /** + * Record a parsed volume item as either an app bind mount or a Mutagen volume containing Magento's root. + * + * @param array $mounts + * @param string $namedVolumeTarget + * @param string $type + * @param string $source + * @param string $target + * @param string $magentoRoot + * @phpstan-param array $mounts + * @phpstan-param-out array $mounts + * @return void + */ + private function recordVolumeItem( + array &$mounts, + string &$namedVolumeTarget, + string $type, + string $source, + string $target, + string $magentoRoot, + ): void { + if ($target === '' || !$this->isAppContainerTarget($target)) { + return; + } + + if ($type === 'bind' && $source !== '') { + $mounts[$target] = $source; + return; + } + + $isCandidateVolume = $type === 'volume' && $this->containsMagentoRoot($target, $magentoRoot); + if ($isCandidateVolume && strlen($target) > strlen($namedVolumeTarget)) { + $namedVolumeTarget = $target; + } + } + + /** + * Check whether the container mount target equals or contains Magento's root path. + * + * @param string $containerTarget + * @param string $magentoRoot + * @return bool + */ + private function containsMagentoRoot(string $containerTarget, string $magentoRoot): bool + { + if ($containerTarget === '' || $magentoRoot === '') { + return false; + } + + return $magentoRoot === $containerTarget || str_starts_with($magentoRoot, $containerTarget . '/'); + } + + /** + * Extract `com.ddev.approot` label for DDEV Mutagen setups where `/var/www/html` uses a named volume. + * + * @param string $yamlContent + * @return string + */ + private function extractDdevApprootLabel(string $yamlContent): string + { + $m = null; + if (preg_match('/^\s*com\.ddev\.approot:\s*(.+)$/m', $yamlContent, $m) !== 1) { + return ''; + } + + return $this->normalizePath($this->unquoteYamlScalar($m[1])); + } + + /** + * Match Magento's server root against the most specific container bind mount. + * + * @param string $magentoRoot + * @param array $bindMounts + * @phpstan-param array $bindMounts + * @return array{0: string, 1: string} + */ + private function resolveMagentoHostRoot(string $magentoRoot, array $bindMounts): array + { + if ($magentoRoot === '') { + return ['', '']; + } + + $targets = array_keys($bindMounts); + usort($targets, static fn(string $a, string $b): int => strlen($b) <=> strlen($a)); + + foreach ($targets as $target) { + if ($magentoRoot === $target || str_starts_with($magentoRoot, $target . '/')) { + $suffix = substr($magentoRoot, strlen($target)); + $source = $bindMounts[$target]; + + return [$this->normalizePath($source . $suffix), $target]; + } + } + + return ['', '']; + } + + /** + * Keep only application filesystem mount targets (excluding `/mnt/ddev_config`, `/etc`, etc.). + * + * @param string $target + * @return bool + */ + private function isAppContainerTarget(string $target): bool + { + foreach (self::APP_CONTAINER_PREFIXES as $prefix) { + $trimmed = rtrim($prefix, '/'); + if ($target === $trimmed || str_starts_with($target, $prefix)) { + return true; + } + } + + return false; + } + + /** + * Strip surrounding YAML quotes and trailing whitespace. + * + * @param string $raw + * @return string + */ + private function unquoteYamlScalar(string $raw): string + { + $trimmed = trim($raw); + $doubleQuoted = str_starts_with($trimmed, '"') && str_ends_with($trimmed, '"'); + $singleQuoted = str_starts_with($trimmed, "'") && str_ends_with($trimmed, "'"); + if (strlen($trimmed) >= 2 && ($doubleQuoted || $singleQuoted)) { + return substr($trimmed, 1, -1); + } + + return $trimmed; + } + + /** + * Normalize path separators and trim trailing slashes. + * + * @param string $path + * @return string + */ + private function normalizePath(string $path): string + { + $normalized = str_replace('\\', '/', trim($path)); + if ($normalized === '/') { + return '/'; + } + + return rtrim($normalized, '/'); + } + + /** + * Read environment variable safely from server/env inputs without discouraged functions. + * + * @param string $name + * @return string + */ + private function readEnvironmentVariable(string $name): string + { + /** @var string $serverVal */ + $serverVal = filter_input(INPUT_SERVER, $name, FILTER_UNSAFE_RAW) ?: ''; + if ($serverVal !== '') { + return $serverVal; + } + + /** @var string $envVal */ + $envVal = filter_input(INPUT_ENV, $name, FILTER_UNSAFE_RAW) ?: ''; + + return $envVal; + } +} diff --git a/src/etc/di.xml b/src/etc/di.xml index 3365a992..6490fffd 100644 --- a/src/etc/di.xml +++ b/src/etc/di.xml @@ -102,4 +102,11 @@ OpenForgeProject\MageForge\Service\NodePackageManager + + + + + Magento\Framework\Filesystem\Driver\File + + diff --git a/src/view/frontend/templates/inspector.phtml b/src/view/frontend/templates/inspector.phtml index 3de592b1..c0278daf 100644 --- a/src/view/frontend/templates/inspector.phtml +++ b/src/view/frontend/templates/inspector.phtml @@ -83,6 +83,8 @@ $alpineBootstrap = <<