CodeSampleX

Ejemplo

react 18.3.1: FormEvent

Muestra verificada para npm react 18.3.1: FormEvent. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: react package.json and React…

sha256:a04dd2da6304a993ff29fb8e940c2f5e75aa8e6b5b80c84bb42d972abb888547

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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.FormEvent in pkg:npm/react@18.3.1
Paquetes
Símbolos
  • react.FormEvent
Creado
2026-08-27T21:14:06Z

Contrato

  1. react package.json and React runtime match version 18.3.1
  2. createSyntheticFormEvent creates a synthetic form event wrapping native event properties including target, currentTarget, nativeEvent, type, bubbles, cancelable, and timeStamp
  3. isReactFormEvent validates synthetic form event contract and rejects invalid objects
  4. preventDefault sets defaultPrevented to true, returns true from isDefaultPrevented, and invokes native preventDefault
  5. stopPropagation stops bubbling, sets isPropagationStopped to true, and invokes native stopPropagation
  6. persist is a no-op in React 18 and event properties remain accessible asynchronously without nullification
  7. handleFormSubmit prevents default form submit and extracts form values from elements
  8. handleFormChange extracts name, value, and checked state from event target

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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

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:4219f1de85823c09624c9883b2435417071388be01e330eec6f153735e593011","contract":["react package.json and React runtime match version 18.3.1","createSyntheticFormEvent creates a synthetic form event wrapping native event properties including target, currentTarget, nativeEvent, type, bubbles, cancelable, and timeStamp","isReactFormEvent validates synthetic form event contract and rejects invalid objects","preventDefault sets defaultPrevented to true, returns true from isDefaultPrevented, and invokes native preventDefault","stopPropagation stops bubbling, sets isPropagationStopped to true, and invokes native stopPropagation","persist is a no-op in React 18 and event properties remain accessible asynchronously without nullification","handleFormSubmit prevents default form submit and extracts form values from elements","handleFormChange extracts name, value, and checked state from event target"],"goal":"verify react.FormEvent in pkg:npm/react@18.3.1","kind":"HOW","packages":["pkg:npm/react@18.3.1"],"schemaVersion":1,"symbols":["react.FormEvent"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react@18.3.1"],"schemaVersion":1,"subject":"pkg:npm/react@18.3.1","symbols":["react.FormEvent"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-react-form-event",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-react-form-event",
      "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-form-event",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "react": "18.3.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify react.FormEvent in pkg:npm/react@18.3.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/react@18.3.1"
  ],
  "symbols": [
    "react.FormEvent"
  ]
}
src/index.mjs
import React from 'react';

/**
 * React 18 FormEvent / SyntheticEvent representation.
 * React creates synthetic events wrapping native browser events for cross-browser consistency.
 */

/**
 * Creates a React Synthetic FormEvent instance wrapping a native or mock DOM event.
 *
 * @param {object} nativeEvent - Native or simulated DOM event.
 * @param {object} [currentTarget] - DOM element or component handling the event.
 * @returns {object} Synthetic FormEvent adhering to React's SyntheticEvent contract.
 */
export function createSyntheticFormEvent(nativeEvent, currentTarget = null) {
  let isPropagationStopped = false;
  let isDefaultPrevented = Boolean(nativeEvent?.defaultPrevented);

  const syntheticEvent = {
    nativeEvent: nativeEvent || {},
    currentTarget: currentTarget || nativeEvent?.currentTarget || null,
    target: nativeEvent?.target || null,
    bubbles: nativeEvent?.bubbles ?? true,
    cancelable: nativeEvent?.cancelable ?? true,
    defaultPrevented: isDefaultPrevented,
    eventPhase: nativeEvent?.eventPhase ?? 3,
    isTrusted: nativeEvent?.isTrusted ?? false,
    timeStamp: nativeEvent?.timeStamp ?? Date.now(),
    type: nativeEvent?.type || "submit",

    preventDefault() {
      isDefaultPrevented = true;
      syntheticEvent.defaultPrevented = true;
      if (typeof nativeEvent?.preventDefault === "function") {
        nativeEvent.preventDefault();
      }
    },

    isDefaultPrevented() {
      return isDefaultPrevented;
    },

    stopPropagation() {
      isPropagationStopped = true;
      if (typeof nativeEvent?.stopPropagation === "function") {
        nativeEvent.stopPropagation();
      }
    },

    isPropagationStopped() {
      return isPropagationStopped;
    },

    persist() {
      // In React 17+, event pooling was removed and persist() is a no-op.
    },

    isPersistent() {
      return true;
    }
  };

  return syntheticEvent;
}

