CodeSampleX

샘플

@cacheable/utils 2.5.0: wrap

검증된 샘플 — npm @cacheable/utils 2.5.0: wrap. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: wrap memoizes the return value of an async function…

sha256:7df8c072e95fe6534231b2ff9a7ce797ee225dbf089ffcdab6c519b74504bbf0

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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 wrap in pkg:npm/%40cacheable/utils@2.5.0
패키지
심벌
  • wrap
생성일
2026-09-05T17:12:07Z

컨트랙트

  1. wrap memoizes the return value of an async function for identical arguments using the provided cache instance
  2. wrap re-executes the underlying function when invoked with different arguments
  3. wrap coalesces concurrent invocations with identical arguments to prevent cache stampedes
  4. wrap applies custom key prefixes when generating default cache keys
  5. wrap uses custom createKey functions to derive cache keys from function references and arguments
  6. wrap forwards configured ttl values to the underlying cache store during set operations
  7. wrap rethrows errors from the wrapped function when throwErrors is enabled
  8. wrap caches errors returned by the wrapped function when cacheErrors is enabled

파일

  • 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 wrap 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:
  - wrap

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:79b0abda6aba7a4875b0bf639330477832db54f91680efa1ff3565168155ef72","contract":["wrap memoizes the return value of an async function for identical arguments using the provided cache instance","wrap re-executes the underlying function when invoked with different arguments","wrap coalesces concurrent invocations with identical arguments to prevent cache stampedes","wrap applies custom key prefixes when generating default cache keys","wrap uses custom createKey functions to derive cache keys from function references and arguments","wrap forwards configured ttl values to the underlying cache store during set operations","wrap rethrows errors from the wrapped function when throwErrors is enabled","wrap caches errors returned by the wrapped function when cacheErrors is enabled"],"goal":"verify wrap in pkg:npm/%40cacheable/utils@2.5.0","kind":"HOW","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"symbols":["wrap"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40cacheable/utils@2.5.0"],"schemaVersion":1,"subject":"pkg:npm/%40cacheable/utils@2.5.0","symbols":["wrap"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-cacheable-utils-wrap",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-cacheable-utils-wrap",
      "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-wrap",
  "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 wrap in pkg:npm/%40cacheable/utils@2.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40cacheable/utils@2.5.0"
  ],
  "symbols": [
    "wrap"
  ]
}
src/index.mjs
import { wrap } from '@cacheable/utils';
import { EventEmitter } from 'node:events';

/**
 * In-memory cache implementation conforming to CacheInstance.
 */
export class MemoryCache extends EventEmitter {
  constructor() {
    super();
    this.store = new Map();
    this.ttls = new Map();
  }

  async get(key) {
    return this.store.get(key);
  }

  async set(key, value, ttl) {
    this.store.set(key, value);
    if (ttl !== undefined) {
      this.ttls.set(key, ttl);
    }
  }

  async has(key) {
    return this.store.has(key);
  }

  async delete(key) {
    this.store.delete(key);
    this.ttls.delete(key);
  }

  async clear() {
    this.store.clear();
    this.ttls.clear();
  }
}

/**
 * Creates a cached version of an async function with an optional cache instance.
 * @param {Function} fn Function to wrap.
 * @param {Object} [options={}] Options for wrap and cache.
 * @returns {{ cache: MemoryCache, wrapped: Function }}
 */
export function createCachedFunction(fn, options = {}) {
  const cache = options.cache ?? new MemoryCache();
  const wrapped = wrap(fn, { cache, ...options });
  return { cache, wrapped };
}

export { wrap };
export default wrap;
test/contract.mjs
import assert from 'node:assert/strict';
import { wrap } from '@cacheable/utils';
import { MemoryCache, createCachedFunction } from '../src/index.mjs';

