CodeSampleX

Ejemplo

schema-utils 4.3.3: validate

Muestra verificada para npm schema-utils 4.3.3: validate. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó.

sha256:9721780e45da49fc39839a16e651ac2b15e46e638f4a64b2ca1c01d373f64874

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-26

Caso

HOW
Objetivo
verify validate in pkg:npm/schema-utils@4.3.3
Paquetes
Símbolos
  • validate
Creado
2026-08-26T04:33:28Z

Contrato

  1. validate accepts valid options conforming to JSON schema without throwing errors
  2. validate throws ValidationError when an option property has an invalid type
  3. validate throws ValidationError when a required property is missing from options
  4. validate throws ValidationError when unknown additional properties are passed with additionalProperties set to false
  5. validate applies custom configuration including name, baseDataPath, and postFormatter to format ValidationError messages
  6. validate verifies nested object and array structures according to schema definitions
  7. validate verifies enum constraints and oneOf/anyOf schema alternatives

Archivos

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

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 validate in pkg:npm/schema-utils@4.3.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/schema-utils@4.3.3
Demonstrate these symbols/APIs:
  - validate

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:b20c9605c95ff6ce1cbb8274eae312eede842462d88679c6cd48fb2f73d3070d","contract":["validate accepts valid options conforming to JSON schema without throwing errors","validate throws ValidationError when an option property has an invalid type","validate throws ValidationError when a required property is missing from options","validate throws ValidationError when unknown additional properties are passed with additionalProperties set to false","validate applies custom configuration including name, baseDataPath, and postFormatter to format ValidationError messages","validate verifies nested object and array structures according to schema definitions","validate verifies enum constraints and oneOf/anyOf schema alternatives"],"goal":"verify validate in pkg:npm/schema-utils@4.3.3","kind":"HOW","packages":["pkg:npm/schema-utils@4.3.3"],"schemaVersion":1,"symbols":["validate"]},"contractCommand":["node","test/contract.js"],"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/schema-utils@4.3.3"],"schemaVersion":1,"subject":"pkg:npm/schema-utils@4.3.3","symbols":["validate"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-schema-utils",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-schema-utils",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "schema-utils": "4.3.3"
      }
    },
    "node_modules/@types/json-schema": {
      "version": "7.0.15",
      "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
      "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
      "license": "MIT"
    },
    "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/ajv-formats": {
      "version": "2.1.1",
      "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz",
      "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",
      "license": "MIT",
      "dependencies": {
        "ajv": "^8.0.0"
      },
      "peerDependencies": {
        "ajv": "^8.0.0"
      },
      "peerDependenciesMeta": {
        "ajv": {
          "optional": true
        }
      }
    },
    "node_modules/ajv-keywords": {
      "version": "5.1.0",
      "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz",
      "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==",
      "license": "MIT",
      "dependencies": {
        "fast-deep-equal": "^3.1.3"
      },
      "peerDependencies": {
        "ajv": "^8.8.2"
      }
    },
    "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"
      }
    },
    "node_modules/schema-utils": {
      "version": "4.3.3",
      "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz",
      "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==",
      "license": "MIT",
      "dependencies": {
        "@types/json-schema": "^7.0.9",
        "ajv": "^8.9.0",
        "ajv-formats": "^2.1.1",
        "ajv-keywords": "^5.1.0"
      },
      "engines": {
        "node": ">= 10.13.0"
      },
      "funding": {
        "type": "opencollective",
        "url": "https://opencollective.com/webpack"
      }
    }
  }
}
package.json
{
  "name": "sample-schema-utils",
  "version": "1.0.0",
  "private": true,
  "description": "verify validate in pkg:npm/schema-utils@4.3.3",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "schema-utils": "4.3.3"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify validate in pkg:npm/schema-utils@4.3.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/schema-utils@4.3.3"
  ],
  "symbols": [
    "validate"
  ]
}
src/index.js
'use strict';

const { validate, ValidationError } = require('schema-utils');

/**
 * Validates options object against a JSON schema.
 *
 * @param {object} schema - JSON Schema object.
 * @param {object} options - Options object to validate.
 * @param {object} [configuration] - Configuration options (e.g. name, baseDataPath, postFormatter).
 * @returns {void}
 */
function validateOptions(schema, options, configuration) {
  validate(schema, options, configuration);
}

/**
 * Creates a reusable validator function for a specific schema.
 *
 * @param {object} schema - JSON Schema object.
 * @param {object} [defaultConfig] - Default configuration options.
 * @returns {(options: object, overrideConfig?: object) => void}
 */
function createValidator(schema, defaultConfig = {}) {
  return function (options, overrideConfig = {}) {
    const config = Object.assign({}, defaultConfig, overrideConfig);
    validate(schema, options, config);
  };
}

/**
 * Checks whether an error is a SchemaUtils ValidationError.
 *
 * @param {unknown} err - Value to check.
 * @returns {boolean}
 */
function isValidationError(err) {
  return err instanceof ValidationError;
}

module.exports = {
  validate,
  ValidationError,
  validateOptions,
  createValidator,
  isValidationError
};
test/contract.js
'use strict';

const assert = require('node:assert');
const {
  validate,
  ValidationError,
  validateOptions,
  createValidator,
  isValidationError
} = require('../src/index.js');

function testValidOptions() {
  const schema = {
    type: 'object',
    properties: {
      entry: { type: 'string' },
      port: { type: 'number' },
      minify: { type: 'boolean' }
    },
    required: ['entry'],
    additionalProperties: false
  };

  const options = {
    entry: 'src/main.js',
    port: 3000,
    minify: false
  };

  assert.doesNotThrow(() => {
    validate(schema, options, { name: 'BuildPlugin', baseDataPath: 'options' });
  });

  assert.doesNotThrow(() => {
    validateOptions(schema, options);
  });

  const validator = createValidator(schema, { name: 'BuildPlugin' });
  assert.doesNotThrow(() => {
    validator(options);
  });
}

