CodeSampleX

Пример

react 18.3.1: useRef

Проверенный пример — npm react 18.3.1: useRef. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: react package.json declares export…

sha256:bb6be8e65d91094ac083d5608eb2c5ac7243ba8d02ee96e29859e80268386452

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

Кейс

HOW
Цель
verify react.useRef in pkg:npm/react@18.3.1
Пакеты
Символы
  • react.useRef
Окружение
node 22.23.2
Создан
2026-08-27T17:39:37Z

Контракт

  1. react package.json declares export mappings for client and react-server entries at version 18.3.1
  2. react exports useRef as a function on the default client runtime interface
  3. react useRef throws a TypeError when invoked outside an active component render dispatcher
  4. react useRef delegates initialValue to the active ReactCurrentDispatcher and returns the ref object
  5. react useRef preserves passed primitives and undefined initial values when delegating to dispatcher
  6. react react-server entry points to shared-subset which requires experimental channel in version 18.3.1

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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.useRef in pkg:npm/react@18.3.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/react@18.3.1
Demonstrate these symbols/APIs:
  - react.useRef

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:27a8e1c4f41d879f969a060cc08a083a2dd56147608631294eacb98be66c6ec0","contract":["react package.json declares export mappings for client and react-server entries at version 18.3.1","react exports useRef as a function on the default client runtime interface","react useRef throws a TypeError when invoked outside an active component render dispatcher","react useRef delegates initialValue to the active ReactCurrentDispatcher and returns the ref object","react useRef preserves passed primitives and undefined initial values when delegating to dispatcher","react react-server entry points to shared-subset which requires experimental channel in version 18.3.1"],"goal":"verify react.useRef in pkg:npm/react@18.3.1","kind":"HOW","packages":["pkg:npm/react@18.3.1"],"schemaVersion":1,"symbols":["react.useRef"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","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@18.3.1"],"schemaVersion":1,"subject":"pkg:npm/react@18.3.1","symbols":["react.useRef"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-react-use-ref",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-react-use-ref",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "react": "18.3.1"
      }
    },
    "node_modules/js-tokens": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
      "license": "MIT"
    },
    "node_modules/loose-envify": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
      "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
      "license": "MIT",
      "dependencies": {
        "js-tokens": "^3.0.0 || ^4.0.0"
      },
      "bin": {
        "loose-envify": "cli.js"
      }
    },
    "node_modules/react": {
      "version": "18.3.1",
      "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
      "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0"
      },
      "engines": {
        "node": ">=0.10.0"
      }
    }
  }
}
package.json
{
  "name": "sample-react-use-ref",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "react": "18.3.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify react.useRef in pkg:npm/react@18.3.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/react@18.3.1"
  ],
  "symbols": [
    "react.useRef"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import React from 'react';

const require = createRequire(import.meta.url);

// Contract 1: react package.json declares export mappings for client and react-server entries at version 18.3.1
{
  const pkgJsonPath = require.resolve('react/package.json');
  assert.ok(fs.existsSync(pkgJsonPath));
  const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
  assert.strictEqual(pkgJson.name, 'react');
  assert.strictEqual(pkgJson.version, '18.3.1');
  assert.strictEqual(pkgJson.exports['.']['default'], './index.js');
  assert.strictEqual(pkgJson.exports['.']['react-server'], './react.shared-subset.js');
}

// Contract 2: react exports useRef as a function on the default client runtime interface
{
  assert.strictEqual(typeof React.useRef, 'function');
  assert.strictEqual(React.version, '18.3.1');
}

// Contract 3: react useRef throws a TypeError when invoked outside an active component render dispatcher
{
  const internals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  assert.ok(internals && typeof internals === 'object');
  assert.strictEqual(internals.ReactCurrentDispatcher.current, null);

  assert.throws(
    () => {
      React.useRef(null);
    },
    {
      name: 'TypeError'
    }
  );
}

// Contract 4: react useRef delegates initialValue to the active ReactCurrentDispatcher and returns the ref object
{
  const internals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  let receivedInitialValue = undefined;
  const mockRef = { current: 'test-value' };

  internals.ReactCurrentDispatcher.current = {
    useRef(initialValue) {
      receivedInitialValue = initialValue;
      return mockRef;
    }
  };

  try {
    const initial = { count: 0 };
    const ref = React.useRef(initial);

    assert.strictEqual(ref, mockRef);
    assert.strictEqual(receivedInitialValue, initial);
  } finally {
    internals.ReactCurrentDispatcher.current = null;
  }
}

// Contract 5: react useRef preserves passed primitives and undefined initial values when delegating to dispatcher
{
  const internals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  const calls = [];

  internals.ReactCurrentDispatcher.current = {
    useRef(initialValue) {
      calls.push(initialValue);
      return { current: initialValue };
    }
  };

  try {
    const ref1 = React.useRef();
    assert.strictEqual(calls[0], undefined);
    assert.strictEqual(ref1.current, undefined);

    const ref2 = React.useRef(42);
    assert.strictEqual(calls[1], 42);
    assert.strictEqual(ref2.current, 42);

    const ref3 = React.useRef('hello');
    assert.strictEqual(calls[2], 'hello');
    assert.strictEqual(ref3.current, 'hello');
  } finally {
    internals.ReactCurrentDispatcher.current = null;
  }
}

// Contract 6: react react-server entry points to shared-subset which requires experimental channel in version 18.3.1
{
  const pkgJsonPath = require.resolve('react/package.json');
  const pkgDir = path.dirname(pkgJsonPath);
  const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
  const reactServerEntry = path.join(pkgDir, pkgJson.exports['.']['react-server']);
  assert.ok(fs.existsSync(reactServerEntry));

  assert.throws(
    () => {
      require(reactServerEntry);
    },
    (err) => {
      return err instanceof Error && /experimental channels/.test(err.message);
    }
  );
}

console.log('All react.useRef contract tests passed.');

Исходный сидер

аноним