API reference
This page lists every public export of @ltv/cwb 0.2.0, checked against the package's public API snapshot (etc/cwb.api.d.ts). Anything not exported from @ltv/cwb or @ltv/cwb/datasources is internal and may change in any release (support policy).
Kinds: function, class, const (runtime value), type (type alias or interface, erased at runtime), namespace.
@ltv/cwb
App and modules
| Export | Kind | Description |
|---|---|---|
createApp(config) | function | Builds a Hono app with the standard middleware stack, module routes and OpenAPI router. Guide |
AppConfig<E> | type | Options for createApp. Reference |
RequestIdConfig | type | boolean or RequestIdOptions |
RequestIdOptions | type | {trustIncomingHeader?: boolean} |
RequestLoggingConfig | type | boolean or RequestLoggingOptions |
RequestLoggingOptions | type | {level?, skip?} for the per-request log line |
RequestLogLevel | type | 'trace', 'debug', 'info' or 'warn' |
defineModule(module) | function | Normalizes an ApiModule (version 2 becomes 'v2', default 'v1'). Guide |
ApiModule | type | {version?, routes, middleware?} |
RouteKey | type | Template literal type for "METHOD /path" keys |
RouteMethod | type | 'GET', 'POST', 'PUT', 'PATCH' or 'DELETE' |
EndpointRegistry | class | Collects endpoints and applies them to a chanfana router (register, get, post, put, patch, delete, applyTo, getEndpoints) |
EndpointConfig | type | {method, path, handler, middleware?} stored by the registry |
EndpointMethod | type | Lowercase route method |
ENDPOINT_METHODS | const | ['get', 'post', 'put', 'patch', 'delete'] |
OpenAPIRouter | type | Minimal shape of a chanfana router, as returned by fromHono(app) |
buildEndpointPath(base, version, route) | function | Joins base path, optional version and route into a normalized path |
Context and responses
| Export | Kind | Description |
|---|---|---|
contextHelpers | const | Middleware that adds the c.respond* helpers; installed by createApp. Guide |
ContextResponseHelpers | type | Signatures of the c.respond* methods added to Hono's Context |
buildPaginationMeta(page, limit, total) | function | Pagination metadata; throws a 400 BAD_REQUEST ApiError on invalid input |
PaginationMeta | type | {page, limit, total, totalPages, hasNext, hasPrev} |
ApiResponse<T> | type | ApiSuccessResponse<T> or ApiErrorResponse, discriminated on success |
ApiSuccessResponse<T> | type | {success: true, data, meta?} |
ApiErrorResponse | type | {success: false, error: {id, code, message, details?}, meta?} |
ApiResponseMeta | type | {timestamp, requestId?, traceId?, pagination?} |
PaginationParams | type | {page?, limit?, sort?, order?} list-query shape |
QueryParams | type | PaginationParams plus search? and filter? |
BaseUser | type | {id, email?, name?} |
BaseTenant | type | {id, name} |
BaseContextVariables | type | user, tenant, tenantId, requestId, traceId; no index signature |
BaseEnvironmentBindings | type | NODE_ENV?, APP_VERSION? |
AppEnv<Variables, Bindings> | type | Hono env generic: {Variables, Bindings} |
TenantContext | type | {tenantId?, tenant?} |
TenantContextVariables | type | BaseContextVariables with tenant extended by schema?, features?, config? |
OpenAPI schemas
All json* helpers return a chanfana responses object keyed by status code. Guide
| Export | Kind | Description |
|---|---|---|
jsonSuccess(description, schema) | function | 200 success envelope |
jsonCreated(description, schema) | function | 201 success envelope |
jsonAccepted(description, schema) | function | 202 success envelope |
jsonNoContent(description) | function | 204 without body |
jsonPaginated(description, schema) | function | 200 with data: schema[] and required meta.pagination |
jsonBadRequest(description?) | function | 400 error envelope |
jsonUnauthorized(description?) | function | 401 error envelope |
jsonForbidden(description?) | function | 403 error envelope |
jsonNotFound(description?) | function | 404 error envelope |
jsonConflict(description?) | function | 409 error envelope |
jsonValidationError(description?) | function | 422 envelope with details: [{field, message, code?}] |
jsonInternalError(description?) | function | 500 error envelope |
jsonCrudResponses(resource, schema) | function | 200, 400, 401, 404, 500 |
jsonListResponses(resource, schema) | function | Paginated 200, 400, 401, 500 |
jsonCreateResponses(resource, schema) | function | 201, 400, 401, 409, 422, 500 |
jsonUpdateResponses(resource, schema) | function | 200, 400, 401, 404, 422, 500 |
jsonDeleteResponses(resource) | function | 204, 400, 401, 404, 500 |
jsonCustomResponse(statusCode, description, schema?) | function | Any status, no envelope |
MetaSchema | const | zod schema for meta |
PaginationMetaSchema | const | zod schema for meta.pagination |
ErrorSchema | const | zod schema for error (id, code, message, details?) |
Errors
| Export | Kind | Description |
|---|---|---|
ApiError | class | Error with id, code, status, category, severity, details, cause; static factories and type guards |
ApiErrorOptions | type | Constructor options for ApiError |
ApiErrorJSON | type | Result of ApiError#toJSON() (no stack) |
ErrorCategory | const | AUTHENTICATION, AUTHORIZATION, VALIDATION, BUSINESS_LOGIC, EXTERNAL_SERVICE, DATABASE, RATE_LIMIT, SYSTEM, UNKNOWN |
ErrorCategoryType | type | Union of ErrorCategory values |
ErrorSeverity | const | LOW, MEDIUM, HIGH, CRITICAL |
ErrorSeverityType | type | Union of ErrorSeverity values |
createErrorHandler(config?) | function | Hono error handler producing the envelope, with logging, reporting, redaction, throttling and getMetrics() |
errorHandler | const | createErrorHandler() with default options, for plain Hono apps |
ErrorHandlerConfig | type | Options for createErrorHandler and AppConfig.errors. Reference |
ErrorHandlerWithMetrics | type | Hono ErrorHandler plus getMetrics() |
ErrorHandlerFactory | type | (config?) => ErrorHandlerWithMetrics |
ErrorClassifier | type | (error, c) => {category, severity} |
ErrorTransformer | type | (error, c) => ErrorTransformResult |
ErrorTransformResult | type | ApiErrorOptions plus an optional client-safe message |
ErrorInfo | type | Structured error passed to logs, customLogger and errorReporter |
ErrorContext | type | Request context in ErrorInfo (ids, method, path, ip, user agent, redacted headers and query) |
ErrorContextRedaction | type | {headers?, queryParams?, includeClientInfo?} for buildErrorContext |
ErrorResponse | type | Error envelope shape with required meta |
ErrorMetrics | type | {total, byCategory, bySeverity, byStatusCode, rate} |
ErrorMetricsTracker | class | Per-isolate counters and one-minute window used for metrics and throttling |
buildErrorContext(c, requestId, redaction?) | function | Collects redacted request, user and tenant context |
isProductionContext(c) | function | true unless c.env.NODE_ENV (or the Worker env) is a development value |
Logging
| Export | Kind | Description |
|---|---|---|
logger | const | Root pino logger with base fields |
Logger | type | Type of logger |
createLogger(context) | function | Child of the root logger with extra fields |
getRequestLogger(c) | function | Request-scoped logger bound to requestId, or the root logger |
serializers | const | pino serializers err, req, res with redaction |
serializeError(error, options?) | function | JSON-safe error with its cause chain; never throws |
SerializedError | type | {type?, message, stack?, code?, statusCode?, cause?} |
SerializeErrorOptions | type | {includeStack?, maxDepth?} |
RequestLike | type | Fetch Request, HonoRequest or similar object accepted by serializers.req |
ResponseLike | type | Object with optional status and headers |
createLoggerOptions(writers?) | function | The pino options used by the library, with optional per-level writers |
LogWriter | type | (entry: object) => void |
baseLogBindings | const | {env, service, runtime} attached to every line |
Redaction
| Export | Kind | Description |
|---|---|---|
redactHeaders(headers, extra?) | function | Headers as a plain object with sensitive values replaced |
redactQueryParams(query, extra?) | function | Copy of query params with sensitive values replaced |
redactUrl(url, extra?) | function | URL with sensitive query values replaced; unparseable URLs returned as-is |
addSensitiveHeaders(...names) | function | Registers extra header names to redact everywhere |
addSensitiveQueryParams(...names) | function | Registers extra query parameter names to redact everywhere |
isSensitiveName(name, exactNames) | function | true for an exact match or a name containing a sensitive fragment |
SENSITIVE_HEADERS | const | Header names redacted by exact match |
SENSITIVE_QUERY_PARAMS | const | Query parameter names redacted by exact match |
SENSITIVE_NAME_FRAGMENTS | const | Fragments that mark any header or parameter name as sensitive |
REDACTED | const | '[REDACTED]' |
Environment
| Export | Kind | Description |
|---|---|---|
env | namespace | env.default(key, default?) raw reader with typed readers string, int, float, number, bool, json, array, date |
env.StringOrUndefined, env.NumberOrUndefined, env.BooleanOrUndefined, env.DateOrUndefined, env.ArrayOfStringOrUndefined, env.CustomOrUndefined | type | Return types of the typed readers |
NODE_ENV | const | NODE_ENV at load time, default 'production' |
isDev | const | NODE_ENV is a development value |
isProd | const | !isDev |
DEVELOPMENT_ENVIRONMENTS | const | ['development', 'dev', 'test', 'local'] |
isDevelopmentEnvironment(nodeEnv) | function | Fail-safe check: only those values are non-production |
LOG_LEVEL | const | Resolved log level |
LOG_LEVELS | const | ['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent'] |
resolveLogLevel(value, fallback, warn?) | function | Normalizes a level; unknown values warn and return fallback |
SERVICE_NAME | const | SERVICE_NAME at load time, default '@ltv/cwb' |
KV cache and utilities
| Export | Kind | Description |
|---|---|---|
KVCache | class | Read-through KV cache: buildKey, memoize, invalidate, clearAll. Guide |
KVCacheOptions | type | {defaultNamespace?, defaultTtl?, waitUntil?, logger?} |
CacheOptions<T> | type | {ttl?, namespace?, revive?} |
InvalidateOptions | type | {cursor?, maxOperations?} |
InvalidateResult | type | {deleted, complete, cursor?, failed} |
MIN_KV_TTL_SECONDS | const | 60 |
DEFAULT_MAX_KV_OPERATIONS | const | 900 |
getWaitUntil(c) | function | executionCtx.waitUntil of a Hono context, or undefined |
runInBackground(promise, waitUntil, onError) | function | Runs work past the response; errors go to onError |
WaitUntil | type | (promise: Promise<unknown>) => void |
createId() | function | CUID2 id: 24 lowercase alphanumeric characters, starting with a letter |
@ltv/cwb/datasources
Requires the optional peer drizzle-orm 0.45.x. Datasources guide, multi-tenancy guide
Classes
| Export | Kind | Description |
|---|---|---|
AbstractDatasource<TContext> | class (abstract) | Context-bound base: logger, withCache, cacheBinding, cacheNamespace, clear, init, connect, disconnect, healthCheck |
BaseDatasource<TContext> | type | Interface: name, context?, optional lifecycle methods |
DrizzleD1Datasource<TSchema, TContext> | class (abstract) | Drizzle on D1: lazy db, batch, healthCheck, createQueryLogger |
DrizzleD1DatasourceOptions<TSchema> | type | {schema?, binding?, logQueries?} |
DrizzleSchema | type | Record<string, unknown> |
DrizzleD1TenantDatasource<TSchema, TContext> | class (abstract) | Tenant-scoped datasource: tenantId, where, values, scopedSelect, scopedCount, scopedInsert, scopedInsertMany, scopedUpsert, scopedUpdate, scopedDelete |
DrizzleD1TenantDatasourceOptions<TSchema> | type | DrizzleD1DatasourceOptions plus tenantId? |
Tenant helpers and types
| Export | Kind | Description |
|---|---|---|
tenantWhere(table, tenantId, ...conditions) | function | Where clause restricting a table to a tenant; conditions are parenthesized |
withTenantId(values, tenantId) | function | Stamps tenantId on one row or many rows, overriding existing values |
withoutTenantId(values) | function | Removes tenantId from update values |
toScopedWriteQuery(builder) | function | Wraps an already tenant-filtered Drizzle insert, update or delete builder in a ScopedWriteQuery; adds no filter itself |
toScopedInsertQuery(builder) | function | Same for insert builders, exposing only onConflictDoNothing |
ScopedWriteQuery<TTable> | type | Awaitable D1Result with returning() |
ScopedInsertQuery<TTable> | type | ScopedWriteQuery plus onConflictDoNothing() |
ScopedSelectOptions | type | {where?, orderBy?, limit?, offset?} |
ScopedOrderBy | type | SQLite column or SQL expression |
TenantScopedTable | type | Any Drizzle table with a string tenantId column |
TenantTable | type | SQLiteTable & TenantScopedTable |
TenantInsert<TTable> | type | Insert model without tenantId |
TenantUpsertSet<TTable> | type | Upsert set values: insert columns (except tenantId) or SQL |
WithTenantId<V> | type | V (or each row of V) with tenantId: string |
Type augmentations
Importing @ltv/cwb augments the hono module:
| Augmentation | Effect |
|---|---|
Context extends ContextResponseHelpers | c.respond* methods are typed on every context (present at runtime only with contextHelpers) |
ContextVariableMap.cwbLogger?: Logger | Typed c.var.cwbLogger |
ContextVariableMap.traceId?: string | Typed c.get('traceId') / c.set('traceId', ...) |