CodeSampleX

Exemple

react-dom 19.2.8: Handle automatic document metadata hoisting, stylesheet precedence deduplication, and resource hints in react-dom/server across React 19

Échantillon vérifié pour npm react-dom 19.2.8: Handle automatic document metadata hoisting, stylesheet precedence deduplication, and resource hints in…

sha256:ffbf1189d6c67b17effd53b4f30bb520e3a01b2c792450fda6198ef4c832f34e

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré node linux x64 node node npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

Cas

HOW
Objectif
Handle automatic document metadata hoisting, stylesheet precedence deduplication, and resource hints in react-dom/server across React 19
Paquets
Symboles
  • react-dom/server.renderToString
  • react-dom.preload
  • react-dom.preinit
Environnement
node
Créé
2026-08-16T07:54:02Z

Contrat

  1. assert nested title and meta tags are hoisted out of container markup to the document root
  2. assert stylesheets with precedence are hoisted, formatted as data-precedence, and deduplicated across components
  3. assert stylesheets without precedence and non-async scripts remain inline in parent container
  4. assert imperative preload and preinit emit hoisted link and script tags ahead of markup

Fichiers

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/index.mjs
  • test/contract.mjs

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# React DOM Resource Hoisting & Metadata Trap

## CSX Search Result
- `search_known_solution` answered with existing samples `sha256:d2d2a344c3d423d5725df086dd3263d1813bf6519cd592f5302c538364efc8b2` (hydratable text node comments) and `sha256:059011629c7734f8ac38604635b6d097a2b80c286715c0bbcc0db022a73afa54` (duplicate React peer resolution); this sample tests the distinct React 19 resource hoisting and metadata deduplication boundary in `react-dom/server`.

## What a Model Would Have Written
A model would have assumed that `react-dom/server.renderToString` preserves the component hierarchy strictly in place, keeping `<title>`, `<meta>`, `<link>`, and `<script>` nested inside their parent JSX containers and emitting duplicate stylesheet tags verbatim.

