CodeSampleX

示例

react-dom 19.0.0: preconnect

已验证示例 — npm react-dom 19.0.0: preconnect. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: preconnect is exported as a function from react-dom

sha256:c15a5f2a726b241e18fef45f3a30ae27b310e64e63d5af2ac1af5cb027a52346

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

案例

HOW
目标
verify react-dom.preconnect in pkg:npm/react-dom@19.0.0
包
符号
  • react-dom.preconnect
环境
node 22.23.2
创建时间
2026-09-06T22:47:50Z

契约

  1. preconnect is exported as a function from react-dom
  2. preconnect emits hoisted link rel preconnect in ReactDOMServer renderToStaticMarkup
  3. preconnect supports crossOrigin options anonymous and use-credentials during SSR
  4. duplicate preconnect calls across components in the render tree are deduplicated during SSR
  5. preconnect injects link rel preconnect elements into document.head during client root render
  6. duplicate preconnect calls during client root render are deduplicated in document.head

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# React 19 react-dom.preconnect Contract Verification

## Prior CSX search
`search_known_solution` returned `NO_SAFE_MATCH` for explicit verification of `react-dom.preconnect` in `pkg:npm/react-dom@19.0.0`. While existing samples verified other React 19 DOM capabilities (e.g. `createRoot`, `hydrateRoot`, and broad multi-API resource preloading), this sample establishes a minimal, clean contract for `preconnect`.

## The tempting wrong model
1. Assuming `preconnect` requires manual DOM manipulation (e.g. `document.createElement('link')`) or third-party `<head>` management packages like `react-helmet`.
2. Assuming redundant `preconnect` calls across sibling or nested components will emit duplicated `<link rel="preconnect">` elements in SSR markup or `document.head`.
3. Expecting `preconnect(href)` called outside an active React rendering cycle to mutate DOM head elements immediately (it requires an active render context).
4. Forgetting that `crossOrigin: "anonymous"` emits `crossorigin=""` on the `<link>` element in HTML/DOM.

## Observable failure and verified behavior
- Calling `preconnect(href)` or `preconnect(href, { crossOrigin })` during SSR automatically hoists `<link rel="preconnect">` tags to the start of the output HTML markup.
- In client DOM rendering, calling `preconnect` during root rendering dynamically injects the appropriate `<link rel="preconnect">` element into `document.head`.
- Duplicate calls for the exact same destination URL (and options) within the render tree are deduplicated by the React 19 DOM runtime in both SSR and client environments.
- The `crossOrigin` option properly distinguishes between `'anonymous'` (yielding `crossorigin=""`) and `'use-credentials'` (yielding `crossorigin="use-credentials"`).
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify react-dom.preconnect in pkg:npm/react-dom@19.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/react-dom@19.0.0
Demonstrate these symbols/APIs:
  - react-dom.preconnect
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:ae70ee3415bfcbdfbae3d50610a1d941f2d610063716fa4a4563439f13f32aa3","constraints":{"executionContext":"node"},"contract":["preconnect is exported as a function from react-dom","preconnect emits hoisted link rel preconnect in ReactDOMServer renderToStaticMarkup","preconnect supports crossOrigin options anonymous and use-credentials during SSR","duplicate preconnect calls across components in the render tree are deduplicated during SSR","preconnect injects link rel preconnect elements into document.head during client root render","duplicate preconnect calls during client root render are deduplicated in document.head"],"goal":"verify react-dom.preconnect in pkg:npm/react-dom@19.0.0","kind":"HOW","packages":["pkg:npm/react-dom@19.0.0"],"schemaVersion":1,"symbols":["react-dom.preconnect"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react-dom@19.0.0"],"schemaVersion":1,"subject":"pkg:npm/react-dom@19.0.0","symbols":["react-dom.preconnect"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-react-dom-preconnect",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-react-dom-preconnect",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "react": "19.0.0",
        "react-dom": "19.0.0"
      }
    },
    "node_modules/react": {
      "version": "19.0.0",
      "resolved": "https://registry.npmjs.org/react/-/react-19.0.0.tgz",
      "integrity": "sha512-V8AVnmPIICiWpGfm6GLzCR/W5FXLchHop40W4nXBmdlEceh16rCN8O8LNWm5bh5XUX91fh7KpA+W0TgMKmgTpQ==",
      "license": "MIT",
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/react-dom": {
      "version": "19.0.0",
      "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.0.0.tgz",
      "integrity": "sha512-4GV5sHFG0e/0AD4X+ySy6UJd3jVl1iNsNHdpad0qhABJ11twS3TTBnseqsKurKcsNqCEFeGL3uLpVChpIO3QfQ==",
      "license": "MIT",
      "dependencies": {
        "scheduler": "^0.25.0"
      },
      "peerDependencies": {
        "react": "^19.0.0"
      }
    },
    "node_modules/scheduler": {
      "version": "0.25.0",
      "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.25.0.tgz",
      "integrity": "sha512-xFVuu11jh+xcO7JOAGJNOXld8/TcEHK/4CituBUeUb5hqxJLj9YuemAEuvm9gQ/+pgXYfbQuqAkiYu+u7YEsNA==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-react-dom-preconnect",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "react": "19.0.0",
    "react-dom": "19.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify react-dom.preconnect in pkg:npm/react-dom@19.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/react-dom@19.0.0"
  ],
  "symbols": [
    "react-dom.preconnect"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "runtime": "node@22.23.2"
  }
}
src/index.mjs
import React from 'react';
import { preconnect } from 'react-dom';

