CodeSampleX

Exemple

@vitest/mocker 3.2.7

Échantillon vérifié pour npm @vitest/mocker 3.2.7. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi.

sha256:9a5559216e50f3d90e66d9da4a06bcc471ba24d250929ddc330ab08c95b6f286

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: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/%40vitest/mocker@3.2.7
Paquets
Environnement
node 22.23.2
Créé
2026-08-23T14:25:37Z

Contrat

  1. MockerRegistry registers manual mocks with factory functions and resolves cached exports
  2. MockerRegistry registers redirect and automock module descriptors and looks up entries by id or url
  3. MockerRegistry serializes mock definitions to JSON with toJSON and supports deletion and clear
  4. mockObject recursively generates spy wrappers around target object methods

Fichiers

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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/%40vitest/mocker@3.2.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/mocker@3.2.7
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:e9d9ea6f67b5691ac83d020ef9b0b7bb78472ec0808e64fac000ff173689eb25","constraints":{"executionContext":"node"},"contract":["MockerRegistry registers manual mocks with factory functions and resolves cached exports","MockerRegistry registers redirect and automock module descriptors and looks up entries by id or url","MockerRegistry serializes mock definitions to JSON with toJSON and supports deletion and clear","mockObject recursively generates spy wrappers around target object methods"],"goal":"verify pkg:npm/%40vitest/mocker@3.2.7","kind":"HOW","packages":["pkg:npm/%40vitest/mocker@3.2.7"],"schemaVersion":1},"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/%40vitest/mocker@3.2.7"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/mocker@3.2.7","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-vitest-mocker",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-mocker",
      "version": "1.0.0",
      "dependencies": {
        "@vitest/mocker": "3.2.7"
      }
    },
    "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/@types/estree": {
      "version": "1.0.9",
      "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
      "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
      "license": "MIT"
    },
    "node_modules/@vitest/mocker": {
      "version": "3.2.7",
      "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz",
      "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==",
      "license": "MIT",
      "dependencies": {
        "@vitest/spy": "3.2.7",
        "estree-walker": "^3.0.3",
        "magic-string": "^0.30.17"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      },
      "peerDependencies": {
        "msw": "^2.4.9",
        "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
      },
      "peerDependenciesMeta": {
        "msw": {
          "optional": true
        },
        "vite": {
          "optional": true
        }
      }
    },
    "node_modules/@vitest/spy": {
      "version": "3.2.7",
      "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz",
      "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==",
      "license": "MIT",
      "dependencies": {
        "tinyspy": "^4.0.3"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/estree-walker": {
      "version": "3.0.3",
      "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
      "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
      "license": "MIT",
      "dependencies": {
        "@types/estree": "^1.0.0"
      }
    },
    "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/tinyspy": {
      "version": "4.0.4",
      "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz",
      "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-mocker",
  "version": "1.0.0",
  "description": "Clean-room verification of @vitest/mocker",
  "type": "module",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@vitest/mocker": "3.2.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40vitest/mocker@3.2.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/mocker@3.2.7"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
import {
  MockerRegistry,
  AutomockedModule,
  AutospiedModule,
  ManualMockedModule,
  RedirectedModule,
  mockObject,
} from '@vitest/mocker';

/**
 * Creates and initializes a new MockerRegistry instance.
 *
 * @returns {MockerRegistry} A new mocker registry.
 */
export function createRegistry() {
  return new MockerRegistry();
}

/**
 * Registers a manual mock module with a factory function.
 *
 * @param {MockerRegistry} registry - The registry to add the mock to.
 * @param {string} raw - The raw import specifier.
 * @param {string} id - The resolved module id.
 * @param {string} url - The resolved module URL.
 * @param {() => Record<string | symbol, unknown> | Promise<Record<string | symbol, unknown>>} factory - The module factory.
 * @returns {ManualMockedModule} The registered manual mock module.
 */
export function registerManualMock(registry, raw, id, url, factory) {
  return registry.register('manual', raw, id, url, factory);
}

/**
 * Registers a module redirection in the registry.
 *
 * @param {MockerRegistry} registry - The registry to add the mock to.
 * @param {string} raw - The raw import specifier.
 * @param {string} id - The resolved module id.
 * @param {string} url - The resolved module URL.
 * @param {string} redirect - Target redirected URL or path.
 * @returns {RedirectedModule} The registered redirected module.
 */
export function registerRedirectMock(registry, raw, id, url, redirect) {
  return registry.register('redirect', raw, id, url, redirect);
}

/**
 * Registers an automock module descriptor in the registry.
 *
 * @param {MockerRegistry} registry - The registry to add the mock to.
 * @param {string} raw - The raw import specifier.
 * @param {string} id - The resolved module id.
 * @param {string} url - The resolved module URL.
 * @returns {AutomockedModule} The registered automocked module.
 */
export function registerAutomock(registry, raw, id, url) {
  return registry.register('automock', raw, id, url);
}

/**
 * Mocks an object structure by replacing functions with spy wrappers.
 *
 * @param {Record<string | symbol, unknown>} target - Object to mock.
 * @param {(obj: Record<string | symbol, unknown>, prop: string | symbol) => unknown} spyOn - Spy factory function.
 * @param {'automock' | 'autospy' | 'manual' | 'redirect'} [type='automock'] - Mocking mode.
 * @returns {Record<string | symbol, unknown>} The mocked object.
 */
export function createMockObject(target, spyOn, type = 'automock') {
  return mockObject(
    {
      type,
      globalConstructors: {
        Object,
        Function,
        RegExp,
        Array,
        Map,
      },
      spyOn,
    },
    target
  );
}

export {
  MockerRegistry,
  AutomockedModule,
  AutospiedModule,
  ManualMockedModule,
  RedirectedModule,
  mockObject,
};
test/contract.mjs
import assert from 'node:assert';
import {
  createRegistry,
  registerManualMock,
  registerRedirectMock,
  registerAutomock,
  createMockObject,
  MockerRegistry,
  AutomockedModule,
  AutospiedModule,
  ManualMockedModule,
  RedirectedModule,
  mockObject,
} from '../src/index.js';

async function runContract() {
  // 1. MockerRegistry registers manual mocks with factory function and resolves cached exports
  const registry = createRegistry();
  assert.ok(registry instanceof MockerRegistry, 'createRegistry should return MockerRegistry instance');

  let factoryInvocationCount = 0;
  const manualMock = registerManualMock(
    registry,
    'mock-pkg',
    'pkg-id-1',
    'file:///workspace/mock-pkg.js',
    async () => {
      factoryInvocationCount++;
      return {
        greet: (name) => `Hello, ${name}!`,
        version: '1.0.0',
      };
    }
  );

  assert.ok(manualMock instanceof ManualMockedModule, 'should return ManualMockedModule instance');
  assert.strictEqual(manualMock.type, 'manual');
  assert.strictEqual(manualMock.raw, 'mock-pkg');
  assert.strictEqual(manualMock.id, 'pkg-id-1');
  assert.strictEqual(manualMock.url, 'file:///workspace/mock-pkg.js');

  const resolvedA = await manualMock.resolve();
  assert.strictEqual(resolvedA.greet('CodeSampleX'), 'Hello, CodeSampleX!');
  assert.strictEqual(resolvedA.version, '1.0.0');
  assert.strictEqual(factoryInvocationCount, 1);

  // Calling resolve again should return cached instance without invoking factory again
  const resolvedB = await manualMock.resolve();
  assert.strictEqual(resolvedB, resolvedA);
  assert.strictEqual(factoryInvocationCount, 1);

  // 2. MockerRegistry registers redirect and automock module descriptors and checks membership by id/url
  const redirectMock = registerRedirectMock(
    registry,
    'alias-pkg',
    'pkg-id-2',
    'file:///workspace/alias-pkg.js',
    'file:///workspace/actual-pkg.js'
  );
  assert.ok(redirectMock instanceof RedirectedModule, 'should return RedirectedModule instance');
  assert.strictEqual(redirectMock.type, 'redirect');
  assert.strictEqual(redirectMock.redirect, 'file:///workspace/actual-pkg.js');

  const automock = registerAutomock(
    registry,
    'auto-pkg',
    'pkg-id-3',
    'file:///workspace/auto-pkg.js'
  );
  assert.ok(automock instanceof AutomockedModule, 'should return AutomockedModule instance');
  assert.strictEqual(automock.type, 'automock');

  // Verify lookup by URL and ID
  assert.strictEqual(registry.has('file:///workspace/mock-pkg.js'), true);
  assert.strictEqual(registry.has('file:///workspace/alias-pkg.js'), true);
  assert.strictEqual(registry.has('file:///workspace/auto-pkg.js'), true);
  assert.strictEqual(registry.has('file:///workspace/non-existent.js'), false);

  assert.strictEqual(registry.get('file:///workspace/mock-pkg.js'), manualMock);
  assert.strictEqual(registry.getById('pkg-id-1'), manualMock);
  assert.strictEqual(registry.get('file:///workspace/alias-pkg.js'), redirectMock);
  assert.strictEqual(registry.getById('pkg-id-2'), redirectMock);

  // 3. MockerRegistry supports serialization with toJSON and removal of registered mocks
  const serializedRedirect = redirectMock.toJSON();
  assert.deepStrictEqual(serializedRedirect, {
    type: 'redirect',
    url: 'file:///workspace/alias-pkg.js',
    id: 'pkg-id-2',
    raw: 'alias-pkg',
    redirect: 'file:///workspace/actual-pkg.js',
  });

  const deserializedRedirect = RedirectedModule.fromJSON(serializedRedirect);
  assert.ok(deserializedRedirect instanceof RedirectedModule);
  assert.strictEqual(deserializedRedirect.redirect, 'file:///workspace/actual-pkg.js');

  const serializedAutomock = automock.toJSON();
  assert.deepStrictEqual(serializedAutomock, {
    type: 'automock',
    url: 'file:///workspace/auto-pkg.js',
    id: 'pkg-id-3',
    raw: 'auto-pkg',
  });

  // Test registry delete and clear
  registry.delete('file:///workspace/alias-pkg.js');
  assert.strictEqual(registry.has('file:///workspace/alias-pkg.js'), false);

  registry.clear();
  assert.strictEqual(registry.has('file:///workspace/mock-pkg.js'), false);
  assert.strictEqual(registry.has('file:///workspace/auto-pkg.js'), false);

  // 4. mockObject recursively generates spy wrappers around target object methods
  const recordedSpyCalls = [];
  const mockSpyOn = (obj, prop) => {
    const fn = (...args) => {
      recordedSpyCalls.push({ prop, args });
      return `spied-${String(prop)}`;
    };
    fn.mockImplementation = (impl) => fn;
    fn.mockReset = () => fn;
    fn.mockRestore = () => fn;
    obj[prop] = fn;
    return fn;
  };

  const sampleTarget = {
    add(a, b) {
      return a + b;
    },
    subModule: {
      multiply(x, y) {
        return x * y;
      },
    },
    constantValue: 100,
  };

  const mockedObj = createMockObject(sampleTarget, mockSpyOn, 'automock');
  assert.strictEqual(mockedObj.constantValue, 100);

  mockedObj.add(10, 20);
  mockedObj.subModule.multiply(3, 4);

  assert.strictEqual(recordedSpyCalls.length, 2);
  assert.strictEqual(recordedSpyCalls[0].prop, 'add');
  assert.deepStrictEqual(recordedSpyCalls[0].args, [10, 20]);
  assert.strictEqual(recordedSpyCalls[1].prop, 'multiply');
  assert.deepStrictEqual(recordedSpyCalls[1].args, [3, 4]);

  console.log('All contract assertions passed successfully.');
}

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

Seeder d'origine

anonyme