function testInvalidTypeThrowsValidationError() {
  const schema = {
    type: 'object',
    properties: {
      port: { type: 'number' }
    },
    additionalProperties: false
  };

  const invalidOptions = { port: '3000' };

  let capturedError;
  try {
    validate(schema, invalidOptions, { name: 'ServerPlugin' });
  } catch (err) {
    capturedError = err;
  }

  assert.ok(capturedError, 'Expected validation to throw an error');
  assert.ok(capturedError instanceof ValidationError, 'Error should be instanceof ValidationError');
  assert.strictEqual(capturedError.name, 'ValidationError');
  assert.strictEqual(isValidationError(capturedError), true);
  assert.ok(Array.isArray(capturedError.errors), 'ValidationError should have an errors array');
  assert.ok(capturedError.errors.length > 0, 'errors array should not be empty');
  assert.match(capturedError.message, /should be a number/);
}

function testMissingRequiredProperty() {
  const schema = {
    type: 'object',
    properties: {
      target: { type: 'string' },
      output: { type: 'string' }
    },
    required: ['target', 'output'],
    additionalProperties: false
  };

  const invalidOptions = { target: 'node' };

  assert.throws(
    () => {
      validate(schema, invalidOptions, { name: 'TargetPlugin' });
    },
    (err) => {
      assert.ok(err instanceof ValidationError);
      assert.match(err.message, /misses the property 'output'/);
      return true;
    }
  );
}

function testAdditionalPropertiesForbidden() {
  const schema = {
    type: 'object',
    properties: {
      name: { type: 'string' }
    },
    additionalProperties: false
  };

  const invalidOptions = {
    name: 'bundle',
    extraOption: true
  };

  assert.throws(
    () => {
      validate(schema, invalidOptions, { name: 'StrictPlugin' });
    },
    (err) => {
      assert.ok(err instanceof ValidationError);
      assert.match(err.message, /has an unknown property 'extraOption'/);
      return true;
    }
  );
}

function testCustomConfigurationAndFormatting() {
  const schema = {
    type: 'object',
    properties: {
      filename: { type: 'string' }
    },
    required: ['filename']
  };

  let customFormatterCalled = false;
  const customConfig = {
    name: 'CustomFormatterPlugin',
    baseDataPath: 'config',
    postFormatter: (formattedError, errorPart) => {
      customFormatterCalled = true;
      return `[CUSTOM PREFIX] ${formattedError}`;
    }
  };

  assert.throws(
    () => {
      validate(schema, {}, customConfig);
    },
    (err) => {
      assert.ok(err instanceof ValidationError);
      assert.ok(customFormatterCalled, 'postFormatter should have been invoked');
      assert.ok(err.message.includes('[CUSTOM PREFIX]'), 'Custom prefix should appear in formatted error');
      assert.ok(err.message.includes('CustomFormatterPlugin'), 'Plugin name should appear in error');
      assert.ok(err.message.includes('config misses the property'), 'baseDataPath should be used');
      return true;
    }
  );
}

function testNestedObjectsAndArrays() {
  const schema = {
    type: 'object',
    properties: {
      server: {
        type: 'object',
        properties: {
          host: { type: 'string' },
          port: { type: 'number' }
        },
        required: ['host'],
        additionalProperties: false
      },
      rules: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            test: { type: 'string' },
            use: { type: 'string' }
          },
          required: ['test']
        }
      }
    },
    required: ['server', 'rules']
  };

  const validConfig = {
    server: { host: '127.0.0.1', port: 8080 },
    rules: [
      { test: '\\.js$', use: 'babel-loader' },
      { test: '\\.css$', use: 'css-loader' }
    ]
  };

  assert.doesNotThrow(() => {
    validate(schema, validConfig, { name: 'NestedPlugin' });
  });

  const invalidNestedConfig = {
    server: { host: 123 },
    rules: [{ test: '\\.js$' }]
  };

  assert.throws(
    () => {
      validate(schema, invalidNestedConfig, { name: 'NestedPlugin' });
    },
    (err) => {
      assert.ok(err instanceof ValidationError);
      assert.match(err.message, /server\.host should be a string/);
      return true;
    }
  );
}

function testEnumAndOneOfConstraints() {
  const schema = {
    type: 'object',
    properties: {
      mode: {
        enum: ['development', 'production', 'none']
      },
      devtool: {
        oneOf: [
          { type: 'string' },
          { type: 'boolean' }
        ]
      }
    },
    required: ['mode']
  };

  const validDev = { mode: 'development', devtool: 'source-map' };
  const validProd = { mode: 'production', devtool: false };

  assert.doesNotThrow(() => {
    validate(schema, validDev);
    validate(schema, validProd);
  });

  const invalidMode = { mode: 'staging' };
  assert.throws(
    () => {
      validate(schema, invalidMode, { name: 'ModePlugin' });
    },
    (err) => {
      assert.ok(err instanceof ValidationError);
      assert.match(err.message, /should be one of these/);
      return true;
    }
  );
}

function runAll() {
  testValidOptions();
  testInvalidTypeThrowsValidationError();
  testMissingRequiredProperty();
  testAdditionalPropertiesForbidden();
  testCustomConfigurationAndFormatting();
  testNestedObjectsAndArrays();
  testEnumAndOneOfConstraints();
  console.log('Contract tests passed successfully.');
}

runAll();

Seeder de origen

anónimo