// 1. wrap memoizes the return value of an async function for identical arguments using the provided cache instance
{
  const cache = new MemoryCache();
  let calls = 0;
  const fn = async (x) => {
    calls++;
    return x * 10;
  };
  const wrapped = wrap(fn, { cache });

  const res1 = await wrapped(5);
  const res2 = await wrapped(5);

  assert.equal(res1, 50, 'First call returns computed value');
  assert.equal(res2, 50, 'Second call returns cached value');
  assert.equal(calls, 1, 'Underlying function called only once');
}

// 2. wrap re-executes the underlying function when invoked with different arguments
{
  const { cache, wrapped } = createCachedFunction(async (name) => `hello ${name}`);
  const r1 = await wrapped('alice');
  const r2 = await wrapped('bob');

  assert.equal(r1, 'hello alice');
  assert.equal(r2, 'hello bob');
  assert.equal(cache.store.size, 2, 'Cache contains entries for both distinct arguments');
}

// 3. wrap coalesces concurrent invocations with identical arguments to prevent cache stampedes
{
  const cache = new MemoryCache();
  let executions = 0;
  const slowFn = wrap(async (id) => {
    executions++;
    await new Promise((resolve) => setTimeout(resolve, 30));
    return `item-${id}`;
  }, { cache });

  const [resA, resB, resC] = await Promise.all([
    slowFn(42),
    slowFn(42),
    slowFn(42)
  ]);

  assert.equal(resA, 'item-42');
  assert.equal(resB, 'item-42');
  assert.equal(resC, 'item-42');
  assert.equal(executions, 1, 'Underlying function executed once during concurrent requests');
}

// 4. wrap applies custom key prefixes when generating default cache keys
{
  const cache = new MemoryCache();
  const testFn = async (v) => v + 1;
  const wrapped = wrap(testFn, { cache, keyPrefix: 'my-service' });

  await wrapped(100);
  const keys = [...cache.store.keys()];
  assert.equal(keys.length, 1);
  assert.ok(keys[0].startsWith('my-service::'), 'Cache key should start with configured keyPrefix');
}

// 5. wrap uses custom createKey functions to derive cache keys from function references and arguments
{
  const cache = new MemoryCache();
  const customKey = (fn, args) => `custom-key:${args[0]}:${args[1]}`;
  const wrapped = wrap(async (a, b) => a + b, {
    cache,
    createKey: customKey
  });

  await wrapped('alpha', 'beta');
  assert.ok(cache.store.has('custom-key:alpha:beta'), 'Cache should have custom formatted key');
}

// 6. wrap forwards configured ttl values to the underlying cache store during set operations
{
  const cache = new MemoryCache();
  const wrapped = wrap(async (x) => x * 2, {
    cache,
    ttl: 3600
  });

  await wrapped(7);
  const key = [...cache.store.keys()][0];
  assert.equal(cache.ttls.get(key), 3600, 'Configured ttl forwarded to cache store');
}

// 7. wrap rethrows errors from the wrapped function when throwErrors is enabled
{
  const cache = new MemoryCache();
  cache.on('error', () => {}); // Handle emitted error event
  const wrapped = wrap(async () => {
    throw new Error('computation failed');
  }, { cache, throwErrors: true });

  await assert.rejects(
    async () => { await wrapped(); },
    { message: 'computation failed' },
    'Wrapped function should reject with underlying error when throwErrors is true'
  );
}

// 8. wrap caches errors returned by the wrapped function when cacheErrors is enabled
{
  const cache = new MemoryCache();
  cache.on('error', () => {});
  let failures = 0;
  const errorFn = wrap(async () => {
    failures++;
    throw new Error('fatal');
  }, { cache, cacheErrors: true });

  // First call captures error and caches it
  const first = await errorFn();
  // Second call retrieves cached error without invoking the function again
  const second = await errorFn();

  assert.ok(first === undefined || first instanceof Error, 'First execution completes error handling');
  assert.ok(second instanceof Error, 'Second execution returns cached Error instance');
  assert.equal(second.message, 'fatal');
  assert.equal(failures, 1, 'Function executed only once despite error');
}

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

오리진 시더

익명