Skip to content

Add Hono auth example and lifecycle hooks#10

Merged
PatrickJS merged 5 commits into
mainfrom
codex/hono-auth-lifecycle
May 14, 2026
Merged

Add Hono auth example and lifecycle hooks#10
PatrickJS merged 5 commits into
mainfrom
codex/hono-auth-lifecycle

Conversation

@PatrickJS
Copy link
Copy Markdown
Owner

@PatrickJS PatrickJS commented May 14, 2026

Introduce a new examples/hono-auth demo (app, server, config, schemas, package.json, and README) demonstrating registerRestRoutes lifecycleHooks for bearer-token auth, permission checks, and write normalization. Add typings (JsonDbHonoRestLifecycleHooks + lifecycleHooks option) and implement lifecycle hook support in integrations/hono.js: run beforeRequest, beforeWrite (only for mutating methods), then global and resource hooks; hooks may short-circuit responses. Add tests covering hook order, write-only beforeWrite behavior, and short-circuiting. Update docs and example index references, and include examples/*/package.json in package files list.

Summary by CodeRabbit

  • New Features

    • Added lifecycleHooks (beforeRequest, beforeWrite) for REST route authorization and payload normalization.
    • Added CLI commands jsondb schema split and jsondb schema merge for schema manipulation.
    • Added hono-auth example demonstrating Bearer token authentication with REST route lifecycle hooks.
  • Documentation

    • Updated README with lifecycle hooks examples and auth demo reference.
    • Updated SPEC.md to clarify mixed-mode schema behavior and new CLI commands.
    • Added hono-auth example documentation with curl examples and token-to-permissions mapping.

Review Change Stack

Introduce a new examples/hono-auth demo (app, server, config, schemas, package.json, and README) demonstrating registerRestRoutes lifecycleHooks for bearer-token auth, permission checks, and write normalization. Add typings (JsonDbHonoRestLifecycleHooks + lifecycleHooks option) and implement lifecycle hook support in integrations/hono.js: run beforeRequest, beforeWrite (only for mutating methods), then global and resource hooks; hooks may short-circuit responses. Add tests covering hook order, write-only beforeWrite behavior, and short-circuiting. Update docs and example index references, and include examples/*/package.json in package files list.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 14, 2026

Warning

Rate limit exceeded

@PatrickJS has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 46 minutes and 38 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ebea93b8-40a3-4597-b40d-0174628ac87a

📥 Commits

Reviewing files that changed from the base of the PR and between 8041790 and 213e1aa.

📒 Files selected for processing (7)
  • README.md
  • SPEC.md
  • src/cli/commands/schema.js
  • src/cli/output.js
  • src/features/schema/project.js
  • test/cli/cli.test.js
  • test/doctor/doctor.test.js
📝 Walkthrough

Walkthrough

This PR adds lifecycle hooks (beforeRequest, beforeWrite) to Hono REST routing for request filtering and payload normalization, provides a complete runnable hono-auth example demonstrating bearer-token authentication, and introduces schema split and schema merge CLI commands with mixed-mode detection warnings for managing embedded vs. separate schema/seed files.

Changes

Hono REST Lifecycle Hooks and Auth Example

Layer / File(s) Summary
Type contracts and hook execution wiring
src/hono.d.ts, src/integrations/hono.js
New JsonDbHonoRestLifecycleHooks type with optional beforeRequest and beforeWrite properties added to JsonDbHonoRestRoutesOptions. runHonoHooks executes lifecycle hooks before global/resource hooks in deterministic order with short-circuit support via isWriteMethod helper.
Lifecycle hook integration tests
src/integrations/hono.test.js
Four new tests verify hook execution order (beforeRequest → beforeWrite → global → resource), body mutations (title trimming, updatedAt setting), selective invocation of beforeWrite only for write methods (PATCH not GET), and short-circuit behavior preventing further hooks and database writes.
Lifecycle hooks documentation in README
README.md
Updated REST route example shows lifecycleHooks with beforeRequest for session auth and beforeWrite for admin enforcement and payload normalization. Documents deterministic execution order, short-circuit behavior, and references runnable hono-auth example with bearer-token 401/403 rules.
Complete hono-auth example application
examples/hono-auth/src/app.mjs, examples/hono-auth/src/server.mjs, examples/hono-auth/db/users.schema.jsonc, examples/hono-auth/db/pages.schema.jsonc, examples/hono-auth/jsondb.config.mjs, examples/hono-auth/package.json, examples/hono-auth/example.json, examples/hono-auth/README.md
Runnable Hono app factory (createApp()) wires REST routes under /api with beforeRequest extracting bearer tokens to sessions (401 when missing) and beforeWrite enforcing admin-only writes (403 for non-admin) and normalizing payloads. Includes user/page schemas with seed, mirror-mode JSONDB config, npm metadata, example metadata, and comprehensive README with curl examples demonstrating permission enforcement and write hook normalization.
Example integration in test suite
test/examples/examples.test.js
Updates test suite to discover and validate hono-auth example, include it in rendered examples index, expect pages/users resources, and verify app.mjs contains lifecycle hook integration identifiers (registerRestRoutes, lifecycleHooks, beforeRequest, beforeWrite, bearer tokens).

