Public API
Supported KetJS, theme, testing, view, and PostgreSQL package entrypoints.
KetJS 0.8.1 is a preview release; public names may change until 1.0. A composed manifest records the
framework release it was composed with as manifest.ket, which the agent descriptor reports. Import only
from documented package entrypoints; deep imports into dist/ or src/ are implementation details.
Package entrypoints#
| Entrypoint | Runtime |
|---|---|
@ketvietlab/ketjs |
Framework composition, server, data, jobs, sessions, integrations, and selected view helpers. |
@ketvietlab/ketjs/pdf |
Report-safe KTL compilation, constrained markup, HTML preview, fonts, and PDF rendering. |
@ketvietlab/ketjs/theme |
Theme compilation and presentation helpers without the wider server API. |
@ketvietlab/ketjs/testing |
Isolated headless applications, test clients, cookie jars, and fixture types. |
@ketvietlab/ketjs-view |
Browser-safe signals, rendering, SSR, hydration, and islands. |
@ketvietlab/ketjs-view/mirror |
Server-state cache for API answers: shared reads, invalidation, optimistic writes, pages and snapshots. |
@ketvietlab/ketjs-view/store |
Island stores: state that is read-only from outside, batched actions, async tasks and browser wiring after mount. |
@ketvietlab/ketjs-view/jsx-runtime |
Automatic JSX runtime. |
@ketvietlab/ketjs-view/jsx-dev-runtime |
Automatic JSX development runtime. |
@ketvietlab/ketjs-view-tools |
Static page rendering, asset bundling, local development, preview, and project validation. |
@ketvietlab/create-view |
Runnable static ketjs-view project generator. |
@ketvietlab/ketjs-postgres |
Optional PostgreSQL adapter. |
All packages require Node.js 24.22.1 or later on 24.x, or 26.12.1 or later for their supported server/tooling use. @ketvietlab/ketjs-view has no runtime
dependencies and its browser-facing entrypoint avoids Node APIs.
@ketvietlab/ketjs#
Composition and application model#
| API | Purpose |
|---|---|
defineModule, defineTheme |
Validate and preserve module/theme declarations. |
defineDeployment, defineWorkspace |
Declare immutable deployments and the repository workspace. |
resolveWorkspace |
Resolve string module references from configured roots. |
compose, composeWorkspace |
Build checked manifests for one deployment or a workspace. |
compilePermissionBundles, permissionDigest |
Validate and deterministically digest exact bundle classifications and role templates. |
explainWorkspace |
Render a workspace composition summary. |
validateLayout, formatLayoutErrors |
Validate placement and extension relationships. |
diffManifests, formatDiff |
Compare manifest contracts. |
classificationInventory, formatClassification |
Enumerate personal and sensitive fields, and the models that classify none. |
KetError, Diagnostics |
Structured framework errors and accumulated diagnostics. |
isDefectError |
True when an error code means the deployment broke its own contract rather than the caller sending something wrong. |
walkPlacements, countPlacements, MAX_LAYOUT_DEPTH, MAX_LAYOUT_NODES |
Traverse a placement tree and the limits validateLayout enforces on it. |
withPlacementIds, isPlacementId, placementIdErrors, diffPlacements |
Give placements stable ids, check them, and compare two layouts by id for an editor. |
Primary types include Manifest, Module, Theme, Model, DeploymentDeclaration, DeploymentSpec,
WorkspaceDeclaration, ResolvedWorkspace, Placement, and LayoutError.
Permission types include ModulePermissionsDef, PermissionBundleDef, PermissionFunctionDef,
PermissionExemptionDef, PermissionRisk, PermissionPosture, RoleTemplateDef,
PermissionCatalogue, CompiledPermissionBundle, CompiledRoleTemplate, and
CompilePermissionOptions.
Operations and HTTP#
| API | Purpose |
|---|---|
defineFn, callFn |
Declare effect-checked functions and execute the handler bound to the given composed manifest. |
registerFunctions, registerJobs |
Deprecated. Return a module handler map; compose() binds handlers to its manifest, so registration no longer selects what runs. |
enforcePolicy |
Apply one stable domain policy decision and emit sanitized denial evidence. |
project |
Apply output projection rules. |
defineJob |
Declare durable job handlers. |
createKetServer |
Create the low-level HTTP server from composed runtime services. |
bootRuntime, bootDeployment, serveDeployment |
Boot runtime services or a complete HTTP deployment. |
bootWorker, serveWorker |
Boot or continuously serve configured durable queues. |
page, fragment, document |
Create rendered response bodies. |
navigablePage, isNavigationRequest |
Negotiate a full document or lazy named navigation slots. |
NAVIGATION_HEADER, NAVIGATION_VERSION, NAVIGATION_TYPE |
Fragment navigation protocol constants. |
json, text, bytes, streamed, raw |
Create typed non-page response bodies. |
withHeaders |
Add headers without discarding a response body's type. |
multipart |
Parse bounded multipart input. |
assertForm, invalidForm, FormValidationError |
Enforce form schemas and produce structured HTTP 422 failures. |
issuesFromFieldErrors |
Bridge changeset field errors into the shared validation issue contract. |
httpRoutes |
Publish server functions as HTTP operations with derived, checked contracts. |
isSameOriginRequest |
Check origin host/port through TLS termination; cookie bindings require origin evidence by default. |
createClientAddressResolver |
Resolve the socket peer or the nearest untrusted forwarded hop through explicitly trusted proxy IPs. See Authentication starter. |
httpOpenApiDocument, httpContracts |
Generate an OpenAPI 3.1 document, or list route contracts, for one profile. |
statusForError, wantsHtml |
The HTTP status a framework error code answers with, and whether a request prefers an HTML error page. |
websocket |
A route answer that upgrades the request after the route's own checks ran. |
readConfig, sqliteStore |
Read runtime configuration from the environment, and the default single-database opener. |
defineFormAction |
Declare a server function from a @ketvietlab/ketjs-view form contract, with atomic receipt semantics. |
_resetIdempotency |
Deprecated and removed in 1.0. Does nothing: idempotency records are rows in the test database. |
Related types include Fn, FnContext, CallResult, Effect, PolicyDecision,
PolicyDenialEvidence, Job, JobContext, ServeSpec,
ServeContext, BootedDeployment, BootedRuntime, BootedWorker, Route, RouteParams, ResponseBody, and
RouteResult. FnReturns, HttpRouteGroup, HttpEndpoint, HttpBindingSpec, HttpBindingMeta,
HttpRouteContract, HttpContractEntry, and HttpOpenApiOptions describe HTTP bindings and contracts. ReportDef and ComposedReport describe business-owned print declarations in the manifest.
Sessions, streams, queues, and integration effects#
| API | Purpose |
|---|---|
createSessions, memorySessionStore, dbSessionStore |
Create signed sessions over memory or database storage. |
hashPassword, verifyPassword |
Server-only bounded scrypt primitives for application-owned credential models. See Authentication starter. |
parseCookies, SESSION_COOKIE |
Parse cookies and reference the framework session-cookie name. |
createStreams, memoryStreamStore, dbStreamStore |
Create resumable stream writers and backing stores. |
createQueue, queueFor, JOB_CHANNEL |
Manage durable job state and queue wake-up channels. |
validateSchedule, tickAt, ticksBetween, parseEvery, claimDue |
Read a job schedule, and claim its due tick in one tenant. |
claimRateSlot, pruneRateSlots |
Spend one slot of a durable per-caller allowance, and drop stale counters. |
nextSequenceNumber, peekSequenceNumber, sequenceKey |
Allocate and read a company-scoped document number, and the key a sequence is stored under. |
MIN_EVERY_MS |
The shortest every interval a job schedule accepts. |
streamsOf |
The durable stream service of one adapter, shared by everything using that database. |
notificationHub, NOTIFY_PAYLOAD_BYTES |
The publish/subscribe hub of a root adapter, and the largest payload one notification carries. |
withPublicStorage |
Add a separate public backend to private storage without changing private-only callers. |
auditHash, auditId |
Namespaced digest for an identity, and a command-derived event id. |
createIdempotency |
Persist and replay idempotent operation results. |
effectTransport, memoryTransport, unavailableTransport |
Execute or test declared outbound messages. |
validateOutboundMessage |
Validate an outbound transport payload. |
storageFromConfig, localStorage, s3Storage |
Open configured storage implementations. |
namespacedStorage, effectStorage |
Scope object keys and record declared storage effects. |
signRequest, presignUrl, sha256 |
S3 Signature Version 4 primitives. |
logFromConfig, consoleLog, prettyLog, fileLog, memoryLog, nullLog |
Open a built-in operational sink. |
multiLog, leveledLog, bufferedLog, isolatedLog, redactLog |
Compose fan-out, filtering, batching, isolation and redaction. |
createLogger, describeError, traceOf |
Bind record context, reduce a failure to data, and pseudonymise a correlation or actor. |
CORE_EVENTS, MODULE_EVENT, isLogLevel, isLogDriverName |
The framework's event catalogue and the shapes a module event and configuration must have. |
Use the higher-level runtime services when possible. Signing and queue primitives are public for custom
adapters and operational tooling, not a requirement for ordinary modules. Ordinary modules log through
ctx.log; the sink API is for a deployment choosing where records go. See
operational logging.
Data and migration#
| API | Purpose |
|---|---|
sqliteAdapter |
Built-in SQLite adapter. |
assertAdapter, ADAPTER_METHODS |
Validate a custom adapter contract. |
createAdapterPool |
Lease bounded per-key adapters, including tenant databases. |
from, deleteFrom, table, Query |
Build parameterized select, delete, and grouped queries. |
eq, ne, gt, lt, gte, lte, like, ilike |
Comparison expressions. |
inArray, isNull, isNotNull, and, or, not |
Set, null, and boolean expressions. |
asc, desc |
Ordering expressions. |
defineListSearch, parseListState, encodeListState |
Declare allowlisted URL-driven list state. |
compileListFilter, validateListState |
Validate and compile nested list filters. |
dateBucket, localDateTimeToUtc, localDayRange |
Build timezone-aware bucket and UTC range values. |
bucketEq, GROUP_INTERVALS, isGroupInterval, assertGroupInterval |
Match a datetime column's calendar bucket, and the intervals grouping accepts. |
isTimezone, assertTimezone |
Check an IANA timezone name. |
isDateText, parseDateTime |
Check a YYYY-MM-DD date; read date-time text as a UTC instant, without an offset in a given timezone. |
numericCompare |
Compare numerically with an operator chosen at run time; only =, <>, >, <, >=, <= reach SQL. |
likeLiteral |
Escape typed text for use inside a like/ilike pattern. |
changeset, Changeset |
Cast and validate create/update input. |
schemaFromManifest, planMigration, renderSql |
Derive and render schema migration plans. |
tableNameFor |
Resolve the physical table name for a manifest model. |
DestructiveMigrationError |
Identify a plan requiring explicit destructive permission. |
ManualMigrationRequiredError |
Identify a schema change that needs an explicit backfill or conversion. |
confirmManualMigration, ManualMigrationConfirmationError |
Verify physical DDL/backfill before adopting a manual migration. |
verifyPhysicalSchema, PhysicalSchemaVerification |
Read-only audit of the physical catalog against its marker and current manifest. |
physicalSchemaIssues |
Compare modelled SQLite/PostgreSQL catalog objects with explicit schema values. |
migrateOne, migrateFleet, formatFleet |
Apply or report one-database and tenant-fleet migrations. |
The Adapter, Transaction, Scope, Schema, MigrationOp, Dialect, Sql, Table, Expr,
FieldError, and Validator types are exported from the same entrypoint.
Reports and PDF#
| API | Purpose |
|---|---|
compileReportTemplate |
Compile KTL in report-safe mode and return a typed document tree. |
parseReportMarkup, renderReportHtml |
Validate constrained report markup and produce a safe HTML preview. |
renderPdf |
Render deterministic PDF bytes using explicit TrueType fonts. |
interFontUrl |
Resolve the framework-vendored Inter Regular, SemiBold, or Bold asset. |
parseTrueType, parseImage |
Parse supported embedded font and image assets. |
These APIs are exported from @ketvietlab/ketjs so application packages stay on the framework's main public
contract. The narrow @ketvietlab/ketjs/pdf entrypoint exposes the same report-specific surface for independent tooling. Related types
include ReportDocument, ReportElement, ReportNode, PdfRenderOptions, TrueTypeFont, and PdfImage.
Presentation, menus, and capabilities#
| API | Purpose |
|---|---|
buildMenu, activeMenuRoot |
Resolve visible menu trees and the active root section. |
translator, missingMessages, formatMissing, dateTimeFormatter, PSEUDO_LOCALE |
Translate catalogs, reuse Intl date/time formatters, and audit missing messages. |
createTheme, compileKtl, loadTemplates, createJoints |
Compile and execute the theme boundary. |
makeDrop, makeDrops, sealScope |
Expose controlled view-model values to KTL. |
tokensToCss, scopedCss |
Convert design tokens into layered and scoped CSS. |
isTokenValue, partitionTokens |
Check a token value typed into a form, and split a record into renderable and refused tokens. |
renderToString, hydrateRoot, mount, mountHydrated |
Selected @ketvietlab/ketjs-view rendering helpers. |
defineIsland, renderIsland, hydrateIslands, createIslandManager, ISLAND_TAG |
Type, server-render, hydrate, and reconcile named islands. |
BrowserBehavior, BrowserBehaviorContext, BrowserNavigation |
Document-wide progressive enhancement and the public fragment-navigation service. |
reachOf, functionsOf, formatReach, formatInventory |
Inspect function and data/effect permission reach. |
permissionInventory |
Build a deterministic, serializable module/function permission inventory, including modules with no functions. |
agentTools, agentDescriptor, compositionSchema |
Describe the composed application for tooling and agents. |
generateDts |
Generate manifest-derived TypeScript declarations. |
@ketvietlab/ketjs/theme#
Use the narrow theme entrypoint in presentation packages:
// File: src/theme.ts
import {
compileKtl,
createJoints,
createTheme,
loadTemplates,
makeDrop,
makeDrops,
scopedCss,
sealScope,
tokensToCss,
} from '@ketvietlab/ketjs/theme'It also exports LAYER_ORDER and the Compiled, Filter, Scope, and Joints types.
@ketvietlab/ketjs/testing#
// File: test/order.test.ts
import {
CookieJar,
TestClient,
TestHttpError,
createTestDeployment,
} from '@ketvietlab/ketjs/testing'The entrypoint also exports TestDeployment, CreateTestDeploymentOptions, TestClientOptions, TestIdentity,
TestCallOptions, TestFixtures, TestFixtureCallOptions, and TestFixtureTenant. See
Testing for the lifecycle and isolation contract.
@ketvietlab/ketjs-view#
| API | Purpose |
|---|---|
signal, computed, effect, batch |
Fine-grained reactive state and scheduling. |
defineFormSchema, validateForm, validationIssue |
Declare and execute browser-safe form validation. |
valuesFromFormData, createForm |
Preserve native form values and manage reactive form lifecycle state. |
defineFormContract, createFormSession, attachForm |
Share one form declaration between server and island, run an edit session, and adapt native controls to it. |
formActionTransport, formIssuePath, formConflict |
Submit through the function transport, map server issues back to fields, and report a conflict. |
validationProblem, fieldErrorsOf, formErrorsOf |
Build and group the stable validation transport shape. |
html, each, when |
Tagged templates and conditional/list composition. |
isResult, isEach, isMarkup |
Type guards for the three values the renderer understands. |
createRoot, hydrateRoot |
Create or hydrate a rendering root. |
mount, mountHydrated |
Mount component-style view functions. |
renderToString, renderToStaticString, trustedMarkup |
Hydratable server rendering, static document rendering, and explicit trusted markup. |
HydrationMismatch, HOLE_MARKER, HOLE_OPEN |
Hydration diagnostics and the pair of protocol markers. |
EVENT_PREFIX |
The attribute prefix that makes an attribute a listener rather than markup. |
defineIsland, renderIsland, hydrateIslands, createIslandManager, IslandError |
Typed island declarations, serialization, hydration, reconciliation, disposal, and failures. |
ISLAND_TAG, ISLAND_HOST_ATTRIBUTE, ISLAND_SELECTOR |
Legacy and standard-element island host protocol constants. |
countingHost, domHost, escapeHtml, SVG_NAMESPACE |
Host implementations, the escaping primitive, and the namespace SVG elements are created in. |
safeUrl, isUrlAttribute |
The value a bound URL attribute renders with: scripting schemes become an inert unsafe: URL. |
DuplicateKeyError |
Thrown when a keyed list gives two items one key. |
The view entrypoint also exports EachResult, IslandDefinition, IslandFactory,
IslandController, IslandMountContext, IslandManager, IslandManagerOptions, IslandHostTag,
RenderIslandOptions, and their related prop/instance types.
@ketvietlab/ketjs re-exports this entrypoint whole, so an application that installs both packages
may import any of these names from either one.
@ketvietlab/ketjs-view/mirror#
| API | Purpose |
|---|---|
createMirror(options) |
Create a cache with a scope, staleMs, gcMs, retry, refetchOn and structuralSharing. |
mirror.read(options) |
Observe one keyed answer: data, status, fetching, stale, previous, error, updatedAt, refetch, settled, dispose. |
mirror.pages(options) |
Observe a cursor-paged answer with more, loadingMore and loadMore. |
mirror.write(options) |
Run a write with an idempotency key, optional optimistic patch and tag invalidation; resolves to an outcome. |
mirror.invalidate, prefetch, seed, peek |
Mark entries stale, load a key now, store a held answer, read without observing. |
mirror.snapshot, restore |
Hand cached answers from a server render to the browser within one scope. |
mirror.attach(lifetime), attached, dispose |
Start loading, polling, refetch listeners and collection until the lifetime aborts. |
The entrypoint also exports Mirror, MirrorKey, MirrorStatus, MirrorOptions,
MirrorReadOptions, MirrorReading, MirrorPagesOptions, MirrorPaging, MirrorWriteOptions,
MirrorWriting, MirrorWriteOutcome, MirrorPatch, MirrorRetry, MirrorSnapshot and their
related types. @ketvietlab/ketjs does not re-export it. See
Server state with Mirror.
@ketvietlab/ketjs-view/store#
| API | Purpose |
|---|---|
defineStore(id, setup) |
Define a factory that creates one store per island instance from input and deps. |
use.state, use.derived |
Declare state the store writes and values computed from it; both are read-only outside the store. |
use.action(fn) |
Declare a write that runs in one batch, without tracking, and does nothing after dispose. |
use.task(run, options) |
Declare async work with exclusive or latest concurrency; run() resolves to an outcome. |
use.connect(fn), use.own(child) |
Declare browser wiring that runs only while attached; dispose a child with the store. |
store.attach(lifetime), dispose, snapshot |
Start wiring for one lifetime; end everything; copy top-level state as JSON. |
The entrypoint also exports Store, StoreFactory, StoreMembers, StoreScope, Task,
TaskOptions, TaskOutcome and TaskConcurrency. @ketvietlab/ketjs does not re-export it. See
Island state with stores.
TypeScript projects using automatic JSX can configure:
// File: tsconfig.json
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "@ketvietlab/ketjs-view"
}
}@ketvietlab/ketjs-postgres#
// File: src/database.ts
import { postgresAdapter, type PostgresOptions } from '@ketvietlab/ketjs-postgres'The app installs the optional postgres peer dependency and owns its connection configuration. The adapter
implements KetJS's public Adapter contract; core does not import a PostgreSQL driver.
Compatibility policy#
- Use ESM and Node.js 24.22.1 or later on 24.x, or 26.12.1 or later.
- Depend on package entrypoints, not file layout.
- Generate types from the exact composed app with
ket types. - Pin versions while KetJS remains pre-release.
ket newwrites the exact release, and overrides the@ketvietlab/ketjs-viewthat@ketvietlab/ketspecdepends on so one renderer is installed. - Review manifest and migration diffs when upgrading.
- Treat identifiers persisted in databases, queues, storage, and cookies as compatibility contracts even when TypeScript signatures still compile.
A breaking change is one after which an application that composed, migrated and passed its tests needs a change of its own: a composition that is now refused, a public name or signature removed or changed, a documented behavior changed, an HTTP contract that accepts less or answers differently, or a persisted identifier — table, column, index, queue, cookie, digest — read or written differently. Before 1.0 a minor release (0.x to 0.x+1) may contain breaking changes and lists each one in Upgrading; a patch release does not. A deprecated name keeps working for at least one minor release before it is removed, and its documentation says so. From 1.0, breaking changes wait for a major release.