CodeSampleX

샘플

agent-base 7.1.4

검증된 샘플 — npm agent-base 7.1.4. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: Agent class can be subclassed to wrap custom synchronous or…

sha256:a91f787f6aac48a66955589eed3b420a4c06787dfbc33d64cfd3bef77ab4ac7d

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

케이스

HOW
목표
verify pkg:npm/agent-base@7.1.4
패키지
환경
node 22.23.2
생성일
2026-08-23T08:04:29Z

컨트랙트

  1. Agent class can be subclassed to wrap custom synchronous or Promise-returning socket creation functions into an http.Agent
  2. Agent routes HTTP requests through custom sockets produced by connect()
  3. Agent delegates request handling when connect() returns another http.Agent instance
  4. isSecureEndpoint determines secureEndpoint state based on options and protocol
  5. Agent defaultPort and protocol dynamic getters reflect secure state and can be overridden via setters
  6. agent-base helper functions toBuffer, json, and req handle stream buffering and HTTP requests

파일

  • 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/agent-base@7.1.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/agent-base@7.1.4
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:5c0042fa048a6be5bb0eede7ea783a167b8280347f72d037f62dd87975ecdd7f","constraints":{"executionContext":"node"},"contract":["Agent class can be subclassed to wrap custom synchronous or Promise-returning socket creation functions into an http.Agent","Agent routes HTTP requests through custom sockets produced by connect()","Agent delegates request handling when connect() returns another http.Agent instance","isSecureEndpoint determines secureEndpoint state based on options and protocol","Agent defaultPort and protocol dynamic getters reflect secure state and can be overridden via setters","agent-base helper functions toBuffer, json, and req handle stream buffering and HTTP requests"],"goal":"verify pkg:npm/agent-base@7.1.4","kind":"HOW","packages":["pkg:npm/agent-base@7.1.4"],"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/agent-base@7.1.4"],"schemaVersion":1,"subject":"pkg:npm/agent-base@7.1.4","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-agent-base",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-agent-base",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "agent-base": "7.1.4"
      }
    },
    "node_modules/agent-base": {
      "version": "7.1.4",
      "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
      "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 14"
      }
    }
  }
}
package.json
{
  "name": "sample-agent-base",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of agent-base",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "agent-base": "7.1.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/agent-base@7.1.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/agent-base@7.1.4"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const net = require('net');
const http = require('http');
const { Agent, toBuffer, json, req } = require('agent-base');

/**
 * Custom agent extending agent-base Agent with a socket connection callback.
 */
class CustomSocketAgent extends Agent {
  constructor(connectFn, opts) {
    super(opts);
    this._connectFn = connectFn;
  }

  connect(req, opts) {
    if (this._connectFn) {
      return this._connectFn(req, opts);
    }
    return net.connect(opts.port, opts.host);
  }
}

/**
 * Agent extending agent-base Agent with configurable default port and protocol.
 */
class ConfigurableAgent extends Agent {
  constructor(connectFn, opts = {}) {
    super(opts);
    this._connectFn = connectFn;
    if (opts.defaultPort !== undefined) {
      this.defaultPort = opts.defaultPort;
    }
    if (opts.protocol !== undefined) {
      this.protocol = opts.protocol;
    }
  }

  connect(req, opts) {
    if (this._connectFn) {
      return this._connectFn(req, opts);
    }
    return net.connect(opts.port, opts.host);
  }
}

/**
 * Factory function creating a CustomSocketAgent instance.
 *
 * @param {Function} connectFn - Function returning Duplex stream, Promise<Duplex>, or http.Agent
 * @param {object} [opts] - Agent options
 * @returns {CustomSocketAgent}
 */
function createCustomAgent(connectFn, opts) {
  return new CustomSocketAgent(connectFn, opts);
}

module.exports = {
  Agent,
  CustomSocketAgent,
  ConfigurableAgent,
  createCustomAgent,
  toBuffer,
  json,
  req
};
test/contract.mjs
import assert from 'node:assert';
import http from 'node:http';
import net from 'node:net';
import { Readable } from 'node:stream';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  Agent,
  CustomSocketAgent,
  ConfigurableAgent,
  createCustomAgent,
  toBuffer,
  json,
  req
} = require('../src/index.js');

