Skip to content

API Reference

API Reference

Quick reference of all exported functions, types, and classes per package.

@workkit/types

ExportKindDescription
Result<T,E>typeDiscriminated union: { ok: true, value: T } or { ok: false, error: E }
AsyncResult<T,E>typePromise<Result<T,E>>
Ok(value)functionCreate a success Result
Err(error)functionCreate an error Result
isOk(result)functionType guard for success
isErr(result)functionType guard for error
unwrap(result)functionExtract value or throw
Branded<T, Brand>typeNominal typing helper
brand(value, tag)functionBrand a value
kvKey(value)functionBrand as KVKey
d1RowId(value)functionBrand as D1RowId
r2ObjectKey(value)functionBrand as R2ObjectKey
durableObjectId(value)functionBrand as DurableObjectId
queueMessageId(value)functionBrand as QueueMessageId
TypedKVNamespace<T>typeTyped KV binding augmentation
TypedD1Result<T>typeTyped D1 query result
TypedR2ObjecttypeTyped R2 object
TypedQueue<T>typeTyped queue binding
TypedMessageBatch<T>typeTyped message batch
TypedDurableObjectStoragetypeTyped DO storage
JsonValue, JsonObject, JsonArraytypesJSON-safe types
DeepPartial<T>, DeepReadonly<T>typesRecursive utility types
WorkerFetchHandlertypefetch() handler signature
WorkerScheduledHandlertypescheduled() handler signature
WorkerQueueHandlertypequeue() handler signature
WorkerModuletypeFull worker module export
ExecutionContexttypeWorker execution context
ScheduledEventtypeCron trigger event
MaybePromise<T>type`T
Prettify<T>typeFlatten intersection types
assertNever(x)functionExhaustive switch helper

@workkit/errors

ExportKindDescription
WorkkitErrorabstract classBase error with code, statusCode, retryable, retryStrategy
NotFoundErrorclass404, not retryable
ConflictErrorclass409, retryable (exponential)
ValidationErrorclass400, not retryable, carries issues[]
UnauthorizedErrorclass401, not retryable
ForbiddenErrorclass403, not retryable
TimeoutErrorclass504, retryable (exponential)
RateLimitErrorclass429, retryable (fixed)
ServiceUnavailableErrorclass503, retryable (exponential)
BindingErrorclass500, not retryable
BindingNotFoundErrorclass500, not retryable
InternalErrorclass500, not retryable
ConfigErrorclass500, not retryable
RetryStrategiesobjectFactory for retry strategies: .none(), .immediate(), .fixed(), .exponential()
getRetryDelay(strategy, attempt)functionCalculate delay for attempt, returns `number
isRetryable(error)functionType guard: is error retryable?
getRetryStrategy(error)functionExtract retry strategy from any error
errorToResponse(error)functionConvert WorkkitError to HTTP Response
fromHttpStatus(status, msg?)functionCreate WorkkitError from HTTP status code
isWorkkitError(error)functionType guard for WorkkitError
isErrorCode(error, code)functionType guard for specific error code
serializeError(error)functionSerialize any error to structured JSON
wrapError(error, msg?)functionWrap unknown error as WorkkitError

@workkit/env

