CodeSampleX

샘플

@hono/node-server 2.0.12

검증된 샘플 — npm @hono/node-server 2.0.12. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: serve starts an HTTP server and handles fetch requests…

sha256:956be4705973b2021aa421b3f44f0574a21f4af9f038640ccce19034e84a133d

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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-28

케이스

HOW
목표
verify pkg:npm/%40hono/node-server@2.0.12
패키지
환경
node 22.23.2
생성일
2026-08-28T07:51:41Z

컨트랙트

  1. serve starts an HTTP server and handles fetch requests returning standard web Response objects
  2. serve correctly routes requests based on URL path and parses query parameters
  3. serve parses HTTP request methods, JSON request bodies, and custom headers
  4. createAdaptorServer instantiates an http.Server without binding it to a port
  5. getRequestListener creates a request listener callback for Node.js http.createServer

파일

  • 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 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
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:ba74ef91e05091a998dc92c734c0b9f5f22dd602d562b99f9f3fccfdd58b9b0f","constraints":{"executionContext":"node"},"contract":["serve starts an HTTP server and handles fetch requests returning standard web Response objects","serve correctly routes requests based on URL path and parses query parameters","serve parses HTTP request methods, JSON request bodies, and custom headers","createAdaptorServer instantiates an http.Server without binding it to a port","getRequestListener creates a request listener callback for Node.js http.createServer"],"goal":"verify pkg:npm/%40hono/node-server@2.0.12","kind":"HOW","packages":["pkg:npm/%40hono/node-server@2.0.12"],"schemaVersion":1},"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","verifierAdapter":"node-typescript@1"}
index.js
const { serve, createAdaptorServer, getRequestListener, RequestError } = require('@hono/node-server');

/**
 * Creates and starts an HTTP server with the provided fetch handler.
 * @param {Function} fetchHandler - The Fetch API compatible request handler.
 * @param {Object} [options={}] - Options including port and hostname.
 * @param {Function} [onListen] - Optional callback invoked when the server starts.
 * @returns {import('node:http').Server} The active Node.js HTTP server.
 */
function startServer(fetchHandler, options = {}, onListen) {
  return serve(
    {
      fetch: fetchHandler,
      port: options.port !== undefined ? options.port : 0,
      hostname: options.hostname || '127.0.0.1',
      ...options,
    },
    onListen
  );
}

/**
 * Creates an http.Server instance configured with a fetch request handler without automatically binding to a port.
 * @param {Function} fetchHandler - The Fetch API compatible request handler.
 * @param {Object} [options={}] - Additional adapter options.
 * @returns {import('node:http').Server} An unbound Node.js HTTP server instance.
 */
function createHttpServer(fetchHandler, options = {}) {
  return createAdaptorServer({
    fetch: fetchHandler,
    ...options,
  });
}

/**
 * Converts a web Fetch API handler into a standard Node.js (req, res) request listener.
 * @param {Function} fetchHandler - The Fetch API compatible request handler.
 * @param {Object} [options] - Listener options such as error handlers.
 * @returns {Function} Node.js request listener callback.
 */
function createRequestListener(fetchHandler, options) {
  return getRequestListener(fetchHandler, options);
}

