CodeSampleX

샘플

lru-cache 6.0.0: LRU.set

검증된 샘플 — npm lru-cache 6.0.0: LRU.set. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: LRUCache get, set, and has operations store values, evict…

sha256:8ad93c52e727ab02715ee91a3b0d5f9c6ba383fd9c065b186ab66e453d324066

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

케이스

HOW
목표
verify pkg:npm/lru-cache@6.0.0
패키지
심벌
  • LRU.set
환경
node 22.23.2
생성일
2026-08-20T07:22:25Z

컨트랙트

  1. LRUCache get, set, and has operations store values, evict least recently used entries upon reaching max capacity, and update recency order
  2. LRUCache custom length calculation tracks total items weight, enforces max capacity limit, and evicts entries when limit is exceeded
  3. LRUCache maxAge configuration with updateAgeOnGet and prune manages time-based entry expiration and stale entry cleanup
  4. LRUCache dispose callback executes on item eviction, deletion, and overwrites with key and value arguments
  5. LRUCache dump and load serialize and restore cache entries across instances while preserving entry expiration

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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: verify pkg:npm/lru-cache@6.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/lru-cache@6.0.0
Demonstrate these symbols/APIs:
  - LRU.set
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:5b48ab8a1c369b49aecdb412bd88384d1e3cd88497d86c20a02ef4180e02ce9c","constraints":{"executionContext":"node"},"contract":["LRUCache get, set, and has operations store values, evict least recently used entries upon reaching max capacity, and update recency order","LRUCache custom length calculation tracks total items weight, enforces max capacity limit, and evicts entries when limit is exceeded","LRUCache maxAge configuration with updateAgeOnGet and prune manages time-based entry expiration and stale entry cleanup","LRUCache dispose callback executes on item eviction, deletion, and overwrites with key and value arguments","LRUCache dump and load serialize and restore cache entries across instances while preserving entry expiration"],"goal":"verify pkg:npm/lru-cache@6.0.0","kind":"HOW","packages":["pkg:npm/lru-cache@6.0.0"],"schemaVersion":1,"symbols":["LRU.set"]},"contractCommand":["node","test/contract.js"],"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/lru-cache@6.0.0"],"schemaVersion":1,"symbols":["LRU.set"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "lru-cache-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "lru-cache-sample",
      "version": "1.0.0",
      "dependencies": {
        "lru-cache": "6.0.0"
      }
    },
    "node_modules/lru-cache": {
      "version": "6.0.0",
      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
      "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
      "license": "ISC",
      "dependencies": {
        "yallist": "^4.0.0"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/yallist": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
      "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "lru-cache-sample",
  "version": "1.0.0",
  "dependencies": {
    "lru-cache": "6.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/lru-cache@6.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/lru-cache@6.0.0"
  ],
  "symbols": [
    "LRU.set"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const LRUCache = require('lru-cache');

/**
 * Creates an LRU cache instance with the specified options.
 *
 * @param {import('lru-cache').Options<any, any> | number} options
 * @returns {LRUCache}
 */
function createCache(options) {
  return new LRUCache(options);
}

/**
 * Creates an LRU cache with custom length/weight calculator.
 *
 * @param {number} max
 * @param {(value: any, key: any) => number} lengthCalculator
 * @returns {LRUCache}
 */
function createWeightedCache(max, lengthCalculator) {
  return new LRUCache({
    max,
    length: lengthCalculator,
  });
}

/**
 * Creates an LRU cache with time-to-live expiration.
 *
 * @param {number} max
 * @param {number} maxAge
 * @param {boolean} [updateAgeOnGet=false]
 * @returns {LRUCache}
 */
function createTimedCache(max, maxAge, updateAgeOnGet = false) {
  return new LRUCache({
    max,
    maxAge,
    updateAgeOnGet,
  });
}

/**
 * Serializes entries from an LRU cache.
 *
 * @param {LRUCache} cache
 * @returns {Array<{ k: any, v: any, e: number }>}
 */
function serializeCache(cache) {
  return cache.dump();
}

/**
 * Restores dumped entries into a new LRU cache instance.
 *
 * @param {import('lru-cache').Options<any, any> | number} options
 * @param {Array<{ k: any, v: any, e: number }>} entries
 * @returns {LRUCache}
 */
function restoreCache(options, entries) {
  const cache = new LRUCache(options);
  cache.load(entries);
  return cache;
}

module.exports = {
  LRUCache,
  createCache,
  createWeightedCache,
  createTimedCache,
  serializeCache,
  restoreCache,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  LRUCache,
  createCache,
  createWeightedCache,
  createTimedCache,
  serializeCache,
  restoreCache,
} = require('../src/index.js');

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function main() {
  // Contract 1: LRUCache get, set, and has operations store values, evict least recently used entries upon reaching max capacity, and update recency order
  {
    const cache = createCache({ max: 3 });
    assert.strictEqual(cache.set('a', 1), true);
    assert.strictEqual(cache.set('b', 2), true);
    assert.strictEqual(cache.set('c', 3), true);

    assert.strictEqual(cache.itemCount, 3);
    assert.strictEqual(cache.has('a'), true);
    assert.strictEqual(cache.get('a'), 1);

    // Accessing 'a' makes 'b' the oldest (least recently used) entry
    cache.set('d', 4);
    assert.strictEqual(cache.has('b'), false, 'Key b should be evicted as least recently used');
    assert.strictEqual(cache.get('a'), 1);
    assert.strictEqual(cache.get('c'), 3);
    assert.strictEqual(cache.get('d'), 4);

    // peek reads without updating recency order
    assert.strictEqual(cache.peek('c'), 3);
    cache.set('e', 5);
    assert.strictEqual(cache.has('a'), false, 'Key a should be evicted next because peek on c did not touch recency');

    // del removes a key
    cache.del('d');
    assert.strictEqual(cache.has('d'), false);
    assert.strictEqual(cache.itemCount, 2);

    // reset clears all entries
    cache.reset();
    assert.strictEqual(cache.itemCount, 0);
  }

  // Contract 2: LRUCache custom length calculation tracks total items weight, enforces max capacity limit, and evicts entries when limit is exceeded
  {
    const cache = createWeightedCache(100, (value) => value.length);

    cache.set('item1', 'short'); // length 5
    cache.set('item2', 'x'.repeat(40)); // length 40
    cache.set('item3', 'y'.repeat(50)); // length 50

    assert.strictEqual(cache.length, 95);
    assert.strictEqual(cache.itemCount, 3);

    // Adding item4 (length 15) brings total length to 110 (> 100), triggering eviction of item1 and item2
    cache.set('item4', 'z'.repeat(15));
    assert.strictEqual(cache.has('item1'), false);
    assert.strictEqual(cache.has('item2'), false);
    assert.strictEqual(cache.has('item3'), true);
    assert.strictEqual(cache.has('item4'), true);
    assert.strictEqual(cache.length, 65);

    // Entry exceeding max capacity is rejected
    const oversized = 'w'.repeat(150);
    const added = cache.set('tooLarge', oversized);
    assert.strictEqual(added, false);
    assert.strictEqual(cache.has('tooLarge'), false);
    assert.strictEqual(cache.length, 65);
  }

  // Contract 3: LRUCache maxAge configuration with updateAgeOnGet and prune manages time-based entry expiration and stale entry cleanup
  {
    const cache = createTimedCache(10, 200, true);

    cache.set('temp1', 'val1');
    cache.set('temp2', 'val2');

    await delay(120);
    // Accessing temp1 resets its age
    assert.strictEqual(cache.get('temp1'), 'val1');

    await delay(120);
    // temp2 has exceeded 200ms TTL (240ms total), temp1 was refreshed at 120ms (now 120ms old < 200ms)
    assert.strictEqual(cache.has('temp2'), false, 'temp2 should expire after 240ms');
    assert.strictEqual(cache.get('temp2'), undefined);
    assert.strictEqual(cache.get('temp1'), 'val1', 'temp1 remains accessible due to updateAgeOnGet');

    // Setting entry with custom maxAge and testing prune
    cache.set('temp3', 'val3', 50);
    await delay(70);
    assert.strictEqual(cache.has('temp3'), false);
    assert.strictEqual(cache.itemCount, 2); // temp3 is still in Map before prune

    cache.prune();
    assert.strictEqual(cache.itemCount, 1); // prune sweeps expired items
  }

  // Contract 4: LRUCache dispose callback executes on item eviction, deletion, and overwrites with key and value arguments
  {
    const events = [];
    const cache = new LRUCache({
      max: 2,
      dispose: (key, value) => {
        events.push({ key, value });
      },
    });

    cache.set('k1', 'v1');
    cache.set('k2', 'v2');

    // Eviction on reaching capacity
    cache.set('k3', 'v3');
    assert.deepStrictEqual(events, [
      { key: 'k1', value: 'v1' },
    ]);

    // Overwriting existing key
    cache.set('k3', 'v3-updated');
    assert.deepStrictEqual(events, [
      { key: 'k1', value: 'v1' },
      { key: 'k3', value: 'v3' },
    ]);

    // Explicit deletion
    cache.del('k2');
    assert.deepStrictEqual(events, [
      { key: 'k1', value: 'v1' },
      { key: 'k3', value: 'v3' },
      { key: 'k2', value: 'v2' },
    ]);
  }

  // Contract 5: LRUCache dump and load serialize and restore cache entries across instances while preserving entry expiration
  {
    const sourceCache = createCache({ max: 5 });
    sourceCache.set('x', 10);
    sourceCache.set('y', 20);
    sourceCache.set('z', 30);

    const serialized = serializeCache(sourceCache);
    assert.ok(Array.isArray(serialized));
    assert.strictEqual(serialized.length, 3);

    const targetCache = restoreCache({ max: 5 }, serialized);
    assert.strictEqual(targetCache.get('x'), 10);
    assert.strictEqual(targetCache.get('y'), 20);
    assert.strictEqual(targetCache.get('z'), 30);
    assert.strictEqual(targetCache.itemCount, 3);
  }

  console.log('All pkg:npm/lru-cache@6.0.0 contracts passed successfully.');
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

오리진 시더

익명