# hazo_api Change Log

## [2.12.0] — 2026-11-21

### Added
- **`encodeCursor`/`decodeCursor` (`src/lib/cursor.ts`)** — a shared opaque
  keyset-pagination cursor codec. Several consuming apps had each written
  their own identical "base64(JSON.stringify(payload))" cursor envelope with
  their own thrown error on a malformed cursor. `decodeCursor` takes the
  caller's own `validate(parsed): T` and `onInvalid(cursor): never`, so each
  consumer keeps its own payload shape and its own distinct error class
  (e.g. `instanceof SomeAppCursorError` checks at call sites are unaffected)
  while no longer hand-rolling the base64/JSON mechanics.
- **`createRateLimitService` now accepts a hazo_connect adapter directly.**
  `getHazoConnect()` may now resolve to any object exposing `.raw(sql,
  params)` + `.getConfig()` (e.g. hazo_connect's `PgAdapter`,
  `BetterSqlite3Adapter`) — detected via duck-typing and used as-is, with
  dialect inferred from `getConfig().type`. Previously every consumer had to
  hand-write a `{dialect, query(sql, params) => {rows}}` shim themselves
  (memebox's own `telegram/link-token` route is a real example this change
  removes). The legacy `{dialect, query}` shape is still accepted unchanged
  — fully backwards compatible, not a breaking change.

## [2.11.0] — 2026-11-13

### Added
- **`hazo_api/client-core` entry (`src/index.client-core.ts`)** — a second,
  leaner client-safe export containing only `apiGet`/`apiPost`/`apiPatch`/
  `apiRequest`/`ApiError`/`configureApiClient`/`getApiClientConfig`,
  `swaggerUiHtml`, and shared types. Fixes a real consumer break: because
  `tsup.config.ts` builds with `splitting: false`, `dist/index.client.js` is
  a single file, and `index.client.ts` re-exports `ApiKeyManager`/
  `ApiPlayground` (from `src/components/`) alongside the pure fetch helpers.
  Those components statically `import … from 'hazo_ui'`, so importing
  *anything* from `hazo_api/client` — even just `apiGet` — forced
  resolution of that `hazo_ui` import too. A consumer with no `hazo_ui`
  installed (memebox, ticket 06, which only wants `apiGet`) got
  `Cannot find package 'hazo_ui'` on a plain `import('hazo_api/client')`,
  confirmed with a bare `node -e` repro before this fix. `hazo_api/client`
  is unchanged and still requires `hazo_ui` for `ApiKeyManager`/
  `ApiPlayground`; `hazo_api/client-core` is the new entry for consumers
  who only need the HTTP envelope client.
- **`hazo_ui` marked `optional: true` in `peerDependenciesMeta`** — it was
  declared as a required peer even though it's now only actually needed by
  `hazo_api/client`'s two UI components, not by `hazo_api/client-core` or
  any server-side export.

## [2.10.1] — 2026-11-09

### Fixed
- **`ApiKeyManager` CSRF bypass** — `envelopeFetch` (used by all `ApiKeyManager`
  operations) was a bare `fetch()` wrapper that never called `getApiClientConfig()`,
  so `configureApiClient({ getExtraHeaders })` had no effect on it. Mutating calls
  (create / revoke) were sent without the CSRF header, causing 403 `Forbidden` on
  any server that wraps the route with `withCsrf`. Now reads `getApiClientConfig()`
  and merges extra headers on POST/PUT/PATCH/DELETE, same as `apiRequest`.

## [2.9.0] — unreleased

### Added
- **`ApiPlayground` component (`src/components/api_playground.tsx`)** — reusable, client-only
  interactive playground for trying a render API: JSON, "Paste CSV", and Table input modes
  (CSV/table rows are converted to the sankey-shaped JSON body via `csvToJson`/`rowsToJson`),
  a Render button that `POST`s to a caller-supplied `endpoint` and renders the returned image with
  response metadata (status, `X-RateLimit-Remaining`, blob size), and blob-URL cleanup on
  unmount/re-render. Exported from `hazo_api/client` alongside its prop types.
