CodeSampleX

Пример

@vitest/mocker 4.1.11

Проверенный пример — npm @vitest/mocker 4.1.11. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: assert MockerRegistry instantiates with…

sha256:5f33d1a6b9fcc29b13f943b7d260f482007bb7e4faf20802c5a4669c7b302439

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-28

Кейс

HOW
Цель
verify pkg:npm/%40vitest/mocker@4.1.11
Пакеты
Окружение
node 22.23.2
Создан
2026-08-28T06:23:33Z

Контракт

  1. assert MockerRegistry instantiates with empty state
  2. assert registry.register with type manual creates and registers a ManualMockedModule
  3. assert manual mock resolve executes factory and caches result
  4. assert registry.register with type automock creates and registers an AutomockedModule
  5. assert registry.register with type autospy creates and registers an AutospiedModule
  6. assert registry.register with type redirect creates and registers a RedirectedModule
  7. assert registry.get and registry.getById retrieve registered modules
  8. assert AutomockedModule and RedirectedModule serialize to JSON and deserialize via fromJSON
  9. assert mockObject automocks object functions while preserving primitive properties
  10. assert registry.delete removes an entry and registry.clear resets all registered modules

Файлы

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

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/mocker@4.1.11

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:0ff17f57338f05b859f3650b77bc474e1483d416811c01166cc9150d26a9c89c","constraints":{"executionContext":"node"},"contract":["assert MockerRegistry instantiates with empty state","assert registry.register with type manual creates and registers a ManualMockedModule","assert manual mock resolve executes factory and caches result","assert registry.register with type automock creates and registers an AutomockedModule","assert registry.register with type autospy creates and registers an AutospiedModule","assert registry.register with type redirect creates and registers a RedirectedModule","assert registry.get and registry.getById retrieve registered modules","assert AutomockedModule and RedirectedModule serialize to JSON and deserialize via fromJSON","assert mockObject automocks object functions while preserving primitive properties","assert registry.delete removes an entry and registry.clear resets all registered modules"],"goal":"verify pkg:npm/%40vitest/mocker@4.1.11","kind":"HOW","packages":["pkg:npm/%40vitest/mocker@4.1.11"],"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@4.1.11"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/mocker@4.1.11","verifierAdapter":"node-typescript@1"}
index.js
const {
  MockerRegistry,
  AutomockedModule,
  AutospiedModule,
  ManualMockedModule,
  RedirectedModule,
  mockObject,
} = require('@vitest/mocker');

/**
 * Creates a new MockerRegistry instance.
 * @returns {MockerRegistry}
 */
function createRegistry() {
  return new MockerRegistry();
}

/**
 * Registers a manual mock with factory.
 * @param {MockerRegistry} registry
 * @param {string} raw
 * @param {string} id
 * @param {string} url
 * @param {() => any} factory
 * @returns {ManualMockedModule}
 */
function registerManualMock(registry, raw, id, url, factory) {
  return registry.register('manual', raw, id, url, factory);
}

/**
 * Registers an automock.
 * @param {MockerRegistry} registry
 * @param {string} raw
 * @param {string} id
 * @param {string} url
 * @returns {AutomockedModule}
 */
function registerAutomock(registry, raw, id, url) {
  return registry.register('automock', raw, id, url);
}

/**
 * Registers an autospy.
 * @param {MockerRegistry} registry
 * @param {string} id
 * @param {string} raw
 * @param {string} url
 * @returns {AutospiedModule}
 */
function registerAutospy(registry, id, raw, url) {
  return registry.register('autospy', id, raw, url);
}

/**
 * Registers a redirect mock.
 * @param {MockerRegistry} registry
 * @param {string} raw
 * @param {string} id
 * @param {string} url
 * @param {string} redirect
 * @returns {RedirectedModule}
 */
function registerRedirectMock(registry, raw, id, url, redirect) {
  return registry.register('redirect', raw, id, url, redirect);
}

/**
 * Automocks an object with custom procedures.
 * @param {Record<string | symbol, any>} target
 * @param {Function} createMockInstance
 * @returns {Record<string | symbol, any>}
 */
function mockTargetObject(target, createMockInstance) {
  return mockObject(
    {
      type: 'automock',
      globalConstructors: {
        Object,
        Function,
        RegExp,
        Array,
        Map,
      },
      createMockInstance,
    },
    target
  );
}

