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
2 changes: 1 addition & 1 deletion php-transformer/src/ArtifactCompiler/ArtifactCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ private function finalizeArtifact(array $artifact, array $reduction): Transforme
if ( array() !== $entryBlocks['superseded_selectors'] ) {
$sourceReports['superseded_selectors'] = $entryBlocks['superseded_selectors'];
}
$sourceReports['runtime_dependency_parity'] = ( new RuntimeDependencyParityReport() )->fromArtifact($normalized['files'], $html, $serializedBlocks, $entryPath, $entryBlocks['runtime_islands'], $referenceReports['asset_references'], $entryBlocks['interaction_candidates'], $entryBlocks['superseded_selectors']);
$sourceReports['runtime_dependency_parity'] = ( new RuntimeDependencyParityReport() )->fromArtifact($normalized['files'], $html, $serializedBlocks, $entryPath, $entryBlocks['runtime_islands'], $referenceReports['asset_references'], $entryBlocks['interaction_candidates'], $entryBlocks['superseded_selectors'], $allGeneratedBlocks);
foreach ($sourceReports['runtime_dependency_parity']['findings'] ?? array() as $finding) {
if ('runtime_dependency_target_missing' !== ($finding['code'] ?? '') || 'telemetry' === ($finding['script_kind'] ?? '')) {
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ final class RuntimeDependencyParityReport
* as an acceptable, superseded loss rather than a materialization bug.
* @return array<string, mixed>
*/
public function fromArtifact(array $files, string $sourceHtml, string $generatedHtml, string $sourcePath = '', array $runtimeIslands = array(), array $assetReferences = array(), array $interactionCandidates = array(), array $supersededSelectors = array()): array
public function fromArtifact(array $files, string $sourceHtml, string $generatedHtml, string $sourcePath = '', array $runtimeIslands = array(), array $assetReferences = array(), array $interactionCandidates = array(), array $supersededSelectors = array(), array $generatedBlocks = array()): array
{
$sourceTargets = $this->sourceTargets($sourceHtml, $sourcePath);
$generatedTargets = $this->withBlockCommentAnchorTargets(
Expand All @@ -52,9 +52,10 @@ public function fromArtifact(array $files, string $sourceHtml, string $generated
$findings = array();
$flaggedSelectors = array();
$bundleCanvasSelectors = $this->bundleCanvasSelectors($files, $sourceTargets);
$companionTargets = $this->htmlTargets($this->declaredCompanionRenderHtml($generatedBlocks));

foreach ( $files as $file ) {
if ( ! $this->isScriptFile($file) ) {
if ( ! $this->isScriptFile($file) || ! $this->scriptAppliesToSource($file, $sourcePath) ) {
continue;
}

Expand All @@ -68,7 +69,7 @@ public function fromArtifact(array $files, string $sourceHtml, string $generated
foreach ( $this->scriptDependencies($script, $bundleCanvasSelectors) as $dependency ) {
$selector = (string) $dependency['selector'];
$target = $sourceTargets[$selector] ?? array();
$exists = $this->targetExists($dependency, $generatedTargets);
$exists = $this->targetExists($dependency, $generatedTargets) || $this->targetExists($dependency, $companionTargets);
$canvasApi = true === $dependency['canvas_api'] && 'canvas' === ($target['tag'] ?? '');
$dependencyRow = array_filter(array(
'source_path' => $target['source_path'] ?? $sourcePath,
Expand All @@ -83,6 +84,7 @@ public function fromArtifact(array $files, string $sourceHtml, string $generated
'canvas_api' => $canvasApi,
'source_present' => array() !== $target,
'generated_present' => $exists,
'generated_target_evidence' => $this->targetExists($dependency, $companionTargets) ? 'declared_companion_render' : '',
'disposition' => $this->isSupersededSelector($selector, $superseded) ? self::DISPOSITION_SUPERSEDED : '',
), static fn (mixed $value): bool => null !== $value && '' !== $value && array() !== $value);
$dependencies[] = $dependencyRow;
Expand Down Expand Up @@ -163,6 +165,41 @@ public function fromArtifact(array $files, string $sourceHtml, string $generated
return $report;
}

/**
* Page-owned scripts are evaluated only against the page which owns them.
* Shared scripts intentionally retain their cross-page parity behavior.
*
* @param array<string, mixed> $file
*/
private function scriptAppliesToSource(array $file, string $sourcePath): bool
{
$ownership = $file['metadata']['compilation'] ?? null;
if ( ! is_array($ownership) || 'page' !== ($ownership['scope'] ?? null) ) {
return true;
}

return is_string($ownership['id'] ?? null) && $sourcePath === $ownership['id'];
}

/**
* Exact companion render strings are server-rendered DOM contracts only when
* the generated block explicitly declares its static render file.
*
* @param array<int, array<string, mixed>> $generatedBlocks
*/
private function declaredCompanionRenderHtml(array $generatedBlocks): string
{
$renders = array();
foreach ( $generatedBlocks as $block ) {
if ( ! is_array($block) || 'file:./render.php' !== ($block['block_json']['render'] ?? null) || ! is_string($block['render'] ?? null) ) {
continue;
}
$renders[] = $block['render'];
}

return implode("\n", $renders);
}

/**
* Detect source-declared client-script execution dependencies (referenced
* external `<script src>` islands flagged `client_script_execution`) whose
Expand Down
45 changes: 45 additions & 0 deletions php-transformer/src/HtmlToBlocks/HtmlTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5123,6 +5123,13 @@ private function convertElement(DOMElement $element, array &$fallbacks, bool $ca

if ( 'script' === $tagName ) {
if ( $this->captureStaticScriptMetadata($element) ) {
if ( $this->isAddressableStaticJsonTarget($element) ) {
$this->recordRuntimeIsland($element, 'static_script', 'static_script_runtime_target', 'client_script_configuration', array(
'script_role' => 'data',
'required_scripts' => $this->requiredScriptsForElement($element),
));
return $this->staticJsonTargetBlock($element);
}
return null;
}

Expand Down Expand Up @@ -12481,6 +12488,44 @@ private function captureStaticScriptMetadata(DOMElement $element): bool
return $this->fallbackEmitter->captureStaticScriptMetadata($element, $this->scriptMetadata);
}

/**
* Keep a static JSON script in the page only when a carried runtime script
* addresses its id. JSON script types never execute, unlike static JavaScript
* assignments that remain metadata-only.
*/
private function isAddressableStaticJsonTarget(DOMElement $element): bool
{
$id = trim($this->attr($element, 'id'));
$type = strtolower(trim($this->attr($element, 'type')));
if ( '' === $id || ! in_array($type, array('application/json', 'application/ld+json'), true) || ! isset($this->runtimeDomSelectors['#' . $id]) ) {
return false;
}

$metadata = end($this->scriptMetadata);
if ( ! is_array($metadata) || ! empty($metadata['body_truncated']) ) {
return false;
}

return null !== json_decode((string) ($metadata['body'] ?? ''), true);
}

private function staticJsonTargetBlock(DOMElement $element): array
{
$metadata = end($this->scriptMetadata);
$attributes = is_array($metadata['attributes'] ?? null) ? $metadata['attributes'] : array();
ksort($attributes, SORT_STRING);
$attributeHtml = '';
foreach ( $attributes as $name => $value ) {
if ( ! is_string($name) || ! is_string($value) ) {
continue;
}
$attributeHtml .= ' ' . $name . '="' . htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"';
}
$body = str_replace('</script', '<\\/script', (string) ($metadata['body'] ?? ''));

return $this->createBlock('core/html', array('content' => '<script' . $attributeHtml . '>' . $body . '</script>'), array(), $element);
}

/**
* @param array<int, array<string, mixed>> $fallbacks
*/
Expand Down
41 changes: 41 additions & 0 deletions php-transformer/tests/contract/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -3483,6 +3483,47 @@ public function recognize(DOMElement $element, PatternContext $context): ?Patter
'runtime dependency parity does not fail entry output for shared drum script selectors absent from that entry source'
);

$staticJsonRuntimeSite = $compiler->compile(
array(
'entrypoint' => 'index.html',
'files' => array(
'index.html' => '<main><script id="config" type="application/json">{"message":"Ready"}</script><script src="js/app.js"></script><h1>Home</h1></main>',
'js/app.js' => 'JSON.parse(document.getElementById("config").textContent).message;',
),
)
)->toArray();
$staticJsonRuntimeMarkup = (string) ($staticJsonRuntimeSite['serialized_blocks'] ?? '');
$staticJsonRuntimeDependency = array_values(array_filter($staticJsonRuntimeSite['source_reports']['runtime_dependency_parity']['dependencies'] ?? array(), static fn (array $dependency): bool => '#config' === ($dependency['selector'] ?? '')))[0] ?? array();
$assert('pass' === ($staticJsonRuntimeSite['source_reports']['runtime_dependency_parity']['status'] ?? '') && true === ($staticJsonRuntimeDependency['generated_present'] ?? null), 'ID-addressed static JSON remains an addressable runtime target for carried first-party scripts');
$assert(str_contains($staticJsonRuntimeMarkup, '<script id="config" type="application/json">{"message":"Ready"}</script>'), 'addressable static JSON is preserved as bounded non-executable block markup');
$assert(1 === count(array_filter($staticJsonRuntimeSite['source_reports']['runtime_islands'] ?? array(), static fn (array $island): bool => 'static_script' === ($island['kind'] ?? ''))), 'addressable static JSON target is recorded as a runtime configuration island');

$companionRenderReport = (new \Automattic\BlocksEngine\PhpTransformer\ArtifactCompiler\RuntimeDependencyParityReport())->fromArtifact(
array(array('path' => 'js/app.js', 'kind' => 'js', 'content' => 'document.querySelector("a[data-anchor]").addEventListener("click", function () {});')),
'<main><a data-anchor="docs">Docs</a></main>',
'<!-- wp:custom/companion /-->',
'index.html',
array(),
array(),
array(),
array(),
array(array('block_json' => array('render' => 'file:./render.php'), 'render' => '<a data-anchor="docs">Docs</a>'))
);
$companionRenderDependency = $companionRenderReport['dependencies'][0] ?? array();
$assert('pass' === ($companionRenderReport['status'] ?? '') && true === ($companionRenderDependency['generated_present'] ?? null) && 'declared_companion_render' === ($companionRenderDependency['generated_target_evidence'] ?? ''), 'declared exact companion render HTML supplies data-attribute target evidence');
$undeclaredCompanionRenderReport = (new \Automattic\BlocksEngine\PhpTransformer\ArtifactCompiler\RuntimeDependencyParityReport())->fromArtifact(
array(array('path' => 'js/app.js', 'kind' => 'js', 'content' => 'document.querySelector("a[data-anchor]").addEventListener("click", function () {});')),
'<main><a data-anchor="docs">Docs</a></main>',
'<!-- wp:custom/companion /-->',
'index.html',
array(),
array(),
array(),
array(),
array(array('block_json' => array(), 'render' => '<a data-anchor="docs">Docs</a>'))
);
$assert('warning' === ($undeclaredCompanionRenderReport['status'] ?? '') && 'runtime_dependency_target_missing' === ($undeclaredCompanionRenderReport['findings'][0]['code'] ?? ''), 'undeclared companion render strings cannot suppress missing-target failures');

$hamburgerOverlaySite = $compiler->compile(
array(
'entrypoint' => 'index.html',
Expand Down
14 changes: 14 additions & 0 deletions php-transformer/tests/contract/staged-artifact-compilation.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,20 @@
$assert($canonical($manyInline) === $canonical($manyStaged), 'Fifty-page arbitrary-order resume preserves the complete canonical transformer result after observational fields are excluded.');
$manyPageComponent = current(array_filter($manyStaged['components'], static fn(array $component): bool => 'page' === ($component['name'] ?? null)));
$assert(50 === ($manyPageComponent['occurrences'] ?? null), 'A class occurring once per page is qualified from the globally summed uncapped component facts.');
$pageScopedScriptArtifact = array('entrypoint' => 'index.html', 'files' => array(
array('path' => 'index.html', 'content' => '<main id="home-target"><script src="js/home.js"></script><h1>Home</h1></main>'),
array('path' => 'about.html', 'content' => '<main id="about-target"><script src="js/about.js"></script><h1>About</h1></main>'),
array('path' => 'js/home.js', 'content' => 'document.getElementById("home-target").addEventListener("click", function () {});', 'metadata' => array('compilation' => array('scope' => 'page', 'id' => 'index.html'))),
array('path' => 'js/about.js', 'content' => 'document.getElementById("about-target").addEventListener("click", function () {});', 'metadata' => array('compilation' => array('scope' => 'page', 'id' => 'about.html'))),
));
$pageScopedWhole = $compiler->compile($pageScopedScriptArtifact)->toArray();
$pageScopedShared = $compiler->prepareShared($pageScopedScriptArtifact);
$pageScopedReceipts = array();
foreach ($pageScopedShared['analysis']['page_ids'] as $pageId) $pageScopedReceipts[] = $compiler->compilePage($pageScopedScriptArtifact, $pageScopedShared, $pageId);
$pageScopedStaged = $compiler->compose($pageScopedShared, array_reverse($pageScopedReceipts))->toArray();
$pageScopedDependencies = $pageScopedWhole['source_reports']['runtime_dependency_parity']['dependencies'] ?? array();
$assert('pass' === ($pageScopedWhole['source_reports']['runtime_dependency_parity']['status'] ?? '') && array() === array_values(array_filter($pageScopedDependencies, static fn (array $dependency): bool => 'js/about.js' === ($dependency['script_path'] ?? ''))), 'page-owned scripts are not evaluated against another page output');
$assert($canonical($pageScopedWhole) === $canonical($pageScopedStaged), 'page-owned script parity remains deterministic for staged receipt composition.');
$componentArtifact = array('entrypoint' => 'index.html', 'files' => array(
array('path' => 'index.html', 'content' => '<main class="distributed-widget"><h1>Home</h1></main>'),
array('path' => 'second.html', 'content' => '<main class="distributed-widget"><h1>Second</h1></main>'),
Expand Down
Loading