CodeSampleX

サンプル

lru-cache 11.5.3

検証済みサンプル — npm lru-cache 11.5.3. node 22 · linux debian/x64 · docker で contract を実行し、成功しました: require('lru-cache') exports LRUCache in CommonJS and…

sha256:25e97073113eab4e6fcdae27d3e83be61cf0edeb6c4f0ba04e2e9c7ca80e0fb2

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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-11-21

ケース

HOW
ゴール
verify pkg:npm/lru-cache@11.5.3
パッケージ
環境
node 22.23.2
作成日
2026-11-21T17:30:11Z

コントラクト

  1. require('lru-cache') exports LRUCache in CommonJS and constructor throws TypeError when no capacity limit is provided
  2. LRU eviction removes the least recently used entry, get() promotes recency while peek() preserves order, and dispose receives evict, set, and delete reasons
  3. maxSize and maxEntrySize enforce sizeCalculation bounds, rejecting oversized items with status.maxEntrySizeExceeded and maintaining calculatedSize
  4. deterministic TTL tracking via custom perf clock with ttlResolution: 0 reports getRemainingTTL, preserves expired entries under allowStale with noDeleteOnStaleGet, and clears them via purgeStale()
  5. memo() caches memoMethod results with status.memo miss/hit reporting and dump()/load() round-trips entries in MRU order
  6. fetch() coalesces concurrent requests per key, allowStaleOnFetchRejection returns stale values on rejection, and forceFetch() rejects when fetchMethod returns undefined

ファイル

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/cache.cjs
  • test/contract.cjs

