CodeSampleX

Exemplo

@szmarczak/http-timer 4.0.6

Amostra verificada para npm @szmarczak/http-timer 4.0.6. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: measureRequest initializes and…

sha256:e7c5ad4494e94e1c055c8d550e08c525f10590050d2e2f74397f1a09704f6d13

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-21

Caso

HOW
Objetivo
verify pkg:npm/%40szmarczak/http-timer@4.0.6
Pacotes
Ambiente
node 22.23.2
Criado
2026-08-21T09:24:41Z

Contrato

  1. measureRequest initializes and attaches a timings object to a ClientRequest
  2. returns the identical timings instance when called repeatedly on the same request
  3. getTimings extracts the timings object attached to a request or response
  4. tracks HTTP request lifecycle timings and calculates duration phases against an HTTP server
  5. records error timestamp and total elapsed duration when request emits an error event
  6. records abort timestamp and total elapsed duration when request is aborted

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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/%40szmarczak/http-timer@4.0.6
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40szmarczak/http-timer@4.0.6
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:8c7bf14ce0058ddee816194db554a34ee5e933f33d7bf461ba71946d32230d70","constraints":{"executionContext":"node"},"contract":["measureRequest initializes and attaches a timings object to a ClientRequest","returns the identical timings instance when called repeatedly on the same request","getTimings extracts the timings object attached to a request or response","tracks HTTP request lifecycle timings and calculates duration phases against an HTTP server","records error timestamp and total elapsed duration when request emits an error event","records abort timestamp and total elapsed duration when request is aborted"],"goal":"verify pkg:npm/%40szmarczak/http-timer@4.0.6","kind":"HOW","packages":["pkg:npm/%40szmarczak/http-timer@4.0.6"],"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/%40szmarczak/http-timer@4.0.6"],"schemaVersion":1,"subject":"pkg:npm/%40szmarczak/http-timer@4.0.6","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-http-timer",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-http-timer",
      "version": "1.0.0",
      "dependencies": {
        "@szmarczak/http-timer": "4.0.6"
      }
    },
    "node_modules/@szmarczak/http-timer": {
      "version": "4.0.6",
      "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz",
      "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==",
      "license": "MIT",
      "dependencies": {
        "defer-to-connect": "^2.0.0"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/defer-to-connect": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",
      "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      }
    }
  }
}
package.json
{
  "name": "sample-http-timer",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @szmarczak/http-timer",
  "main": "src/index.js",
  "dependencies": {
    "@szmarczak/http-timer": "4.0.6"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40szmarczak/http-timer@4.0.6",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40szmarczak/http-timer@4.0.6"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const timer = require('@szmarczak/http-timer');

/**
 * Attaches HTTP timing measurements to a Node.js ClientRequest instance.
 *
 * @param {import('http').ClientRequest} request - The HTTP/HTTPS client request
 * @returns {object} The timings object associated with the request
 */
function measureRequest(request) {
  return timer(request);
}

/**
 * Retrieves the timings object attached to a request or response object.
 *
 * @param {object} message - The request or response object
 * @returns {object|undefined} The timings object if attached
 */
function getTimings(message) {
  return message ? message.timings : undefined;
}

module.exports = {
  measureRequest,
  getTimings,
  timer
};
test/contract.mjs
import assert from 'node:assert';
import http from 'node:http';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { measureRequest, getTimings, timer } = require('../src/index.js');

// 1. Export verification
assert.strictEqual(typeof timer, 'function', 'timer should be exported as a function');
assert.strictEqual(typeof measureRequest, 'function', 'measureRequest should be exported as a function');
assert.strictEqual(typeof getTimings, 'function', 'getTimings should be exported as a function');

// 2. Initial timings attachment
{
  const dummyReq = new http.ClientRequest({ host: '127.0.0.1', port: 80, createConnection: () => {} });
  const timings = measureRequest(dummyReq);
  assert.strictEqual(typeof timings, 'object', 'timings should be an object');
  assert.strictEqual(typeof timings.start, 'number', 'timings.start should be a number');
  assert.strictEqual(timings.socket, undefined, 'timings.socket should be undefined initially');
  assert.strictEqual(dummyReq.timings, timings, 'request.timings should match returned timings');
  assert.strictEqual(getTimings(dummyReq), timings, 'getTimings should return timings from request');

  // 3. Repeated call returns same instance (idempotency)
  const timings2 = measureRequest(dummyReq);
  assert.strictEqual(timings, timings2, 'measureRequest should return the same timings instance');
}

// 4. HTTP request lifecycle measurement with local offline server
await new Promise((resolve, reject) => {
  const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('ok');
  });

  server.listen(0, '127.0.0.1', () => {
    const port = server.address().port;
    const req = http.request({
      hostname: '127.0.0.1',
      port: port,
      path: '/test',
      method: 'GET'
    }, (res) => {
      let data = '';
      res.on('data', chunk => { data += chunk; });
      res.on('end', () => {
        try {
          assert.strictEqual(data, 'ok', 'response data should match');
          const t = getTimings(req);
          assert.strictEqual(typeof t, 'object', 'timings should exist');
          assert.strictEqual(getTimings(res), t, 'response should share timings with request');

          // Check timestamps
          assert.strictEqual(typeof t.start, 'number', 't.start should be number');
          assert.strictEqual(typeof t.socket, 'number', 't.socket should be number');
          assert.strictEqual(typeof t.lookup, 'number', 't.lookup should be number');
          assert.strictEqual(typeof t.connect, 'number', 't.connect should be number');
          assert.strictEqual(typeof t.upload, 'number', 't.upload should be number');
          assert.strictEqual(typeof t.response, 'number', 't.response should be number');
          assert.strictEqual(typeof t.end, 'number', 't.end should be number');

          // Check phases
          assert.strictEqual(typeof t.phases.wait, 'number', 'wait phase should be number');
          assert.strictEqual(typeof t.phases.dns, 'number', 'dns phase should be number');
          assert.strictEqual(typeof t.phases.tcp, 'number', 'tcp phase should be number');
          assert.strictEqual(typeof t.phases.request, 'number', 'request phase should be number');
          assert.strictEqual(typeof t.phases.firstByte, 'number', 'firstByte phase should be number');
          assert.strictEqual(typeof t.phases.download, 'number', 'download phase should be number');
          assert.strictEqual(typeof t.phases.total, 'number', 'total phase should be number');

          assert(t.phases.total >= 0, 'total phase duration should be non-negative');

          server.close(() => resolve());
        } catch (err) {
          server.close(() => reject(err));
        }
      });
    });

    measureRequest(req);
    req.end();
  });
});

