Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 89 additions & 25 deletions src/Model/TemplateEngine/Decorator/InspectorHints.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,47 @@
*/
class InspectorHints implements TemplateEngineInterface
{
/**
* Non-visual, document-level, or CSP-governed HTML elements that must never
* receive data-mageforge-* attributes.
*
* Under strict CSP (W3C CSP3 § 6.7.2.2 "Is element nonceable?"), <script> and
* <style> elements become non-nonceable and are blocked by the browser whenever
* wrapper templates (e.g. $block->fetchView() or container.phtml) cause a
* duplicate-attribute parse error on them.
*/
private const NON_INSPECTABLE_TAGS = [
'base',
'body',
'head',
'html',
'link',
'meta',
'noscript',
'script',
'style',
'template',
'title',
];

/**
* Quote-aware pattern matching the opening tag of the first root HTML element.
*
* Group 1: leading whitespace + '<' + tag name
* Group 2: tag name
* Group 3: existing attributes (and optional trailing '/') up to '>'
*/
private const ROOT_REGEX = '/^(\s*<([a-zA-Z][a-zA-Z0-9-]*))(?=\s|\/|>)((?:[^>"\']++|"[^"]*+"|\'[^\']*+\')*+)>/s';

/**
* Quote-aware pattern matching individual HTML attributes inside an opening tag.
*
* Group 1 captures each attribute name while consuming any quoted or unquoted
* attribute value (including `/` in unquoted URLs per HTML5 § 13.2.5.38) so
* `data-mageforge-id` substrings inside attribute values are ignored.
*/
private const ATTR_REGEX = '/([^\s=\/>"\']++)(?:\s*+=\s*+(?:"[^"]*+"|\'[^\']*+\'|[^\s>]*+))?/s';

/**
* @var string
*/
Expand Down Expand Up @@ -170,6 +211,26 @@ private function injectInspectorAttributes(
string $templateFile,
array $renderMetrics,
): string {
// Match the opening tag of the first root HTML element before collecting
// block/cache metadata. If content doesn't start with an inspectable HTML
// element (e.g. plain text, URLs, <script>/<style> blocks, or an element
// already annotated by an inner template via fetchView()/getChildHtml()),
// skip injection to avoid corrupting markup or invalidating strict CSP nonces.
$matches = [];
if (preg_match(self::ROOT_REGEX, $html, $matches) !== 1) {
return $html;
}

$tagName = strtolower($matches[2]);
if (in_array($tagName, self::NON_INSPECTABLE_TAGS, true)) {
return $html;
}

$existingAttributes = $matches[3];
if ($this->hasInspectorAttribute($existingAttributes)) {
return $html;
}

$wrapperId = 'mageforge-' . $this->random->getRandomString(16);

// Get block class name
Expand Down Expand Up @@ -221,35 +282,38 @@ private function injectInspectorAttributes(
// so JSON.parse() on the JS side will receive the correct string.
$safeJson = $this->escaper->escapeHtml($jsonMetadata);

// Inject data-mageforge-* attributes on the first root HTML element.
// This avoids HTML comment nodes which corrupt markup when block output is
// embedded inside HTML attribute values (e.g. PageBuilder URL blocks in href="...").
$replaced = false;
$result = preg_replace_callback(
'/^(\s*<[a-zA-Z][a-zA-Z0-9-]*)/s',
static function (array $matches) use ($wrapperId, $safeJson, &$replaced): string {
$replaced = true;
return (
$matches[0]
. ' data-mageforge-id="'
. $wrapperId
. '"'
. ' data-mageforge-block="'
. $safeJson
. '"'
);
},
$html,
1,
return sprintf(
'%s data-mageforge-id="%s" data-mageforge-block="%s"%s>%s',
$matches[1],
$wrapperId,
$safeJson,
$existingAttributes,
substr($html, strlen($matches[0])),
);
}

// If content doesn't start with an HTML element (e.g. plain text, URLs),
// skip injection to avoid corrupting attribute values in parent templates.
if (!$replaced || $result === null) {
return $html;
/**
* Check whether the opening tag already carries a MageForge inspector attribute
*
* @param string $existingAttributes
* @return bool
*/
private function hasInspectorAttribute(string $existingAttributes): bool
{
$attributeMatches = [];
$matchCount = preg_match_all(self::ATTR_REGEX, $existingAttributes, $attributeMatches);
if ($matchCount === false || $matchCount === 0) {
return false;
}

foreach ($attributeMatches[1] as $attributeName) {
$normalizedName = strtolower($attributeName);
if ($normalizedName === 'data-mageforge-id' || $normalizedName === 'data-mageforge-block') {
return true;
}
}

return $result;
return false;
}

/**
Expand Down
65 changes: 13 additions & 52 deletions src/view/frontend/templates/inspector.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -2,74 +2,33 @@

declare(strict_types=1);

use Magento\Framework\Escaper;
use OpenForgeProject\MageForge\Block\Inspector;

/**
* MageForge Inspector Template
*
* Initializes the Alpine.js inspector component.
* The floating button and info badge are created dynamically via JavaScript.
*
* Note: Loads bundled Alpine.js locally as fallback if not already available
* (e.g. for non-Hyvä themes like Luma). No external CDN is used.
* Initializes the Alpine.js toolbar and inspector components without inline
* scripts or inline styles so strict CSP pages (e.g. Hyvä Checkout) remain
* unaffected. Existing Alpine.js instances (`typeof Alpine !== 'undefined'`)
* are detected in `alpine-loader.js` before loading the local fallback bundle.
*
* @var \OpenForgeProject\MageForge\Block\Inspector $block
* @var Inspector $block
* @var Escaper $escaper
*/
?>
<!-- MageForge Inspector Assets -->
<link rel="stylesheet" type="text/css" href="<?= $escaper->escapeUrl($block->getToolbarCssUrl()) ?>" />
<link rel="stylesheet" type="text/css" href="<?= $escaper->escapeUrl($block->getCssUrl()) ?>" />

<!-- Alpine.js Bootstrap (load local fallback only if not already present) -->
<?php

$alpineJsUrl = json_encode($block->getAlpineJsUrl(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
$alpineBootstrap = <<<JS
(function() {
'use strict';

function loadAlpineLocally() {
// Check if Alpine.js is already loaded (Hyvä themes) to avoid conflicts
if (typeof Alpine !== 'undefined') {
console.log('[MageForge Inspector] Alpine.js already loaded');
return;
}

console.log('[MageForge Inspector] Loading bundled Alpine.js');

var alpineScript = document.createElement('script');
alpineScript.src = {$alpineJsUrl};
alpineScript.onload = function() {
console.log('[MageForge Inspector] Alpine.js loaded successfully');
};
alpineScript.onerror = function() {
console.error('[MageForge Inspector] Failed to load bundled Alpine.js');
};

document.head.appendChild(alpineScript);
}

// Use a short microtask delay after DOMContentLoaded so that all deferred
// and module scripts (including Hyvä's Alpine bundle) have had a chance to
// run before we decide to load the local Alpine fallback.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function() {
// setTimeout(0) yields to the script queue, giving defer/module
// scripts priority over this local fallback.
setTimeout(loadAlpineLocally, 0);
});
} else {
setTimeout(loadAlpineLocally, 0);
}
})();
JS;
?>
<?= /* @noEscape */ $secureRenderer->renderTag('script', [], $alpineBootstrap, false) ?>

<script type="module" src="<?= $escaper->escapeUrl($block->getToolbarJsUrl()) ?>"></script>
<script type="module" src="<?= $escaper->escapeUrl($block->getJsUrl()) ?>"></script>

<!-- MageForge Toolbar Component -->
<div class="mageforge-toolbar-root"
x-ignore
x-data="mageforgeToolbar"
data-alpine-url="<?= $escaper->escapeUrl($block->getAlpineJsUrl()) ?>"
data-theme="<?= $escaper->escapeHtmlAttr($block->getTheme()) ?>"
data-position="<?= $escaper->escapeHtmlAttr($block->getPosition()) ?>"
data-show-labels="<?= (int) $block->getShowButtonLabels() ?>"
Expand All @@ -78,7 +37,9 @@ $alpineBootstrap = <<<JS

<!-- MageForge Inspector Component Wrapper -->
<div class="mageforge-inspector"
x-ignore
x-data="mageforgeInspector"
data-alpine-url="<?= $escaper->escapeUrl($block->getAlpineJsUrl()) ?>"
data-theme="<?= $escaper->escapeHtmlAttr($block->getTheme()) ?>"
data-keyboard-shortcuts-enabled="<?= (int) $block->getKeyboardShortcutsEnabled() ?>"
data-shortcut="<?= $escaper->escapeHtmlAttr($block->getInspectorShortcut()) ?>"
Expand Down
4 changes: 4 additions & 0 deletions src/view/frontend/web/css/inspector.css
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,10 @@
color: var(--mageforge-color-red);
}

.mageforge-note-title {
font-weight: 600;
}

.mageforge-tag-list {
display: flex;
flex-wrap: wrap;
Expand Down
134 changes: 134 additions & 0 deletions src/view/frontend/web/js/alpine-loader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/**
* CSP-safe Alpine.js component bootstrap and local fallback loader.
*
* Keeps `inspector.phtml` free of inline `<script>` blocks and prevents
* `@alpinejs/csp` (used by Hyvä Checkout under strict CSP) from evaluating
* `x-data` on MageForge root elements before their `Alpine.data()` factories
* have been registered.
*/

const LOCAL_ALPINE_URL = new URL("./lib/alpine.min.js", import.meta.url).href;
const ALPINE_RUNTIME_FILE_PATTERN =
/^alpine(?:js)?(?:\d+)?(?:-csp|\.csp)?(?:\.esm)?(?:\.min)?\.m?js$/i;
const ALPINE_PACKAGE_PATH_PATTERN = /\/(?:@alpinejs\/csp|alpinejs)(?:@|\/)/i;

let fallbackScheduled = false;

function isAlpineRuntimeScript(script) {
const rawSrc = script.getAttribute("src");
if (!rawSrc || rawSrc.includes("OpenForgeProject_MageForge/")) {
return false;
}

try {
const pathname = new URL(rawSrc, window.location.href).pathname;
const filename = pathname.split("/").pop() || "";
return (
ALPINE_RUNTIME_FILE_PATTERN.test(filename) ||
ALPINE_PACKAGE_PATH_PATTERN.test(pathname)
);
} catch {
return false;
}
}

function findCandidateAlpineScripts() {
return Array.from(
document.querySelectorAll(
"script[src]:not([data-mageforge-alpine-fallback])",
),
).filter(isAlpineRuntimeScript);
}

function injectLocalAlpineFallback() {
if (
typeof window.Alpine !== "undefined" ||
document.querySelector("script[data-mageforge-alpine-fallback]")
) {
return;
}

const alpineScript = document.createElement("script");
alpineScript.src = LOCAL_ALPINE_URL;
alpineScript.defer = true;
alpineScript.setAttribute("data-mageforge-alpine-fallback", "1");
alpineScript.onerror = () => {
console.error("[MageForge Inspector] Failed to load bundled Alpine.js");
};
document.head.appendChild(alpineScript);
}

function resolveAlpineOrLoadFallback() {
if (typeof window.Alpine !== "undefined") {
return;
}

const candidates = findCandidateAlpineScripts();
if (candidates.length === 0 || document.readyState === "complete") {
injectLocalAlpineFallback();
return;
}

const recheckAfterLoad = () => setTimeout(injectLocalAlpineFallback, 0);
candidates.forEach((script) => {
script.addEventListener("load", recheckAfterLoad, { once: true });
script.addEventListener("error", recheckAfterLoad, { once: true });
});
window.addEventListener("load", recheckAfterLoad, { once: true });
}

/**
* Load the bundled local Alpine.js script only when the active theme does not
* provide Alpine.js itself (e.g. Luma / Blank).
*/
export function ensureAlpineFallback() {
if (fallbackScheduled || typeof window.Alpine !== "undefined") {
return;
}
fallbackScheduled = true;

const scheduleCheck = () => setTimeout(resolveAlpineOrLoadFallback, 0);
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", scheduleCheck, {
once: true,
});
} else {
scheduleCheck();
}
}

/**
* Register an Alpine.data() component and initialize matching `[x-data]` roots
* regardless of whether Alpine.js (standard or CSP build) executes before or
* after this ES module.
*
* @param {string} name
* @param {() => object} factory
*/
export function bootstrapAlpineComponent(name, factory) {
const selector = `[x-data="${name}"]`;
ensureAlpineFallback();

const registerAndUnignore = () => {
Alpine.data(name, factory);
document.querySelectorAll(selector).forEach((el) => {
el.removeAttribute("x-ignore");
delete el._x_ignore;
});
};

if (typeof Alpine !== "undefined") {
registerAndUnignore();
queueMicrotask(() => {
document.querySelectorAll(selector).forEach((el) => {
if (!el._x_dataStack && typeof Alpine.initTree === "function") {
Alpine.initTree(el);
}
});
});
} else {
document.addEventListener("alpine:init", registerAndUnignore, {
once: true,
});
}
}
Loading
Loading