CodeSampleX

Пример

semver 5.7.2: cmp

Проверенный пример — npm semver 5.7.2: cmp. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: cmp evaluates equality operators (=, ==…

sha256:30937d8efc83ef3e16ff2ffea9dffe79774d378ec596892ae270aaae3a27bc2e

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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 semver.cmp in pkg:npm/semver@5.7.2
Пакеты
Символы
  • semver.cmp
Окружение
node 22.23.2
Создан
2026-08-28T04:36:21Z

Контракт

  1. cmp evaluates equality operators (=, ==, empty string, and !=)
  2. cmp evaluates strict string identity operators (=== and !==)
  3. cmp evaluates relational ordering operators (>, >=, <, and <=)
  4. cmp supports loose mode for forgiving version string formats
  5. cmp throws TypeError when an invalid comparison operator is provided

Файлы

  • 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 semver.cmp in pkg:npm/semver@5.7.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/semver@5.7.2
Demonstrate these symbols/APIs:
  - semver.cmp

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:f222d12f5d50e8dc0143526cfb411d6fa3ad1b9ada0ba57fd2eb124ca43eb1a3","contract":["cmp evaluates equality operators (=, ==, empty string, and !=)","cmp evaluates strict string identity operators (=== and !==)","cmp evaluates relational ordering operators (\u003e, \u003e=, \u003c, and \u003c=)","cmp supports loose mode for forgiving version string formats","cmp throws TypeError when an invalid comparison operator is provided"],"goal":"verify semver.cmp in pkg:npm/semver@5.7.2","kind":"HOW","packages":["pkg:npm/semver@5.7.2"],"schemaVersion":1,"symbols":["semver.cmp"]},"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/semver@5.7.2"],"schemaVersion":1,"subject":"pkg:npm/semver@5.7.2","symbols":["semver.cmp"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-semver-cmp",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-semver-cmp",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "semver": "5.7.2"
      }
    },
    "node_modules/semver": {
      "version": "5.7.2",
      "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
      "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
      "license": "ISC",
      "bin": {
        "semver": "bin/semver"
      }
    }
  }
}
package.json
{
  "name": "sample-semver-cmp",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for semver.cmp in semver@5.7.2",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "semver": "5.7.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify semver.cmp in pkg:npm/semver@5.7.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/semver@5.7.2"
  ],
  "symbols": [
    "semver.cmp"
  ]
}
src/index.js
const semver = require('semver');

/**
 * Compares two semantic version strings using a specified operator.
 *
 * @param {string} v1 - First version string.
 * @param {string} op - Comparison operator ('===', '!==', '', '=', '==', '!=', '>', '>=', '<', '<=').
 * @param {string} v2 - Second version string.
 * @param {boolean|object} [loose=false] - Whether to allow loose parsing.
 * @returns {boolean} Result of the comparison.
 */
function compareVersions(v1, op, v2, loose = false) {
  return semver.cmp(v1, op, v2, loose);
}

module.exports = {
  semver,
  cmp: semver.cmp,
  compareVersions
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  semver,
  cmp,
  compareVersions
} = require('../src/index.js');

async function runContractTests() {
  // 1. cmp evaluates equality operators (=, ==, empty string, and !=)
  assert.equal(typeof semver.cmp, 'function', 'semver.cmp must be a function');
  assert.equal(typeof cmp, 'function', 'cmp must be a function');
  assert.equal(cmp('1.2.3', '=', '1.2.3'), true, 'equal versions with = should return true');
  assert.equal(cmp('1.2.3', '==', '1.2.3'), true, 'equal versions with == should return true');
  assert.equal(cmp('1.2.3', '', '1.2.3'), true, 'equal versions with empty string op should return true');
  assert.equal(cmp('v1.2.3', '=', '1.2.3'), true, 'equal versions with leading v with = should return true');
  assert.equal(cmp('1.2.3+build1', '=', '1.2.3+build2'), true, 'build metadata ignored in semver equality');
  assert.equal(cmp('1.2.3', '!=', '2.0.0'), true, 'different versions with != should return true');
  assert.equal(cmp('1.2.3', '!=', '1.2.3'), false, 'same version with != should return false');
  assert.equal(compareVersions('1.0.0', '=', '1.0.0'), true, 'compareVersions helper with = should return true');

  // 2. cmp evaluates strict string identity operators (=== and !==)
  assert.equal(cmp('1.2.3', '===', '1.2.3'), true, 'identical string versions with === should return true');
  assert.equal(cmp('v1.2.3', '===', '1.2.3'), false, 'differing representations with === should return false');
  assert.equal(cmp('1.2.3+build1', '===', '1.2.3+build2'), false, 'different build metadata with === should return false');
  assert.equal(cmp('v1.2.3', '!==', '1.2.3'), true, 'differing representations with !== should return true');
  assert.equal(cmp('1.2.3', '!==', '1.2.3'), false, 'identical strings with !== should return false');

  // 3. cmp evaluates relational ordering operators (>, >=, <, and <=)
  assert.equal(cmp('2.0.0', '>', '1.2.3'), true, '2.0.0 > 1.2.3 should return true');
  assert.equal(cmp('1.0.0', '>', '2.0.0'), false, '1.0.0 > 2.0.0 should return false');
  assert.equal(cmp('1.2.3', '>=', '1.2.3'), true, '1.2.3 >= 1.2.3 should return true');
  assert.equal(cmp('1.0.0', '<', '1.0.1'), true, '1.0.0 < 1.0.1 should return true');
  assert.equal(cmp('1.2.3', '<=', '1.2.3'), true, '1.2.3 <= 1.2.3 should return true');
  assert.equal(cmp('1.0.0-alpha', '<', '1.0.0'), true, 'prerelease version is less than release version');

  // 4. cmp supports loose mode for forgiving version string formats
  assert.equal(cmp('v 1.2.3', '=', '1.2.3', true), true, 'loose mode allows space after v');
  assert.equal(cmp('v 1.2.3', '<', '2.0.0', true), true, 'loose mode allows relational comparison with loose version');
  assert.equal(compareVersions('v 1.2.3', '=', '1.2.3', true), true, 'compareVersions helper passes loose mode');

  // 5. cmp throws TypeError when an invalid comparison operator is provided
  assert.throws(
    () => cmp('1.0.0', 'invalid', '2.0.0'),
    (err) => err instanceof TypeError && /Invalid operator/.test(err.message),
    'cmp with invalid operator should throw TypeError'
  );
  assert.throws(
    () => compareVersions('1.0.0', '~=', '1.0.0'),
    (err) => err instanceof TypeError && /Invalid operator/.test(err.message),
    'compareVersions with invalid operator should throw TypeError'
  );

  console.log('All semver.cmp contract tests passed successfully.');
}

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

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

аноним