CodeSampleX

Пример

@cacheable/utils 2.5.0: hash

Проверенный пример — npm @cacheable/utils 2.5.0: hash. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: hash asynchronously produces…

sha256:4aa66e36dc929a2e09fbaa33096f01d5ccbfd23271d5aa47c32e87ff227e3fc7

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

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

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-05

Кейс

HOW
Цель
verify hash in pkg:npm/%40cacheable/utils@2.5.0
Пакеты
Символы
  • hash
Окружение
node 22.23.2
Создан
2026-09-05T16:46:34Z

Контракт

  1. hash asynchronously produces hexadecimal hash strings using default SHA-256 algorithm
  2. hash supports cryptographic algorithms SHA-384 and SHA-512 producing expected digest lengths
  3. hashSync synchronously produces hash strings using default non-cryptographic djb2 algorithm
  4. hashSync supports non-cryptographic algorithms FNV1, MURMER, and CRC32
  5. hash accepts custom serialization function to customize input formatting before hashing
  6. hashToNumber asynchronously converts cryptographic hash values to numbers within specified min and max bounds
  7. hashToNumberSync synchronously converts non-cryptographic hash values to numbers within specified min and max bounds
  8. hashToNumber and hashToNumberSync throw an error when min is greater than or equal to max

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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 hash in pkg:npm/%40cacheable/utils@2.5.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40cacheable/utils@2.5.0
Demonstrate these symbols/APIs:
  - hash

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:cf0e62fec97174589e360b8cbb641669b0c505f477477cfa74724aa11e017971","contract":["hash asynchronously produces hexadecimal hash strings using default SHA-256 algorithm","hash supports cryptographic algorithms SHA-384 and SHA-512 producing expected digest lengths","hashSync synchronously produces hash strings using default non-cryptographic djb2 algorithm","hashSync supports non-cryptographic algorithms FNV1, MURMER, and CRC32","hash accepts custom serialization function to customize input formatting before hashing","hashToNumber asynchronously converts cryptographic hash values to numbers within specified min and max bounds","hashToNumberSync synchronously converts non-cryptographic hash values to numbers within specified min and max bounds","hashToNumber and hashToNumberSync throw an error when min is greater than or equal to max"],"goal":"verify hash in pkg:npm/%40cacheable/utils@2.5.0","kind":"HOW","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"symbols":["hash"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"subject":"pkg:npm/%40cacheable/utils@2.5.0","symbols":["hash"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-cacheable-utils-hash",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-cacheable-utils-hash",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@cacheable/utils": "2.5.0"
      }
    },
    "node_modules/@cacheable/utils": {
      "version": "2.5.0",
      "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz",
      "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==",
      "license": "MIT",
      "dependencies": {
        "hashery": "^1.5.1",
        "keyv": "^5.6.0"
      }
    },
    "node_modules/@keyv/serialize": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz",
      "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==",
      "license": "MIT"
    },
    "node_modules/hashery": {
      "version": "1.5.1",
      "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz",
      "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==",
      "license": "MIT",
      "dependencies": {
        "hookified": "^1.15.0"
      },
      "engines": {
        "node": ">=20"
      }
    },
    "node_modules/hookified": {
      "version": "1.15.1",
      "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz",
      "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==",
      "license": "MIT"
    },
    "node_modules/keyv": {
      "version": "5.6.0",
      "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz",
      "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==",
      "license": "MIT",
      "dependencies": {
        "@keyv/serialize": "^1.1.1"
      }
    }
  }
}
package.json
{
  "name": "sample-cacheable-utils-hash",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@cacheable/utils": "2.5.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hash in pkg:npm/%40cacheable/utils@2.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40cacheable/utils@2.5.0"
  ],
  "symbols": [
    "hash"
  ]
}
src/index.mjs
import {
  hash,
  hashSync,
  hashToNumber,
  hashToNumberSync,
  HashAlgorithm
} from '@cacheable/utils';

export {
  hash,
  hashSync,
  hashToNumber,
  hashToNumberSync,
  HashAlgorithm
};

