CodeSampleX

サンプル

cacheable-lookup 5.0.4

検証済みサンプル — npm cacheable-lookup 5.0.4. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: CacheableLookup instance resolves hostname via mock DNS…

sha256:8f2c04aaff8af365c4f72763e5c5fe659dadf71cba301e2e800bf1065aaab8a3

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

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
2
ビルドした署名鍵
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
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-07

ケース

HOW
ゴール
verify pkg:npm/cacheable-lookup@5.0.4
パッケージ
環境
node 22.23.2
作成日
2026-08-26T09:17:17Z

コントラクト

  1. CacheableLookup instance resolves hostname via mock DNS resolver and caches IP entry in custom cache
  2. CacheableLookup lookup callback and lookupAsync methods return cached address and family or all entries when all option is enabled
  3. CacheableLookup clear method removes cached entries for a specific hostname or all hostnames
  4. CacheableLookup install attaches lookup to http.Agent and uninstall restores original createConnection method
  5. CacheableLookup throws ENOTFOUND error when hostname cannot be resolved by resolver or fallback

ファイル

  • 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/cacheable-lookup@5.0.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/cacheable-lookup@5.0.4

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:8f1e7158f3739c4dd6b58bfacfed6a6c588bcc4159b8676f93b4c9bdace01221","contract":["CacheableLookup instance resolves hostname via mock DNS resolver and caches IP entry in custom cache","CacheableLookup lookup callback and lookupAsync methods return cached address and family or all entries when all option is enabled","CacheableLookup clear method removes cached entries for a specific hostname or all hostnames","CacheableLookup install attaches lookup to http.Agent and uninstall restores original createConnection method","CacheableLookup throws ENOTFOUND error when hostname cannot be resolved by resolver or fallback"],"goal":"verify pkg:npm/cacheable-lookup@5.0.4","kind":"HOW","packages":["pkg:npm/cacheable-lookup@5.0.4"],"schemaVersion":1},"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/cacheable-lookup@5.0.4"],"schemaVersion":1,"subject":"pkg:npm/cacheable-lookup@5.0.4","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "cacheable-lookup-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "cacheable-lookup-sample",
      "version": "1.0.0",
      "dependencies": {
        "cacheable-lookup": "5.0.4"
      }
    },
    "node_modules/cacheable-lookup": {
      "version": "5.0.4",
      "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",
      "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==",
      "license": "MIT",
      "engines": {
        "node": ">=10.6.0"
      }
    }
  }
}
package.json
{
  "name": "cacheable-lookup-sample",
  "version": "1.0.0",
  "dependencies": {
    "cacheable-lookup": "5.0.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/cacheable-lookup@5.0.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/cacheable-lookup@5.0.4"
  ]
}
src/index.js
const CacheableLookup = require('cacheable-lookup');

/**
 * Creates a CacheableLookup instance configured with given options.
 * @param {import('cacheable-lookup').Options} [options]
 * @returns {CacheableLookup}
 */
function createCacheableLookup(options = {}) {
  return new CacheableLookup(options);
}

/**
 * Resolves a hostname asynchronously using the provided CacheableLookup instance.
 * @param {CacheableLookup} cacheable
 * @param {string} hostname
 * @param {object} [options]
 * @returns {Promise<import('cacheable-lookup').EntryObject | import('cacheable-lookup').EntryObject[]>}
 */
async function resolveHost(cacheable, hostname, options) {
  return cacheable.lookupAsync(hostname, options);
}

/**
 * Installs CacheableLookup on an Agent and returns an uninstall function.
 * @param {CacheableLookup} cacheable
 * @param {import('http').Agent} agent
 * @returns {() => void}
 */
function attachToAgent(cacheable, agent) {
  cacheable.install(agent);
  return () => cacheable.uninstall(agent);
}

module.exports = {
  CacheableLookup,
  createCacheableLookup,
  resolveHost,
  attachToAgent
};
test/contract.js
const assert = require('node:assert/strict');
const http = require('node:http');
const {
  CacheableLookup,
  createCacheableLookup,
  resolveHost,
  attachToAgent
} = require('../src/index.js');

// Mock offline DNS resolver satisfying CacheableLookup requirements
function createMockResolver(records = {}) {
  return {
    resolve4(hostname, options, callback) {
      if (typeof options === 'function') {
        callback = options;
      }
      if (records[hostname] && records[hostname].v4) {
        const results = records[hostname].v4.map((addr) => ({
          address: addr,
          ttl: 300
        }));
        return callback ? callback(null, results) : Promise.resolve(results);
      }
      const err = new Error(`queryA ENOTFOUND ${hostname}`);
      err.code = 'ENOTFOUND';
      return callback ? callback(err) : Promise.reject(err);
    },
    resolve6(hostname, options, callback) {
      if (typeof options === 'function') {
        callback = options;
      }
      if (records[hostname] && records[hostname].v6) {
        const results = records[hostname].v6.map((addr) => ({
          address: addr,
          ttl: 300
        }));
        return callback ? callback(null, results) : Promise.resolve(results);
      }
      const err = new Error(`queryAaaa ENODATA ${hostname}`);
      err.code = 'ENODATA';
      return callback ? callback(err) : Promise.reject(err);
    },
    getServers() {
      return ['127.0.0.1'];
    },
    setServers(_servers) {}
  };
}

