CodeSampleX

Exemple

ajv 6.15.0

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

sha256:9319ccda379d0558a1904491dcaa11139d5ec02748dc984b9f9c8a0bff6d6854

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é node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

Cas

HOW
Objectif
verify pkg:npm/ajv@6.15.0
Paquets
Environnement
node 22.23.2
Créé
2026-08-19T22:28:04Z

Contrat

  1. Ajv compiles JSON Schema definitions and validates data objects against types and required properties
  2. Ajv collects detailed validation error objects when data violates schema constraints
  3. Ajv resolves schema references across schemas registered with addSchema
  4. Ajv applies default values and coerces types when useDefaults and coerceTypes options are enabled

Fichiers

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

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@6.15.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/ajv@6.15.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - 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:7686dfa500942fb15969390eb89862a0acc69cdde566c56974305777bc7b2fbe","constraints":{"executionContext":"node"},"contract":["Ajv compiles JSON Schema definitions and validates data objects against types and required properties","Ajv collects detailed validation error objects when data violates schema constraints","Ajv resolves schema references across schemas registered with addSchema","Ajv applies default values and coerces types when useDefaults and coerceTypes options are enabled"],"goal":"verify pkg:npm/ajv@6.15.0","kind":"HOW","packages":["pkg:npm/ajv@6.15.0"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/ajv@6.15.0"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "ajv-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "ajv-sample",
      "version": "1.0.0",
      "dependencies": {
        "ajv": "6.15.0"
      }
    },
    "node_modules/ajv": {
      "version": "6.15.0",
      "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
      "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
      "license": "MIT",
      "dependencies": {
        "fast-deep-equal": "^3.1.1",
        "fast-json-stable-stringify": "^2.0.0",
        "json-schema-traverse": "^0.4.1",
        "uri-js": "^4.2.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-json-stable-stringify": {
      "version": "2.1.0",
      "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
      "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
      "license": "MIT"
    },
    "node_modules/json-schema-traverse": {
      "version": "0.4.1",
      "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
      "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
      "license": "MIT"
    },
    "node_modules/punycode": {
      "version": "2.3.1",
      "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
      "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/uri-js": {
      "version": "4.4.1",
      "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
      "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
      "license": "BSD-2-Clause",
      "dependencies": {
        "punycode": "^2.1.0"
      }
    }
  }
}
package.json
{
  "name": "ajv-sample",
  "version": "1.0.0",
  "dependencies": {
    "ajv": "6.15.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/ajv@6.15.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/ajv@6.15.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const Ajv = require('ajv');

/**
 * Creates and configures an Ajv validator instance.
 *
 * @param {object} [options] - Ajv configuration options.
 * @returns {import('ajv').Ajv} Configured Ajv instance.
 */
function createValidator(options) {
  return new Ajv(options);
}

/**
 * Compiles a schema and returns the validation function.
 *
 * @param {object} schema - JSON Schema object.
 * @param {object} [options] - Ajv configuration options.
 * @returns {import('ajv').ValidateFunction} Validation function.
 */
function compileSchema(schema, options) {
  const ajv = new Ajv(options);
  return ajv.compile(schema);
}

/**
 * Validates data against a schema, returning validity and any error records.
 *
 * @param {object} schema - JSON Schema object.
 * @param {unknown} data - Data to validate.
 * @param {object} [options] - Ajv configuration options.
 * @returns {{ valid: boolean, errors: import('ajv').ErrorObject[] | null }} Validation result.
 */
function validateData(schema, data, options) {
  const ajv = new Ajv({ allErrors: true, ...options });
  const validate = ajv.compile(schema);
  const valid = Boolean(validate(data));
  return {
    valid,
    errors: valid ? null : validate.errors,
  };
}

/**
 * Compiles a schema with support for referenced schemas.
 *
 * @param {object} mainSchema - Root JSON Schema.
 * @param {object[]} [referencedSchemas] - Array of schemas to register.
 * @returns {import('ajv').ValidateFunction} Validation function.
 */
function compileWithReferences(mainSchema, referencedSchemas = []) {
  const ajv = new Ajv();
  for (const refSchema of referencedSchemas) {
    ajv.addSchema(refSchema);
  }
  return ajv.compile(mainSchema);
}

module.exports = {
  Ajv,
  createValidator,
  compileSchema,
  validateData,
  compileWithReferences,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  createValidator,
  compileSchema,
  validateData,
  compileWithReferences,
} = require('../src/index.js');

// Contract 1: Ajv compiles JSON Schema definitions and validates data objects against types and required properties
{
  const schema = {
    type: 'object',
    properties: {
      id: { type: 'integer', minimum: 1 },
      title: { type: 'string', minLength: 2 },
      tags: {
        type: 'array',
        items: { type: 'string' },
        minItems: 1,
      },
    },
    required: ['id', 'title'],
    additionalProperties: false,
  };

  const validate = compileSchema(schema);

  const validRecord = { id: 101, title: 'Release Notes', tags: ['changelog'] };
  assert.strictEqual(validate(validRecord), true, 'Valid record should satisfy schema constraints');

  const invalidRecord = { id: 'not-an-int', title: 'A' };
  assert.strictEqual(validate(invalidRecord), false, 'Invalid record should fail validation');
}

// Contract 2: Ajv collects detailed validation error objects when data violates schema constraints
{
  const schema = {
    type: 'object',
    properties: {
      username: { type: 'string', minLength: 3 },
      age: { type: 'integer', minimum: 0 },
    },
    required: ['username', 'age'],
  };

  const result = validateData(schema, { username: 'a', age: -1 });
  assert.strictEqual(result.valid, false, 'Validation should fail for invalid inputs');
  assert.ok(Array.isArray(result.errors), 'Errors should be an array');
  assert.strictEqual(result.errors.length, 2, 'Should collect errors for both invalid fields');

  const keywords = result.errors.map((err) => err.keyword);
  assert.ok(keywords.includes('minLength'), 'Error list should include minLength violation');
  assert.ok(keywords.includes('minimum'), 'Error list should include minimum violation');
}

// Contract 3: Ajv resolves schema references across schemas registered with addSchema
{
  const addressSchema = {
    $id: 'http://example.com/schemas/address.json',
    type: 'object',
    properties: {
      city: { type: 'string', minLength: 1 },
      zipCode: { type: 'string', pattern: '^\\d{5}$' },
    },
    required: ['city', 'zipCode'],
  };

  const userSchema = {
    type: 'object',
    properties: {
      name: { type: 'string', minLength: 1 },
      address: { $ref: 'http://example.com/schemas/address.json' },
    },
    required: ['name', 'address'],
  };

  const validate = compileWithReferences(userSchema, [addressSchema]);

  const validUser = {
    name: 'Ada Lovelace',
    address: { city: 'London', zipCode: '12345' },
  };
  assert.strictEqual(validate(validUser), true, 'User with valid referenced address should pass');

  const invalidUser = {
    name: 'Ada Lovelace',
    address: { city: 'London', zipCode: 'invalid-zip' },
  };
  assert.strictEqual(validate(invalidUser), false, 'User with invalid referenced address should fail');
}

// Contract 4: Ajv applies default values and coerces types when useDefaults and coerceTypes options are enabled
{
  const ajv = createValidator({ useDefaults: true, coerceTypes: true });

  const schema = {
    type: 'object',
    properties: {
      retries: { type: 'integer', default: 3 },
      timeout: { type: 'number' },
      debug: { type: 'boolean', default: false },
    },
    required: ['retries', 'timeout'],
  };

  const validate = ajv.compile(schema);

  const rawData = { timeout: '5000' };
  const valid = validate(rawData);

  assert.strictEqual(valid, true, 'Data should validate after coercion and defaulting');
  assert.strictEqual(rawData.retries, 3, 'Default value 3 should be populated');
  assert.strictEqual(rawData.timeout, 5000, 'String "5000" should be coerced to number 5000');
  assert.strictEqual(rawData.debug, false, 'Default boolean value should be populated');
}

console.log('All pkg:npm/ajv@6.15.0 contracts passed successfully.');

Seeder d'origine

anonyme