CodeSampleX

Exemple

send 0.18.0: stream static files and handle conditional range requests with send

Échantillon vérifié pour npm send 0.18.0: stream static files and handle conditional range requests with send. Le contrat s'est exécuté sur node 22 · linux…

sha256:131e90ab1dbaa285cfc4dfe3c263a9e5c0ecbb9f9dc3cea6caafdc4c0f50fb94

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
stream static files and handle conditional range requests with send
Paquets
Symboles
  • send
Créé
2026-08-23T18:17:45Z

Contrat

  1. send(req, path, { root }) streams static files with Content-Type, Content-Length, ETag, Last-Modified, and Accept-Ranges headers
  2. send(req, path, { root }) returns HTTP 304 Not Modified when If-None-Match matches ETag
  3. send(req, path, { root }) returns HTTP 206 Partial Content with Content-Range header for byte range requests
  4. send(req, path, { root, maxAge }) sets the Cache-Control max-age header
  5. send(req, path, { root }).on('headers', fn) allows setting custom headers before streaming
  6. send(req, path, { root }) emits an error with status 404 when the file does not exist
  7. send(req, path, { root, dotfiles: 'deny' }) emits an error with status 403 for dotfiles

Fichiers

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • public/.secret
  • public/hello.txt
  • public/index.html
  • spec.json
  • src/index.mjs
  • test/contract.mjs

Télécharger l’artefact source (tar.gz)

Code source

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: stream static files and handle conditional range requests with send
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/send@0.18.0
Demonstrate these symbols/APIs:
  - send

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:472134b605813aeffda025eede73e1695a12834dd9b32c02683023e1c84126f8","contract":["send(req, path, { root }) streams static files with Content-Type, Content-Length, ETag, Last-Modified, and Accept-Ranges headers","send(req, path, { root }) returns HTTP 304 Not Modified when If-None-Match matches ETag","send(req, path, { root }) returns HTTP 206 Partial Content with Content-Range header for byte range requests","send(req, path, { root, maxAge }) sets the Cache-Control max-age header","send(req, path, { root }).on('headers', fn) allows setting custom headers before streaming","send(req, path, { root }) emits an error with status 404 when the file does not exist","send(req, path, { root, dotfiles: 'deny' }) emits an error with status 403 for dotfiles"],"goal":"stream static files and handle conditional range requests with send","kind":"HOW","packages":["pkg:npm/send@0.18.0"],"schemaVersion":1,"symbols":["send"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/send@0.18.0"],"schemaVersion":1,"subject":"pkg:npm/send@0.18.0","symbols":["send"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "send-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "send-sample",
      "version": "1.0.0",
      "dependencies": {
        "send": "0.18.0"
      }
    },
    "node_modules/debug": {
      "version": "2.6.9",
      "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
      "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
      "license": "MIT",
      "dependencies": {
        "ms": "2.0.0"
      }
    },
    "node_modules/debug/node_modules/ms": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
      "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
      "license": "MIT"
    },
    "node_modules/depd": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
      "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8"
      }
    },
    "node_modules/destroy": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
      "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8",
        "npm": "1.2.8000 || >= 1.4.16"
      }
    },
    "node_modules/ee-first": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
      "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
      "license": "MIT"
    },
    "node_modules/encodeurl": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
      "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8"
      }
    },
    "node_modules/escape-html": {
      "version": "1.0.3",
      "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
      "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
      "license": "MIT"
    },
    "node_modules/etag": {
      "version": "1.8.1",
      "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
      "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.6"
      }
    },
    "node_modules/fresh": {
      "version": "0.5.2",
      "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
      "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.6"
      }
    },
    "node_modules/http-errors": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
      "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
      "license": "MIT",
      "dependencies": {
        "depd": "2.0.0",
        "inherits": "2.0.4",
        "setprototypeof": "1.2.0",
        "statuses": "2.0.1",
        "toidentifier": "1.0.1"
      },
      "engines": {
        "node": ">= 0.8"
      }
    },
    "node_modules/inherits": {
      "version": "2.0.4",
      "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
      "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
      "license": "ISC"
    },
    "node_modules/mime": {
      "version": "1.6.0",
      "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
      "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
      "license": "MIT",
      "bin": {
        "mime": "cli.js"
      },
      "engines": {
        "node": ">=4"
      }
    },
    "node_modules/ms": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
      "license": "MIT"
    },
    "node_modules/on-finished": {
      "version": "2.4.1",
      "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
      "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
      "license": "MIT",
      "dependencies": {
        "ee-first": "1.1.1"
      },
      "engines": {
        "node": ">= 0.8"
      }
    },
    "node_modules/range-parser": {
      "version": "1.2.1",
      "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
      "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.6"
      }
    },
    "node_modules/send": {
      "version": "0.18.0",
      "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz",
      "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==",
      "license": "MIT",
      "dependencies": {
        "debug": "2.6.9",
        "depd": "2.0.0",
        "destroy": "1.2.0",
        "encodeurl": "~1.0.2",
        "escape-html": "~1.0.3",
        "etag": "~1.8.1",
        "fresh": "0.5.2",
        "http-errors": "2.0.0",
        "mime": "1.6.0",
        "ms": "2.1.3",
        "on-finished": "2.4.1",
        "range-parser": "~1.2.1",
        "statuses": "2.0.1"
      },
      "engines": {
        "node": ">= 0.8.0"
      }
    },
    "node_modules/setprototypeof": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
      "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
      "license": "ISC"
    },
    "node_modules/statuses": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
      "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8"
      }
    },
    "node_modules/toidentifier": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
      "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
      "license": "MIT",
      "engines": {
        "node": ">=0.6"
      }
    }
  }
}
package.json
{
  "name": "send-sample",
  "version": "1.0.0",
  "description": "Stream static files and handle conditional range requests with send",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "send": "0.18.0"
  }
}
public/.secret
secret content
public/hello.txt
Hello, CodeSampleX! This is a test static file for send streaming verification.
public/index.html
<!DOCTYPE html>
<html>
<head><title>Test Page</title></head>
<body><h1>Hello World</h1></body>
</html>
spec.json
{
  "schemaVersion": 1,
  "goal": "stream static files and handle conditional range requests with send",
  "kind": "HOW",
  "packages": [
    "pkg:npm/send@0.18.0"
  ],
  "symbols": [
    "send"
  ]
}
src/index.mjs
import http from 'node:http';
import send from 'send';

