CodeSampleX

Exemplo

react 18.3.1: useSyncExternalStore

Amostra verificada para npm react 18.3.1: useSyncExternalStore. O contrato rodou em node 22 · linux alpine/x64 · docker e passou.

sha256:b61895d0a79f8cb254b0171a0bf872f21f7aab305f1804e2bc33a590e9555d41

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
verify React.useSyncExternalStore in pkg:npm/react@18.3.1
Pacotes
Símbolos
  • React.useSyncExternalStore
Ambiente
node 22.23.2
Criado
2026-08-27T10:06:32Z

Contrato

  1. react package.json declares export mappings for client and react-server entries at version 18.3.1
  2. react exports useSyncExternalStore as a function on the default client runtime interface and as a named export
  3. react useSyncExternalStore throws a TypeError when invoked outside an active component render dispatcher
  4. react useSyncExternalStore delegates subscribe, getSnapshot, and getServerSnapshot callbacks to the active ReactCurrentDispatcher
  5. react useSyncExternalStore passes undefined for omitted getServerSnapshot argument to the active ReactCurrentDispatcher
  6. react useSyncExternalStore operates with external store subscribe and getSnapshot protocol returning current state snapshot
  7. react react-server entry points to shared-subset which requires experimental channel in version 18.3.1

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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.useSyncExternalStore 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.useSyncExternalStore

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:6eb0feb8315654d4135eb2caefca828336b95923df9096cb3c3ab58a99773fe7","contract":["react package.json declares export mappings for client and react-server entries at version 18.3.1","react exports useSyncExternalStore as a function on the default client runtime interface and as a named export","react useSyncExternalStore throws a TypeError when invoked outside an active component render dispatcher","react useSyncExternalStore delegates subscribe, getSnapshot, and getServerSnapshot callbacks to the active ReactCurrentDispatcher","react useSyncExternalStore passes undefined for omitted getServerSnapshot argument to the active ReactCurrentDispatcher","react useSyncExternalStore operates with external store subscribe and getSnapshot protocol returning current state snapshot","react react-server entry points to shared-subset which requires experimental channel in version 18.3.1"],"goal":"verify React.useSyncExternalStore in pkg:npm/react@18.3.1","kind":"HOW","packages":["pkg:npm/react@18.3.1"],"schemaVersion":1,"symbols":["React.useSyncExternalStore"]},"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.useSyncExternalStore"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-react-use-sync-external-store",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-react-use-sync-external-store",
      "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-sync-external-store",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "react": "18.3.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify React.useSyncExternalStore in pkg:npm/react@18.3.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/react@18.3.1"
  ],
  "symbols": [
    "React.useSyncExternalStore"
  ]
}
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, { useSyncExternalStore } 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 useSyncExternalStore as a function on the default client runtime interface and as a named export
{
  assert.strictEqual(typeof React.useSyncExternalStore, 'function');
  assert.strictEqual(typeof useSyncExternalStore, 'function');
  assert.strictEqual(React.useSyncExternalStore, useSyncExternalStore);
  assert.strictEqual(React.version, '18.3.1');
}

// Contract 3: react useSyncExternalStore 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.useSyncExternalStore(() => () => {}, () => ({}));
    },
    {
      name: 'TypeError'
    }
  );
}

// Contract 4: react useSyncExternalStore delegates subscribe, getSnapshot, and getServerSnapshot callbacks to the active ReactCurrentDispatcher
{
  const internals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  let receivedCall = null;
  const mockSnapshot = { count: 10, data: 'test-value' };
  const mockServerSnapshot = { count: 0, data: 'server-value' };

  internals.ReactCurrentDispatcher.current = {
    useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
      receivedCall = { subscribe, getSnapshot, getServerSnapshot };
      return getSnapshot();
    }
  };

  try {
    const subscribe = (onStoreChange) => {
      return () => {};
    };
    const getSnapshot = () => mockSnapshot;
    const getServerSnapshot = () => mockServerSnapshot;

    const result = React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
    assert.strictEqual(result, mockSnapshot);
    assert.ok(receivedCall !== null);
    assert.strictEqual(receivedCall.subscribe, subscribe);
    assert.strictEqual(receivedCall.getSnapshot, getSnapshot);
    assert.strictEqual(receivedCall.getServerSnapshot, getServerSnapshot);
  } finally {
    internals.ReactCurrentDispatcher.current = null;
  }
}

// Contract 5: react useSyncExternalStore passes undefined for omitted getServerSnapshot argument to the active ReactCurrentDispatcher
{
  const internals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  let receivedCall = null;

  internals.ReactCurrentDispatcher.current = {
    useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
      receivedCall = { subscribe, getSnapshot, getServerSnapshot };
      return getSnapshot();
    }
  };

  try {
    const subscribe = () => () => {};
    const getSnapshot = () => 'snapshot-only';

    const result = React.useSyncExternalStore(subscribe, getSnapshot);
    assert.strictEqual(result, 'snapshot-only');
    assert.ok(receivedCall !== null);
    assert.strictEqual(receivedCall.subscribe, subscribe);
    assert.strictEqual(receivedCall.getSnapshot, getSnapshot);
    assert.strictEqual(receivedCall.getServerSnapshot, undefined);
  } finally {
    internals.ReactCurrentDispatcher.current = null;
  }
}

// Contract 6: react useSyncExternalStore operates with external store subscribe and getSnapshot protocol returning current state snapshot
{
  const internals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

  function createSimpleStore(initialState) {
    let state = initialState;
    const listeners = new Set();
    return {
      getSnapshot: () => state,
      getServerSnapshot: () => ({ ...state, server: true }),
      setState: (nextState) => {
        state = typeof nextState === 'function' ? nextState(state) : nextState;
        listeners.forEach((listener) => listener());
      },
      subscribe: (listener) => {
        listeners.add(listener);
        return () => {
          listeners.delete(listener);
        };
      }
    };
  }

  const store = createSimpleStore({ value: 100 });
  let listenerCalled = 0;

  internals.ReactCurrentDispatcher.current = {
    useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
      return getSnapshot();
    }
  };

  try {
    const snapshot1 = React.useSyncExternalStore(store.subscribe, store.getSnapshot);
    assert.deepStrictEqual(snapshot1, { value: 100 });

    const unsubscribe = store.subscribe(() => {
      listenerCalled += 1;
    });

    store.setState({ value: 200 });
    assert.strictEqual(listenerCalled, 1);

    const snapshot2 = React.useSyncExternalStore(store.subscribe, store.getSnapshot);
    assert.deepStrictEqual(snapshot2, { value: 200 });

    unsubscribe();
    store.setState({ value: 300 });
    assert.strictEqual(listenerCalled, 1); // Not called after unsubscribe
  } finally {
    internals.ReactCurrentDispatcher.current = null;
  }
}

// Contract 7: 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.useSyncExternalStore contract tests passed.');

Seeder de origem

anônimo