// 5. Error handling timing
await new Promise((resolve, reject) => {
  // Use a port that is not listening to trigger connection error
  const req = http.request({
    hostname: '127.0.0.1',
    port: 1,
    path: '/',
    method: 'GET'
  });

  const timings = measureRequest(req);

  req.on('error', (err) => {
    try {
      assert.strictEqual(typeof timings.error, 'number', 'timings.error should be recorded');
      assert.strictEqual(typeof timings.phases.total, 'number', 'timings.phases.total should be calculated on error');
      assert(timings.phases.total >= 0, 'total phase duration on error should be non-negative');
      resolve();
    } catch (assertionError) {
      reject(assertionError);
    }
  });

  req.end();
});

// 6. Abort handling timing
{
  const dummyReq = new http.ClientRequest({ host: '127.0.0.1', port: 80, createConnection: () => {} });
  const timings = measureRequest(dummyReq);
  assert.strictEqual(timings.abort, undefined, 'timings.abort should be undefined initially');
  
  dummyReq.emit('abort');
  assert.strictEqual(typeof timings.abort, 'number', 'timings.abort should be recorded on abort');
  assert.strictEqual(typeof timings.phases.total, 'number', 'timings.phases.total should be calculated on abort');
  assert(timings.phases.total >= 0, 'total phase duration on abort should be non-negative');
}

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

Seeder de origem

anônimo