CodeSampleX

Пример

@hono/node-server 2.0.12: RequestError

Проверенный пример — npm @hono/node-server 2.0.12: RequestError. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:ff6de9f6cb646b2c17b508b20571201874ce398a21854ec20028cfc22deba17d

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-06

Кейс

HOW
Цель
verify @hono/node-server.RequestError in pkg:npm/%40hono/node-server@2.0.12
Пакеты
Символы
  • @hono/node-server.RequestError
Окружение
node 22.23.2
Создан
2026-09-06T11:26:56Z

Контракт

  1. RequestError is an instance of Error with name RequestError and preserves message and options cause
  2. getRequestListener passes a RequestError with message Missing host header to custom errorHandler when host header is missing
  3. getRequestListener passes a RequestError with message Invalid host header to custom errorHandler when host header contains invalid characters
  4. serve handles RequestError with default HTTP 400 Bad Request response when no custom errorHandler is provided

Файлы

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

Скачать артефакт с исходным кодом (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 @hono/node-server.RequestError in pkg:npm/%40hono/node-server@2.0.12
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40hono/node-server@2.0.12
Demonstrate these symbols/APIs:
  - @hono/node-server.RequestError

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:73eadadb40ee2536416677f63e468f79315e1290f3f152643cbb126dc4f4d6f4","contract":["RequestError is an instance of Error with name RequestError and preserves message and options cause","getRequestListener passes a RequestError with message Missing host header to custom errorHandler when host header is missing","getRequestListener passes a RequestError with message Invalid host header to custom errorHandler when host header contains invalid characters","serve handles RequestError with default HTTP 400 Bad Request response when no custom errorHandler is provided"],"goal":"verify @hono/node-server.RequestError in pkg:npm/%40hono/node-server@2.0.12","kind":"HOW","packages":["pkg:npm/%40hono/node-server@2.0.12"],"schemaVersion":1,"symbols":["@hono/node-server.RequestError"]},"contractCommand":["node","test/contract.cjs"],"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/%40hono/node-server@2.0.12"],"schemaVersion":1,"subject":"pkg:npm/%40hono/node-server@2.0.12","symbols":["@hono/node-server.RequestError"],"verifierAdapter":"node-typescript@1"}
index.js
const {
  RequestError,
  serve,
  createAdaptorServer,
  getRequestListener,
} = require("@hono/node-server");

/**
 * Creates a RequestError with the specified message and optional cause.
 * @param {string} message - Error description.
 * @param {{ cause?: unknown }} [options] - Error options including cause.
 * @returns {RequestError} Instance of RequestError.
 */
function createRequestError(message, options) {
  return new RequestError(message, options);
}

/**
 * Creates a request listener with custom error handling.
 * @param {Function} fetchHandler - Fetch request handler.
 * @param {Function} [errorHandler] - Error handler for RequestError and other errors.
 * @param {Object} [options={}] - Additional options.
 * @returns {Function} Node.js request listener.
 */
function createListenerWithErrorHandling(fetchHandler, errorHandler, options = {}) {
  return getRequestListener(fetchHandler, {
    ...options,
    errorHandler,
  });
}

/**
 * Starts a server with default error handling.
 * @param {Function} fetchHandler - Fetch request handler.
 * @param {Object} [options={}] - Server options.
 * @returns {import("node:http").Server} Active server.
 */
function startServer(fetchHandler, options = {}) {
  return serve({
    fetch: fetchHandler,
    port: options.port !== undefined ? options.port : 0,
    ...options,
  });
}

module.exports = {
  RequestError,
  serve,
  createAdaptorServer,
  getRequestListener,
  createRequestError,
  createListenerWithErrorHandling,
  startServer,
};
package-lock.json
{
  "name": "verify-hono-node-server-requesterror",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-hono-node-server-requesterror",
      "version": "1.0.0",
      "dependencies": {
        "@hono/node-server": "2.0.12"
      }
    },
    "node_modules/@hono/node-server": {
      "version": "2.0.12",
      "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.0.12.tgz",
      "integrity": "sha512-eWpQYr67tqJLeaSUl0Q+TquuYfUdTibpOJlUMV2FfUP7+KqCC5TufnwnlXL6mobZBJbGAYRd7ZvEBDCbLInjhg==",
      "license": "MIT",
      "engines": {
        "node": ">=20"
      },
      "peerDependencies": {
        "hono": "^4"
      }
    },
    "node_modules/hono": {
      "version": "4.13.5",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.5.tgz",
      "integrity": "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw==",
      "license": "MIT",
      "peer": true,
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "verify-hono-node-server-requesterror",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for @hono/node-server RequestError",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "@hono/node-server": "2.0.12"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @hono/node-server.RequestError in pkg:npm/%40hono/node-server@2.0.12",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40hono/node-server@2.0.12"
  ],
  "symbols": [
    "@hono/node-server.RequestError"
  ]
}
test/contract.cjs
const assert = require("node:assert/strict");
const http = require("node:http");
const net = require("node:net");
const {
  RequestError,
  serve,
  getRequestListener,
  createRequestError,
  createListenerWithErrorHandling,
  startServer,
} = require("../index.js");

