CodeSampleX

Пример

file-entry-cache 8.0.0

Проверенный пример — npm file-entry-cache 8.0.0. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: create initializes a new cache instance…

sha256:22cab54434b18c5d0ef0373cea0d5fa2e949d44abf0b0afd0fe1325f0a829ea7

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

Кейс

HOW
Цель
verify pkg:npm/file-entry-cache@8.0.0
Пакеты
Окружение
node 22.23.2
Создан
2026-08-26T08:25:06Z

Контракт

  1. create initializes a new cache instance and tracks file modifications using mtime and size
  2. createFromFile initializes a cache instance from a single cache file path
  3. hasFileChanged detects new and modified files and returns false after reconcile
  4. getUpdatedFiles filters and returns only files that have changed
  5. analyzeFiles categorizes files into changedFiles, notChangedFiles, and notFoundFiles
  6. getFileDescriptor stores and persists custom metadata across cache instances
  7. removeEntry clears cached metadata for a specified file
  8. deleteCacheFile removes the cache file from disk
  9. checksum mode tracks file modifications via MD5 hash comparison

Файлы

  • 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/file-entry-cache@8.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/file-entry-cache@8.0.0
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:f62638b36f5eb9a8ff2d170de00093a4d43ec8f28a2847bc14a45cbee72f16b5","constraints":{"executionContext":"node"},"contract":["create initializes a new cache instance and tracks file modifications using mtime and size","createFromFile initializes a cache instance from a single cache file path","hasFileChanged detects new and modified files and returns false after reconcile","getUpdatedFiles filters and returns only files that have changed","analyzeFiles categorizes files into changedFiles, notChangedFiles, and notFoundFiles","getFileDescriptor stores and persists custom metadata across cache instances","removeEntry clears cached metadata for a specified file","deleteCacheFile removes the cache file from disk","checksum mode tracks file modifications via MD5 hash comparison"],"goal":"verify pkg:npm/file-entry-cache@8.0.0","kind":"HOW","packages":["pkg:npm/file-entry-cache@8.0.0"],"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/file-entry-cache@8.0.0"],"schemaVersion":1,"subject":"pkg:npm/file-entry-cache@8.0.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-file-entry-cache",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-file-entry-cache",
      "version": "1.0.0",
      "dependencies": {
        "file-entry-cache": "8.0.0"
      }
    },
    "node_modules/file-entry-cache": {
      "version": "8.0.0",
      "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
      "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==",
      "license": "MIT",
      "dependencies": {
        "flat-cache": "^4.0.0"
      },
      "engines": {
        "node": ">=16.0.0"
      }
    },
    "node_modules/flat-cache": {
      "version": "4.0.1",
      "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz",
      "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==",
      "license": "MIT",
      "dependencies": {
        "flatted": "^3.2.9",
        "keyv": "^4.5.4"
      },
      "engines": {
        "node": ">=16"
      }
    },
    "node_modules/flatted": {
      "version": "3.4.4",
      "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz",
      "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==",
      "license": "ISC"
    },
    "node_modules/json-buffer": {
      "version": "3.0.1",
      "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
      "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",
      "license": "MIT"
    },
    "node_modules/keyv": {
      "version": "4.5.4",
      "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
      "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",
      "license": "MIT",
      "dependencies": {
        "json-buffer": "3.0.1"
      }
    }
  }
}
package.json
{
  "name": "sample-file-entry-cache",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of file-entry-cache",
  "main": "src/index.js",
  "dependencies": {
    "file-entry-cache": "8.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/file-entry-cache@8.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/file-entry-cache@8.0.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const fileEntryCache = require('file-entry-cache');

/**
 * Creates or loads a file entry cache instance.
 * @param {string} cacheId - Cache identifier.
 * @param {string} [cacheDir] - Directory where cache file is stored.
 * @param {boolean} [useCheckSum=false] - Whether to use checksums instead of mtime/size.
 * @param {string} [cwd] - Current working directory for path resolution.
 * @returns {object} Cache instance.
 */
function createCache(cacheId, cacheDir, useCheckSum = false, cwd) {
  return fileEntryCache.create(cacheId, cacheDir, useCheckSum, cwd);
}

/**
 * Creates or loads a file entry cache instance from a specified cache file path.
 * @param {string} cachePath - Full path to cache file.
 * @param {boolean} [useCheckSum=false] - Whether to use checksums.
 * @param {string} [cwd] - Current working directory.
 * @returns {object} Cache instance.
 */
function createCacheFromFile(cachePath, useCheckSum = false, cwd) {
  return fileEntryCache.createFromFile(cachePath, useCheckSum, cwd);
}

/**
 * Analyzes file paths against cache state.
 * @param {object} cache - Cache instance.
 * @param {string[]} filePaths - File paths to inspect.
 * @returns {{changedFiles: string[], notChangedFiles: string[], notFoundFiles: string[]}}
 */
function analyzeFiles(cache, filePaths) {
  return cache.analyzeFiles(filePaths);
}

/**
 * Sets custom metadata on a cached file descriptor.
 * @param {object} cache - Cache instance.
 * @param {string} filePath - Path to file.
 * @param {object} data - Key-value metadata.
 * @returns {object} File descriptor.
 */
function setFileMetadata(cache, filePath, data) {
  const descriptor = cache.getFileDescriptor(filePath);
  if (descriptor && descriptor.meta) {
    descriptor.meta.data = Object.assign({}, descriptor.meta.data, data);
  }
  return descriptor;
}

module.exports = {
  fileEntryCache,
  createCache,
  createCacheFromFile,
  analyzeFiles,
  setFileMetadata
};
test/contract.mjs
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const {
  fileEntryCache,
  createCache,
  createCacheFromFile,
  analyzeFiles,
  setFileMetadata
} = require('../src/index.js');

// 1. Export verification
assert.strictEqual(typeof fileEntryCache.create, 'function', 'fileEntryCache.create should be a function');
assert.strictEqual(typeof fileEntryCache.createFromFile, 'function', 'fileEntryCache.createFromFile should be a function');
assert.strictEqual(typeof createCache, 'function', 'createCache helper should be a function');
assert.strictEqual(typeof createCacheFromFile, 'function', 'createCacheFromFile helper should be a function');
assert.strictEqual(typeof analyzeFiles, 'function', 'analyzeFiles helper should be a function');
assert.strictEqual(typeof setFileMetadata, 'function', 'setFileMetadata helper should be a function');

const testDir = path.join(__dirname, 'tmp_sandbox');
fs.mkdirSync(testDir, { recursive: true });

try {
  // 2. create initializes cache and tracks modifications using mtime/size
  const fileA = path.join(testDir, 'fileA.txt');
  const fileB = path.join(testDir, 'fileB.txt');
  fs.writeFileSync(fileA, 'initial content A');
  fs.writeFileSync(fileB, 'initial content B');

  const cache = createCache('cache_mtime', testDir);
  assert.ok(cache, 'Cache instance should be created');

  // 3. hasFileChanged detects new and modified files
  assert.strictEqual(cache.hasFileChanged(fileA), true, 'New file should report as changed');
  assert.strictEqual(cache.hasFileChanged(fileB), true, 'New file should report as changed');

  // Reconcile saves state
  cache.reconcile();
  assert.strictEqual(cache.hasFileChanged(fileA), false, 'Reconciled file should report unchanged');
  assert.strictEqual(cache.hasFileChanged(fileB), false, 'Reconciled file should report unchanged');

  // Modify fileA
  // Ensure mtime changes even on fast filesystems by setting mtime ahead
  const statA = fs.statSync(fileA);
  fs.writeFileSync(fileA, 'modified content A');
  fs.utimesSync(fileA, statA.atime.getTime() / 1000 + 2, statA.mtime.getTime() / 1000 + 2);

  assert.strictEqual(cache.hasFileChanged(fileA), true, 'Modified file should report changed');
  assert.strictEqual(cache.hasFileChanged(fileB), false, 'Unmodified file should report unchanged');

  // 4. getUpdatedFiles returns changed files only
  const updatedFiles = cache.getUpdatedFiles([fileA, fileB]);
  assert.strictEqual(updatedFiles.length, 1);
  assert.ok(updatedFiles[0].includes('fileA.txt'), 'getUpdatedFiles should identify modified file');

  // 5. analyzeFiles categorizes into changed, notChanged, and notFound
  const missingFile = path.join(testDir, 'missing.txt');
  const analysis = analyzeFiles(cache, [fileA, fileB, missingFile]);
  assert.strictEqual(analysis.changedFiles.length, 1, 'Should have 1 changed file');
  assert.strictEqual(analysis.notChangedFiles.length, 1, 'Should have 1 unchanged file');
  assert.strictEqual(analysis.notFoundFiles.length, 1, 'Should have 1 missing file');

  // 6. getFileDescriptor stores and persists custom metadata across cache instances
  setFileMetadata(cache, fileB, { linterResult: 'passed', ruleCount: 42 });
  cache.reconcile();

  const cacheReloaded = createCache('cache_mtime', testDir);
  const descB = cacheReloaded.getFileDescriptor(fileB);
  assert.ok(descB && descB.meta && descB.meta.data, 'Descriptor should retain meta.data');
  assert.strictEqual(descB.meta.data.linterResult, 'passed');
  assert.strictEqual(descB.meta.data.ruleCount, 42);

  // 7. removeEntry clears cached entry
  cacheReloaded.removeEntry(fileB);
  assert.strictEqual(cacheReloaded.hasFileChanged(fileB), true, 'Removed entry should be detected as changed/new');
  cacheReloaded.deleteCacheFile();

  // 8. createFromFile initializes from cache file path and deleteCacheFile removes disk file
  const directCachePath = path.join(testDir, '.direct_cache');
  const directCache = createCacheFromFile(directCachePath);
  directCache.getFileDescriptor(fileA);
  directCache.reconcile();
  assert.strictEqual(fs.existsSync(directCachePath), true, 'Direct cache file should exist on disk after reconcile');
  directCache.deleteCacheFile();
  assert.strictEqual(fs.existsSync(directCachePath), false, 'Direct cache file should be deleted');

  // 9. Checksum mode tracks modifications via MD5 hash comparison
  const fileChecksum = path.join(testDir, 'fileCS.txt');
  fs.writeFileSync(fileChecksum, 'checksum content 1');

  const csCache = createCache('cache_checksum', testDir, true);
  const csDesc1 = csCache.getFileDescriptor(fileChecksum);
  assert.ok(csDesc1.meta && csDesc1.meta.hash, 'Descriptor in checksum mode should contain MD5 hash');
  csCache.reconcile();

  assert.strictEqual(csCache.hasFileChanged(fileChecksum), false, 'Checksum cache should show false after reconcile');

  fs.writeFileSync(fileChecksum, 'checksum content 2 (modified)');
  assert.strictEqual(csCache.hasFileChanged(fileChecksum), true, 'Modified content should change hash and trigger change');

  csCache.deleteCacheFile();
} finally {
  fs.rmSync(testDir, { recursive: true, force: true });
}

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

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

аноним