# Middleware API URL: /runtime/api/middleware # Middleware API [#middleware-api] `defineMiddleware` wraps description, evaluation, view rendering, and exports. Hooks compose through an onion pipeline without owning the kernel's native handle. ## Types [#types] **`KernelMiddleware`** — Middleware lifecycle hooks and declaration maps for the v2 runtime. - **`name`** (`string`, required) - **`version`** (`string`, required) - **`enabled`** (`boolean | undefined`, optional) - **`mutates`** (`boolean | undefined`, optional) - **`content`** (`Content | undefined`, optional) - **`stateSchema`** (`StateSchema | undefined`, optional) - **`optionsSchema`** (`OptionsSchema | undefined`, optional) - **`resolve`** (`MiddlewareResolveHook> | undefined`, optional) - **`wrapDescribe`** (`WrapDescribeHook, z.core.output> | undefined`, optional) - **`wrapEvaluate`** (`WrapEvaluateHook, z.core.output> | undefined`, optional) - **`wrapRender`** (`WrapRenderHook, z.core.output, ViewContentKeys> | undefined`, optional) - **`wrapExport`** (`WrapExportHook, z.core.output, ExportContentKeys> | undefined`, optional) **`MiddlewareState`** — State retained for one middleware operation and validated on update. - **`value`** (`_PartialDeep`, required) — Current state value. Type is PartialDeep since update() may be called with partial data or not called at all. - **`update`** (`(partial: Partial) => void`, required) — Update the state with partial data. Values are validated against the Zod schema before being merged. Tags: @param partial - Partial data to merge into the state **`KernelMiddlewareServices`** — Operation-scoped services and typed middleware state. - **`signal`** (`AbortSignal`, required) - **`tracer`** (`RuntimeSpanTracer`, required) - **`logger`** (`RuntimeLogger`, required) - **`filesystem`** (`KernelFileSystem`, required) - **`compute`** (`KernelComputeCapability`, required) - **`state`** (`MiddlewareState`, required) - **`options`** (`Options`, required) - **`dependencies`** (`readonly Dependency[]`, required) - **`dependencyHash`** (`string`, required) **`MiddlewareDependencyServices`** — Services available during middleware dependency resolution. - **`signal`** (`AbortSignal`, required) - **`logger`** (`RuntimeLogger`, required) - **`filesystem`** (`KernelFileSystem`, required) - **`options`** (`Options`, required) **`MiddlewarePlugin`** — Registration object for a middleware plugin. Returned by factory functions like `parameterCache()`. - **`permissions`** (`RuntimePluginPermissions | undefined`, optional) — Declarative review metadata; runtime execution does not enforce these permissions. - **`id`** (`Id`, required) — Unique identifier for this middleware - **`options`** (`Record | undefined`, optional) — Middleware-specific options **`MiddlewareDependency`** — File whose changes affect selected middleware operations. - **`path`** (`string`, required) - **`affects`** (`readonly ("describe" | "evaluate" | "render" | "export")[]`, required) - **`watchDebounce`** (`number | undefined`, optional) **`EvaluateRequest`** — Evaluation request independent of any selected view. - **`entryPath`** (`string`, required) - **`parameters`** (`Record`, required) - **`options`** (`Record | undefined`, optional) **`RenderRequest`** — Request for one rendered view and its selected media type. - **`view`** (`({ view: string; mimeType: MediaType; instance?: string; options: Record; } & ContentHookInputFor)["view"]`, required) - **`mimeType`** (`({ view: string; mimeType: MediaType; instance?: string; options: Record; } & ContentHookInputFor)["mimeType"]`, required) - **`instance`** (`({ view: string; mimeType: MediaType; instance?: string; options: Record; } & ContentHookInputFor)["instance"] | undefined`, optional) - **`options`** (`({ view: string; mimeType: MediaType; instance?: string; options: Record; } & ContentHookInputFor)["options"]`, required) **`ExportRequest`** — Request for one export and its selected extension and media type. - **`exportId`** (`({ exportId: string; mimeType: MediaType; extension: string; options: Record; } & ContentHookInputFor)["exportId"]`, required) - **`mimeType`** (`({ exportId: string; mimeType: MediaType; extension: string; options: Record; } & ContentHookInputFor)["mimeType"]`, required) - **`extension`** (`({ exportId: string; mimeType: MediaType; extension: string; options: Record; } & ContentHookInputFor)["extension"]`, required) - **`options`** (`({ exportId: string; mimeType: MediaType; extension: string; options: Record; } & ContentHookInputFor)["options"]`, required) ## defineMiddleware [#definemiddleware] Calling its `MiddlewarePluginFactory` yields serializable registration metadata and a private executable definition. `WrapDescribeHook`, `WrapEvaluateHook`, `WrapRenderHook`, and `WrapExportHook` receive `(input, next, services)`. Await `next(input)` to continue; return the corresponding hook result. Evaluation is independent of views. Render requests identify a view, MIME type, and optional instance. Export requests identify an export, extension, and MIME type. State and options schemas infer parsed output on services; do not forward unparsed caller options. Middleware participates in cache identity. A pure telemetry tap may declare `mutates: false`, return successful results unchanged, and declare no dependencies. Other middleware is assumed to mutate results. ## Content [#content] `MiddlewareContent` declares view MIME types and export extensions. `ViewContentKeys`/`ExportContentKeys` extract supported keys; `ViewContentMap`/`ExportContentMap` preserve per-route inference. Hooks receive only selected-route content. A provider cannot add content support to unrelated media/routes. ## Dependencies and Cancellation [#dependencies-and-cancellation] `MiddlewareResolveHook` returns `MiddlewareDependency` records with canonical root-relative paths and explicit `affects` operations. Missing files remain unresolved dependencies so their creation can heal the model. Other filesystem failures propagate. Middleware never registers watchers imperatively. Each hook receives a fresh operation-scoped `signal`; pass it to cancellable APIs and release operation state on settlement. ### Usage [#usage] ```typescript import { defineMiddleware } from '@taucad/runtime/middleware'; export const settingsFiles = defineMiddleware({ id: 'settings', name: 'settings', resolve({ entryPath }) { return [{ path: `.tau/settings/${entryPath}.json`, affects: ['evaluate'], watchDebounce: 0 }]; }, }); ``` ## Factories [#factories] `@taucad/middleware` provides `middleware()` presets (`default`, `cache`, `units`) and role factories: `parameterFileResolver()`, `parameterUnits()`, `geometryCache()`, `gltfEdgeDetection()`. Compose them in the worker-owned runtime definition. `describeResultSchema` validates a middleware description result at an untyped boundary. ## Related [#related] * [Use Middleware](/runtime/guides/using-middleware) * [Create Custom Middleware](/runtime/guides/custom-middleware) * [Cooperate with Cancellation](/runtime/guides/cooperate-with-cancellation) * [Middleware Model](/runtime/concepts/middleware-model)