## How the Wrong Version Fails
The wrong version fails silently with a green build: rendering succeeds without runtime errors, but `<title>`, `<meta>`, `<link rel="stylesheet" precedence="...">`, and `<script async>` are silently extracted from container subtrees, hoisted to the document root, deduplicated, and given `data-precedence` attributes, breaking container-scoped queries, HTML snapshot assertions, and DOM structure expectations.
csx.json
{"case":{"caseId":"case:sha256:08b5afa4573a17b0414217cecfc268de0f54fc21a1f659ac3016700f635df156","contract":["assert nested title and meta tags are hoisted out of container markup to the document root","assert stylesheets with precedence are hoisted, formatted as data-precedence, and deduplicated across components","assert stylesheets without precedence and non-async scripts remain inline in parent container","assert imperative preload and preinit emit hoisted link and script tags ahead of markup"],"goal":"Handle automatic document metadata hoisting, stylesheet precedence deduplication, and resource hints in react-dom/server across React 19","kind":"HOW","packages":["pkg:npm/react-dom@19.2.8","pkg:npm/react@19.2.8"],"schemaVersion":1,"symbols":["react-dom/server.renderToString","react-dom.preload","react-dom.preinit"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react-dom@19.2.8","pkg:npm/react@19.2.8"],"schemaVersion":1,"symbols":["react-dom/server.renderToString","react-dom.preload","react-dom.preinit"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-react-dom-version",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-react-dom-version",
      "version": "1.0.0",
      "dependencies": {
        "react": "19.2.8",
        "react-dom": "19.2.8"
      }
    },
    "node_modules/react": {
      "version": "19.2.8",
      "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
      "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
      "license": "MIT",
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/react-dom": {
      "version": "19.2.8",
      "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
      "integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==",
      "license": "MIT",
      "dependencies": {
        "scheduler": "^0.27.0"
      },
      "peerDependencies": {
        "react": "^19.2.8"
      }
    },
    "node_modules/scheduler": {
      "version": "0.27.0",
      "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
      "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "npm-react-dom-version",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "react": "19.2.8",
    "react-dom": "19.2.8"
  }
}
src/index.mjs
import React, { createElement as h } from 'react';
import ReactDOM, { preload, preinit } from 'react-dom';
import { renderToString } from 'react-dom/server';

/**
 * Renders nested articles that include title, meta, and stylesheet links with precedence.
 * In React 19, react-dom/server hoists and deduplicates these resources out of the container.
 */
export function renderArticleTree() {
  function CardA() {
    return h('article', { id: 'card-a' },
      h('title', null, 'Article A Title'),
      h('meta', { name: 'topic', content: 'alpha' }),
      h('link', { rel: 'stylesheet', href: 'https://example.com/shared.css', precedence: 'medium' }),
      h('p', null, 'Content A')
    );
  }

  function CardB() {
    return h('article', { id: 'card-b' },
      h('title', null, 'Article B Title'),
      h('link', { rel: 'stylesheet', href: 'https://example.com/shared.css', precedence: 'medium' }),
      h('link', { rel: 'stylesheet', href: 'https://example.com/unique-b.css', precedence: 'high' }),
      h('p', null, 'Content B')
    );
  }

  return renderToString(
    h('main', { id: 'feed' },
      h(CardA),
      h(CardB)
    )
  );
}

/**
 * Renders components containing both hoistable resources (link with precedence, script with async)
 * and non-hoistable elements (link without precedence, script without async).
 */
export function renderMixedResources() {
  function ResourceContainer() {
    return h('div', { id: 'resource-box' },
      // Hoistable resources
      h('link', { rel: 'stylesheet', href: 'https://example.com/hoisted.css', precedence: 'default' }),
      h('script', { async: true, src: 'https://example.com/hoisted.js' }),
      // Non-hoistable resources (remain inline)
      h('link', { rel: 'stylesheet', href: 'https://example.com/inline.css' }),
      h('script', { src: 'https://example.com/inline.js' }),
      h('span', null, 'Resource Box Text')
    );
  }

  return renderToString(h(ResourceContainer));
}

/**
 * Renders a component using react-dom's imperative resource loading hints (preload, preinit).
 */
export function renderWithResourceHints() {
  function ResourceHintsComponent() {
    preload('https://example.com/font.woff2', {
      as: 'font',
      type: 'font/woff2',
      crossOrigin: 'anonymous'
    });
    preinit('https://example.com/critical.js', { as: 'script' });

    return h('section', { id: 'hero' },
      h('h1', null, 'Hero Section')
    );
  }

  return renderToString(h(ResourceHintsComponent));
}
test/contract.mjs
import assert from 'node:assert/strict';
import {
  renderArticleTree,
  renderMixedResources,
  renderWithResourceHints
} from '../src/index.mjs';

// --- CONTRACT SUITE: React 19 Document Metadata & Resource Hoisting in react-dom/server ---

// Test 1: Nested metadata (<title>, <meta>) and stylesheets (<link precedence>) are hoisted and deduplicated
{
  const html = renderArticleTree();

  // Assertion 1.1: Shared stylesheet link with precedence is hoisted to the front and deduplicated
  // In React 18: emitted twice, inside #card-a and #card-b with attribute precedence="medium"
  // In React 19: emitted exactly once at document root with data-precedence="medium"
  const sharedMatches = html.match(/href="https:\/\/example\.com\/shared\.css"/g) || [];
  assert.equal(
    sharedMatches.length,
    1,
    `Shared stylesheet with precedence must be deduplicated across components: ${html}`
  );
  assert.ok(
    html.includes('<link rel="stylesheet" href="https://example.com/shared.css" data-precedence="medium"/>'),
    `precedence attribute must be serialized as data-precedence: ${html}`
  );
  assert.ok(
    html.includes('<link rel="stylesheet" href="https://example.com/unique-b.css" data-precedence="high"/>'),
    `Unique stylesheet with precedence must be hoisted: ${html}`
  );

  // Assertion 1.2: Title and meta tags are hoisted out of nested articles
  assert.ok(html.includes('<title>Article A Title</title>'), 'Title A must be present in hoisted output');
  assert.ok(html.includes('<title>Article B Title</title>'), 'Title B must be present in hoisted output');
  assert.ok(html.includes('<meta name="topic" content="alpha"/>'), 'Meta tag must be present in hoisted output');

  // Assertion 1.3: The container markup must NOT contain the hoisted elements
  // The <main id="feed"> subtree must only contain pure article content
  const mainSubtreeMatch = html.match(/<main id="feed">([\s\S]*?)<\/main>/);
  assert.ok(mainSubtreeMatch, 'Main container must be rendered');
  const mainSubtree = mainSubtreeMatch[1];

  assert.equal(
    mainSubtree,
    '<article id="card-a"><p>Content A</p></article><article id="card-b"><p>Content B</p></article>',
    'Container hierarchy must be stripped of hoisted metadata and precedence stylesheets'
  );

  // Assertion 1.4: Hoisted tags precede the <main> container in output order
  const mainIndex = html.indexOf('<main id="feed">');
  const linkIndex = html.indexOf('https://example.com/shared.css');
  const titleIndex = html.indexOf('Article A Title');
  assert.ok(linkIndex < mainIndex, 'Hoisted stylesheet must precede container HTML');
  assert.ok(titleIndex < mainIndex, 'Hoisted title must precede container HTML');
}

// Test 2: Selective hoisting based on precedence and async props
{
  const html = renderMixedResources();

  // Assertion 2.1: Precedence link and async script are hoisted OUTSIDE #resource-box
  const boxMatch = html.match(/<div id="resource-box">([\s\S]*?)<\/div>/);
  assert.ok(boxMatch, 'Resource box container must be rendered');
  const boxInner = boxMatch[1];

  // Hoisted elements are NOT inside #resource-box
  assert.ok(
    !boxInner.includes('hoisted.css'),
    'Link with precedence must NOT be inside container'
  );
  assert.ok(
    !boxInner.includes('hoisted.js'),
    'Script with async must NOT be inside container'
  );

  // Non-hoistable elements MUST remain inline inside #resource-box
  assert.ok(
    boxInner.includes('<link rel="stylesheet" href="https://example.com/inline.css"/>'),
    'Link without precedence must remain inline inside container'
  );
  assert.ok(
    boxInner.includes('<script src="https://example.com/inline.js"></script>'),
    'Script without async must remain inline inside container'
  );
  assert.ok(
    boxInner.includes('<span>Resource Box Text</span>'),
    'Child elements must remain inside container'
  );

  // Assertion 2.2: Hoisted elements appear before #resource-box at the root level
  const boxIndex = html.indexOf('<div id="resource-box">');
  const hoistedLinkIndex = html.indexOf('https://example.com/hoisted.css');
  const hoistedScriptIndex = html.indexOf('https://example.com/hoisted.js');

  assert.ok(hoistedLinkIndex < boxIndex, 'Hoisted link must precede container');
  assert.ok(hoistedScriptIndex < boxIndex, 'Hoisted script must precede container');
}

// Test 3: Imperative resource hints (preload, preinit) from react-dom
{
  const html = renderWithResourceHints();

  // Assertion 3.1: preload() emits <link rel="preload"> at the document root
  assert.ok(
    html.includes('<link rel="preload" href="https://example.com/font.woff2" as="font" crossorigin="" type="font/woff2"/>'),
    `preload() must inject <link rel="preload"> with attributes: ${html}`
  );

  // Assertion 3.2: preinit() emits <script async=""> at the document root
  assert.ok(
    html.includes('<script src="https://example.com/critical.js" async=""></script>'),
    `preinit() must inject <script async="">: ${html}`
  );

  // Assertion 3.3: Injected resource hints precede the rendered component JSX
  const heroIndex = html.indexOf('<section id="hero">');
  const fontPreloadIndex = html.indexOf('font.woff2');
  const scriptPreinitIndex = html.indexOf('critical.js');

  assert.ok(fontPreloadIndex < heroIndex, 'Preloaded font must precede component markup');
  assert.ok(scriptPreinitIndex < heroIndex, 'Preinited script must precede component markup');
}

console.log('CONTRACT PASS: react-dom/server resource hoisting, deduplication, and hint injection verified');

Seeder d'origine

csx-seed