ソースアーティファクトをダウンロード (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@11.5.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/lru-cache@11.5.3
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:c4137cd6746911b4edf66561ef552cf8bb5f1bd2530f2cf145c119384535b71f","constraints":{"executionContext":"node"},"contract":["require('lru-cache') exports LRUCache in CommonJS and constructor throws TypeError when no capacity limit is provided","LRU eviction removes the least recently used entry, get() promotes recency while peek() preserves order, and dispose receives evict, set, and delete reasons","maxSize and maxEntrySize enforce sizeCalculation bounds, rejecting oversized items with status.maxEntrySizeExceeded and maintaining calculatedSize","deterministic TTL tracking via custom perf clock with ttlResolution: 0 reports getRemainingTTL, preserves expired entries under allowStale with noDeleteOnStaleGet, and clears them via purgeStale()","memo() caches memoMethod results with status.memo miss/hit reporting and dump()/load() round-trips entries in MRU order","fetch() coalesces concurrent requests per key, allowStaleOnFetchRejection returns stale values on rejection, and forceFetch() rejects when fetchMethod returns undefined"],"goal":"verify pkg:npm/lru-cache@11.5.3","kind":"HOW","packages":["pkg:npm/lru-cache@11.5.3"],"schemaVersion":1},"contractCommand":["node","test/contract.cjs"],"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@11.5.3"],"schemaVersion":1,"subject":"pkg:npm/lru-cache@11.5.3","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "lru-cache-verify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "lru-cache-verify",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "lru-cache": "11.5.3"
      }
    },
    "node_modules/lru-cache": {
      "version": "11.5.3",
      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
      "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
      "license": "BlueOak-1.0.0",
      "engines": {
        "node": "20 || >=22"
      }
    }
  }
}
package.json
{
  "name": "lru-cache-verify",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "lru-cache": "11.5.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/lru-cache@11.5.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/lru-cache@11.5.3"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/cache.cjs
'use strict';

const { LRUCache } = require('lru-cache');

function createBoundedCache(options) {
  return new LRUCache(options);
}

function createClock(initialMs = 1000) {
  let current = initialMs;
  return {
    perf: {
      now() {
        return current;
      },
    },
    advance(ms) {
      current += ms;
    },
  };
}

module.exports = {
  LRUCache,
  createBoundedCache,
  createClock,
};
test/contract.cjs
'use strict';

const assert = require('node:assert/strict');
const { LRUCache, createBoundedCache, createClock } = require('../src/cache.cjs');

async function main() {
  // 1. Named CommonJS export and constructor capacity validation
  assert.equal(typeof LRUCache, 'function');
  assert.throws(() => new LRUCache({}), TypeError);

  // 2. LRU eviction order, get() vs peek(), and dispose reasons
  const disposed = [];
  const lru = createBoundedCache({
    max: 2,
    dispose(value, key, reason) {
      disposed.push({ key, value, reason });
    },
  });

  lru.set('a', 1);
  lru.set('b', 2);
  assert.equal(lru.peek('a'), 1);
  assert.deepEqual([...lru.keys()], ['b', 'a']);

  assert.equal(lru.get('a'), 1);
  assert.deepEqual([...lru.keys()], ['a', 'b']);

  lru.set('c', 3);
  assert.equal(lru.has('b'), false);
  assert.deepEqual([...lru.keys()], ['c', 'a']);

  lru.set('a', 10);
  lru.delete('c');
  assert.deepEqual(disposed, [
    { key: 'b', value: 2, reason: 'evict' },
    { key: 'a', value: 1, reason: 'set' },
    { key: 'c', value: 3, reason: 'delete' },
  ]);

  // 3. Size-bounded cache with maxSize, maxEntrySize, and status tracking
  const sized = createBoundedCache({
    maxSize: 10,
    maxEntrySize: 6,
    sizeCalculation(value) {
      return value.length;
    },
  });

  const oversizedStatus = {};
  sized.set('too-big', '1234567', { status: oversizedStatus });
  assert.equal(sized.has('too-big'), false);
  assert.equal(oversizedStatus.maxEntrySizeExceeded, true);
  assert.equal(oversizedStatus.set, 'miss');

  sized.set('k1', '12345');
  sized.set('k2', '12345');
  assert.equal(sized.calculatedSize, 10);
  sized.set('k3', '12');
  assert.equal(sized.has('k1'), false);
  assert.equal(sized.has('k2'), true);
  assert.equal(sized.has('k3'), true);
  assert.equal(sized.calculatedSize, 7);

  // 4. Deterministic TTL expiration, stale reads, and purgeStale()
  const clock = createClock(1000);
  const ttlCache = createBoundedCache({
    max: 5,
    ttl: 100,
    ttlResolution: 0,
    perf: clock.perf,
  });

  ttlCache.set('token', 'fresh');
  assert.equal(ttlCache.getRemainingTTL('token'), 100);
  clock.advance(40);
  assert.equal(ttlCache.getRemainingTTL('token'), 60);

  clock.advance(70);
  assert.equal(ttlCache.has('token'), false);
  assert.equal(
    ttlCache.get('token', { allowStale: true, noDeleteOnStaleGet: true }),
    'fresh'
  );
  assert.equal(ttlCache.size, 1);
  assert.equal(ttlCache.purgeStale(), true);
  assert.equal(ttlCache.size, 0);
  assert.equal(ttlCache.purgeStale(), false);

  // 5. Synchronous memo() and dump()/load() serialization round-trip
  let memoCalls = 0;
  const memoCache = createBoundedCache({
    max: 5,
    memoMethod(key) {
      memoCalls += 1;
      return `computed:${key}`;
    },
  });

  const s1 = {};
  const s2 = {};
  assert.equal(memoCache.memo('x', { status: s1 }), 'computed:x');
  assert.equal(memoCache.memo('x', { status: s2 }), 'computed:x');
  assert.equal(memoCalls, 1);
  assert.equal(s1.memo, 'miss');
  assert.equal(s2.memo, 'hit');

  memoCache.set('y', 'manual:y');
  const snapshot = memoCache.dump();
  const restored = createBoundedCache({ max: 5 });
  restored.load(snapshot);
  assert.deepEqual([...restored.entries()], [
    ['y', 'manual:y'],
    ['x', 'computed:x'],
  ]);

  // 6. Async fetch() coalescing, forceFetch() rejection on undefined, stale fallback on rejection
  const fetchClock = createClock(5000);
  let fetchCount = 0;
  let mode = 'ok';
  const asyncCache = createBoundedCache({
    max: 5,
    ttl: 50,
    ttlResolution: 0,
    perf: fetchClock.perf,
    async fetchMethod(key) {
      fetchCount += 1;
      await Promise.resolve();
      if (mode === 'fail') {
        throw new Error('upstream failure');
      }
      if (mode === 'missing') {
        return undefined;
      }
      return `v${fetchCount}:${key}`;
    },
  });

  const [r1, r2] = await Promise.all([
    asyncCache.fetch('item'),
    asyncCache.fetch('item'),
  ]);
  assert.equal(r1, 'v1:item');
  assert.equal(r2, 'v1:item');
  assert.equal(fetchCount, 1);

  fetchClock.advance(60);
  mode = 'fail';
  const fallback = await asyncCache.fetch('item', {
    allowStaleOnFetchRejection: true,
  });
  assert.equal(fallback, 'v1:item');

  mode = 'missing';
  await assert.rejects(
    () => asyncCache.forceFetch('absent'),
    /fetch\(\) returned undefined/
  );
}

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

オリジンシーダー

匿名