CodeSampleX

Ejemplo

http-cache-semantics 4.2.0: revalidationHeaders

Muestra verificada para npm http-cache-semantics 4.2.0: revalidationHeaders. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó.

sha256:332f7cfa8113fccdfd4e72a6fde1c2ce79f1d68568f5b5d76bd79771f00a72e7

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 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

Caso

HOW
Objetivo
verify http-cache-semantics.revalidationHeaders in pkg:npm/http-cache-semantics@4.2.0
Paquetes
Símbolos
  • http-cache-semantics.revalidationHeaders
Entorno
node 22.23.2
Creado
2026-09-05T23:37:56Z

Contrato

  1. revalidationHeaders returns headers with If-None-Match when cached response has ETag
  2. revalidationHeaders returns headers with If-Modified-Since when cached response has Last-Modified
  3. revalidationHeaders preserves existing incoming If-None-Match and appends cached ETag
  4. revalidationHeaders removes If-None-Match and If-Modified-Since when request does not match cached response or cache is not storable
  5. revalidationHeaders strips hop-by-hop headers and if-range from incoming request
  6. revalidationHeaders removes weak validators when request method is not GET
  7. revalidationHeaders throws Error when incoming request headers are missing

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 http-cache-semantics.revalidationHeaders in pkg:npm/http-cache-semantics@4.2.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/http-cache-semantics@4.2.0
Demonstrate these symbols/APIs:
  - http-cache-semantics.revalidationHeaders

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:058e9313d4c9c0593a59aa1d2d179b7bd1fa6d5f30c9aebf4cbce193fee02b04","constraints":{"executionContext":"node"},"contract":["revalidationHeaders returns headers with If-None-Match when cached response has ETag","revalidationHeaders returns headers with If-Modified-Since when cached response has Last-Modified","revalidationHeaders preserves existing incoming If-None-Match and appends cached ETag","revalidationHeaders removes If-None-Match and If-Modified-Since when request does not match cached response or cache is not storable","revalidationHeaders strips hop-by-hop headers and if-range from incoming request","revalidationHeaders removes weak validators when request method is not GET","revalidationHeaders throws Error when incoming request headers are missing"],"goal":"verify http-cache-semantics.revalidationHeaders in pkg:npm/http-cache-semantics@4.2.0","kind":"HOW","packages":["pkg:npm/http-cache-semantics@4.2.0"],"schemaVersion":1,"symbols":["http-cache-semantics.revalidationHeaders"]},"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/http-cache-semantics@4.2.0"],"schemaVersion":1,"subject":"pkg:npm/http-cache-semantics@4.2.0","symbols":["http-cache-semantics.revalidationHeaders"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-http-cache-semantics",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-http-cache-semantics",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "http-cache-semantics": "4.2.0"
      }
    },
    "node_modules/http-cache-semantics": {
      "version": "4.2.0",
      "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",
      "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==",
      "license": "BSD-2-Clause"
    }
  }
}
package.json
{
  "name": "sample-http-cache-semantics",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for http-cache-semantics@4.2.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "http-cache-semantics": "4.2.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify http-cache-semantics.revalidationHeaders in pkg:npm/http-cache-semantics@4.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/http-cache-semantics@4.2.0"
  ],
  "symbols": [
    "http-cache-semantics.revalidationHeaders"
  ]
}
src/index.js
'use strict';

const CachePolicy = require('http-cache-semantics');

/**
 * Creates a new CachePolicy instance.
 *
 * @param {object} req - HTTP request representation.
 * @param {object} res - HTTP response representation.
 * @param {object} [options] - Cache policy options.
 * @returns {CachePolicy} The created cache policy.
 */
function createPolicy(req, res, options) {
  return new CachePolicy(req, res, options);
}

/**
 * Computes headers to send in a revalidation request for a stale cache entry.
 *
 * @param {CachePolicy} policy - Current CachePolicy instance.
 * @param {object} incomingReq - Incoming HTTP request asking for the cached resource.
 * @returns {Record<string, string>} Headers to send in the revalidation request to origin.
 */
function getRevalidationHeaders(policy, incomingReq) {
  return policy.revalidationHeaders(incomingReq);
}