/**
 * Component that registers a preconnect resource hint during rendering.
 *
 * @param {object} props
 * @param {string} props.href - Destination origin URL to establish early connection to.
 * @param {'anonymous' | 'use-credentials'} [props.crossOrigin] - Cross-origin credential policy.
 * @returns {import('react').ReactElement}
 */
export function PreconnectHint({ href, crossOrigin }) {
  if (href) {
    if (crossOrigin) {
      preconnect(href, { crossOrigin });
    } else {
      preconnect(href);
    }
  }
  return React.createElement('meta', { 'data-testid': 'preconnect-hint-marker' });
}

/**
 * Helper to preconnect multiple origins within a React component render tree.
 *
 * @param {object} props
 * @param {Array<{ href: string, crossOrigin?: 'anonymous' | 'use-credentials' }>} props.connections
 * @returns {null}
 */
export function PreconnectList({ connections = [] }) {
  for (const conn of connections) {
    if (conn && conn.href) {
      if (conn.crossOrigin) {
        preconnect(conn.href, { crossOrigin: conn.crossOrigin });
      } else {
        preconnect(conn.href);
      }
    }
  }
  return null;
}

export { preconnect };
test/contract.mjs
import assert from 'node:assert/strict';

// Set up minimal self-contained DOM environment for Node.js offline execution
class Node {}
class Element extends Node {}
class HTMLElement extends Element {}
class HTMLIFrameElement extends HTMLElement {}
class Document extends Node {}
class DocumentFragment extends Node {}

const headElements = [];
const head = {
  nodeType: 1,
  tagName: 'HEAD',
  nodeName: 'HEAD',
  childNodes: headElements,
  children: headElements,
  ownerDocument: null,
  appendChild(child) {
    headElements.push(child);
    child.parentNode = head;
    return child;
  },
  insertBefore(newChild, refChild) {
    const idx = headElements.indexOf(refChild);
    if (idx >= 0) headElements.splice(idx, 0, newChild);
    else headElements.push(newChild);
    newChild.parentNode = head;
    return newChild;
  },
  removeChild(child) {
    const idx = headElements.indexOf(child);
    if (idx >= 0) headElements.splice(idx, 1);
    child.parentNode = null;
    return child;
  }
};

const window = {
  event: undefined,
  Node,
  Element,
  HTMLElement,
  HTMLIFrameElement,
  Document,
  DocumentFragment
};

