CodeSampleX

샘플

hono 4.13.23

검증된 샘플 — npm hono 4.13.23. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: Outer app.use middleware sets request context via c.set() before await…

sha256:e3b4ada04e4c2d0f29893444be4b5a418914c228fc54e382e0acb9f3218188db

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

케이스

HOW
목표
verify pkg:npm/hono@4.13.23
패키지
환경
node 22.23.2
생성일
2026-11-28T03:51:09Z

컨트랙트

  1. Outer app.use middleware sets request context via c.set() before await next() and appends the x-handled-trace response header via c.header() after downstream handlers finish.
  2. Sub-router mounted via app.basePath('/api').route('/items', router) reads path parameters via c.req.param(), query parameters via c.req.query(), and inherited middleware state via c.get().
  3. POST /api/items validates JSON bodies with hono/validator validator('json', ...), returning 201 with c.req.valid('json') on valid input and 400 on invalid input.
  4. Throwing HTTPException from hono/http-exception (409 on duplicate id, 404 on missing item) is handled by app.onError with JSON error payloads and preserved middleware headers.
  5. Unmatched routes invoke custom app.notFound returning 404 JSON while still running outer middleware post-processing.

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/app.js
  • test/contract.js

소스 아티팩트 내려받기 (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/hono@4.13.23
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.23
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:fcd3d9cf5dfa6c09b9c584b55af7ff88b61a8ce150fb27252b61b157d87094e7","constraints":{"executionContext":"node"},"contract":["Outer app.use middleware sets request context via c.set() before await next() and appends the x-handled-trace response header via c.header() after downstream handlers finish.","Sub-router mounted via app.basePath('/api').route('/items', router) reads path parameters via c.req.param(), query parameters via c.req.query(), and inherited middleware state via c.get().","POST /api/items validates JSON bodies with hono/validator validator('json', ...), returning 201 with c.req.valid('json') on valid input and 400 on invalid input.","Throwing HTTPException from hono/http-exception (409 on duplicate id, 404 on missing item) is handled by app.onError with JSON error payloads and preserved middleware headers.","Unmatched routes invoke custom app.notFound returning 404 JSON while still running outer middleware post-processing."],"goal":"verify pkg:npm/hono@4.13.23","kind":"HOW","packages":["pkg:npm/hono@4.13.23"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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/hono@4.13.23"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.23","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "hono-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "hono-sample",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.13.23"
      }
    },
    "node_modules/hono": {
      "version": "4.13.23",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.23.tgz",
      "integrity": "sha512-OS90dj7dcsftEEWCOef8jRbnHE5lbrOq0hNRqjSyPsOnaGZvvfof1KS05hQNb4kUOCfDq1mG3PmHoX37DMnHQg==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "hono-sample",
  "version": "1.0.0",
  "private": true,
  "description": "Minimal CJS verification sample for hono@4.13.23",
  "main": "src/app.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "hono": "4.13.23"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/hono@4.13.23",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.23"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/app.js
'use strict';

const { Hono } = require('hono');
const { HTTPException } = require('hono/http-exception');
const { validator } = require('hono/validator');

function createApp() {
  const store = new Map([
    ['item-1', { id: 'item-1', name: 'Widget', count: 3 }],
  ]);

  const app = new Hono();

  // Outer middleware: set context state before next() and attach response header after next()
  app.use('*', async (c, next) => {
    const traceId = c.req.header('x-trace-id') || 'default-trace';
    c.set('traceId', traceId);
    await next();
    c.header('x-handled-trace', c.get('traceId'));
  });

  const itemsRouter = new Hono();

  itemsRouter.get('/:id', (c) => {
    const id = c.req.param('id');
    const item = store.get(id);
    if (!item) {
      throw new HTTPException(404, { message: `Item not found: ${id}` });
    }
    const includeMeta = c.req.query('meta') === '1';
    const body = includeMeta
      ? { ...item, traceId: c.get('traceId') }
      : item;
    return c.json(body, 200);
  });

  itemsRouter.post(
    '/',
    validator('json', (value, c) => {
      if (
        !value ||
        typeof value !== 'object' ||
        typeof value.id !== 'string' ||
        value.id.trim() === '' ||
        typeof value.name !== 'string' ||
        value.name.trim() === '' ||
        typeof value.count !== 'number' ||
        !Number.isInteger(value.count) ||
        value.count < 0
      ) {
        return c.json({ error: 'invalid_payload' }, 400);
      }
      return {
        id: value.id.trim(),
        name: value.name.trim(),
        count: value.count,
      };
    }),
    (c) => {
      const payload = c.req.valid('json');
      if (store.has(payload.id)) {
        throw new HTTPException(409, { message: 'Duplicate item id' });
      }
      store.set(payload.id, payload);
      return c.json({ created: payload, traceId: c.get('traceId') }, 201);
    }
  );

  const api = app.basePath('/api');
  api.route('/items', itemsRouter);

  app.onError((err, c) => {
    if (err instanceof HTTPException) {
      return c.json(
        { error: err.message, status: err.status, traceId: c.get('traceId') },
        err.status
      );
    }
    return c.json({ error: 'internal_error', status: 500 }, 500);
  });

  app.notFound((c) => {
    return c.json({ error: 'not_found', path: c.req.path }, 404);
  });

  return app;
}

module.exports = { createApp };
test/contract.js
'use strict';

const assert = require('node:assert/strict');
const { createApp } = require('../src/app.js');

async function main() {
  const app = createApp();

  // 1. GET existing item with path param, query param, and middleware context/header propagation
  {
    const res = await app.request('http://localhost/api/items/item-1?meta=1', {
      headers: { 'x-trace-id': 'trace-alpha' },
    });
    assert.equal(res.status, 200);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-alpha');
    const body = await res.json();
    assert.deepEqual(body, {
      id: 'item-1',
      name: 'Widget',
      count: 3,
      traceId: 'trace-alpha',
    });
  }

  // 2. POST valid JSON passes validator('json') and returns 201 with created item
  {
    const res = await app.request('http://localhost/api/items', {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'x-trace-id': 'trace-create',
      },
      body: JSON.stringify({ id: 'item-2', name: 'Gadget', count: 5 }),
    });
    assert.equal(res.status, 201);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-create');
    const body = await res.json();
    assert.deepEqual(body, {
      created: { id: 'item-2', name: 'Gadget', count: 5 },
      traceId: 'trace-create',
    });
  }

  // 3. POST invalid JSON payload is rejected by validator('json') with 400
  {
    const res = await app.request('http://localhost/api/items', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ id: 'item-3', name: 'Bad', count: -1 }),
    });
    assert.equal(res.status, 400);
    assert.equal(res.headers.get('x-handled-trace'), 'default-trace');
    const body = await res.json();
    assert.deepEqual(body, { error: 'invalid_payload' });
  }

  // 4. POST duplicate id throws HTTPException(409) handled by app.onError
  {
    const res = await app.request('http://localhost/api/items', {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'x-trace-id': 'trace-dup',
      },
      body: JSON.stringify({ id: 'item-2', name: 'Gadget', count: 5 }),
    });
    assert.equal(res.status, 409);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-dup');
    const body = await res.json();
    assert.deepEqual(body, {
      error: 'Duplicate item id',
      status: 409,
      traceId: 'trace-dup',
    });
  }

  // 5. GET unknown item id throws HTTPException(404) handled by app.onError
  {
    const res = await app.request('http://localhost/api/items/missing-id', {
      headers: { 'x-trace-id': 'trace-missing' },
    });
    assert.equal(res.status, 404);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-missing');
    const body = await res.json();
    assert.deepEqual(body, {
      error: 'Item not found: missing-id',
      status: 404,
      traceId: 'trace-missing',
    });
  }

  // 6. Unmatched route invokes custom app.notFound while preserving outer middleware header
  {
    const res = await app.request('http://localhost/unknown/path', {
      headers: { 'x-trace-id': 'trace-404' },
    });
    assert.equal(res.status, 404);
    assert.equal(res.headers.get('x-handled-trace'), 'trace-404');
    const body = await res.json();
    assert.deepEqual(body, { error: 'not_found', path: '/unknown/path' });
  }

  console.log('hono@4.13.23 contract checks passed');
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

오리진 시더

익명