CodeSampleX

Exemple

ajv 8.20.0

Échantillon vérifié pour npm ajv 8.20.0. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi : Ajv compiles JSON Schema definitions…

sha256:6034448091e83acd71353a24dfef0b3ce4787f68fb81f17c094b61e7686a1b0e

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
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-23

Cas

HOW
Objectif
verify pkg:npm/ajv@8.20.0
Paquets
Créé
2026-08-23T06:00:29Z

Contrat

  1. Ajv compiles JSON Schema definitions and validates data against type, range, and format constraints
  2. Ajv populates errors with keyword, instancePath, and params when validation fails
  3. Ajv resolves internal and cross-schema references via $id and $ref registered with addSchema
  4. Ajv with allErrors true collects all schema validation failures instead of stopping on first error
  5. Ajv with useDefaults true assigns default property values defined in the schema to target objects
  6. Ajv with coerceTypes true coerces data types to match expected schema property types
  7. Ajv supports custom keyword definitions with user-defined validation logic

Fichiers

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

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

Code source

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 pkg:npm/ajv@8.20.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/ajv@8.20.0

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:cda1eb837659c6d00224eba01877c96436902d2429b2bb23b3520f230b68fb1c","contract":["Ajv compiles JSON Schema definitions and validates data against type, range, and format constraints","Ajv populates errors with keyword, instancePath, and params when validation fails","Ajv resolves internal and cross-schema references via $id and $ref registered with addSchema","Ajv with allErrors true collects all schema validation failures instead of stopping on first error","Ajv with useDefaults true assigns default property values defined in the schema to target objects","Ajv with coerceTypes true coerces data types to match expected schema property types","Ajv supports custom keyword definitions with user-defined validation logic"],"goal":"verify pkg:npm/ajv@8.20.0","kind":"HOW","packages":["pkg:npm/ajv@8.20.0"],"schemaVersion":1},"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/ajv@8.20.0"],"schemaVersion":1,"subject":"pkg:npm/ajv@8.20.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-ajv",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-ajv",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "ajv": "8.20.0"
      }
    },
    "node_modules/ajv": {
      "version": "8.20.0",
      "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
      "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
      "license": "MIT",
      "dependencies": {
        "fast-deep-equal": "^3.1.3",
        "fast-uri": "^3.0.1",
        "json-schema-traverse": "^1.0.0",
        "require-from-string": "^2.0.2"
      },
      "funding": {
        "type": "github",
        "url": "https://github.com/sponsors/epoberezkin"
      }
    },
    "node_modules/fast-deep-equal": {
      "version": "3.1.3",
      "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
      "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
      "license": "MIT"
    },
    "node_modules/fast-uri": {
      "version": "3.1.6",
      "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.6.tgz",
      "integrity": "sha512-7Ical1vFEMr0onbVzEDIreM22I4khW+fzyQPwvAFWBp1iwdshSZRsL4jjRvPG9JP1uiqMHRto+YU6R2/CzDz5Q==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/fastify"
        },
        {
          "type": "opencollective",
          "url": "https://opencollective.com/fastify"
        }
      ],
      "license": "BSD-3-Clause"
    },
    "node_modules/json-schema-traverse": {
      "version": "1.0.0",
      "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
      "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
      "license": "MIT"
    },
    "node_modules/require-from-string": {
      "version": "2.0.2",
      "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
      "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
      "license": "MIT",
      "engines": {
        "node": ">=0.10.0"
      }
    }
  }
}
package.json
{
  "name": "sample-ajv",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for ajv@8.20.0",
  "license": "MIT-0",
  "dependencies": {
    "ajv": "8.20.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/ajv@8.20.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/ajv@8.20.0"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import Ajv from 'ajv';

async function testAll() {
  // 1. Ajv compiles JSON Schema definitions and validates data against type, range, and format constraints
  const ajv = new Ajv();
  const schema = {
    type: 'object',
    properties: {
      id: { type: 'integer', minimum: 1 },
      username: { type: 'string', minLength: 3, maxLength: 20 },
      email: { type: 'string' },
      roles: {
        type: 'array',
        items: { type: 'string' },
        minItems: 1,
        uniqueItems: true
      }
    },
    required: ['id', 'username'],
    additionalProperties: false
  };

  const validate = ajv.compile(schema);
  assert.equal(typeof validate, 'function', 'compile must return a validation function');

  const validRecord = {
    id: 101,
    username: 'developer',
    roles: ['admin', 'editor']
  };
  const isValid = validate(validRecord);
  assert.equal(isValid, true, 'valid data must pass validation');
  assert.equal(validate.errors, null, 'validate.errors must be null on success');

  // 2. Ajv populates errors with keyword, instancePath, and params when validation fails
  const invalidRecord = {
    id: 0,
    username: 'ab',
    extraField: true
  };
  const isInvalid = validate(invalidRecord);
  assert.equal(isInvalid, false, 'invalid data must fail validation');
  assert.ok(Array.isArray(validate.errors), 'validate.errors must be an array');
  assert.ok(validate.errors.length > 0, 'errors must not be empty');

  const firstError = validate.errors[0];
  assert.ok('keyword' in firstError, 'error object must include keyword');
  assert.ok('instancePath' in firstError, 'error object must include instancePath');
  assert.ok('message' in firstError, 'error object must include message');

  // 3. Ajv resolves internal and cross-schema references via $id and $ref registered with addSchema
  const ajvRef = new Ajv();
  const addressSchema = {
    $id: 'https://example.com/schemas/address.json',
    type: 'object',
    properties: {
      street: { type: 'string', minLength: 1 },
      zipCode: { type: 'string', pattern: '^[0-9]{5}$' }
    },
    required: ['street', 'zipCode'],
    additionalProperties: false
  };
  ajvRef.addSchema(addressSchema);

  const customerSchema = {
    $id: 'https://example.com/schemas/customer.json',
    type: 'object',
    properties: {
      name: { type: 'string', minLength: 1 },
      billingAddress: { $ref: 'https://example.com/schemas/address.json' }
    },
    required: ['name', 'billingAddress']
  };

  const validateCustomer = ajvRef.compile(customerSchema);
  assert.equal(
    validateCustomer({
      name: 'Tester',
      billingAddress: { street: '123 Main St', zipCode: '12345' }
    }),
    true,
    'valid referenced schema data must pass'
  );
  assert.equal(
    validateCustomer({
      name: 'Tester',
      billingAddress: { street: '123 Main St', zipCode: 'INVALID' }
    }),
    false,
    'invalid referenced schema data must fail'
  );

  // 4. Ajv with allErrors true collects all schema validation failures instead of stopping on first error
  const ajvAllErrors = new Ajv({ allErrors: true });
  const validateAll = ajvAllErrors.compile(schema);
  const multiErrorRecord = {
    id: -1,
    username: 'x',
    roles: []
  };
  const isMultiInvalid = validateAll(multiErrorRecord);
  assert.equal(isMultiInvalid, false);
  assert.ok(
    validateAll.errors.length >= 3,
    `allErrors should collect multiple errors, received: ${validateAll.errors.length}`
  );

  // 5. Ajv with useDefaults true assigns default property values defined in the schema to target objects
  const ajvDefaults = new Ajv({ useDefaults: true });
  const schemaWithDefaults = {
    type: 'object',
    properties: {
      status: { type: 'string', default: 'pending' },
      retries: { type: 'integer', default: 3 },
      meta: {
        type: 'object',
        properties: {
          enabled: { type: 'boolean', default: true }
        }
      }
    }
  };
  const validateDefaults = ajvDefaults.compile(schemaWithDefaults);
  const targetObject = { meta: {} };
  const defaultsValid = validateDefaults(targetObject);
  assert.equal(defaultsValid, true);
  assert.equal(targetObject.status, 'pending', 'default property value must be assigned');
  assert.equal(targetObject.retries, 3, 'default numeric value must be assigned');
  assert.equal(targetObject.meta.enabled, true, 'nested default value must be assigned');

  // 6. Ajv with coerceTypes true coerces data types to match expected schema property types
  const ajvCoerce = new Ajv({ coerceTypes: true });
  const schemaCoerce = {
    type: 'object',
    properties: {
      port: { type: 'integer' },
      debug: { type: 'boolean' }
    },
    required: ['port', 'debug']
  };
  const validateCoerce = ajvCoerce.compile(schemaCoerce);
  const inputToCoerce = { port: '8080', debug: 'true' };
  const coerceValid = validateCoerce(inputToCoerce);
  assert.equal(coerceValid, true, 'type coercion must succeed');
  assert.strictEqual(inputToCoerce.port, 8080, 'string number must be coerced to integer');
  assert.strictEqual(inputToCoerce.debug, true, 'string boolean must be coerced to boolean');

  // 7. Ajv supports custom keyword definitions with user-defined validation logic
  const ajvCustom = new Ajv();
  ajvCustom.addKeyword({
    keyword: 'isDivisibleBy',
    type: 'number',
    validate: (divisor, data) => typeof data === 'number' && data % divisor === 0
  });

  const schemaCustom = {
    type: 'object',
    properties: {
      score: { type: 'number', isDivisibleBy: 5 }
    }
  };
  const validateCustom = ajvCustom.compile(schemaCustom);
  assert.equal(validateCustom({ score: 25 }), true, 'custom keyword validation must pass when true');
  assert.equal(validateCustom({ score: 23 }), false, 'custom keyword validation must fail when false');

  console.log('Contract passed');
}

testAll().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Seeder d'origine

anonyme