module.exports = {
  serve,
  createAdaptorServer,
  getRequestListener,
  RequestError,
  startServer,
  createHttpServer,
  createRequestListener,
};
package-lock.json
{
  "name": "verify-hono-node-server",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-hono-node-server",
      "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",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for @hono/node-server",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "@hono/node-server": "2.0.12"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40hono/node-server@2.0.12",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40hono/node-server@2.0.12"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.cjs
const assert = require("node:assert/strict");
const http = require("node:http");
const {
  serve,
  createAdaptorServer,
  getRequestListener,
  startServer,
  createHttpServer,
  createRequestListener,
} = require("../index.js");

async function runContractTests() {
  // Contract 1: serve starts an HTTP server and handles fetch requests returning standard web Response objects.
  {
    let listenCalled = false;
    let listenInfo = null;

    const server = serve(
      {
        fetch(req) {
          return new Response("hello from hono node-server", {
            status: 200,
            headers: {
              "Content-Type": "text/plain",
              "X-Custom-Header": "node-server-test",
            },
          });
        },
        port: 0,
        hostname: "127.0.0.1",
      },
      (info) => {
        listenCalled = true;
        listenInfo = info;
      }
    );

    await new Promise((resolve) => server.on("listening", resolve));
    assert.strictEqual(listenCalled, true, "Server listen callback should be invoked");
    assert.ok(listenInfo && typeof listenInfo.port === "number", "Listen info should contain port number");

    const port = server.address().port;
    const res = await fetch("http://127.0.0.1:" + port + "/");
    assert.strictEqual(res.status, 200);
    assert.strictEqual(res.headers.get("x-custom-header"), "node-server-test");
    const text = await res.text();
    assert.strictEqual(text, "hello from hono node-server");

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

  // Contract 2: serve correctly routes requests based on URL path and parses query parameters.
  {
    const server = startServer((req) => {
      const url = new URL(req.url);
      if (url.pathname === "/api/data") {
        const key = url.searchParams.get("key");
        return new Response(JSON.stringify({ receivedKey: key }), {
          status: 200,
          headers: { "Content-Type": "application/json" },
        });
      }
      return new Response("Not Found", { status: 404 });
    });

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

    const res = await fetch("http://127.0.0.1:" + port + "/api/data?key=hono-test-123");
    assert.strictEqual(res.status, 200);
    const json = await res.json();
    assert.strictEqual(json.receivedKey, "hono-test-123");

    const notFoundRes = await fetch("http://127.0.0.1:" + port + "/nonexistent");
    assert.strictEqual(notFoundRes.status, 404);

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

  // Contract 3: serve parses HTTP request methods, JSON request bodies, and custom headers.
  {
    const server = startServer(async (req) => {
      if (req.method === "POST") {
        const body = await req.json();
        const authHeader = req.headers.get("authorization");
        return new Response(
          JSON.stringify({
            echoed: body,
            authorized: authHeader === "Bearer sample-token",
          }),
          {
            status: 201,
            headers: { "Content-Type": "application/json" },
          }
        );
      }
      return new Response("Method Not Allowed", { status: 405 });
    });

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

    const res = await fetch("http://127.0.0.1:" + port + "/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer sample-token",
      },
      body: JSON.stringify({ item: "test-item", count: 42 }),
    });

    assert.strictEqual(res.status, 201);
    const data = await res.json();
    assert.strictEqual(data.authorized, true);
    assert.strictEqual(data.echoed.item, "test-item");
    assert.strictEqual(data.echoed.count, 42);

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

  // Contract 4: createAdaptorServer instantiates an http.Server without binding it to a port.
  {
    const unboundServer = createHttpServer((req) => new Response("unbound-response"));
    assert.ok(unboundServer instanceof http.Server, "Should create an http.Server instance");
    assert.strictEqual(unboundServer.listening, false, "Server should not be listening immediately");

    await new Promise((resolve) => unboundServer.listen(0, "127.0.0.1", resolve));
    assert.strictEqual(unboundServer.listening, true, "Server should now be listening");

    const port = unboundServer.address().port;
    const res = await fetch("http://127.0.0.1:" + port + "/");
    assert.strictEqual(res.status, 200);
    const text = await res.text();
    assert.strictEqual(text, "unbound-response");

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

  // Contract 5: getRequestListener creates a request listener callback for Node.js http.createServer.
  {
    const listener = createRequestListener((req) => {
      return new Response("listener-handled", { status: 200 });
    });

    assert.strictEqual(typeof listener, "function", "getRequestListener should return a function");

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

    const port = nativeServer.address().port;
    const res = await fetch("http://127.0.0.1:" + port + "/");
    assert.strictEqual(res.status, 200);
    const text = await res.text();
    assert.strictEqual(text, "listener-handled");

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

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

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

오리진 시더

익명