CodeSampleX

示例

hono 4.13.7: logger

已验证示例 — npm hono 4.13.7: logger. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: createAppWithCustomLogger and createAppWithDefaultLogger configure…

sha256:de0ed8eb77195a99234eb7befb8002444d8175fb56e9aadd235be6c58a543e95

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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 logger in pkg:npm/hono@4.13.7
包
符号
  • logger
创建时间
2026-09-06T04:18:54Z

契约

  1. createAppWithCustomLogger and createAppWithDefaultLogger configure Hono applications with logger middleware
  2. logger export is a callable function returning a Hono middleware handler function
  3. logger middleware captures incoming HTTP request method and path using the incoming prefix
  4. logger middleware captures outgoing HTTP response status code and elapsed time using the outgoing prefix
  5. logger middleware invokes custom print callback on incoming and outgoing request lifecycle events
  6. logger middleware records accurate status codes for successful, created, not found, and internal server error responses
  7. logger middleware with default print handler completes the request-response lifecycle without errors

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 logger 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:
  - logger

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:4fffeee674307a3d1a736a05f01bba6b2c275f9ad1e1062e7d555465cdcf03cf","contract":["createAppWithCustomLogger and createAppWithDefaultLogger configure Hono applications with logger middleware","logger export is a callable function returning a Hono middleware handler function","logger middleware captures incoming HTTP request method and path using the incoming prefix","logger middleware captures outgoing HTTP response status code and elapsed time using the outgoing prefix","logger middleware invokes custom print callback on incoming and outgoing request lifecycle events","logger middleware records accurate status codes for successful, created, not found, and internal server error responses","logger middleware with default print handler completes the request-response lifecycle without errors"],"goal":"verify logger in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["logger"]},"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":["logger"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-logger",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-logger",
      "version": "1.0.0",
      "license": "MIT-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-logger",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for logger in hono@4.13.7",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify logger in pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "logger"
  ]
}
src/index.js
'use strict';

const { Hono } = require('hono');
const { logger } = require('hono/logger');

/**
 * Creates a Hono app configured with a custom logger callback.
 *
 * @param {Function} printFn - Custom logging function (message: string) => void
 * @returns {Hono}
 */
function createAppWithCustomLogger(printFn) {
  const app = new Hono();

  app.use('*', logger(printFn));

  app.get('/api/hello', (c) => {
    return c.json({ message: 'hello world' });
  });

  app.post('/api/items', async (c) => {
    const body = await c.req.json().catch(() => ({}));
    return c.json({ success: true, item: body }, 201);
  });

  app.get('/api/error', (c) => {
    return c.text('internal error', 500);
  });

  return app;
}

/**
 * Creates a Hono app configured with default logger (console.log).
 *
 * @returns {Hono}
 */
function createAppWithDefaultLogger() {
  const app = new Hono();
  app.use('*', logger());

  app.get('/api/ping', (c) => {
    return c.text('pong');
  });

  return app;
}

module.exports = {
  createAppWithCustomLogger,
  createAppWithDefaultLogger,
  Hono,
  logger
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  createAppWithCustomLogger,
  createAppWithDefaultLogger,
  Hono,
  logger
} = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof createAppWithCustomLogger, 'function', 'createAppWithCustomLogger must be a function');
  assert.equal(typeof createAppWithDefaultLogger, 'function', 'createAppWithDefaultLogger must be a function');
  assert.equal(typeof Hono, 'function', 'Hono export must be a function');
  assert.equal(typeof logger, 'function', 'logger export must be a function');

  // 2. logger() returns a middleware handler function
  const middleware = logger();
  assert.equal(typeof middleware, 'function', 'logger() must return a middleware handler function');

  // 3. Custom logger records incoming and outgoing logs for GET /api/hello (200 OK)
  const logs = [];
  const customPrint = (str) => logs.push(str);
  const app = createAppWithCustomLogger(customPrint);

  const resHello = await app.fetch(new Request('http://localhost/api/hello'));
  assert.equal(resHello.status, 200, 'GET /api/hello should return 200');
  const bodyHello = await resHello.json();
  assert.deepEqual(bodyHello, { message: 'hello world' });

  assert.equal(logs.length, 2, 'Two log messages should be recorded: incoming and outgoing');
  // Incoming log format: "<-- GET /api/hello"
  assert.ok(logs[0].startsWith('<--'), 'First message should be incoming prefix <--');
  assert.ok(logs[0].includes('GET'), 'Incoming log should include method GET');
  assert.ok(logs[0].includes('/api/hello'), 'Incoming log should include pathname /api/hello');

  // Outgoing log format: "--> GET /api/hello 200 <time>"
  assert.ok(logs[1].startsWith('-->'), 'Second message should be outgoing prefix -->');
  assert.ok(logs[1].includes('GET'), 'Outgoing log should include method GET');
  assert.ok(logs[1].includes('/api/hello'), 'Outgoing log should include pathname /api/hello');
  assert.ok(logs[1].includes('200'), 'Outgoing log should include status 200');

  // 4. Custom logger records POST /api/items (201 Created)
  logs.length = 0;
  const resPost = await app.fetch(
    new Request('http://localhost/api/items', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ item: 'notebook' })
    })
  );
  assert.equal(resPost.status, 201, 'POST /api/items should return 201');
  assert.equal(logs.length, 2, 'Two log messages should be recorded for POST');
  assert.ok(logs[0].includes('POST'), 'Incoming log should include method POST');
  assert.ok(logs[0].includes('/api/items'), 'Incoming log should include pathname /api/items');
  assert.ok(logs[1].includes('POST'), 'Outgoing log should include method POST');
  assert.ok(logs[1].includes('201'), 'Outgoing log should include status 201');

  // 5. Custom logger records 500 error response
  logs.length = 0;
  const resErr = await app.fetch(new Request('http://localhost/api/error'));
  assert.equal(resErr.status, 500, 'GET /api/error should return 500');
  assert.equal(logs.length, 2, 'Two log messages should be recorded for 500');
  assert.ok(logs[1].includes('500'), 'Outgoing log should include status 500');

  // 6. Custom logger records 404 not found response
  logs.length = 0;
  const resNotFound = await app.fetch(new Request('http://localhost/api/nonexistent'));
  assert.equal(resNotFound.status, 404, 'Unknown route should return 404');
  assert.equal(logs.length, 2, 'Two log messages should be recorded for 404');
  assert.ok(logs[1].includes('404'), 'Outgoing log should include status 404');

  // 7. Default logger works without errors
  const defaultApp = createAppWithDefaultLogger();
  const resPing = await defaultApp.fetch(new Request('http://localhost/api/ping'));
  assert.equal(resPing.status, 200, 'GET /api/ping should return 200 with default logger');
  const textPing = await resPing.text();
  assert.equal(textPing, 'pong');
}

testAll().then(
  () => {
    console.log('Contract assertions passed successfully');
    process.exit(0);
  },
  (err) => {
    console.error('Contract failed:', err);
    process.exit(1);
  }
);

原始种子者

匿名