function createElement(tag) {
  const elChildren = [];
  const attrs = {};
  const el = {
    nodeType: 1,
    nodeName: tag.toUpperCase(),
    tagName: tag.toUpperCase(),
    childNodes: elChildren,
    children: elChildren,
    parentNode: null,
    style: {},
    ownerDocument: doc,
    setAttribute(k, v) {
      attrs[k.toLowerCase()] = String(v);
      this[k] = v;
    },
    getAttribute(k) {
      return attrs[k.toLowerCase()] ?? this[k] ?? null;
    },
    appendChild(child) {
      elChildren.push(child);
      child.parentNode = el;
      return child;
    },
    removeChild(child) {
      const idx = elChildren.indexOf(child);
      if (idx >= 0) elChildren.splice(idx, 1);
      child.parentNode = null;
      return child;
    },
    insertBefore(newChild, refChild) {
      const idx = elChildren.indexOf(refChild);
      if (idx >= 0) elChildren.splice(idx, 0, newChild);
      else elChildren.push(newChild);
      newChild.parentNode = el;
      return newChild;
    },
    addEventListener() {},
    removeEventListener() {}
  };
  return el;
}

const doc = {
  nodeType: 9,
  nodeName: '#document',
  activeElement: null,
  defaultView: window,
  head: head,
  querySelector(sel) {
    return headElements.find(el => {
      if (sel.includes('link') && el.tagName !== 'LINK') return false;
      const relMatch = sel.match(/rel="([^"]+)"/);
      if (relMatch && el.rel !== relMatch[1]) return false;
      const hrefMatch = sel.match(/href="([^"]+)"/);
      if (hrefMatch && el.href !== hrefMatch[1]) return false;
      const crossMatch = sel.match(/crossorigin="([^"]+)"/);
      if (crossMatch && el.getAttribute('crossorigin') !== crossMatch[1]) return false;
      return true;
    }) || null;
  },
  querySelectorAll(sel) {
    return headElements.filter(el => {
      if (sel.includes('link') && el.tagName !== 'LINK') return false;
      const relMatch = sel.match(/rel="([^"]+)"/);
      if (relMatch && el.rel !== relMatch[1]) return false;
      const hrefMatch = sel.match(/href="([^"]+)"/);
      if (hrefMatch && el.href !== hrefMatch[1]) return false;
      return true;
    });
  },
  createElement,
  createTextNode(text) {
    return {
      nodeType: 3,
      nodeName: '#text',
      nodeValue: String(text),
      textContent: String(text),
      parentNode: null,
      ownerDocument: doc
    };
  },
  createComment(data) {
    return {
      nodeType: 8,
      nodeName: '#comment',
      nodeValue: String(data),
      parentNode: null,
      ownerDocument: doc
    };
  },
  addEventListener() {},
  removeEventListener() {}
};

head.ownerDocument = doc;
window.document = doc;
globalThis.window = window;
globalThis.document = doc;
globalThis.Node = Node;
globalThis.Element = Element;
globalThis.HTMLElement = HTMLElement;
globalThis.HTMLIFrameElement = HTMLIFrameElement;
globalThis.Document = Document;
globalThis.DocumentFragment = DocumentFragment;

const React = await import('react');
const ReactDOM = await import('react-dom');
const ReactDOMServer = await import('react-dom/server');
const ReactDOMClient = await import('react-dom/client');
const { PreconnectHint, PreconnectList, preconnect } = await import('../src/index.mjs');
const { flushSync } = ReactDOM;

// Contract Assertion 1: preconnect is exported as a function from react-dom
assert.strictEqual(typeof preconnect, 'function', 'preconnect must be exported as a function from react-dom');
assert.strictEqual(typeof ReactDOM.preconnect, 'function', 'ReactDOM.preconnect must be exported from react-dom');

// Contract Assertion 2 & 3: preconnect emits hoisted link rel preconnect in ReactDOMServer renderToStaticMarkup,
// and supports crossOrigin options anonymous and use-credentials during SSR
function SSRDemo() {
  return React.createElement(
    'div',
    null,
    React.createElement(PreconnectHint, { href: 'https://api.example.com' }),
    React.createElement(PreconnectHint, { href: 'https://cdn.example.com', crossOrigin: 'anonymous' }),
    React.createElement(PreconnectHint, { href: 'https://auth.example.com', crossOrigin: 'use-credentials' }),
    React.createElement('main', null, 'SSR Content')
  );
}

