CodeSampleX

Пример

@hono/node-server 2.1.0: serve

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

sha256:0c294e68ac37d664840045ec5b18ee4bc7788c70633258f6a720c64e6451fc4f

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

Кейс

HOW
Цель
verify serve in pkg:npm/%40hono/node-server@2.1.0
Пакеты
Символы
  • serve
Окружение
node 22.23.2
Создан
2026-09-01T22:29:32Z

Контракт

  1. @hono/node-server exports serve function
  2. serve starts an HTTP server and returns an http.Server instance
  3. serve invokes listeningListener with server AddressInfo including port and address
  4. serve dispatches HTTP GET requests to fetch handler and responds with status, headers, and body
  5. serve dispatches HTTP POST requests with JSON payload to fetch handler
  6. serve supports custom createServer factory function in options
  7. serve HTTP server can be closed via server.close()

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

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

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

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:8a42e6ed0f241dda40e3986de00c20659340b2a05b51b261a0454271cf71921c","contract":["@hono/node-server exports serve function","serve starts an HTTP server and returns an http.Server instance","serve invokes listeningListener with server AddressInfo including port and address","serve dispatches HTTP GET requests to fetch handler and responds with status, headers, and body","serve dispatches HTTP POST requests with JSON payload to fetch handler","serve supports custom createServer factory function in options","serve HTTP server can be closed via server.close()"],"goal":"verify serve in pkg:npm/%40hono/node-server@2.1.0","kind":"HOW","packages":["pkg:npm/%40hono/node-server@2.1.0"],"schemaVersion":1,"symbols":["serve"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","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.1.0"],"schemaVersion":1,"subject":"pkg:npm/%40hono/node-server@2.1.0","symbols":["serve"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-node-server-serve",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-node-server-serve",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@hono/node-server": "2.1.0"
      }
    },
    "node_modules/@hono/node-server": {
      "version": "2.1.0",
      "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.0.tgz",
      "integrity": "sha512-XovyyCCnBzW+zKu+z/zq8hwNs4KOR5rEMAOxo2f40Q5xoOI37IMm6MIg2COOUtUApo0i6850MTBKH2u4QLGIqg==",
      "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": "sample-hono-node-server-serve",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "@hono/node-server": "2.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify serve in pkg:npm/%40hono/node-server@2.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40hono/node-server@2.1.0"
  ],
  "symbols": [
    "serve"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import http from 'node:http';
import { serve, createAdaptorServer } from '@hono/node-server';

// Contract 1: @hono/node-server exports serve function
{
  assert.strictEqual(typeof serve, 'function');
  assert.strictEqual(typeof createAdaptorServer, 'function');
}

// Contract 2: serve starts an HTTP server and returns an http.Server instance
// Contract 3: serve invokes listeningListener with server AddressInfo including port and address
// Contract 4: serve dispatches HTTP GET requests to fetch handler and responds with status, headers, and body
// Contract 5: serve dispatches HTTP POST requests with JSON payload to fetch handler
{
  let listeningInfo = null;
  const server = serve(
    {
      fetch: async (req) => {
        const url = new URL(req.url);
        if (url.pathname === '/test') {
          return new Response(JSON.stringify({ ok: true, method: req.method }), {
            status: 200,
            headers: { 'content-type': 'application/json' },
          });
        }
        if (url.pathname === '/echo' && req.method === 'POST') {
          const body = await req.json();
          return new Response(JSON.stringify({ received: body }), {
            status: 201,
            headers: { 'content-type': 'application/json' },
          });
        }
        return new Response('Not Found', { status: 404 });
      },
      port: 0,
      hostname: '127.0.0.1',
    },
    (info) => {
      listeningInfo = info;
    }
  );

  assert.ok(server instanceof http.Server);

  await new Promise((resolve) => {
    if (server.listening) resolve();
    else server.once('listening', resolve);
  });

  const address = server.address();
  assert.ok(address && typeof address === 'object');
  assert.strictEqual(typeof address.port, 'number');
  assert.strictEqual(address.address, '127.0.0.1');
  assert.deepStrictEqual(listeningInfo, address);

  const baseUrl = `http://127.0.0.1:${address.port}`;

  // GET request
  const getRes = await fetch(`${baseUrl}/test`);
  assert.strictEqual(getRes.status, 200);
  assert.strictEqual(getRes.headers.get('content-type'), 'application/json');
  const getData = await getRes.json();
  assert.deepStrictEqual(getData, { ok: true, method: 'GET' });

  // POST request
  const postRes = await fetch(`${baseUrl}/echo`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ message: 'hono-node-server' }),
  });
  assert.strictEqual(postRes.status, 201);
  const postData = await postRes.json();
  assert.deepStrictEqual(postData, { received: { message: 'hono-node-server' } });

  // 404 Not Found
  const notFoundRes = await fetch(`${baseUrl}/missing`);
  assert.strictEqual(notFoundRes.status, 404);

  // Contract 7: serve HTTP server can be closed via server.close()
  await new Promise((resolve, reject) => {
    server.close((err) => (err ? reject(err) : resolve()));
  });
  assert.strictEqual(server.listening, false);
}

// Contract 6: serve supports custom createServer factory function in options
{
  let customFactoryCalled = false;
  const server = serve({
    fetch: () => new Response('custom factory response'),
    port: 0,
    hostname: '127.0.0.1',
    createServer: (options, listener) => {
      customFactoryCalled = true;
      return http.createServer(options, listener);
    },
  });

  assert.strictEqual(customFactoryCalled, true);
  assert.ok(server instanceof http.Server);

  await new Promise((resolve) => {
    if (server.listening) resolve();
    else server.once('listening', resolve);
  });

  const address = server.address();
  const res = await fetch(`http://127.0.0.1:${address.port}/`);
  assert.strictEqual(res.status, 200);
  const text = await res.text();
  assert.strictEqual(text, 'custom factory response');

  await new Promise((resolve, reject) => {
    server.close((err) => (err ? reject(err) : resolve()));
  });
  assert.strictEqual(server.listening, false);
}

console.log('All @hono/node-server serve contract tests passed.');

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

аноним