CLI Schema Split/Merge Commands and Mixed-Mode Detection

Layer / File(s) Summary
Mixed-mode detection and diagnostic
src/features/schema/project.js
Adds warning diagnostic in loadProjectSchema when a resource has both embedded seed in schema and separate data fixture, using mixedModeSchemaSeedDiagnostic helper to generate structured warning with resource paths and split guidance.
Schema split/merge CLI command handlers
src/cli/commands/schema.js
runSchemaSplit validates resource, rejects in-place rewriting of .schema.mjs without --schema-out, writes schema JSON always and seed JSON conditionally to computed paths with logging. runSchemaMerge generates combined schema source with seed, prints if --out omitted, otherwise writes to specified path. Updates schemaSourceForResource to conditionally include seed when options.includeSeed is true; adds outputPath, defaultSchemaOutFile, defaultSeedOutFile helpers.
CLI help and output documentation
src/cli/output.js
Updates printHelp() and printSchemaHelp() to document new schema split (with --schema-out and --seed-out flags) and schema merge (with --out flag) subcommands with usage examples and detailed options.
CLI schema command testing
test/cli/cli.test.js
Adds test for mixed-mode warning emission, schema split success case extracting embedded seed to separate fixture, schema split rejection for .schema.mjs without --schema-out, and schema merge test verifying merged output preserves seed and field typing.
Specification documentation and package distribution
SPEC.md, package.json
Clarifies mixed-mode behavior (embedded seed ignored when separate data fixture present) with CLI warning/split guidance. Documents new jsondb schema split and jsondb schema merge commands. Updates package.json files list to include examples/*/package.json in published distribution.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant beforeRequest as beforeRequest hook
  participant beforeWrite as beforeWrite hook
  participant globalHook as Global hook
  participant resourceHook as Resource hook
  participant Handler as Method handler
  
  Client->>beforeRequest: Execute for all methods
  alt short-circuits
    beforeRequest-->>Client: Return response, stop
  else continues
    alt Write method (create/patch/put/delete)
      beforeRequest->>beforeWrite: Execute only for writes
      alt short-circuits
        beforeWrite-->>Client: Return response, stop
      else continues
        beforeWrite->>globalHook: Continue chain
      end
    else Read method
      beforeRequest->>globalHook: Skip beforeWrite
    end
    globalHook->>resourceHook: Execute if defined
    resourceHook->>Handler: Execute core handler
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • PatrickJS/jsondb#7: Both PRs modify CLI schema/help plumbing in src/cli/commands/schema.js and src/cli/output.js, with the main PR's schema split/merge documentation building on prior help/UI infrastructure changes.
  • PatrickJS/jsondb#9: Both PRs extend Hono REST routing integration by modifying hook execution logic and TypeScript typings in src/integrations/hono.js and src/hono.d.ts for request filtering and short-circuit behavior.

Poem

🐰 Hooks dance in the request stream,
Before and after—a developer's dream!
Split and merge the schema's way,
Auth examples show the play.
Now REST routes own their fate,
While CLI tools separate! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly summarizes the main changes: adding a new Hono auth example and implementing lifecycle hooks for the REST API routing.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/hono-auth-lifecycle

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Introduce two new schema commands: `jsondb schema split` to extract embedded `seed` into a separate data fixture (with --schema-out and --seed-out options) and `jsondb schema merge` to produce a schema source that includes seed from an existing data fixture (with --out). Add mixed-mode diagnostics: warn when a schema file contains `seed` but a separate data fixture exists. Update CLI help text, project loader, and schema utilities (output path helpers and schema export option includeSeed). Add tests for validate warnings, split, merge, and executable-schema restrictions; update SPEC to document behavior and suggested workflow.
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
test/examples/examples.test.js (1)

77-78: ⚡ Quick win

Avoid asserting exact demo bearer token literals in this integration test.

These two checks make the test fail on doc-string changes without affecting lifecycle-hook behavior; keep assertions focused on integration identifiers.

Suggested diff
 test('hono auth example shows lifecycle hook integration code', async () => {
   const source = await readFile(path.resolve('examples/hono-auth/src/app.mjs'), 'utf8');

   assert.match(source, /registerRestRoutes/);
   assert.match(source, /lifecycleHooks/);
   assert.match(source, /beforeRequest/);
   assert.match(source, /beforeWrite/);
-  assert.match(source, /Bearer admin-token/);
-  assert.match(source, /Bearer user-token/);
+  assert.match(source, /Authorization/);
 });
As per coding guidelines, "Tests should create their own `db/` fixtures and avoid depending on generated repo state."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/examples/examples.test.js` around lines 77 - 78, Replace the brittle
exact-token assertions in examples.test.js: instead of assert.match(source,
/Bearer admin-token/) and assert.match(source, /Bearer user-token/), assert more
robust integration identifiers (e.g., use assert.match(source,
/Bearer\s+\w+-token/) or assert.match(source, /Bearer.*(admin|user)/)) so the
test no longer depends on literal demo tokens; also ensure the test creates its
own db fixtures rather than relying on generated repo state (update any setup in
the same test file to build required db/ fixtures).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/cli/cli.test.js`:
- Around line 124-211: Add a new test in test/cli/cli.test.js that exercises the
CLI schema split/merge using relative --schema-out and --seed-out together with
--cwd to ensure paths are resolved relative to the project root created by
makeProject(); specifically invoke execFileAsync(process.execPath,
[path.resolve('src/cli.js'), 'schema', 'split' or 'merge', 'users', '--cwd',
cwd, '--schema-out', './db/custom.schema.json' (or '--seed-out',
'./db/custom.json')]) and then use readFile(path.join(cwd,
'db/custom.schema.json')) or readFile(path.join(cwd, 'db/custom.json')) to
assert the files are actually written under cwd (and assert stdout contains
Generated db/...); reuse helpers from the file (makeProject, writeFixture,
readFile, execFileAsync) and mirror the existing test patterns (assert.match,
assert.deepEqual) for verification.

---

Nitpick comments:
In `@test/examples/examples.test.js`:
- Around line 77-78: Replace the brittle exact-token assertions in
examples.test.js: instead of assert.match(source, /Bearer admin-token/) and
assert.match(source, /Bearer user-token/), assert more robust integration
identifiers (e.g., use assert.match(source, /Bearer\s+\w+-token/) or
assert.match(source, /Bearer.*(admin|user)/)) so the test no longer depends on
literal demo tokens; also ensure the test creates its own db fixtures rather
than relying on generated repo state (update any setup in the same test file to
build required db/ fixtures).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3b026c9a-696a-42c0-93e5-6d7cce73ace0

📥 Commits

Reviewing files that changed from the base of the PR and between 0ba2f87 and 8041790.

📒 Files selected for processing (19)
  • README.md
  • SPEC.md
  • examples/hono-auth/README.md
  • examples/hono-auth/db/pages.schema.jsonc
  • examples/hono-auth/db/users.schema.jsonc
  • examples/hono-auth/example.json
  • examples/hono-auth/jsondb.config.mjs
  • examples/hono-auth/package.json
  • examples/hono-auth/src/app.mjs
  • examples/hono-auth/src/server.mjs
  • package.json
  • src/cli/commands/schema.js
  • src/cli/output.js
  • src/features/schema/project.js
  • src/hono.d.ts
  • src/integrations/hono.js
  • src/integrations/hono.test.js
  • test/cli/cli.test.js
  • test/examples/examples.test.js

Comment thread test/cli/cli.test.js Outdated
PatrickJS added 3 commits May 14, 2026 15:39
Replace the CLI schema subcommands: `split` -> `unbundle` and `merge` -> `bundle`. Updated SPEC examples, CLI command routing, help/output text, diagnostic hints, and related error codes/messages to reflect the new names. Adjusted tests and expected output filenames to match the new `unbundle`/`bundle` behavior and updated error identifiers for executable schema source checks.
Add safer write semantics and new flags for schema bundle/unbundle. Introduces --force and --empty-seed flags, prevents accidental overwrites by comparing semantic JSON content, and rejects writing bundle outputs inside the active fixture directory unless --force is passed. Warns when unbundling rewrites .schema.jsonc (comments may be lost). Updates CLI help, default bundle example paths (artifacts/...), and adds helper functions (writeOutput, contentMatches, stableJsonStringify, isEmptySeed, isInsidePath, hasFlag). Tests and docs (README, SPEC) updated to cover the new behaviors.
Adds a test that ensures `schema unbundle` honors the provided `--cwd` when writing `--schema-out` and `--seed-out` paths. The test creates a project fixture with a users schema containing an inline seed, runs the CLI with relative output paths and `--cwd`, then verifies stdout messages, that the generated schema no longer contains the seed, and that the seed file was written with the expected data.
@PatrickJS PatrickJS merged commit 353c861 into main May 14, 2026
4 checks passed
@PatrickJS PatrickJS deleted the codex/hono-auth-lifecycle branch May 14, 2026 22:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant