CodeSampleX

Ejemplo

@vitest/snapshot 2.1.9: SnapshotState, NodeSnapshotEnvironment

Muestra verificada para npm @vitest/snapshot 2.1.9: SnapshotState, NodeSnapshotEnvironment. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y…

sha256:c2b813070b2c42589f552ed45c9571c9977d469a26d9173582eee395c2c109e0

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

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 pkg:npm/%40vitest/snapshot@2.1.9
Paquetes
Símbolos
  • SnapshotState
  • NodeSnapshotEnvironment
Entorno
node 22.23.2
Creado
2026-08-26T14:47:52Z

Contrato

  1. SnapshotState.create initializes state with NodeSnapshotEnvironment and matches new snapshots when updateSnapshot is 'all'.
  2. SnapshotState.prototype.save writes snapshot files to disk with formatted serialized contents.
  3. When updateSnapshot is 'none', SnapshotState.prototype.match passes for matching values and fails on mismatch.
  4. SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions.

Archivos

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

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

Código fuente

NOTES.md
# Notes on @vitest/snapshot SnapshotState and NodeSnapshotEnvironment

Search via `search_known_solution` returned `NO_SAFE_MATCH` for `@vitest/snapshot@2.1.9`, requiring fresh verification.

## API Characteristics

1. **Snapshot State Initialization:**
   `SnapshotState.create(testFilePath, options)` initializes a snapshot management instance. It requires `snapshotEnvironment` (an instance of `NodeSnapshotEnvironment` or custom `SnapshotEnvironment`) and `updateSnapshot` mode (`'all'`, `'new'`, or `'none'`).

2. **Matching and Formatting:**
   - Calling `state.match(...)` compares the serialized representation of `received` data against stored snapshots.
   - When updating or matching successfully, `pass` is `true`.
   - When `updateSnapshot: 'none'` and values differ, `pass` is `false`, and structured results with formatted values are provided.
   - `state.save()` commits the snapshot file to disk via the configured `SnapshotEnvironment`.

3. **Metrics Reporting:**
   - Calling `state.pack()` produces a summary containing counts of `added`, `matched`, `unmatched`, `updated`, and `unchecked` keys.

## Verified Contract

The contract in `test/contract.mjs` verifies:
- `SnapshotState.create` initializes state with `NodeSnapshotEnvironment` and matches new snapshots when `updateSnapshot` is `'all'`.
- `SnapshotState.prototype.save` writes snapshot files to disk with formatted serialized contents.
- When `updateSnapshot` is `'none'`, `SnapshotState.prototype.match` passes for matching values and fails on mismatch.
- `SnapshotState.prototype.pack` returns matched and unmatched counters for executed snapshot assertions.
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/%40vitest/snapshot@2.1.9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/snapshot@2.1.9
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:3311d53c154d23e5d943247beeb6cd077f6f92afcf5cfb16a254334b58d3c47a","constraints":{"executionContext":"node"},"contract":["SnapshotState.create initializes state with NodeSnapshotEnvironment and matches new snapshots when updateSnapshot is 'all'.","SnapshotState.prototype.save writes snapshot files to disk with formatted serialized contents.","When updateSnapshot is 'none', SnapshotState.prototype.match passes for matching values and fails on mismatch.","SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions."],"goal":"verify pkg:npm/%40vitest/snapshot@2.1.9","kind":"HOW","packages":["pkg:npm/%40vitest/snapshot@2.1.9"],"schemaVersion":1,"symbols":["SnapshotState","NodeSnapshotEnvironment"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40vitest/snapshot@2.1.9"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/snapshot@2.1.9","symbols":["SnapshotState","NodeSnapshotEnvironment"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { SnapshotState, addSerializer } from '@vitest/snapshot';
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment';

export async function createSnapshotManager(testFilePath, options = {}) {
  const env = new NodeSnapshotEnvironment();
  const state = await SnapshotState.create(testFilePath, {
    updateSnapshot: options.updateSnapshot || 'new',
    snapshotEnvironment: env,
  });
  return state;
}

export function registerCustomSerializer(serializer) {
  addSerializer(serializer);
}
package-lock.json
{
  "name": "vitest-snapshot-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "vitest-snapshot-sample",
      "version": "1.0.0",
      "dependencies": {
        "@vitest/snapshot": "2.1.9"
      }
    },
    "node_modules/@jridgewell/sourcemap-codec": {
      "version": "1.5.5",
      "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
      "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
      "license": "MIT"
    },
    "node_modules/@vitest/pretty-format": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
      "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
      "license": "MIT",
      "dependencies": {
        "tinyrainbow": "^1.2.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/snapshot": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",
      "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
      "license": "MIT",
      "dependencies": {
        "@vitest/pretty-format": "2.1.9",
        "magic-string": "^0.30.12",
        "pathe": "^1.1.2"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/magic-string": {
      "version": "0.30.21",
      "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
      "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
      "license": "MIT",
      "dependencies": {
        "@jridgewell/sourcemap-codec": "^1.5.5"
      }
    },
    "node_modules/pathe": {
      "version": "1.1.2",
      "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
      "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
      "license": "MIT"
    },
    "node_modules/tinyrainbow": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
      "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "vitest-snapshot-sample",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "@vitest/snapshot": "2.1.9"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40vitest/snapshot@2.1.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/snapshot@2.1.9"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { SnapshotState } from '@vitest/snapshot';
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const tmpDir = path.join(__dirname, 'tmp_sandbox');

async function main() {
  await fs.mkdir(tmpDir, { recursive: true });
  const testFilePath = path.join(tmpDir, 'sample.test.js');
  const env = new NodeSnapshotEnvironment();

  try {
    // 1. SnapshotState.create initializes state with NodeSnapshotEnvironment and matches new snapshots when updateSnapshot is 'all'
    const stateUpdate = await SnapshotState.create(testFilePath, {
      updateSnapshot: 'all',
      snapshotEnvironment: env,
    });
    assert.ok(stateUpdate, 'SnapshotState instance should be created');

    const matchRes1 = stateUpdate.match({
      testId: 'test-user-profile',
      testName: 'renders user profile correctly',
      received: { id: 101, username: 'agent-alice', active: true },
      isInline: false,
    });
    assert.equal(matchRes1.pass, true, 'Matching new snapshot in all mode must pass');
    assert.equal(matchRes1.key, 'renders user profile correctly 1');

    // 2. SnapshotState.prototype.save writes snapshot files to disk with formatted serialized contents
    const saveResult = await stateUpdate.save();
    assert.equal(saveResult.saved, true, 'SnapshotState save should return saved: true');

    const packedUpdate = await stateUpdate.pack();
    assert.equal(packedUpdate.added, 1, 'Packed summary must show 1 snapshot added');
    assert.equal(packedUpdate.unmatched, 0);

    // 3. When updateSnapshot is 'none', SnapshotState.prototype.match passes for matching values and fails on mismatch
    const stateReadonly = await SnapshotState.create(testFilePath, {
      updateSnapshot: 'none',
      snapshotEnvironment: env,
    });

    const matchPass = stateReadonly.match({
      testId: 'test-user-profile',
      testName: 'renders user profile correctly',
      received: { id: 101, username: 'agent-alice', active: true },
      isInline: false,
    });
    assert.equal(matchPass.pass, true, 'Matching identical value against existing snapshot must pass');

    const matchFail = stateReadonly.match({
      testId: 'test-user-profile',
      testName: 'renders user profile correctly',
      received: { id: 101, username: 'agent-bob', active: false },
      isInline: false,
    });
    assert.equal(matchFail.pass, false, 'Matching modified value with updateSnapshot none must fail');
    assert.ok(matchFail.actual !== undefined, 'Mismatch result should include actual value');

    // 4. SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions
    const packedReadonly = await stateReadonly.pack();
    assert.equal(packedReadonly.matched, 1, 'Matched count should be 1');
    assert.equal(packedReadonly.unmatched, 1, 'Unmatched count should be 1');
    assert.equal(packedReadonly.added, 0, 'Added count should be 0');

    console.log('All contract assertions passed successfully.');
  } finally {
    await fs.rm(tmpDir, { recursive: true, force: true });
  }
}

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

Seeder de origen

anónimo