/**
 * Creates an HTTP request listener that serves static files from a root directory using send.
 *
 * @param {string} rootDir - Root directory for serving static files
 * @param {object} [defaultOptions] - Optional configuration passed to send
 * @returns {import('node:http').RequestListener}
 */
export function createStaticFileHandler(rootDir, defaultOptions = {}) {
  return function handleRequest(req, res) {
    const url = new URL(req.url, 'http://localhost');
    const pathname = decodeURIComponent(url.pathname);

    const options = {
      root: rootDir,
      ...defaultOptions
    };

    const stream = send(req, pathname, options);

    stream.on('error', (err) => {
      res.statusCode = err.status || 500;
      res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
      res.end(`Error: ${err.message}`);
    });

    stream.pipe(res);
  };
}

/**
 * Starts a static file server on the specified port.
 *
 * @param {string} rootDir
 * @param {number} [port=0]
 * @returns {Promise<import('node:http').Server>}
 */
export function startServer(rootDir, port = 0) {
  const handler = createStaticFileHandler(rootDir);
  const server = http.createServer(handler);

  return new Promise((resolve, reject) => {
    server.listen(port, '127.0.0.1', () => resolve(server));
    server.on('error', reject);
  });
}
test/contract.mjs
import http from 'node:http';
import path from 'node:path';
import fs from 'node:fs';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import send from 'send';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PUBLIC_DIR = path.resolve(__dirname, '../public');

function request(port, pathname, headers = {}) {
  return new Promise((resolve, reject) => {
    const req = http.request(
      {
        hostname: '127.0.0.1',
        port,
        path: pathname,
        method: 'GET',
        headers
      },
      (res) => {
        let body = '';
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
          body += chunk;
        });
        res.on('end', () => {
          resolve({
            statusCode: res.statusCode,
            headers: res.headers,
            body
          });
        });
      }
    );
    req.on('error', reject);
    req.end();
  });
}