/**
 * Validates whether an event object satisfies the React FormEvent interface.
 *
 * @param {any} event
 * @returns {boolean}
 */
export function isReactFormEvent(event) {
  if (!event || typeof event !== "object") {
    return false;
  }
  return (
    "nativeEvent" in event &&
    "target" in event &&
    "currentTarget" in event &&
    "type" in event &&
    typeof event.preventDefault === "function" &&
    typeof event.isDefaultPrevented === "function" &&
    typeof event.stopPropagation === "function" &&
    typeof event.isPropagationStopped === "function" &&
    typeof event.persist === "function" &&
    typeof event.isPersistent === "function"
  );
}

/**
 * Handles form submit event with automatic preventDefault and structured data extraction.
 *
 * @param {Function} onSubmitCallback
 * @param {object} event - FormEvent
 * @returns {{ prevented: boolean, values: Record<string, any> }}
 */
export function handleFormSubmit(onSubmitCallback, event) {
  if (!isReactFormEvent(event)) {
    throw new TypeError("Expected a React FormEvent");
  }

  event.preventDefault();

  const values = {};
  const formElement = event.currentTarget || event.target;

  if (formElement && Array.isArray(formElement.elements)) {
    for (const el of formElement.elements) {
      if (el.name && !el.disabled) {
        if (el.type === "checkbox") {
          values[el.name] = el.checked;
        } else if (el.type === "radio") {
          if (el.checked) {
            values[el.name] = el.value;
          }
        } else {
          values[el.name] = el.value;
        }
      }
    }
  }

  if (typeof onSubmitCallback === "function") {
    onSubmitCallback(values, event);
  }

  return {
    prevented: event.isDefaultPrevented(),
    values
  };
}

/**
 * Handles form input change event and returns extracted name, value, and checked state.
 *
 * @param {Function} onChangeCallback
 * @param {object} event - FormEvent
 * @returns {{ name: string, value: any, checked?: boolean }}
 */