const staticHtml = ReactDOMServer.renderToStaticMarkup(React.createElement(SSRDemo));
assert.ok(
  staticHtml.includes('<link rel="preconnect" href="https://api.example.com"/>'),
  'SSR markup must emit hoisted preconnect link tag without crossorigin attribute'
);
assert.ok(
  staticHtml.includes('<link rel="preconnect" href="https://cdn.example.com" crossorigin=""/>'),
  'SSR markup must emit hoisted preconnect link with crossorigin="" for anonymous mode'
);
assert.ok(
  staticHtml.includes('<link rel="preconnect" href="https://auth.example.com" crossorigin="use-credentials"/>'),
  'SSR markup must emit hoisted preconnect link with crossorigin="use-credentials"'
);

// Contract Assertion 4: duplicate preconnect calls across components in the render tree are deduplicated during SSR
function SSRDuplicateDemo() {
  return React.createElement(
    'section',
    null,
    React.createElement(PreconnectHint, { href: 'https://shared.example.com' }),
    React.createElement(PreconnectHint, { href: 'https://shared.example.com' }),
    React.createElement(PreconnectList, {
      connections: [
        { href: 'https://shared.example.com' },
        { href: 'https://list-item.example.com' },
      ],
    })
  );
}

const dupHtml = ReactDOMServer.renderToStaticMarkup(React.createElement(SSRDuplicateDemo));
const sharedOccurrences = dupHtml.match(/https:\/\/shared\.example\.com/g);
assert.strictEqual(
  sharedOccurrences.length,
  1,
  'Duplicate preconnect calls for identical href must be deduplicated in SSR output'
);
assert.ok(
  dupHtml.includes('<link rel="preconnect" href="https://list-item.example.com"/>'),
  'PreconnectList must emit preconnect hints in SSR'
);

// Contract Assertion 5: preconnect injects link rel preconnect elements into document.head during client root render
function ClientDemo() {
  return React.createElement(
    'div',
    null,
    React.createElement(PreconnectHint, {
      href: 'https://client-api.example.com',
      crossOrigin: 'use-credentials',
    }),
    React.createElement('span', null, 'Mounted Client Component')
  );
}

const container = doc.createElement('div');
const root = ReactDOMClient.createRoot(container);
flushSync(() => {
  root.render(React.createElement(ClientDemo));
});

const clientLinks = headElements.filter(el => el.href === 'https://client-api.example.com');
assert.strictEqual(clientLinks.length, 1, 'Client root render must inject link element into document.head');
assert.strictEqual(clientLinks[0].tagName, 'LINK', 'Injected element must be a LINK tag');
assert.strictEqual(clientLinks[0].rel, 'preconnect', 'Injected element rel attribute must be preconnect');
assert.strictEqual(
  clientLinks[0].getAttribute('crossorigin'),
  'use-credentials',
  'Injected element crossorigin attribute must be use-credentials'
);

// Contract Assertion 6: duplicate preconnect calls during client root render are deduplicated in document.head
function ClientDuplicateDemo() {
  return React.createElement(
    'div',
    null,
    React.createElement(PreconnectHint, {
      href: 'https://client-api.example.com',
      crossOrigin: 'use-credentials',
    }),
    React.createElement(PreconnectHint, {
      href: 'https://client-api.example.com',
      crossOrigin: 'use-credentials',
    }),
    React.createElement('span', null, 'Duplicate Preconnect Mount')
  );
}

flushSync(() => {
  root.render(React.createElement(ClientDuplicateDemo));
});

const dedupClientLinks = headElements.filter(el => el.href === 'https://client-api.example.com');
assert.strictEqual(
  dedupClientLinks.length,
  1,
  'Duplicate preconnect calls across client render tree must be deduplicated in document.head'
);

root.unmount();

console.log('CONTRACT PASS: react-dom.preconnect verified');

原始种子者

匿名