// Create test HTTP server
const server = http.createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');
  const pathname = decodeURIComponent(url.pathname);
  const options = { root: PUBLIC_DIR };

  if (url.searchParams.get('maxAge')) {
    options.maxAge = Number(url.searchParams.get('maxAge'));
  }
  if (url.searchParams.get('dotfiles')) {
    options.dotfiles = url.searchParams.get('dotfiles');
  }

  const stream = send(req, pathname, options);

  if (url.searchParams.get('customHeader')) {
    stream.on('headers', (res) => {
      res.setHeader('X-Custom-Header', 'send-contract-value');
    });
  }

  stream.on('error', (err) => {
    res.statusCode = err.status || 500;
    res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
    res.end(err.message);
  });

  stream.pipe(res);
});

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

  try {
    // 1. send(req, path, { root }) streams static files with Content-Type, Content-Length, ETag, Last-Modified, and Accept-Ranges headers
    {
      const res = await request(port, '/hello.txt');
      assert.equal(res.statusCode, 200, 'Expected status 200 OK');
      assert.match(res.body, /Hello, CodeSampleX!/, 'Body must match static file content');
      assert.equal(res.headers['content-type'], 'text/plain; charset=UTF-8', 'Content-Type must be text/plain; charset=UTF-8');
      assert.ok(res.headers['content-length'], 'Content-Length must be present');
      assert.ok(res.headers['etag'], 'ETag header must be present');
      assert.ok(res.headers['last-modified'], 'Last-Modified header must be present');
      assert.equal(res.headers['accept-ranges'], 'bytes', 'Accept-Ranges must be bytes');
    }

    // 2. send(req, path, { root }) returns HTTP 304 Not Modified when If-None-Match matches ETag
    {
      const initial = await request(port, '/hello.txt');
      const etag = initial.headers['etag'];
      assert.ok(etag, 'ETag must be returned');

      const conditional = await request(port, '/hello.txt', { 'if-none-match': etag });
      assert.equal(conditional.statusCode, 304, 'Expected status 304 Not Modified');
      assert.equal(conditional.body, '', '304 response body must be empty');
    }

    // 3. send(req, path, { root }) returns HTTP 206 Partial Content with Content-Range header for byte range requests
    {
      const rangeRes = await request(port, '/hello.txt', { range: 'bytes=0-4' });
      assert.equal(rangeRes.statusCode, 206, 'Expected status 206 Partial Content');
      assert.match(rangeRes.headers['content-range'], /^bytes 0-4\/\d+$/, 'Content-Range header must specify byte range');
      assert.equal(rangeRes.body, 'Hello', 'Body must contain only the requested bytes');
    }

    // 4. send(req, path, { root, maxAge }) sets the Cache-Control max-age header
    {
      const maxAgeRes = await request(port, '/hello.txt?maxAge=3600000');
      assert.equal(maxAgeRes.statusCode, 200);
      assert.equal(maxAgeRes.headers['cache-control'], 'public, max-age=3600', 'Cache-Control header must match maxAge');
    }

    // 5. send(req, path, { root }).on('headers', fn) allows setting custom headers before streaming
    {
      const customRes = await request(port, '/hello.txt?customHeader=1');
      assert.equal(customRes.statusCode, 200);
      assert.equal(customRes.headers['x-custom-header'], 'send-contract-value', 'Custom header must be present');
    }

    // 6. send(req, path, { root }) emits an error with status 404 when the file does not exist
    {
      const notFoundRes = await request(port, '/nonexistent.txt');
      assert.equal(notFoundRes.statusCode, 404, 'Expected status 404 Not Found');
    }

    // 7. send(req, path, { root, dotfiles: 'deny' }) emits an error with status 403 for dotfiles
    {
      const forbiddenRes = await request(port, '/.secret?dotfiles=deny');
      assert.equal(forbiddenRes.statusCode, 403, 'Expected status 403 Forbidden');
    }

    console.log('All 7 contract assertions passed successfully.');
  } finally {
    server.close();
  }
}

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

Seeder d'origine

anonyme