export function handleFormChange(onChangeCallback, event) {
  if (!isReactFormEvent(event)) {
    throw new TypeError("Expected a React FormEvent");
  }

  const target = event.target || {};
  const name = target.name || "";
  const value = target.type === "checkbox" ? target.checked : target.value;
  const changeData = {
    name,
    value,
    checked: target.type === "checkbox" ? target.checked : undefined
  };

  if (typeof onChangeCallback === "function") {
    onChangeCallback(changeData, event);
  }

  return changeData;
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import React from 'react';
import {
  createSyntheticFormEvent,
  isReactFormEvent,
  handleFormSubmit,
  handleFormChange
} from '../src/index.mjs';

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

// Contract 1: react package.json and React runtime version 18.3.1
{
  const pkgPath = require.resolve('react/package.json');
  assert.ok(fs.existsSync(pkgPath), 'react package.json must exist');
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
  assert.strictEqual(pkg.name, 'react');
  assert.strictEqual(pkg.version, '18.3.1');
  assert.strictEqual(React.version, '18.3.1');
}

// Contract 2: createSyntheticFormEvent creates a synthetic form event wrapping native event properties
{
  const mockTarget = { name: 'username', value: 'testuser' };
  const mockForm = { id: 'login-form' };
  let nativePreventDefaultCalled = false;
  let nativeStopPropagationCalled = false;

  const nativeEvent = {
    type: 'submit',
    target: mockTarget,
    currentTarget: mockForm,
    bubbles: true,
    cancelable: true,
    defaultPrevented: false,
    eventPhase: 2,
    isTrusted: true,
    timeStamp: 123456789,
    preventDefault() {
      nativePreventDefaultCalled = true;
    },
    stopPropagation() {
      nativeStopPropagationCalled = true;
    }
  };

  const formEvent = createSyntheticFormEvent(nativeEvent, mockForm);

  assert.strictEqual(formEvent.type, 'submit');
  assert.strictEqual(formEvent.target, mockTarget);
  assert.strictEqual(formEvent.currentTarget, mockForm);
  assert.strictEqual(formEvent.nativeEvent, nativeEvent);
  assert.strictEqual(formEvent.bubbles, true);
  assert.strictEqual(formEvent.cancelable, true);
  assert.strictEqual(formEvent.defaultPrevented, false);
  assert.strictEqual(formEvent.eventPhase, 2);
  assert.strictEqual(formEvent.isTrusted, true);
  assert.strictEqual(formEvent.timeStamp, 123456789);
  assert.strictEqual(formEvent.isDefaultPrevented(), false);
  assert.strictEqual(formEvent.isPropagationStopped(), false);
  assert.strictEqual(isReactFormEvent(formEvent), true);
}

// Contract 3: isReactFormEvent validates synthetic form event contract and rejects invalid objects
{
  assert.strictEqual(isReactFormEvent(null), false);
  assert.strictEqual(isReactFormEvent({}), false);
  assert.strictEqual(isReactFormEvent({ type: 'submit' }), false);

  const validEvent = createSyntheticFormEvent({ type: 'submit' });
  assert.strictEqual(isReactFormEvent(validEvent), true);
}

// Contract 4: preventDefault sets defaultPrevented to true and invokes native preventDefault
{
  let nativePreventDefaultCalled = false;
  const nativeEvent = {
    type: 'submit',
    defaultPrevented: false,
    preventDefault() {
      nativePreventDefaultCalled = true;
    }
  };

  const formEvent = createSyntheticFormEvent(nativeEvent);
  assert.strictEqual(formEvent.defaultPrevented, false);
  assert.strictEqual(formEvent.isDefaultPrevented(), false);

  formEvent.preventDefault();

  assert.strictEqual(formEvent.defaultPrevented, true);
  assert.strictEqual(formEvent.isDefaultPrevented(), true);
  assert.strictEqual(nativePreventDefaultCalled, true);
}

// Contract 5: stopPropagation stops bubbling and sets isPropagationStopped to true
{
  let nativeStopPropagationCalled = false;
  const nativeEvent = {
    type: 'submit',
    stopPropagation() {
      nativeStopPropagationCalled = true;
    }
  };

  const formEvent = createSyntheticFormEvent(nativeEvent);
  assert.strictEqual(formEvent.isPropagationStopped(), false);

  formEvent.stopPropagation();

  assert.strictEqual(formEvent.isPropagationStopped(), true);
  assert.strictEqual(nativeStopPropagationCalled, true);
}

// Contract 6: persist is a no-op in React 18 and event properties remain accessible asynchronously
{
  const formEvent = createSyntheticFormEvent({
    type: 'input',
    target: { name: 'search', value: 'query' }
  });

  assert.strictEqual(formEvent.isPersistent(), true);
  formEvent.persist();
  assert.strictEqual(formEvent.isPersistent(), true);

  // In React 18, event fields are not pooled/nullified after microtask
  await Promise.resolve();
  assert.strictEqual(formEvent.type, 'input');
  assert.strictEqual(formEvent.target.value, 'query');
}

// Contract 7: handleFormSubmit prevents default form submit and extracts form values
{
  const formElements = [
    { name: 'email', value: 'user@example.com', type: 'text', disabled: false },
    { name: 'subscribe', checked: true, type: 'checkbox', disabled: false },
    { name: 'ignored', value: 'skip', type: 'text', disabled: true }
  ];

  let callbackCalled = false;
  let capturedValues = null;

  const mockNativeEvent = {
    type: 'submit',
    defaultPrevented: false,
    preventDefault() {}
  };

  const formEvent = createSyntheticFormEvent(mockNativeEvent, { elements: formElements });

  const result = handleFormSubmit((values) => {
    callbackCalled = true;
    capturedValues = values;
  }, formEvent);

  assert.strictEqual(callbackCalled, true);
  assert.strictEqual(result.prevented, true);
  assert.strictEqual(formEvent.isDefaultPrevented(), true);
  assert.deepStrictEqual(capturedValues, {
    email: 'user@example.com',
    subscribe: true
  });
}

// Contract 8: handleFormChange extracts name, value, and checked state from event target
{
  let textChangeCaptured = null;
  const textEvent = createSyntheticFormEvent({
    type: 'change',
    target: { name: 'title', value: 'New Title', type: 'text' }
  });

  const textResult = handleFormChange((data) => {
    textChangeCaptured = data;
  }, textEvent);

  assert.deepStrictEqual(textResult, {
    name: 'title',
    value: 'New Title',
    checked: undefined
  });
  assert.deepStrictEqual(textChangeCaptured, textResult);

  let checkboxChangeCaptured = null;
  const checkboxEvent = createSyntheticFormEvent({
    type: 'change',
    target: { name: 'active', checked: true, type: 'checkbox' }
  });

  const checkboxResult = handleFormChange((data) => {
    checkboxChangeCaptured = data;
  }, checkboxEvent);

  assert.deepStrictEqual(checkboxResult, {
    name: 'active',
    value: true,
    checked: true
  });
  assert.deepStrictEqual(checkboxChangeCaptured, checkboxResult);
}

console.log('CONTRACT PASS: react.FormEvent contract verified for pkg:npm/react@18.3.1');

Seeder de origen

anónimo