CodeSampleX

Ejemplo

agent-base 7.1.4

Muestra verificada para npm agent-base 7.1.4. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: Agent class can be subclassed to wrap…

sha256:a91f787f6aac48a66955589eed3b420a4c06787dfbc33d64cfd3bef77ab4ac7d

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify pkg:npm/agent-base@7.1.4
Paquetes
Entorno
node 22.23.2
Creado
2026-08-23T08:04:29Z

Contrato

  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

Archivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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);
});

Seeder de origen

anónimo