- **Table tab wired to the real `EditableDataTable` (hazo_ui ^6.17.0, Plan 1).** `ApiPlayground`'s
  public `tableComponent` prop keeps a deliberately simple, hazo_ui-agnostic contract
  (`{ columns: {key,label,editable}[], rows, onRowsChange }`) rather than taking on
  `EditableDataTable`'s richer prop shape directly; a new internal `PlaygroundTableAdapter`
  bridges the two — translating `onChange`→`onRowsChange` and supplying `getRowKey` and
  `createRow` (per-column defaults: `0` for `value`, `''` otherwise) — and is the prop's default,
  so the table tab works out of the box with no fallback/stub text. A consumer may still pass a
  different `tableComponent` to swap in its own editor without depending on hazo_ui's shape.
  Since playground rows are plain `{source,target,value}` records with no natural unique id,
  `createRow` (and the seed `tableRows` state) stamp a synthetic `_rowId` (`crypto.randomUUID()`)
  at creation time, and `getRowKey` reads that id — not the array index — because
  `EditableDataTable`'s drag-reorder is unconditional and uses `getRowKey`'s return value as both
  the dnd-kit sortable id and the row component's React `key`; a position-based key would let a
  drag leave an in-progress, uncommitted edit behind at the old index instead of carrying it with
  the row (same bug class fixed in hazo_canvas's graph forms — see `hazo_canvas/src/graph/forms/
  row-key.ts` — one layer up).
- **`peerDependencies.hazo_ui` raised to `^6.17.0`** (was `^6.14.0`) — the table tab's top-level,
  unconditional static import of `EditableDataTable` only exists from hazo_ui 6.17.0 onward; the
  old floor advertised support for 6.14.0–6.16.x consumers who would get a broken import the
  moment the table tab rendered.

## [2.8.0] — unreleased

### Added
- **`createHazoConnectRateLimitService` (`src/lib/rate_limit_service_hazo_connect.ts`)** —
  PostgREST-compatible alternative to `createRateLimitService` for consumers that only have a
  `HazoConnectAdapter` (REST-only, no raw Postgres connection) at runtime. Same token-bucket
  semantics and `RateLimitService` interface, same `hazo_api_rate_limits`-shaped table
  (`bucket_key` PK, `tokens`/`capacity`/`refill_rate`/`updated_at`), different mechanism: a prior
  read (`createCrudService(...).findOneBy`) + an optimistic-concurrency conditional `PATCH`
  (`.query().where('bucket_key', 'eq', ...).where('updated_at', 'eq', <observed>).execute('PATCH',
  ...)`, retried up to 3 times on a CAS miss, fail-closed after that) instead of the raw-SQL
  version's single atomic `UPDATE ... RETURNING`. Row creation uses
  `.onConflict(['bucket_key']).doNothing()` (PostgREST `ignore-duplicates`), mirroring `INSERT ...
  ON CONFLICT DO NOTHING` without depending on error-message sniffing. Deliberately does **not**
  use `HazoConnectAdapter.claimRows` — `PostgrestAdapter.claimRows` hardcodes the `id` column for
  both its candidate `SELECT` and its claim `PATCH` (confirmed in
  `hazo_connect/src/lib/adapters/postgrest-adapter.ts`), and this table has no `id` column, only
  `bucket_key`; `idColumn` is documented as unhonored by `PgAdapter`/`PostgrestAdapter`. Exported
  from the main barrel alongside `createRateLimitService`.
- **Test suite** — `src/lib/__tests__/rate_limit_service_hazo_connect.test.ts`: fresh-bucket
  insert+deduct, rapid repeated consumes, bucket exhaustion + `retry_after_sec`, custom `cost`, a
  denied request still persisting its time-based refill (not a frozen pre-denial value), a CAS-miss
  retry (mocked PATCH returns `[]` once then succeeds), and fail-closed behavior after exhausting
  retries under sustained contention.
- **Adopted the canonical `hazo_core/i18n` bridge (first i18n adoption for this package).** New
  `src/locales/en.json` — a flat, literal-dotted-key catalog (`{{var}}` mustache interpolation) —
  and `src/lib/i18n.ts` exporting `t = createPackageT('hazo_api', en)`, re-exported from
  `hazo_api/client`. hazo_api ships no server-rendered UI strings; the only consumer is the
  client-only `<ApiKeyManager>` component, whose ~30 hardcoded strings (heading, table headers,
  loading/empty states, status badges, the revoke confirmation dialog, the create-key dialog's
  fields/placeholders, and the reveal-key dialog) were all extracted to `t()` calls.
- Added `hazo_i18n` as an optional peer (`^0.5.0`) — matches the workspace-wide `hazo_core/i18n`
  adoption convention: `createPackageT` auto-registers this package's catalog into `hazo_i18n`'s
  cross-package registry as a fire-and-forget side effect if `hazo_i18n` is installed, but `t()`
  itself never depends on it and always reads the bundled English fallback catalog.
- Bumped `hazo_core` peer to `^2.4.0` (the release that ships `hazo_core/i18n`).
- Added an `i18n` scenario group (`hazo_api_i18n`) to the test-app's `/autotest` page
  (`hazo_api_i18n_scenarios.ts`) covering catalog load, sampled-key resolution, `{{label}}`
  interpolation (including the missing-key fallback), and a catalog-coverage assertion.

## [2.7.0] — unreleased

### Added
- **Client-safe envelope fetch wrapper (`src/lib/api_client.ts`)** — `apiGet`, `apiPost`, `apiPatch`
  (built on a new `apiRequest`), and `ApiError`, exported from `hazo_api/client`. Parses an
  `EnvelopeResponse<T>` response body and either resolves with `data` or throws `ApiError` (`code`,
  `message`, `status`, `details`) when `ok: false`. Promotes the hand-rolled fetch wrapper pattern
  every `hazo_api`-consuming app was rewriting for itself (e.g. stockguru's
  `apps/web/src/lib/api-client.ts`) into the package.
- **`configureApiClient({ getExtraHeaders })` / `getApiClientConfig()`** — module-level config (same
  get/set shape as `utils/logger.ts`'s `get_logger`/`set_logger`) that lets a consuming app inject
  headers (e.g. a CSRF token) onto every non-GET/HEAD request made through `apiRequest`/`apiPost`/
  `apiPatch`. `getExtraHeaders` may return synchronously or a `Promise<Record<string,string>>`.
  hazo_api does NOT depend on `hazo_secure` or any other CSRF package — this hook is the decoupling
  point; the caller supplies its own header logic. Caller-supplied `init.headers` on an individual
  call still wins over the hook on a key conflict.
- **Test suite** — `src/__tests__/api_client.test.ts` (12 cases): success path for `apiGet`/
  `apiRequest`, fail-envelope → `ApiError` (with and without `details`), `apiPost`/`apiPatch` method
  and body/content-type handling, and the `getExtraHeaders` hook (sync + async, applied only to
  non-GET/HEAD, caller headers override, resets to no-op on `configureApiClient(undefined)`).
- **Test-app demo** — new `/api_client` page exercising `apiGet` against `/api/v1/demo/ping`,
  `apiPost` against `/api/v1/demo/echo` (valid body, and an invalid body to show the thrown
  `ApiError`), and `apiPatch` against the existing `/api/v1/actions/[id]` route with
  `configureApiClient({ getExtraHeaders })` injecting the `If-Match` header it requires — proves the
  hook reaches the outgoing request with both a matching and a stale etag.

## [2.6.0] — unreleased

### Added
- **`PERMISSION_DENIED` error code (FR-017)** — legacy back-compat alias for `FORBIDDEN`. Added to
  both `ErrorCodes` (status 403) and `ErrorCodeHazoMap` (`HazoAuthError`, `forbidden: true`), so
  `fail('PERMISSION_DENIED', …)` now resolves to HTTP 403 with full `HazoAuthError` enrichment
  instead of falling through to the unknown-code 500 default. `FORBIDDEN` remains the documented
  canonical code.
- **`PermissionFailureDetails` type** — new `src/types/permission_failure.ts`, exported from both
  `src/index.ts` and `src/index.client.ts` (type-only, client-safe). Documents the canonical shape
  of `error.details` on a `FORBIDDEN`/`PERMISSION_DENIED` envelope: `{ missing_permissions,
  permission_descriptions?, scope_id? }`.

## [2.5.1] — 2026-06-22

### Changed
- `fail()` now accepts `ErrorCode | (string & {})` — package-specific error codes (e.g.
  `HAZO_CANVAS_NOT_FOUND`) pass through without a cast and are preserved verbatim in the
  response body. Known `ErrorCode` values retain full autocomplete. Unknown codes fall back to
  `INTERNAL_ERROR` for HazoError enrichment only; the original code is always in the body.

## 2.5.0 (2026-06-14)

### Added
- **`createVerifyOnlyService(verify)`** — wraps a consumer-owned `ApiKeyValidator` callback as an `ApiKeyService` for backends whose keys live outside hazo_api's `hazo_api_keys` table (env vars, a JSON file, a foreign table). `validate()` delegates to the callback; the five management methods (`issue`/`list`/`update`/`revoke`/`enable`) reject with a `HazoConfigError` carrying code `HAZO_API_VERIFY_ONLY_NO_MANAGEMENT`. Exported from the server barrel (`src/index.ts`).
- **Test suite** — `src/__tests__/verify_only_service.test.ts` (7 cases): validate hit/miss delegation plus each management method rejecting with the expected code.
- **Test-app demo** — `/verify_auth` interactive page plus `protected_verify` (inline `verify`) and `protected_verify_service` (`createVerifyOnlyService` wrapper) demo routes, backed by an in-memory `external_key_store.ts` that represents a consumer-owned backend (no hazo_api table involved).

## 2.4.0 (2026-06-13)

### Added
- **`description` field on API key create** — `CreateBody` in `createApiKeyRoutes` now accepts an optional `description: string` alongside `label` and `scopes`. The service already stored it; the route now exposes it.
- **`update` handler in `createApiKeyRoutes`** — returns a new `update(req, ctx)` function that handles PATCH requests. Accepts `{ label?, description? }` body, returns the updated `ApiKey` in the standard `ok()` envelope, maps `HAZO_API_KEY_NOT_FOUND` → 404 `NOT_FOUND` envelope.
- **Regression test suite** — 16 new jest cases across `auth_routes`, `auth_service` (SQLite-dialect block), `zod_helpers` (z.record two-arg form), and `openapi_generator` (JSON Schema content assertions). 2 new autotest scenarios in the browser harness (description round-trip + PATCH key update).

### Fixed
- `WithApiKeyOptions` type: `service` is now correctly typed as optional (`service?`) alongside the `verify` alternative. Both were already functional at runtime; the type now matches.

## 2.3.1 (2026-06-06)

### Fixed (PostgREST api-key service — surfaced by seo_monitor)
- `createPostgrestApiKeyService().issue()` no longer always sends a `description`
  field in the PostgREST insert body. `description` is optional and absent from the
  base `hazo_api_keys` schema (only migration `003_add_description.sql` adds it), so
  unconditionally posting `description: null` made PostgREST reject every insert with
  `PGRST204: Could not find the 'description' column of 'hazo_api_keys'`. It is now
  included only when the caller supplies a non-null `description`.
- `db_setup_postgres.sql` now declares the optional `description TEXT` column, matching
  `migrations/003_add_description.sql` (the consolidated setup script had drifted).
- `src/index.ts` now actually re-exports `createPostgrestApiKeyService` /
  `CreatePostgrestApiKeyServiceOptions` from source (the export had shipped in the 2.3.0
  build artifact but was never committed to the barrel).

## 2.1.1 (2026-05-30)

### Fixed (bundling defect surfaced by seo_monitor)
- Removed `import 'server-only';` from the public barrel (`src/index.ts`) and from 11 lib files re-exported through it. Next 15's "Collecting page data" build phase evaluates `route.ts` files without setting the `react-server` resolution condition, so the marker throws and breaks `next build` for every legitimate server-side consumer. Documented the deliberate omission in the barrel. Handlers still use Node-only APIs (`fs`, `crypto`, `node:async_hooks`), so a real Client Component import still fails at runtime — we just lose fail-fast at module load. Same root cause as hazo_logs@2.0.2 and the gotimer hazo_ui "use client" defect.

## 2.1.0 (2026-05-29)

### Added
- **`hazo_core` required peer dep** — graduated from optional. All other Wave 2 packages now resolve the same hazo_core for shared error classes, correlation IDs, and utilities.
- `src/utils/logger.ts` — `get_logger()` / `set_logger()` pattern. Default delegates to `createLogger('hazo_api')` from hazo_core; consumers (and tests) can override.
- `src/utils/uuid.ts` — `generateUUID()` backed by `generateRequestId()` from hazo_core (strips `req_` prefix). All `node:crypto.randomUUID()` call sites in `src/` now route through this helper.

### Changed
- All dynamic peer-dep loads (`hazo_auth/server`, `hazo_debug/server`, `hazo_logs/server`, `hazo_config/server`) now use `optional_import()` from hazo_core. Removes the 5 `audit:duplicates` violations and gives a single canonical pattern for optional peer wiring.
- Server-side bare `throw new Error(...)` sites replaced with `HazoError` subclasses:
  - `auth_middleware.ts` missing-`hazo_auth` setup error → `HazoConfigError` (`HAZO_API_CONFIG_MISSING_HAZO_AUTH`).
  - `route_registry.ts` duplicate-route error → `HazoConfigError` (`HAZO_API_CONFIG_DUPLICATE_ROUTE`).
  - `auth_service.ts` revoke-not-found → `HazoNotFoundError` (`HAZO_API_KEY_NOT_FOUND`).
- `engines.node` field removed from `package.json` (workspace standard — runtime requirements are documented in README, not enforced at install).
- `request_context.ts` now uses `get_logger()` for the per-request logger; the inline JSON-console fallback is gone (hazo_core's logger handles both the hazo_logs case and the bare-stderr case internally).
- `db_setup_postgres.sql` and `db_setup_sqlite.sql` are now full idempotent schemas (previously stubs pointing at `migrations/`). PostgreSQL file ends with `NOTIFY pgrst, 'reload schema';`.

### Internal
- `design/feature_requests/INDEX.md` added (S16 audit backfill — moves hazo_api from WARN→PASS).

## 2.0.0 (2026-05-28)

### Added
- **hazo_core integration (D-013)**: `withRequestContext` now delegates to `hazo_core`'s `withContext` / `getContext` — one AsyncLocalStorage instance shared across the entire suite. `request_id` and `correlationId` are the same value.
- **HazoError adoption**: `fail(code, message)` now creates the matching HazoError subclass (VALIDATION_FAILED → HazoValidationError, etc.) and includes its `toJSON()` in the response body, attaching `correlationId`, `pkg`, `retryable`, `env`, and `httpStatus` automatically. Gracefully falls back to plain error object if `hazo_core` is absent.
- **`env` in response meta (D-020 hook 4)**: `ok()` and `fail()` now include `env` in the `meta` block (`HAZO_ENV ?? NODE_ENV ?? 'development'`), visible in browser dev-tools network panel.
- **`MemoryRateLimitStore` consolidated (D-014)**: Rate-limiting store moved from `hazo_secure` to `hazo_api/rate_limit`. `hazo_secure` re-exports for one major version.
- `hazo_core` added as optional peer dependency (`^1.0.0`).

### Breaking changes
- `withRequestContext` now requires `hazo_core` to be installed for full correlation-ID sharing. Without it, falls back to local ALS (backward compatible for existing consumers with no hazo_core).
- Response `error` body shape gains new fields (`pkg`, `retryable`, `correlationId`, `env`) when hazo_core is present. Consumers parsing the error field strictly may need to update their schemas.

## 1.1.1 (2026-05-17)

### Added
- `ApiKeyManager` `scopes_field` prop — pluggable scopes input. Modes: `text` (default, comma-separated input), `catalog` (checkbox list backed by a fixed `ScopeOption[]`), `hidden` (server fills scopes in), and `custom` (bring-your-own renderer receiving `{ selected, onChange }`).
- `ApiKeyManager` `user_id` prop — consuming app supplies the user UUID (typically from session). End users no longer see a "User ID" text input in the create dialog.
- New exported types from `hazo_api/client`: `ScopeOption`, `ScopesFieldConfig`, `ScopesFieldCustomContext`.
- `DialogDescription` on the create / reveal dialogs (Radix a11y).
- test-app `/keys` page now demos all three scopes-field modes via a mode switcher.

### Changed
- Create dialog spacing tightened and labels normalized.

## 1.1.0 (2026-05-17)

### Added
- `createApiKeyService({ getHazoConnect })` — issue / list / revoke / validate API keys backed by the `hazo_api_keys` table.
- `withApiKey({ service, require_scopes, bind_user })` — middleware replacing the v1.0.0 stub. Parses `Authorization: Bearer …` then `X-Api-Key`.
- `createApiKeyRoutes({ service })` — list/create/revoke route-handler factories.
- `createRateLimitService({ getHazoConnect })` + `withRateLimit({ service, bucket_key, limit, window_sec })` — DB-backed token-bucket rate limiter with atomic recompute. Fail-open on adapter errors.
- `okStream(iterable, { format: 'sse' | 'ndjson' })` — streaming response envelopes.
- `ApiKeyManager` React component (client entry) — full issue/list/revoke UI built on `hazo_ui` primitives.
- `RATE_LIMITED: 429` error code.
- `fail()` / `ok()` honor `meta.headers` to set arbitrary Response headers; stripped from the body before serialization.
- `[auth]` and `[rate_limit]` INI sections.
- Two SQL migrations under `migrations/` (PostgreSQL active, SQLite documented).
- Optional `hazo_auth` peer for `withApiKey({ bind_user: true })` user-active validation.
- test-app sidebar pages: `/keys`, `/streaming`, `/rate_limit`, `/auth`.

### Changed
- `react`, `react-dom` promoted from optional → required peer deps.
- `hazo_connect` and `hazo_ui` are now required peer deps.
- `hazo_auth` added as optional peer.

### Removed
- v1.0.0 design-only `withApiKey` stub (replaced by real impl).

## 1.0.1 (2026-05-16)

### Added
- `withRequestContext` now calls `pushRequestToDebug` on both success and error
  paths, gated by `[debug] enabled` in the INI. Forward-compat with future
  hazo_debug server-side `recordRequest`; silent no-op until then.
- test-app wires `hazo_debug`'s `<DebugProvider>` into the root layout via a
  new `DebugWrapper` client component. INI flag `[debug] enabled` toggles it
  server-side (default `true` in test-app, `false` in the package sample).
- test-app `dev` and `start` scripts honor `PORT` env var (e.g.
  `PORT=3005 npm run dev:test-app`), defaulting to `3040`.

## 1.0.0 (2026-05-16)

Initial release. Foundation-layer toolkit for `hazo_*` HTTP APIs.

### Added
- `ok()` / `fail()` response envelope builders returning native `Response`.
- `ErrorCodes` frozen enum with six codes mapped to HTTP statuses
  (VALIDATION_FAILED, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, CONFLICT, INTERNAL_ERROR).
- `withRequestContext()` / `getRequestContext()` — `AsyncLocalStorage`-backed
  request context carrying `request_id`, `start_time`, request-scoped logger.
- `defineRoute()` / `generateOpenAPI()` — Zod-schema-driven OpenAPI 3.1 emission
  via `@asteasolutions/zod-to-openapi`.
- `swaggerUiHtml()` — self-contained HTML page loading swagger-ui-dist from CDN
  (no `swagger-ui-react` dep).
- `zodIssuesToDetails()` — flattens Zod errors into PRD-shaped `{field, issue}` arrays.
- `resolveApiConfig()` — INI-backed config via `hazo_config`.
- `withApiKey()` design-only stub for v1.1.0 forward-compat.
- INI configuration template: `config/hazo_api_config.ini.sample`.
- Next.js test-app with sidebar navigation and 10 demo pages.

### Design decisions captured in spec
- Native `Response` over `NextResponse` (cross-runtime portability).
- `hazo_logs` remains a pure capture library; `hazo_api` owns its own ALS for
  transactional state and mirrors `reference: request_id` one-way.
- Wraps `@asteasolutions/zod-to-openapi` rather than hand-rolling a Zod walker.

See `design/2026-05-16-hazo_api-v1.0.0-design.md` for the full spec.
