CodeSampleX

Пример

hono 4.13.7: validator

Проверенный пример — npm hono 4.13.7: validator. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: validator is exported as a middleware…

sha256:855b012a8bd0802de872ed834bd38431043423d8db33962546e4e96487616b10

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

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

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

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

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

Окружение Контракт Этапы Запуск
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/validator in pkg:npm/hono@4.13.7
Пакеты
Символы
  • hono/validator
Создан
2026-09-06T04:35:43Z

Контракт

  1. validator is exported as a middleware factory function from hono/validator
  2. validator validates and sanitizes JSON request body, providing validated data via c.req.valid('json')
  3. validator validates and transforms query parameters, providing validated data via c.req.valid('query')
  4. validator validates path parameters and short-circuits with custom error response when validation fails
  5. validator validates custom request headers, returning 401 when required header is missing or invalid

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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 hono/validator in pkg:npm/hono@4.13.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.7
Demonstrate these symbols/APIs:
  - hono/validator

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:e536335a6e11781a97e592a66e83b5a0935807127c04092a91591c8a867fad2a","contract":["validator is exported as a middleware factory function from hono/validator","validator validates and sanitizes JSON request body, providing validated data via c.req.valid('json')","validator validates and transforms query parameters, providing validated data via c.req.valid('query')","validator validates path parameters and short-circuits with custom error response when validation fails","validator validates custom request headers, returning 401 when required header is missing or invalid"],"goal":"verify hono/validator in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["hono/validator"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["hono/validator"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-validator",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-validator",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.13.7"
      }
    },
    "node_modules/hono": {
      "version": "4.13.7",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz",
      "integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-validator",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for hono/validator in pkg:npm/hono@4.13.7",
  "type": "module",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hono/validator in pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "hono/validator"
  ]
}
src/index.mjs
import { Hono } from 'hono';
import { validator } from 'hono/validator';

/**
 * Creates and configures a Hono application demonstrating hono/validator.
 * @returns {Hono} Configured Hono application instance.
 */
export function createApp() {
  const app = new Hono();

  // Validate and sanitize JSON body for POST /api/posts
  app.post(
    '/api/posts',
    validator('json', (value, c) => {
      const title = value && typeof value.title === 'string' ? value.title.trim() : null;
      const count = Number(value?.count);
      if (!title || Number.isNaN(count) || count < 0) {
        return c.json({ error: 'Invalid title or count' }, 400);
      }
      return { title, count };
    }),
    (c) => {
      const validData = c.req.valid('json');
      return c.json({ success: true, data: validData });
    }
  );

  // Validate and transform query parameters for GET /api/search
  app.get(
    '/api/search',
    validator('query', (value, c) => {
      const limit = Number(value.limit);
      const page = Number(value.page);
      if (Number.isNaN(limit) || Number.isNaN(page) || limit <= 0 || page <= 0) {
        return c.json({ error: 'Invalid query parameters' }, 400);
      }
      return { limit, page };
    }),
    (c) => {
      const validQuery = c.req.valid('query');
      return c.json({ limit: validQuery.limit, page: validQuery.page });
    }
  );

  // Validate path parameter for GET /api/items/:id
  app.get(
    '/api/items/:id',
    validator('param', (value, c) => {
      const id = Number(value.id);
      if (Number.isNaN(id) || id <= 0) {
        return c.json({ error: 'Invalid numeric ID' }, 400);
      }
      return { id };
    }),
    (c) => {
      const { id } = c.req.valid('param');
      return c.json({ itemId: id });
    }
  );

  // Validate custom request headers for GET /api/protected
  app.get(
    '/api/protected',
    validator('header', (value, c) => {
      const apiKey = value['x-api-key'];
      if (!apiKey || apiKey !== 'secret-key-123') {
        return c.text('Unauthorized Header', 401);
      }
      return { apiKey };
    }),
    (c) => {
      const { apiKey } = c.req.valid('header');
      return c.json({ authorized: true, apiKey });
    }
  );

  return app;
}

export { validator };
test/contract.mjs
import assert from 'node:assert/strict';
import { createApp, validator } from '../src/index.mjs';
import { validator as rawValidator } from 'hono/validator';

async function runContractTests() {
  // 1. validator is exported as a middleware factory function from hono/validator
  assert.equal(typeof validator, 'function', 'validator must be exported as a function');
  assert.equal(typeof rawValidator, 'function', 'hono/validator must export validator function');
  const mw = validator('json', (value) => value);
  assert.equal(typeof mw, 'function', 'validator factory must return a middleware function');

  const app = createApp();

  // 2. validator validates and sanitizes JSON request body, providing validated data via c.req.valid('json')
  {
    const validRes = await app.request('http://localhost/api/posts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: '  Clean Code  ', count: 5 })
    });
    assert.equal(validRes.status, 200, 'Valid JSON request should return 200');
    const validData = await validRes.json();
    assert.deepEqual(validData, { success: true, data: { title: 'Clean Code', count: 5 } });

    const invalidRes = await app.request('http://localhost/api/posts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: '', count: -1 })
    });
    assert.equal(invalidRes.status, 400, 'Invalid JSON request should return 400');
    const invalidData = await invalidRes.json();
    assert.deepEqual(invalidData, { error: 'Invalid title or count' });
  }

  // 3. validator validates and transforms query parameters, providing validated data via c.req.valid('query')
  {
    const validRes = await app.request('http://localhost/api/search?limit=10&page=2');
    assert.equal(validRes.status, 200, 'Valid query should return 200');
    const validData = await validRes.json();
    assert.deepEqual(validData, { limit: 10, page: 2 });

    const invalidRes = await app.request('http://localhost/api/search?limit=abc&page=2');
    assert.equal(invalidRes.status, 400, 'Invalid query should return 400');
    const invalidData = await invalidRes.json();
    assert.deepEqual(invalidData, { error: 'Invalid query parameters' });
  }

  // 4. validator validates path parameters and short-circuits with custom error response when validation fails
  {
    const validRes = await app.request('http://localhost/api/items/123');
    assert.equal(validRes.status, 200, 'Valid param should return 200');
    const validData = await validRes.json();
    assert.deepEqual(validData, { itemId: 123 });

    const invalidRes = await app.request('http://localhost/api/items/invalid-id');
    assert.equal(invalidRes.status, 400, 'Invalid param should return 400');
    const invalidData = await invalidRes.json();
    assert.deepEqual(invalidData, { error: 'Invalid numeric ID' });
  }

  // 5. validator validates custom request headers, returning 401 when required header is missing or invalid
  {
    const validRes = await app.request('http://localhost/api/protected', {
      headers: { 'x-api-key': 'secret-key-123' }
    });
    assert.equal(validRes.status, 200, 'Valid header should return 200');
    const validData = await validRes.json();
    assert.deepEqual(validData, { authorized: true, apiKey: 'secret-key-123' });

    const invalidRes = await app.request('http://localhost/api/protected', {
      headers: { 'x-api-key': 'wrong-key' }
    });
    assert.equal(invalidRes.status, 401, 'Invalid header should return 401');
    const text = await invalidRes.text();
    assert.equal(text, 'Unauthorized Header');

    const missingRes = await app.request('http://localhost/api/protected');
    assert.equal(missingRes.status, 401, 'Missing header should return 401');
  }

  console.log('All contracts for hono/validator in pkg:npm/hono@4.13.7 passed.');
}

await runContractTests();

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

аноним