export default hash;
test/contract.mjs
import assert from 'node:assert/strict';
import {
  hash,
  hashSync,
  hashToNumber,
  hashToNumberSync,
  HashAlgorithm
} from '@cacheable/utils';
import defaultHash from '../src/index.mjs';

// 1. hash asynchronously produces hexadecimal hash strings using default SHA-256 algorithm
{
  const result = await hash('cache-key-1');
  assert.equal(typeof result, 'string');
  assert.equal(result.length, 64);
  assert.match(result, /^[0-9a-f]{64}$/);

  const defaultResult = await defaultHash('cache-key-1');
  assert.equal(defaultResult, result);

  const result2 = await hash('cache-key-2');
  assert.notEqual(result, result2);
}

// 2. hash supports cryptographic algorithms SHA-384 and SHA-512 producing expected digest lengths
{
  const sha384 = await hash('payload', { algorithm: HashAlgorithm.SHA384 });
  assert.equal(typeof sha384, 'string');
  assert.equal(sha384.length, 96);
  assert.match(sha384, /^[0-9a-f]{96}$/);

  const sha512 = await hash('payload', { algorithm: HashAlgorithm.SHA512 });
  assert.equal(typeof sha512, 'string');
  assert.equal(sha512.length, 128);
  assert.match(sha512, /^[0-9a-f]{128}$/);
}

// 3. hashSync synchronously produces hash strings using default non-cryptographic djb2 algorithm
{
  const syncResult = hashSync('cache-key-sync');
  assert.equal(typeof syncResult, 'string');
  assert.ok(syncResult.length > 0);

  const repeatResult = hashSync('cache-key-sync');
  assert.equal(syncResult, repeatResult);

  const differentResult = hashSync('cache-key-sync-other');
  assert.notEqual(syncResult, differentResult);
}

// 4. hashSync supports non-cryptographic algorithms FNV1, MURMER, and CRC32
{
  const fnv = hashSync('test-data', { algorithm: HashAlgorithm.FNV1 });
  const mur = hashSync('test-data', { algorithm: HashAlgorithm.MURMER });
  const crc = hashSync('test-data', { algorithm: HashAlgorithm.CRC32 });

  assert.equal(typeof fnv, 'string');
  assert.equal(typeof mur, 'string');
  assert.equal(typeof crc, 'string');
  assert.ok(fnv.length > 0);
  assert.ok(mur.length > 0);
  assert.ok(crc.length > 0);
}

// 5. hash accepts custom serialization function to customize input formatting before hashing
{
  const obj = { id: 101, tag: 'featured' };
  const customHash = await hash(obj, {
    serialize: (item) => `${item.tag}#${item.id}`
  });
  const directHash = await hash('featured#101', {
    serialize: (str) => str
  });
  assert.equal(customHash, directHash);
}

// 6. hashToNumber asynchronously converts cryptographic hash values to numbers within specified min and max bounds
{
  const min = 10;
  const max = 50;
  const num = await hashToNumber({ route: '/api/v1/users' }, {
    min,
    max,
    algorithm: HashAlgorithm.SHA256
  });

  assert.equal(typeof num, 'number');
  assert.ok(num >= min);
  assert.ok(num <= max);
  assert.equal(Number.isFinite(num), true);
}

// 7. hashToNumberSync synchronously converts non-cryptographic hash values to numbers within specified min and max bounds
{
  const min = 1;
  const max = 100;
  const numSync = hashToNumberSync('partition-key', {
    min,
    max,
    algorithm: HashAlgorithm.DJB2
  });

  assert.equal(typeof numSync, 'number');
  assert.ok(numSync >= min);
  assert.ok(numSync <= max);
  assert.equal(Number.isFinite(numSync), true);
}

// 8. hashToNumber and hashToNumberSync throw an error when min is greater than or equal to max
{
  await assert.rejects(
    async () => hashToNumber('value', { min: 20, max: 10 }),
    /Invalid range: min \(20\) must be less than max \(10\)/
  );

  assert.throws(
    () => hashToNumberSync('value', { min: 30, max: 30 }),
    /Invalid range: min \(30\) must be less than max \(30\)/
  );
}

console.log('Contract tests passed successfully.');

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

аноним