CodeSampleX

샘플

@vitest/mocker 3.2.7

검증된 샘플 — npm @vitest/mocker 3.2.7. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: MockerRegistry registers manual mocks with factory functions…

sha256:9a5559216e50f3d90e66d9da4a06bcc471ba24d250929ddc330ab08c95b6f286

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-23

케이스

HOW
목표
verify pkg:npm/%40vitest/mocker@3.2.7
패키지
환경
node 22.23.2
생성일
2026-08-23T14:25:37Z

컨트랙트

  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

파일

  • 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: 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);
});

오리진 시더

익명