CodeSampleX

Пример

semver 7.8.5: reverse sort semantic versions with semver.rsort

Проверенный пример — npm semver 7.8.5: reverse sort semantic versions with semver.rsort. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:95a192c3e23346360cce2bd42f3e9e2cfbccdde7a4df8a47200b03a2226a0ab8

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
2
Заявленная среда node windows 11 x64 node javascript npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-19
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-09-07

Кейс

HOW
Цель
reverse sort semantic versions with semver.rsort
Пакеты
Символы
  • rsort
Окружение
node
Создан
2026-08-19T12:29:58Z

Контракт

  1. rsort orders versions in descending order by major minor and patch
  2. rsort places release versions before their corresponding prerelease versions
  3. rsort compares build metadata in descending order when versions are otherwise identical
  4. rsort mutates the array in place and returns the same array reference
  5. rsort supports loose mode for non-standard version strings

Файлы

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

Скачать артефакт с исходным кодом (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: reverse sort semantic versions with semver.rsort
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/semver@7.8.5
Demonstrate these symbols/APIs:
  - rsort
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@11.8.0
  - runtime: node@24.13.1

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:9c29e98eccb9d3647ad828afdf34fdb5bf8d1bff57de630aa8f7dba52ae77332","constraints":{"executionContext":"node"},"contract":["rsort orders versions in descending order by major minor and patch","rsort places release versions before their corresponding prerelease versions","rsort compares build metadata in descending order when versions are otherwise identical","rsort mutates the array in place and returns the same array reference","rsort supports loose mode for non-standard version strings"],"goal":"reverse sort semantic versions with semver.rsort","kind":"HOW","packages":["pkg:npm/semver@7.8.5"],"schemaVersion":1,"symbols":["rsort"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"javascript","moduleSystem":"cjs","os":"windows","osVersionBucket":"11","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/semver@7.8.5"],"schemaVersion":1,"symbols":["rsort"],"verifierAdapter":"node-typescript@1"}
index.js
const semver = require('semver');

/**
 * Sort an array of semantic version strings in descending order.
 * @param {string[]} list
 * @param {boolean|object} [optionsOrLoose]
 * @returns {string[]}
 */
function reverseSortVersions(list, optionsOrLoose) {
  return semver.rsort(list, optionsOrLoose);
}

module.exports = {
  rsort: semver.rsort,
  reverseSortVersions
};
package-lock.json
{
  "name": "sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample",
      "version": "1.0.0",
      "dependencies": {
        "semver": "7.8.5"
      }
    },
    "node_modules/semver": {
      "version": "7.8.5",
      "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
      "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
      "license": "ISC",
      "bin": {
        "semver": "bin/semver.js"
      },
      "engines": {
        "node": ">=10"
      }
    }
  }
}
package.json
{
  "name": "sample",
  "version": "1.0.0",
  "private": true,
  "main": "index.js",
  "dependencies": {
    "semver": "7.8.5"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "reverse sort semantic versions with semver.rsort",
  "kind": "HOW",
  "packages": [
    "pkg:npm/semver@7.8.5"
  ],
  "symbols": [
    "rsort"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@11.8.0",
    "runtime": "node@24.13.1"
  }
}
test/contract.js
const assert = require('assert');
const { rsort, reverseSortVersions } = require('../index.js');

// Assertion 1: rsort orders versions in descending order by major minor and patch
const versions = ['1.0.2', '1.10.0', '1.2.0', '1.0.10', '10.0.0', '2.0.0'];
const expectedNumeric = ['10.0.0', '2.0.0', '1.10.0', '1.2.0', '1.0.10', '1.0.2'];
assert.deepStrictEqual(rsort([...versions]), expectedNumeric);
assert.deepStrictEqual(reverseSortVersions([...versions]), expectedNumeric);

// Assertion 2: rsort places release versions before their corresponding prerelease versions
const prereleases = ['1.0.0-alpha', '1.0.0', '1.0.0-beta.2', '1.0.0-rc.1', '1.0.0-alpha.1', '1.0.0-beta'];
const expectedPrereleases = [
  '1.0.0',
  '1.0.0-rc.1',
  '1.0.0-beta.2',
  '1.0.0-beta',
  '1.0.0-alpha.1',
  '1.0.0-alpha'
];
assert.deepStrictEqual(rsort([...prereleases]), expectedPrereleases);
assert.deepStrictEqual(reverseSortVersions([...prereleases]), expectedPrereleases);

// Assertion 3: rsort compares build metadata in descending order when versions are otherwise identical
const builds = ['1.0.0+build.1', '1.0.0+build.10', '1.0.0+build.2'];
const expectedBuilds = ['1.0.0+build.10', '1.0.0+build.2', '1.0.0+build.1'];
assert.deepStrictEqual(rsort([...builds]), expectedBuilds);
assert.deepStrictEqual(reverseSortVersions([...builds]), expectedBuilds);

// Assertion 4: rsort mutates the array in place and returns the same array reference
const targetArray = ['1.0.0', '2.1.0'];
const returnedArray = rsort(targetArray);
assert.strictEqual(returnedArray, targetArray);
assert.deepStrictEqual(targetArray, ['2.1.0', '1.0.0']);

// Assertion 5: rsort supports loose mode for non-standard version strings
const looseVersions = ['=v2.0.0', 'v1.0.0', '  1.5.0  '];
const expectedLoose = ['=v2.0.0', '  1.5.0  ', 'v1.0.0'];
assert.deepStrictEqual(rsort([...looseVersions], { loose: true }), expectedLoose);
assert.deepStrictEqual(reverseSortVersions([...looseVersions], true), expectedLoose);

console.log('PASS: all contract assertions passed for semver.rsort');

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

аноним