async function runContract() {
  const server = http.createServer((req, res) => {
    if (req.url === '/json') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ status: 'ok', path: req.url }));
    } else {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end(`echo:${req.url}`);
    }
  });

  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const port = server.address().port;

  try {
    // 1. Agent class exports and subclassing
    assert.strictEqual(typeof Agent, 'function', 'Agent must be exported as constructor');
    assert.strictEqual(typeof toBuffer, 'function', 'toBuffer must be exported');
    assert.strictEqual(typeof json, 'function', 'json must be exported');
    assert.strictEqual(typeof req, 'function', 'req must be exported');

    // 2. CustomSocketAgent routes HTTP requests through custom sync socket
    const syncAgent = createCustomAgent((req, opts) => {
      return net.connect(opts.port, opts.host);
    });
    assert(syncAgent instanceof Agent, 'syncAgent must be an instance of Agent');
    assert(syncAgent instanceof http.Agent, 'syncAgent must inherit from http.Agent');

    const res1 = await new Promise((resolve, reject) => {
      const r = http.get(
        {
          host: '127.0.0.1',
          port: port,
          path: '/sync',
          agent: syncAgent
        },
        (res) => {
          let body = '';
          res.on('data', (chunk) => (body += chunk));
          res.on('end', () => resolve({ status: res.statusCode, body }));
        }
      );
      r.on('error', reject);
    });
    assert.strictEqual(res1.status, 200);
    assert.strictEqual(res1.body, 'echo:/sync');

    // 3. CustomSocketAgent supports async Promise-returning socket creation
    let asyncCalled = false;
    const asyncAgent = createCustomAgent(async (req, opts) => {
      await new Promise((r) => setTimeout(r, 10));
      asyncCalled = true;
      return net.connect(opts.port, opts.host);
    });

    const res2 = await new Promise((resolve, reject) => {
      const r = http.get(
        {
          host: '127.0.0.1',
          port: port,
          path: '/async',
          agent: asyncAgent
        },
        (res) => {
          let body = '';
          res.on('data', (chunk) => (body += chunk));
          res.on('end', () => resolve({ status: res.statusCode, body }));
        }
      );
      r.on('error', reject);
    });
    assert.strictEqual(asyncCalled, true);
    assert.strictEqual(res2.status, 200);
    assert.strictEqual(res2.body, 'echo:/async');

    // 4. Agent connect() delegates request handling when returning another http.Agent instance
    const directAgent = new http.Agent();
    const delegatingAgent = createCustomAgent((req, opts) => directAgent);

    const res3 = await new Promise((resolve, reject) => {
      const r = http.get(
        {
          host: '127.0.0.1',
          port: port,
          path: '/delegate',
          agent: delegatingAgent
        },
        (res) => {
          let body = '';
          res.on('data', (chunk) => (body += chunk));
          res.on('end', () => resolve({ status: res.statusCode, body }));
        }
      );
      r.on('error', reject);
    });
    assert.strictEqual(res3.status, 200);
    assert.strictEqual(res3.body, 'echo:/delegate');
    directAgent.destroy();

    // 5. isSecureEndpoint determines secureEndpoint state
    const testAgent = new CustomSocketAgent(() => {});
    assert.strictEqual(testAgent.isSecureEndpoint(), false);
    assert.strictEqual(testAgent.isSecureEndpoint({ secureEndpoint: true }), true);
    assert.strictEqual(testAgent.isSecureEndpoint({ secureEndpoint: false }), false);
    assert.strictEqual(testAgent.isSecureEndpoint({ protocol: 'https:' }), true);
    assert.strictEqual(testAgent.isSecureEndpoint({ protocol: 'http:' }), false);

    // 6. defaultPort and protocol dynamic getters and setters
    assert.strictEqual(testAgent.defaultPort, 80);
    assert.strictEqual(testAgent.protocol, 'http:');
    testAgent.defaultPort = 8080;
    testAgent.protocol = 'custom:';
    assert.strictEqual(testAgent.defaultPort, 8080);
    assert.strictEqual(testAgent.protocol, 'custom:');

    const configuredAgent = new ConfigurableAgent(null, {
      defaultPort: 9000,
      protocol: 'test:'
    });
    assert.strictEqual(configuredAgent.defaultPort, 9000);
    assert.strictEqual(configuredAgent.protocol, 'test:');

    // 7. Helper functions: toBuffer, json, req
    const textStream = Readable.from([Buffer.from('hello '), Buffer.from('world')]);
    const textBuf = await toBuffer(textStream);
    assert.strictEqual(textBuf.toString('utf8'), 'hello world');

    const jsonStream = Readable.from([Buffer.from('{"key":'), Buffer.from('"value"}')]);
    const jsonData = await json(jsonStream);
    assert.deepStrictEqual(jsonData, { key: 'value' });

    const clientReq = req(`http://127.0.0.1:${port}/json`);
    assert.strictEqual(typeof clientReq.then, 'function');
    const reqRes = await clientReq;
    assert.strictEqual(reqRes.statusCode, 200);
    const parsedRes = await json(reqRes);
    assert.deepStrictEqual(parsedRes, { status: 'ok', path: '/json' });

    console.log('Contract tests passed successfully.');
  } finally {
    server.close();
  }
}

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

오리진 시더

익명