async function runContracts() {
  const records = {
    'localhost.test': {
      v4: ['127.0.0.1'],
      v6: ['::1']
    },
    'service.local': {
      v4: ['192.168.1.10', '192.168.1.11']
    }
  };

  const customCache = new Map();
  const mockResolver = createMockResolver(records);
  const cacheable = createCacheableLookup({
    resolver: mockResolver,
    cache: customCache,
    fallbackDuration: 0
  });

  // Contract 1: CacheableLookup instance resolves hostname via mock DNS resolver and caches IP entry in custom cache
  {
    assert.strictEqual(typeof CacheableLookup, 'function', 'CacheableLookup should be a constructor');
    assert.strictEqual(customCache.has('localhost.test'), false, 'Cache should initially be empty for hostname');

    const result = await resolveHost(cacheable, 'localhost.test');
    assert.ok(result, 'Resolved entry should exist');
    assert.strictEqual(result.address, '127.0.0.1', 'Resolved IPv4 address should match');
    assert.strictEqual(result.family, 4, 'Resolved family should be 4');
    assert.strictEqual(customCache.has('localhost.test'), true, 'Resolved entries must be saved to custom cache');
  }

  // Contract 2: CacheableLookup lookup callback and lookupAsync methods return cached address and family or all entries when all option is enabled
  {
    // Async lookup with all: true
    const allEntries = await resolveHost(cacheable, 'localhost.test', { all: true });
    assert.strictEqual(Array.isArray(allEntries), true, 'all: true should return an array');
    assert.strictEqual(allEntries.length, 2, 'Should contain both IPv4 and IPv6 entries');
    assert.strictEqual(allEntries[0].address, '127.0.0.1');
    assert.strictEqual(allEntries[1].address, '::1');

    // Callback lookup
    await new Promise((resolve, reject) => {
      cacheable.lookup('localhost.test', (err, address, family) => {
        if (err) return reject(err);
        try {
          assert.strictEqual(address, '127.0.0.1', 'Callback lookup address should match');
          assert.strictEqual(family, 4, 'Callback lookup family should match');
          resolve();
        } catch (e) {
          reject(e);
        }
      });
    });
  }

  // Contract 3: CacheableLookup clear method removes cached entries for a specific hostname or all hostnames
  {
    assert.strictEqual(customCache.has('localhost.test'), true, 'Entry should exist before clear');
    cacheable.clear('localhost.test');
    assert.strictEqual(customCache.has('localhost.test'), false, 'Entry should be cleared for specific hostname');

    // Populate and clear all
    await resolveHost(cacheable, 'service.local');
    assert.strictEqual(customCache.has('service.local'), true);
    cacheable.clear();
    assert.strictEqual(customCache.size, 0, 'All cache entries should be cleared');
  }

  // Contract 4: CacheableLookup install attaches lookup to http.Agent and uninstall restores original createConnection method
  {
    const agent = new http.Agent();
    const originalCreateConnection = agent.createConnection;

    const detach = attachToAgent(cacheable, agent);
    assert.notStrictEqual(agent.createConnection, originalCreateConnection, 'createConnection should be wrapped');

    // Attempting to install twice should throw
    assert.throws(
      () => cacheable.install(agent),
      /CacheableLookup has been already installed/,
      'Should throw if already installed'
    );

    detach();
    assert.strictEqual(agent.createConnection, originalCreateConnection, 'createConnection should be restored');
  }

  // Contract 5: CacheableLookup throws ENOTFOUND error when hostname cannot be resolved by resolver or fallback
  {
    await assert.rejects(
      async () => resolveHost(cacheable, 'nonexistent.test'),
      (err) => {
        assert.ok(err instanceof Error, 'Should be an Error instance');
        assert.strictEqual(err.code, 'ENOTFOUND', 'Error code should be ENOTFOUND');
        assert.strictEqual(err.hostname, 'nonexistent.test', 'Error hostname should match');
        return true;
      }
    );
  }

  console.log('All pkg:npm/cacheable-lookup@5.0.4 contracts passed successfully.');
}

runContracts().catch((err) => {
  console.error('Contract verification failed:', err);
  process.exit(1);
});

オリジンシーダー

匿名