CodeSampleX

示例

@jest/schemas 29.6.3: validate Jest snapshot formatting configuration using the SnapshotFormat schema

已验证示例 — npm @jest/schemas 29.6.3: validate Jest snapshot formatting configuration using the SnapshotFormat schema. contract 在 node 22 · linux alpine/x64 …

sha256:25db2beeee3b7ea7361bd2a83ba58994c800307acfe343c5d5aeab646cff6093

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-21

案例

HOW
目标
validate Jest snapshot formatting configuration using the SnapshotFormat schema
包
符号
  • SnapshotFormat
环境
node 22.23.2
创建时间
2026-08-21T05:11:14Z

契约

  1. SnapshotFormat provides the JSON schema definition for Jest snapshot options
  2. validateSnapshotFormat validates compliant snapshot formatting options including indent and theme
  3. validateSnapshotFormat accepts empty configuration as all SnapshotFormat options are optional
  4. validateSnapshotFormat rejects invalid option types and negative indentation values
  5. validateSnapshotFormat rejects unrecognized top-level and nested theme properties

文件

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

下载源代码构件 (tar.gz)

源代码

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: validate Jest snapshot formatting configuration using the SnapshotFormat schema
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40jest/schemas@29.6.3
Demonstrate these symbols/APIs:
  - SnapshotFormat
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:ebd38b1df67a449b1bf03051805b16f5973cf4cb12a5d9c36aa5bab587169ca3","constraints":{"executionContext":"node"},"contract":["SnapshotFormat provides the JSON schema definition for Jest snapshot options","validateSnapshotFormat validates compliant snapshot formatting options including indent and theme","validateSnapshotFormat accepts empty configuration as all SnapshotFormat options are optional","validateSnapshotFormat rejects invalid option types and negative indentation values","validateSnapshotFormat rejects unrecognized top-level and nested theme properties"],"goal":"validate Jest snapshot formatting configuration using the SnapshotFormat schema","kind":"HOW","packages":["pkg:npm/%40jest/schemas@29.6.3"],"schemaVersion":1,"symbols":["SnapshotFormat"]},"contractCommand":["node","test/contract.mjs"],"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/%40jest/schemas@29.6.3"],"schemaVersion":1,"subject":"pkg:npm/%40jest/schemas@29.6.3","symbols":["SnapshotFormat"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-jest-schemas",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jest-schemas",
      "version": "1.0.0",
      "dependencies": {
        "@jest/schemas": "29.6.3"
      }
    },
    "node_modules/@jest/schemas": {
      "version": "29.6.3",
      "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz",
      "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==",
      "license": "MIT",
      "dependencies": {
        "@sinclair/typebox": "^0.27.8"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/@sinclair/typebox": {
      "version": "0.27.12",
      "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz",
      "integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-jest-schemas",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @jest/schemas",
  "main": "src/index.js",
  "dependencies": {
    "@jest/schemas": "29.6.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "validate Jest snapshot formatting configuration using the SnapshotFormat schema",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40jest/schemas@29.6.3"
  ],
  "symbols": [
    "SnapshotFormat"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { SnapshotFormat } = require('@jest/schemas');

/**
 * Validates a snapshot format configuration object against the SnapshotFormat schema.
 *
 * @param {Record<string, unknown>} options - Configuration options to validate.
 * @returns {{ isValid: boolean, errors: string[] }} Result of validation.
 */
function validateSnapshotFormat(options) {
  if (typeof options !== 'object' || options === null || Array.isArray(options)) {
    return {
      isValid: false,
      errors: ['SnapshotFormat options must be a plain object']
    };
  }

  const errors = [];
  const schemaProps = SnapshotFormat.properties;

  for (const key of Object.keys(options)) {
    if (!Object.prototype.hasOwnProperty.call(schemaProps, key)) {
      errors.push(`Unknown option: "${key}"`);
      continue;
    }

    const val = options[key];
    if (val === undefined) {
      continue;
    }

    const propSchema = schemaProps[key];

    if (key === 'theme') {
      if (typeof val !== 'object' || val === null || Array.isArray(val)) {
        errors.push('Option "theme" must be an object');
      } else {
        const themeProps = propSchema.properties;
        for (const themeKey of Object.keys(val)) {
          if (!Object.prototype.hasOwnProperty.call(themeProps, themeKey)) {
            errors.push(`Unknown theme option: "${themeKey}"`);
          } else if (val[themeKey] !== undefined && typeof val[themeKey] !== 'string') {
            errors.push(`Option "theme.${themeKey}" must be a string`);
          }
        }
      }
    } else if (propSchema.type === 'boolean') {
      if (typeof val !== 'boolean') {
        errors.push(`Option "${key}" must be a boolean`);
      }
    } else if (propSchema.type === 'number') {
      if (typeof val !== 'number' || Number.isNaN(val) || (propSchema.minimum !== undefined && val < propSchema.minimum)) {
        errors.push(`Option "${key}" must be a number >= ${propSchema.minimum ?? 0}`);
      }
    } else if (propSchema.type === 'null') {
      if (val !== null) {
        errors.push(`Option "${key}" must be null`);
      }
    }
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

module.exports = {
  SnapshotFormat,
  validateSnapshotFormat
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { SnapshotFormat, validateSnapshotFormat } = require('../src/index.js');

// 1. Symbol & Schema verification
assert.strictEqual(typeof SnapshotFormat, 'object', 'SnapshotFormat should be an object');
assert.strictEqual(SnapshotFormat.type, 'object', 'SnapshotFormat schema type should be object');
assert.ok(SnapshotFormat.properties, 'SnapshotFormat schema should have properties');
assert.strictEqual(typeof SnapshotFormat.properties.indent, 'object', 'indent property schema should exist');
assert.strictEqual(SnapshotFormat.properties.indent.minimum, 0, 'indent minimum should be 0');
assert.strictEqual(SnapshotFormat.properties.theme.type, 'object', 'theme property should be an object');
assert.strictEqual(typeof validateSnapshotFormat, 'function', 'validateSnapshotFormat should be a function');

// 2. Validate valid snapshot format configuration
const validConfig = {
  callToJSON: true,
  escapeRegex: false,
  escapeString: true,
  highlight: false,
  indent: 2,
  maxDepth: 10,
  maxWidth: 80,
  min: false,
  printBasicPrototype: true,
  printFunctionName: true,
  theme: {
    comment: 'gray',
    content: 'reset',
    prop: 'yellow',
    tag: 'cyan',
    value: 'green'
  }
};

const validResult = validateSnapshotFormat(validConfig);
assert.deepStrictEqual(validResult, {
  isValid: true,
  errors: []
}, 'Valid configuration should pass validation without errors');

// 3. Validate empty / partial configuration (all properties are optional in SnapshotFormat)
const emptyResult = validateSnapshotFormat({});
assert.strictEqual(emptyResult.isValid, true, 'Empty configuration should be valid');

// 4. Reject invalid options, types, and out-of-bound values
const invalidTypesConfig = {
  callToJSON: 'not-a-boolean',
  indent: -2,
  compareKeys: 'not-null'
};
const invalidTypesResult = validateSnapshotFormat(invalidTypesConfig);
assert.strictEqual(invalidTypesResult.isValid, false, 'Invalid types should fail validation');
assert.ok(invalidTypesResult.errors.some(e => e.includes('callToJSON')), 'Should report error for callToJSON');
assert.ok(invalidTypesResult.errors.some(e => e.includes('indent')), 'Should report error for indent');
assert.ok(invalidTypesResult.errors.some(e => e.includes('compareKeys')), 'Should report error for compareKeys');

// 5. Reject unknown properties and invalid nested theme properties
const unknownPropsConfig = {
  unrecognizedProperty: true,
  theme: {
    invalidThemeField: 123,
    comment: 456
  }
};
const unknownPropsResult = validateSnapshotFormat(unknownPropsConfig);
assert.strictEqual(unknownPropsResult.isValid, false, 'Unknown properties should fail validation');
assert.ok(unknownPropsResult.errors.some(e => e.includes('unrecognizedProperty')), 'Should report error for unrecognized property');
assert.ok(unknownPropsResult.errors.some(e => e.includes('invalidThemeField')), 'Should report error for unrecognized theme field');
assert.ok(unknownPropsResult.errors.some(e => e.includes('theme.comment')), 'Should report error for non-string theme.comment');

console.log('Contract tests passed successfully.');

原始种子者

匿名