/**
 * Sends a raw HTTP request over TCP socket and returns response string.
 * @param {number} port - Target server port.
 * @param {string} rawHttp - Raw HTTP request bytes.
 * @returns {Promise<string>}
 */
function sendRawRequest(port, rawHttp) {
  return new Promise((resolve, reject) => {
    const client = net.createConnection({ port, host: "127.0.0.1" }, () => {
      client.write(rawHttp);
    });
    let data = "";
    client.on("data", (chunk) => {
      data += chunk.toString();
    });
    client.on("end", () => {
      resolve(data);
    });
    client.on("error", reject);
  });
}

async function runContractTests() {
  // Contract 1: RequestError is an instance of Error with name RequestError and preserves message and options cause
  {
    const causeErr = new Error("underlying connection fault");
    const err = createRequestError("request validation failed", { cause: causeErr });

    assert.ok(err instanceof Error, "RequestError must be an instance of Error");
    assert.ok(err instanceof RequestError, "err must be an instance of RequestError");
    assert.strictEqual(err.name, "RequestError", "Error name must be RequestError");
    assert.strictEqual(err.message, "request validation failed", "Error message must match");
    assert.strictEqual(err.cause, causeErr, "Error cause must match provided cause");
  }

  // Contract 2: getRequestListener passes a RequestError with message Missing host header to custom errorHandler when host header is missing
  {
    let capturedError = null;
    const listener = createListenerWithErrorHandling(
      () => new Response("ok", { status: 200 }),
      (err) => {
        capturedError = err;
        return new Response("Handled: " + err.message, {
          status: 400,
          headers: { "X-Error-Type": err.name },
        });
      }
    );

    const server = http.createServer(listener);
    await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
    const port = server.address().port;

    const response = await sendRawRequest(port, "GET / HTTP/1.0\r\nConnection: close\r\n\r\n");

    assert.ok(response.startsWith("HTTP/1.1 400 Bad Request"), "Response status must be 400");
    assert.ok(response.includes("X-Error-Type: RequestError"), "Header must reflect RequestError");
    assert.ok(response.includes("Handled: Missing host header"), "Body must reflect Missing host header");
    assert.ok(capturedError instanceof RequestError, "Captured error must be instance of RequestError");
    assert.strictEqual(capturedError.name, "RequestError");
    assert.strictEqual(capturedError.message, "Missing host header");

    await new Promise((resolve) => server.close(resolve));
  }

  // Contract 3: getRequestListener passes a RequestError with message Invalid host header to custom errorHandler when host header contains invalid characters
  {
    let capturedError = null;
    const listener = createListenerWithErrorHandling(
      () => new Response("ok", { status: 200 }),
      (err) => {
        capturedError = err;
        return new Response("Handled: " + err.message, {
          status: 400,
          headers: { "X-Error-Type": err.name },
        });
      }
    );

    const server = http.createServer(listener);
    await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
    const port = server.address().port;

    const response = await sendRawRequest(
      port,
      "GET / HTTP/1.1\r\nHost: inv@lid_host\r\nConnection: close\r\n\r\n"
    );

    assert.ok(response.startsWith("HTTP/1.1 400 Bad Request"), "Response status must be 400");
    assert.ok(response.includes("X-Error-Type: RequestError"), "Header must reflect RequestError");
    assert.ok(response.includes("Handled: Invalid host header"), "Body must reflect Invalid host header");
    assert.ok(capturedError instanceof RequestError, "Captured error must be instance of RequestError");
    assert.strictEqual(capturedError.name, "RequestError");
    assert.strictEqual(capturedError.message, "Invalid host header");

    await new Promise((resolve) => server.close(resolve));
  }

  // Contract 4: serve handles RequestError with default HTTP 400 Bad Request response when no custom errorHandler is provided
  {
    const server = startServer(() => new Response("ok-healthy", { status: 200 }));

    await new Promise((resolve) => server.on("listening", resolve));
    const port = server.address().port;

    const badRes = await sendRawRequest(port, "GET / HTTP/1.0\r\nConnection: close\r\n\r\n");
    assert.ok(badRes.startsWith("HTTP/1.1 400 Bad Request"), "Should return default 400 Bad Request");

    const goodRes = await sendRawRequest(
      port,
      "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"
    );
    assert.ok(goodRes.startsWith("HTTP/1.1 200 OK"), "Valid request should return 200 OK");
    assert.ok(goodRes.includes("ok-healthy"), "Body should match expected handler output");

    await new Promise((resolve) => server.close(resolve));
  }

  console.log("All @hono/node-server.RequestError contract tests passed successfully.");
}

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

Исходный сидер

аноним