module.exports = {
  CachePolicy,
  createPolicy,
  getRevalidationHeaders,
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { CachePolicy, createPolicy, getRevalidationHeaders } = require('../src/index.js');

async function testAll() {
  // 1. Export and symbol verification
  assert.equal(typeof CachePolicy, 'function', 'CachePolicy should be a constructor function');
  assert.equal(typeof createPolicy, 'function', 'createPolicy should be a function');
  assert.equal(typeof getRevalidationHeaders, 'function', 'getRevalidationHeaders should be a function');
  assert.equal(
    typeof CachePolicy.prototype.revalidationHeaders,
    'function',
    'CachePolicy.prototype.revalidationHeaders must be a function'
  );

  // Base request
  const req = {
    url: '/api/resource',
    method: 'GET',
    headers: { host: 'example.com' },
  };

  // 2. revalidationHeaders returns headers with If-None-Match when cached response has ETag
  {
    const res = {
      status: 200,
      headers: {
        'cache-control': 'public, max-age=60',
        etag: '"tag-v1"',
      },
    };
    const policy = createPolicy(req, res);
    const revalHeaders = getRevalidationHeaders(policy, {
      url: '/api/resource',
      method: 'GET',
      headers: { host: 'example.com' },
    });
    assert.equal(revalHeaders['if-none-match'], '"tag-v1"');
  }

  // 3. revalidationHeaders returns headers with If-Modified-Since when cached response has Last-Modified
  {
    const lastModified = 'Sat, 05 Sep 2026 12:00:00 GMT';
    const res = {
      status: 200,
      headers: {
        'cache-control': 'public, max-age=60',
        'last-modified': lastModified,
      },
    };
    const policy = createPolicy(req, res);
    const revalHeaders = getRevalidationHeaders(policy, {
      url: '/api/resource',
      method: 'GET',
      headers: { host: 'example.com' },
    });
    assert.equal(revalHeaders['if-modified-since'], lastModified);
  }

  // 4. revalidationHeaders preserves existing incoming If-None-Match and appends cached ETag
  {
    const res = {
      status: 200,
      headers: {
        'cache-control': 'public, max-age=60',
        etag: '"server-tag"',
      },
    };
    const policy = createPolicy(req, res);
    const revalHeaders = getRevalidationHeaders(policy, {
      url: '/api/resource',
      method: 'GET',
      headers: {
        host: 'example.com',
        'if-none-match': '"client-tag"',
      },
    });
    assert.equal(revalHeaders['if-none-match'], '"client-tag", "server-tag"');
  }

  // 5. revalidationHeaders removes If-None-Match and If-Modified-Since when request does not match cached response or cache is not storable
  {
    const res = {
      status: 200,
      headers: {
        'cache-control': 'no-store',
        etag: '"tag-v1"',
        'last-modified': 'Sat, 05 Sep 2026 12:00:00 GMT',
      },
    };
    const policy = createPolicy(req, res);
    assert.equal(policy.storable(), false);
    const revalHeaders = getRevalidationHeaders(policy, {
      url: '/api/resource',
      method: 'GET',
      headers: {
        host: 'example.com',
        'if-none-match': '"tag-v1"',
        'if-modified-since': 'Sat, 05 Sep 2026 12:00:00 GMT',
      },
    });
    assert.equal(revalHeaders['if-none-match'], undefined);
    assert.equal(revalHeaders['if-modified-since'], undefined);

    // Mismatched URL
    const storablePolicy = createPolicy(req, {
      status: 200,
      headers: {
        'cache-control': 'public, max-age=60',
        etag: '"tag-v1"',
      },
    });
    const mismatchedHeaders = getRevalidationHeaders(storablePolicy, {
      url: '/api/different-path',
      method: 'GET',
      headers: {
        host: 'example.com',
        'if-none-match': '"tag-v1"',
      },
    });
    assert.equal(mismatchedHeaders['if-none-match'], undefined);
  }

  // 6. revalidationHeaders strips hop-by-hop headers and if-range from incoming request
  {
    const res = {
      status: 200,
      headers: {
        'cache-control': 'public, max-age=60',
        etag: '"tag-v1"',
      },
    };
    const policy = createPolicy(req, res);
    const revalHeaders = getRevalidationHeaders(policy, {
      url: '/api/resource',
      method: 'GET',
      headers: {
        host: 'example.com',
        connection: 'close',
        'keep-alive': 'timeout=5',
        'if-range': '"tag-v1"',
        'x-custom-header': 'value',
      },
    });
    assert.equal(revalHeaders.connection, undefined);
    assert.equal(revalHeaders['keep-alive'], undefined);
    assert.equal(revalHeaders['if-range'], undefined);
    assert.equal(revalHeaders['x-custom-header'], 'value');
    assert.equal(revalHeaders['if-none-match'], '"tag-v1"');
  }

  // 7. revalidationHeaders removes weak validators when request method is not GET
  {
    const postReq = {
      url: '/api/resource',
      method: 'POST',
      headers: { host: 'example.com' },
    };
    const res = {
      status: 200,
      headers: {
        'cache-control': 'public, max-age=60',
        etag: 'W/"weak-tag"',
        'last-modified': 'Sat, 05 Sep 2026 12:00:00 GMT',
      },
    };
    const policy = createPolicy(postReq, res);
    const revalHeaders = getRevalidationHeaders(policy, {
      url: '/api/resource',
      method: 'POST',
      headers: { host: 'example.com' },
    });
    assert.equal(revalHeaders['if-modified-since'], undefined);
    assert.equal(revalHeaders['if-none-match'], undefined);
  }

  // 8. revalidationHeaders throws Error when incoming request headers are missing
  {
    const res = {
      status: 200,
      headers: { 'cache-control': 'public, max-age=60' },
    };
    const policy = createPolicy(req, res);
    assert.throws(
      () => policy.revalidationHeaders(null),
      /Request headers missing/
    );
    assert.throws(
      () => policy.revalidationHeaders({}),
      /Request headers missing/
    );
  }

  console.log('All http-cache-semantics revalidationHeaders contract assertions passed.');
}

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

Seeder de origen

anónimo