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

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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);
});

オリジンシーダー

匿名