module.exports = {
  MockerRegistry,
  AutomockedModule,
  AutospiedModule,
  ManualMockedModule,
  RedirectedModule,
  mockObject,
  createRegistry,
  registerManualMock,
  registerAutomock,
  registerAutospy,
  registerRedirectMock,
  mockTargetObject,
};
package-lock.json
{
  "name": "sample-vitest-mocker",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-mocker",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@vitest/mocker": "4.1.11"
      }
    },
    "node_modules/@jridgewell/sourcemap-codec": {
      "version": "1.6.0",
      "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
      "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
      "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": "4.1.11",
      "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
      "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
      "license": "MIT",
      "dependencies": {
        "@vitest/spy": "4.1.11",
        "estree-walker": "^3.0.3",
        "magic-string": "^0.30.21"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      },
      "peerDependencies": {
        "msw": "^2.4.9",
        "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
      },
      "peerDependenciesMeta": {
        "msw": {
          "optional": true
        },
        "vite": {
          "optional": true
        }
      }
    },
    "node_modules/@vitest/spy": {
      "version": "4.1.11",
      "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
      "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
      "license": "MIT",
      "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"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-mocker",
  "version": "1.0.0",
  "description": "Clean-room sample verifying @vitest/mocker",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "@vitest/mocker": "4.1.11"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40vitest/mocker@4.1.11",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/mocker@4.1.11"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import {
  MockerRegistry,
  AutomockedModule,
  AutospiedModule,
  ManualMockedModule,
  RedirectedModule,
  createRegistry,
  registerManualMock,
  registerAutomock,
  registerAutospy,
  registerRedirectMock,
  mockTargetObject,
} from '../index.js';

// 1. Instantiation and initial empty state
const registry = createRegistry();
assert.ok(registry instanceof MockerRegistry, 'createRegistry should return a MockerRegistry instance');
assert.strictEqual(registry.has('file:///mock/target'), false, 'registry should not have target initially');
assert.strictEqual(registry.get('file:///mock/target'), undefined, 'get should return undefined for non-existent mock');
assert.strictEqual(registry.getById('/mock/target'), undefined, 'getById should return undefined for non-existent mock');
assert.deepStrictEqual(Array.from(registry.keys()), [], 'keys() should be empty initially');

// 2. Register manual mock with factory
let factoryCalls = 0;
const manualFactory = () => {
  factoryCalls++;
  return { calculate: (a, b) => a + b, tag: 'manual-v1' };
};
const manualMock = registerManualMock(
  registry,
  'my-calc-module',
  '/mock/calc',
  'file:///mock/calc',
  manualFactory
);

assert.ok(manualMock instanceof ManualMockedModule, 'manual mock should be an instance of ManualMockedModule');
assert.strictEqual(manualMock.type, 'manual', 'manual mock type should be "manual"');
assert.strictEqual(manualMock.raw, 'my-calc-module', 'manual mock raw should match');
assert.strictEqual(manualMock.id, '/mock/calc', 'manual mock id should match');
assert.strictEqual(manualMock.url, 'file:///mock/calc', 'manual mock url should match');

// 3. Resolve manual mock factory and check cache
const resolvedExports1 = manualMock.resolve();
assert.strictEqual(factoryCalls, 1, 'factory should be invoked once upon first resolve');
assert.strictEqual(typeof resolvedExports1.calculate, 'function', 'calculate should be a function');
assert.strictEqual(resolvedExports1.calculate(10, 20), 30, 'calculate(10, 20) should return 30');
assert.strictEqual(resolvedExports1.tag, 'manual-v1', 'tag should match');
assert.strictEqual(manualMock.cache, resolvedExports1, 'manualMock.cache should store resolved exports');

const resolvedExports2 = manualMock.resolve();
assert.strictEqual(factoryCalls, 1, 'subsequent resolve calls should return cached exports without re-invoking factory');
assert.strictEqual(resolvedExports1, resolvedExports2, 'cached reference should be identical');

// 4. Register automock module
const autoMock = registerAutomock(registry, 'auto-module', '/mock/auto', 'file:///mock/auto');
assert.ok(autoMock instanceof AutomockedModule, 'automock should be an instance of AutomockedModule');
assert.strictEqual(autoMock.type, 'automock', 'automock type should be "automock"');
assert.strictEqual(autoMock.raw, 'auto-module', 'automock raw should match');
assert.strictEqual(autoMock.id, '/mock/auto', 'automock id should match');
assert.strictEqual(autoMock.url, 'file:///mock/auto', 'automock url should match');

// 5. Register autospy module
const autoSpy = registerAutospy(registry, '/mock/spy', 'spy-module', 'file:///mock/spy');
assert.ok(autoSpy instanceof AutospiedModule, 'autospy should be an instance of AutospiedModule');
assert.strictEqual(autoSpy.type, 'autospy', 'autospy type should be "autospy"');
assert.strictEqual(autoSpy.raw, '/mock/spy', 'autospy raw should match');
assert.strictEqual(autoSpy.id, 'spy-module', 'autospy id should match');
assert.strictEqual(autoSpy.url, 'file:///mock/spy', 'autospy url should match');

// 6. Register redirect module
const redirectMock = registerRedirectMock(
  registry,
  'redirect-module',
  '/mock/redirect',
  'file:///mock/redirect',
  '/mock/destination'
);
assert.ok(redirectMock instanceof RedirectedModule, 'redirect should be an instance of RedirectedModule');
assert.strictEqual(redirectMock.type, 'redirect', 'redirect type should be "redirect"');
assert.strictEqual(redirectMock.raw, 'redirect-module', 'redirect raw should match');
assert.strictEqual(redirectMock.id, '/mock/redirect', 'redirect id should match');
assert.strictEqual(redirectMock.url, 'file:///mock/redirect', 'redirect url should match');
assert.strictEqual(redirectMock.redirect, '/mock/destination', 'redirect destination should match');

// 7. Querying registry by url and id
assert.strictEqual(registry.has('file:///mock/calc'), true, 'registry.has(url) should return true for manual mock');
assert.strictEqual(registry.get('file:///mock/calc'), manualMock, 'registry.get(url) should return manualMock');
assert.strictEqual(registry.getById('/mock/calc'), manualMock, 'registry.getById(id) should return manualMock');
assert.strictEqual(registry.get('file:///mock/auto'), autoMock, 'registry.get(url) should return autoMock');
assert.strictEqual(registry.getById('/mock/auto'), autoMock, 'registry.getById(id) should return autoMock');
assert.strictEqual(registry.get('file:///mock/spy'), autoSpy, 'registry.get(url) should return autoSpy');
assert.strictEqual(registry.getById('spy-module'), autoSpy, 'registry.getById(id) should return autoSpy');
assert.strictEqual(registry.get('file:///mock/redirect'), redirectMock, 'registry.get(url) should return redirectMock');
assert.strictEqual(registry.getById('/mock/redirect'), redirectMock, 'registry.getById(id) should return redirectMock');

// 8. Serialization and Deserialization
const serializedAuto = autoMock.toJSON();
assert.deepStrictEqual(serializedAuto, {
  type: 'automock',
  raw: 'auto-module',
  id: '/mock/auto',
  url: 'file:///mock/auto',
}, 'serialized automock structure should match');

const serializedRedirect = redirectMock.toJSON();
assert.deepStrictEqual(serializedRedirect, {
  type: 'redirect',
  raw: 'redirect-module',
  id: '/mock/redirect',
  url: 'file:///mock/redirect',
  redirect: '/mock/destination',
}, 'serialized redirect structure should match');

const reconstructedRedirect = RedirectedModule.fromJSON(serializedRedirect);
assert.ok(reconstructedRedirect instanceof RedirectedModule, 'fromJSON should reconstruct RedirectedModule');
assert.strictEqual(reconstructedRedirect.type, 'redirect', 'reconstructed type should be redirect');
assert.strictEqual(reconstructedRedirect.redirect, '/mock/destination', 'reconstructed redirect path should match');

// 9. mockObject helper verification
const mockFactory = () => () => 'mock-fn-result';
const originalObject = {
  version: 42,
  title: 'mocker test',
  isActive: true,
  execute: (x) => x * 2,
  subModule: {
    run: () => 'real-run',
  },
};
const mockedObject = mockTargetObject(originalObject, mockFactory);
assert.strictEqual(mockedObject.version, 42, 'mockObject preserves numeric properties');
assert.strictEqual(mockedObject.title, 'mocker test', 'mockObject preserves string properties');
assert.strictEqual(mockedObject.isActive, true, 'mockObject preserves boolean properties');
assert.strictEqual(typeof mockedObject.execute, 'function', 'execute should be a mocked function');
assert.strictEqual(mockedObject.execute(), 'mock-fn-result', 'mocked execute() should return mock factory result');
assert.strictEqual(mockedObject.subModule.run(), 'mock-fn-result', 'nested function should also be mocked');

// 10. Deletion and clearing
registry.delete('file:///mock/auto');
assert.strictEqual(registry.has('file:///mock/auto'), false, 'registry.has should be false after delete');
assert.strictEqual(registry.get('file:///mock/auto'), undefined, 'registry.get should be undefined after delete');

registry.clear();
assert.strictEqual(registry.has('file:///mock/calc'), false, 'registry.has should be false after clear');
assert.strictEqual(registry.getById('/mock/calc'), undefined, 'registry.getById should be undefined after clear');
assert.deepStrictEqual(Array.from(registry.keys()), [], 'registry.keys() should be empty after clear');

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

Исходный сидер

аноним