ExportKindDescription
parseEnv(rawEnv, schema)async functionValidate env (async validators)
parseEnvSync(rawEnv, schema)functionValidate env (sync only, throws on async)
createEnvParser(schema)functionCreate reusable parser with .parse() and .parseSync()
EnvValidationErrorclassError with .issues: EnvIssue[]
isStandardSchema(value)functionType guard for Standard Schema objects
detectPlatform()functionReturns `‘workerd'
resolveEnv()functionGet env from current platform
EnvSchematypeRecord<string, StandardSchemaV1>
InferEnv<T>typeInfer output types from schema
InferRawEnv<T>typeInfer input types from schema

@workkit/env/validators

ExportKindDescription
d1()functionD1Database binding validator
kv()functionKVNamespace binding validator
r2()functionR2Bucket binding validator
queue()functionQueue binding validator
ai()functionAI binding validator
durableObject()functionDurableObjectNamespace binding validator
service()functionService binding validator

@workkit/d1

ExportKindDescription
d1(binding, options?)functionCreate typed D1 client
D1ErrorclassBase D1 error
D1QueryErrorclassSQL query error
D1ConstraintErrorclassConstraint violation (409)
D1BatchErrorclassBatch operation error
D1MigrationErrorclassMigration error
classifyD1Error(error, sql?, params?)functionClassify raw D1 errors
snakeToCamel(column)functionColumn name transformer
migrate(db, migrations, options?)functionRun pending migrations
migrationStatus(db, migrations, options?)functionCheck migration status

TypedD1 Client Methods

MethodReturnsDescription
.first<T>(sql, params?)Promise<T | null>Single row query
.all<T>(sql, params?)Promise<T[]>Multi-row query
.run(sql, params?)Promise<D1RunResult>Mutation (INSERT/UPDATE/DELETE)
.exec(sql)Promise<D1ExecResult>Raw SQL execution
.prepare<T>(sql, params?)TypedPreparedStatement<T>Create prepared statement
.batch(statements)Promise<D1BatchResult[]>Atomic batch execution
.select<T>(table)SelectBuilder<T>Fluent SELECT builder
.insert(table)InsertBuilderFluent INSERT builder
.update(table)UpdateBuilderFluent UPDATE builder
.delete(table)DeleteBuilderFluent DELETE builder
.rawD1DatabaseUnderlying binding

@workkit/kv

ExportKindDescription
kv<T>(binding, options?)functionCreate typed KV client
validateKey(key)functionValidate KV key
prefixKey(prefix, key)functionPrepend prefix to key
stripPrefix(prefix, key)functionRemove prefix from key
wrapKVError(error, context)functionWrap KV errors with context
assertKVBinding(binding)functionAssert binding exists
assertValidTtl(ttl)functionAssert TTL >= 60

WorkkitKV Client Methods

MethodReturnsDescription
.get(key, options?)Promise<T | null>Get value
.getWithMetadata<M>(key, options?)Promise<{value, metadata, cacheStatus}>Get with metadata
.put(key, value, options?)Promise<void>Store value
.delete(key)Promise<void>Delete key
.getMany(keys, options?)Promise<Map<string, T>>Batch get
.putMany(entries, options?)Promise<void>Batch put
.deleteMany(keys)Promise<void>Batch delete
.list<M>(options?)AsyncIterable<KVListEntry<M>>List keys (auto-paginate)
.listKeys(options?)Promise<KVListEntry[]>Collect all keys
.has(key)Promise<boolean>Check key existence
.rawKVNamespaceUnderlying binding

@workkit/auth

ExportKindDescription
signJWT(payload, options)async functionSign a JWT token
verifyJWT(token, options)async functionVerify and decode JWT
decodeJWT(token)functionDecode JWT without verification
parseDuration(str)functionParse ‘1h’, ‘30m’, ‘7d’ to seconds
hashPassword(password, options?)async functionPBKDF2 password hashing
verifyPassword(password, stored)async functionConstant-time password verification
createSessionManager(config)functionKV-backed session manager
createAuthHandler(config)functionAuth middleware factory
extractBearerToken(request)functionExtract Bearer token from header
extractBasicAuth(request)functionExtract Basic auth credentials

@workkit/ratelimit

ExportKindDescription
fixedWindow(options)functionFixed window rate limiter
slidingWindow(options)functionSliding window rate limiter
tokenBucket(options)functionToken bucket rate limiter
composite(limiters)functionCombine multiple limiters
parseDuration(str)functionParse duration to milliseconds
rateLimitHeaders(result)functionGenerate X-RateLimit-* headers
rateLimitResponse(result, msg?)functionGenerate 429 Response

@workkit/ai

ExportKindDescription
ai(binding)functionCreate typed AI client
streamAI(binding, model, input, options?)async functionStream text generation
fallback(binding, models, inputs, options?)async functionTry models in order
withRetry(fn, options?)async functionRetry wrapper
estimateTokens(text)functionApproximate token count

@workkit/ai-gateway

ExportKindDescription
createGateway(config)functionMulti-provider AI gateway
createRouter(config)functionModel-to-provider router
createCostTracker(config)functionToken usage and cost tracker
withCache(gateway, config)functionCache wrapper for gateway
withLogging(gateway, config)functionLogging wrapper for gateway

@workkit/queue

ExportKindDescription
queue<T>(binding)functionCreate typed queue producer
createConsumer<T>(options)functionPer-message consumer handler
createBatchConsumer<T>(options)functionBatch consumer handler
createDLQProcessor<T>(options)functionDead letter queue processor
RetryActionenumACK, RETRY, DEAD_LETTER

@workkit/cron

ExportKindDescription
createCronHandler(options)functionRoute scheduled events to tasks
matchCron(schedule, cron)functionCheck if cron matches
parseCron(expression)functionParse cron expression
describeCron(expression)functionHuman-readable description
nextRun(expression)functionNext scheduled Date
isValidCron(expression)functionValidate cron expression
withTimeout(ms)functionTimeout middleware
withRetry(maxRetries, options?)functionRetry middleware
withErrorReporting(getQueue, reporter?)functionError reporting middleware
withLock(getKV, key, options, handler)functionDistributed lock wrapper
acquireLock(kv, key, options?)functionAcquire a KV-based lock

@workkit/do

ExportKindDescription
typedStorage<T>(raw)functionType-safe DO storage wrapper
createStateMachine(config)functionFinite state machine for DOs
scheduleAlarm(storage, schedule)async functionSchedule a DO alarm
createAlarmHandler(config)functionRoute alarms to named handlers
parseDuration(str)functionParse duration to milliseconds
createDOClient<T>(namespace, id)functionTyped RPC client for DO stubs
singleton(namespace, name)functionGet named DO instance

@workkit/logger

ExportKindDescription
createLogger(options?)functionCreate a standalone structured logger
logger(options?)functionHono middleware for structured request logging
getLogger(c)functionGet a logger from Hono context with request context
getRequestContext()functionGet current request context from AsyncLocalStorage
LogLeveltype"debug" | "info" | "warn" | "error"
LogFieldstypeRecord<string, unknown>
LogEntrytypeStructured log entry with level, msg, ts, and fields
LoggertypeLogger interface with .debug(), .info(), .warn(), .error(), .child()
CreateLoggerOptionstypeOptions for createLogger
LoggerMiddlewareOptionstypeOptions for logger middleware
RequestContexttypeRequest context: requestId, method, path, startTime, fields

@workkit/testing

ExportKindDescription
createTestEnv(config)functionOne-call typed env factory
createMockKV()functionIn-memory KVNamespace mock
createMockD1()functionIn-memory D1Database mock
createFailingD1()functionAlways-failing D1 mock
createMockR2()functionIn-memory R2Bucket mock
createMockQueue()functionIn-memory Queue mock
createMockDO()functionIn-memory DO storage mock
createRequest(path, options?)functionRequest factory
createExecutionContext()functionMock ExecutionContext

@workkit/r2

ExportKindDescription
r2(bucket, options?)functionTyped R2 client wrapper
createPresignedUrl(bucket, options)functionGenerate presigned PUT/GET URLs
multipartUpload(bucket, key, options?)functionStart a multipart upload session
streamToBuffer(stream) / streamToText(stream) / streamToJson<T>(stream)functionBody stream helpers
fromS3Key(key) / toS3Key(key)functionS3 ↔ R2 key migration helpers
validateR2Key(key) / assertR2Binding(b) / wrapR2Error(err, ctx)functionDefensive helpers

@workkit/cache

ExportKindDescription
cache(kv, options?)functionTyped KV-backed cache client
swr(kv, key, fetcher, options?)functionStale-while-revalidate read-through
cacheAside(kv, options?)functionCache-aside pattern helper
taggedCache(kv, options?)functionTagged invalidation client
createMemoryCache(options?)functionIn-process LRU cache
buildCacheUrl(key)functionCompose cache key URL

@workkit/crypto

ExportKindDescription
encrypt(key, data) / decrypt(key, ciphertext)functionAES-256-GCM encrypt / decrypt
encryptWithAAD(key, data, aad) / decryptWithAAD(key, ciphertext, aad)functionAES-GCM with additional authenticated data
generateKey() / exportKey(key) / importKey(base64)functionAES-256-GCM key lifecycle
deriveKey(source, context)functionPBKDF2 (string) or HKDF (CryptoKey) key derivation
envelope.seal / open / rotateobjectEnvelope encryption (DEK + master key)
hash(algo, data)functionSHA-1 / SHA-256 / SHA-384 / SHA-512
hmac(secret, data) / hmac.verify(secret, data, mac)functionHMAC sign + constant-time verify
generateSigningKeyPair(algo?)functionEd25519 (default) or ECDSA keypair
exportSigningKey(key) / importSigningKey(base64, type, algo?)functionPublic/private signing key serialization
sign(privateKey, data) / sign.verify(publicKey, data, signature)functionDetached signature + verify
randomBytes(n) / randomHex(n) / randomUUID()functionCrypto-secure random

@workkit/api

ExportKindDescription
api(config)functionDefine a typed API surface
createRouter(config)functionBuild a router from API definitions
generateOpenAPI(api)functionBuild OpenAPI 3.1 spec from definitions
parsePath / matchPath / buildPath / toOpenAPIPath / parseQueryfunctionPath utilities
validate / validateSync / tryValidate / isStandardSchemafunctionStandard Schema validation helpers
createLlmsRoutes / generateLlmsTxt / generateLlmsFullTxtfunctionllms.txt generation

@workkit/health

ExportKindDescription
createHealthCheck(probes, options?)functionCompose probes into a HealthChecker
healthHandler(probes, options?)functionHono-style /health handler
kvProbe(kv) / d1Probe(db) / r2Probe(bucket) / doProbe(ns) / aiProbe(ai) / queueProbe(q)functionBuilt-in binding probes

@workkit/turnstile

ExportKindDescription
verifyTurnstile(token, secret, options?)functionServer-side CAPTCHA verification
turnstile(options)functionHono middleware that gates handlers on a valid token

@workkit/features

ExportKindDescription
createFlags(kv, options?)functionKV-backed feature flag client
evaluate(flag, context)functionEvaluate a flag against a user context (rollout %, targeting)

@workkit/mail

ExportKindDescription
mail(binding, options?)functionTyped email send client over SendEmail binding
parseEmail(raw)functionParse Email Routing inbound message
createEmailHandler(opts)functionBuild an inbound email handler
createEmailRouter(routes)functionRoute inbound emails to handlers
composeMessage(opts)functionCompose a MailMessage from address/subject/body parts
validateAddress(addr) / isValidAddress(addr)functionAddress validation helpers
MailError / InvalidAddressError / DeliveryErrorclassDomain errors

@workkit/chat

ExportKindDescription
createChatTransport(env, options?)functionWebSocket transport factory
ChatSessionDODO classRe-exportable Durable Object for chat sessions
ChatMessagetypeDiscriminated union of typed chat events

@workkit/notify

ExportKindDescription
define(spec, options)functionDefine a typed notification with channel rendering
createNotifyConsumer(adapters)functionQueue consumer that dispatches via adapters
ALL_MIGRATIONSconstD1 schema for core (preferences, opt-out, records)

Subpath imports: @workkit/notify/email, @workkit/notify/inapp, @workkit/notify/whatsapp — each ships an *_MIGRATION_SQL plus an *Adapter factory.

@workkit/browser

ExportKindDescription
browser(binding, options?)functionAcquire a Browser Rendering session
withPage(session, fn, options?)functionRun fn(page) with guaranteed cleanup
loadFonts(page, fonts, options?)functionInject @font-face declarations safely

@workkit/pdf

ExportKindDescription
renderPdf(session, html, options?)functionRender HTML to PDF with header/footer presets
storePdf(bucket, key, bytes, options?)functionStore rendered PDF in R2
presignPdf(bucket, key, options)functionGenerate a presigned download URL
presetsobjectPage-size and margin presets
raw(html)functionMark a string as already-escaped HTML

@workkit/agent

ExportKindDescription
tool(spec)functionDefine a Standard-Schema-validated tool
defineAgent(spec)functionCompose a multi-turn agent loop
handoff(target, options?)functionSynthetic tool that hands off to another agent
AgentEventtypeDiscriminated union streamed by agent.stream()
HandoffCycleError / BudgetExceededErrorerror classDomain-specific failures

@workkit/memory

ExportKindDescription
createMemory(options)functionMemory factory (D1 + optional Vectorize/AI/KV)
getSchema()functionD1 schema SQL for migrations
cosineSimilarity / estimateTokens / extractSearchTermsfunctionRecall scoring utilities
Memory / Conversation / Fact / RecallResult / MemoryErrortypePublic types

@workkit/mcp

ExportKindDescription
createMCPServer(config)functionMCP server with tools, resources, prompts
generateOpenAPISpec(server)functionExport OpenAPI from a server instance
validateInput(schema, input)functionStandard Schema validation helper
ToolAnnotationstypeMCP 2025-06 tool safety hints

@workkit/workflow

ExportKindDescription
createDurableWorkflow(name, config)functionBuilder for DO-backed workflows
createWorkflow(name, config)functionAlias for non-durable testing flows
WorkflowExecutionDODO classRe-exportable Durable Object for execution state
parseDuration(str)functionParse "30s", "5m", "1h" to ms
generateExecutionId()functionCreate a unique execution ID

@workkit/approval

ExportKindDescription
createApprovalGate(config)functionApproval gate factory
ApprovalRequestDODO classRe-exportable Durable Object for live requests
evaluatePolicies(action, policies)functionMatch an action against registered policies
generateApprovalToken / verifyApprovalToken / generateApprovalKeysfunctionEd25519 signed approval tokens
createAuditProjection(db)functionAppend-only audit projection over D1

@workkit/cli

The workkit CLI is published as a single binary. Run via bunx workkit <cmd>.

CommandDescription
initScaffold a new Workers project with workkit defaults
add [packages...]Interactively add @workkit/* packages to an existing project
catalogList every workkit package with one-line descriptions
checkRun the constitution check on the current repo
gen-clientGenerate a typed client from an @workkit/api definition
gen-docsGenerate API reference markdown from src/index.ts exports
migrateApply D1 migrations from a directory
seedSeed a D1 database from a JSON or SQL fixture