# Docs - [Defjs](/): Design and publish TypeScript SDKs with reusable API definitions and application-owned clients. - Guide - [Guide](/docs): Design SDK contracts and operations, publish them, and configure execution in consuming applications. - [Calling AI APIs](/docs/ai-api): Call an AI service from an application without exposing provider credentials, and read a fictional offline event stream. - [AI-assisted development](/docs/ai): Install the Defjs skill, ask for a typed GET endpoint, and check the result against the installed SDK. - [Client configuration / Client](/docs/client): Configure how your application calls imported SDK operations, independently of their API definitions. - [Design decisions](/docs/design-decisions): How separating API definitions from client execution makes SDKs easier to design, publish, and reuse. - [Error handling](/docs/errors): Declare service error contracts in your SDK and handle typed execution failures in the consuming application. - [HTTP requests](/docs/http): Design HTTP operations for your SDK and call them with application-owned configuration and cancellation. - [Interceptors](/docs/interceptors): Apply authentication and transport policies to the application client without changing your SDK's API definitions. - [SSE event streams](/docs/sse): Export typed event-stream definitions from your SDK and let consuming applications open, consume, and close them. - [Quick start](/docs/start): Export your first SDK operation, call it from a separate application, and reuse the definition with another client. - [Data contracts / Struct](/docs/struct): Define the input and response contracts your SDK shares with its consumers, with types and runtime validation. - [WebSocket sessions](/docs/web-socket): Define your SDK's WebSocket message contract while applications own connection configuration and session lifetime. - Plugins - [Plugins](/docs/integrations): Optional packages that plug into an application-owned Defjs client. - [OpenTelemetry server](/docs/integrations/opentelemetry-server): Instrument SDK calls on the server application's client while keeping API definitions independent of telemetry setup. - [React](/docs/integrations/react): Consume a framework-independent SDK with a React-provided client and component-owned request lifetime. - [Vue](/docs/integrations/vue): Consume a framework-independent SDK with an application-provided Vue client and caller-owned cleanup. - Examples - [Examples](/recipes): Build and publish a reusable SDK, then configure authentication, calls, and realtime work in consuming applications. - [Cancellation and timeouts](/recipes/cancel-http): Abort or time out a call and read NET_ABORTED / NET_TIMEOUT. - [Consume SSE events](/recipes/consume-sse): Open a typed event stream, iterate once, then close and await closed. - [ETag conditional requests](/recipes/etag-revalidate): Treat 304 as an HTTP status fault; keep the cache Map outside the operation call. - [Handle a declared 404](/recipes/get-declared-404): Call one GET and branch on typed 200 vs declared 404. - [GraphQL requests](/recipes/graphql-http-envelope): Keep GraphQL as HTTP 200 + application unwrap; Core does not ship a GraphQL protocol. - [Send JSON](/recipes/post-json): Send a typed JSON body and decode a declared 201. - [Build and publish an SDK](/recipes/publish-http-sdk): Export API definitions as an npm package with types, and let each application configure its own client. - [Refresh a token after 401](/recipes/refresh-bearer-once): Attach Authorization and replay once inside one interceptor; next() only goes inward. - [Local HTTP tests](/recipes/test-with-handle): Swap Fetch for one client with withHTTPHandle and keep the operation unchanged. - [Manage WebSocket sessions](/recipes/websocket-session): Connect, send one typed envelope, receive once, then close and await closed. - API - [API Reference](/api): Look up SDK definition APIs, application client configuration, and typed execution results. - [Client](/api/client): createClient, option helpers, and the Client type. - [Errors](/api/errors): Fault variants and factory helpers. - [HTTP](/api/http): defineRequest, request options, and HTTP request/response types. - [Interceptors](/api/interceptors): HTTP, SSE, and WebSocket interceptor constructors. - [@defjs/opentelemetry-server](/api/opentelemetry-server): withOpenTelemetryServer and per-transport options. - [@defjs/react](/api/react): ClientProvider, useClient with an optional client override, and provider props. - [SSE](/api/sse): defineEventStream, request options, and the stream handle. - [Struct](/api/struct): struct facade, Infer, and StructError. - [@defjs/vue](/api/vue): Vue plugin, default or custom injection keys, and injectClient. - [WebSocket](/api/web-socket): defineWebSocket, session, and request options. - Core - [AnyFault](/api/core/anyfault-type): Any fault at all, whatever its decoded error-body type. - [AnyStruct](/api/core/anystruct-type): Broad struct constraint that accepts any struct, for endpoint and client generics. - [basicAuthHttpInterceptor](/api/core/basicauthhttpinterceptor): HTTP interceptor that sets an Authorization: Basic … header from credentials. - [BasicAuthInterceptorOptions](/api/core/basicauthinterceptoroptions-type): Options for basic-auth interceptors, including a custom credential encoder. - [basicAuthSSEInterceptor](/api/core/basicauthsseinterceptor): SSE interceptor that sets an Authorization: Basic … header from credentials. - [BuilderInput](/api/core/builderinput-type): Parsed endpoint input that a request builder receives. - [Client](/api/core/client-type): Client value that operations accept. - [ClientConfig](/api/core/clientconfig-type): Resolved client configuration after option helpers have been applied. - [ClientOption](/api/core/clientoption-type): Function type of the option helpers accepted by createClient. - [ClientOptions](/api/core/clientoptions-type): Input-shaped client options, including SSE and WebSocket, that mirror what the option helpers configure. - [ClientSSEConfig](/api/core/clientsseconfig-type): Resolved SSE configuration with a required fetch handle. - [ClientSSEOptions](/api/core/clientsseoptions-type): Optional SSE settings applied when creating a client: fetch handle, invalid-event hook, and reconnect policy. - [ClientWebSocketOptions](/api/core/clientwebsocketoptions-type): Optional WebSocket settings applied when creating a client: constructor, beforeConnect hook, heartbeat, protocols, and reconnect policy. - [createClient](/api/core/createclient): Creates a Defjs DerivableClient from option helpers. - [createDecodeFault](/api/core/createdecodefault): Builds a decode fault for a response that arrived but could not be read as declared. - [createHttpInterceptor](/api/core/createhttpinterceptor): Wraps an InterceptorFn as a tagged HttpInterceptor. - [createHttpStatusFault](/api/core/createhttpstatusfault): Builds an HTTP_STATUS fault for a non-2xx response whose body decoded against the declared error struct. - [createNetworkFault](/api/core/createnetworkfault): Builds a NET_* PreflightFault, choosing the code from the shape of cause. - [createPreflightFault](/api/core/createpreflightfault): Builds a fault for a failure that may have happened before any response existed. - [createResolvedRequestUrl](/api/core/createresolvedrequesturl): Resolves a relative definition path under the base endpoint's origin and directory into a URL. - [createSSEInterceptor](/api/core/createsseinterceptor): Wraps an SSEInterceptorFn as a tagged SSEInterceptor. - [createUndecodedHttpStatusFault](/api/core/createundecodedhttpstatusfault): Builds an HTTP_STATUS fault for a non-2xx response that was never decoded, because the endpoint declared no error struct. - [createWebSocketInterceptor](/api/core/createwebsocketinterceptor): Wraps a WebSocketInterceptorFn as a tagged WebSocketInterceptor. - [DecodedResponse](/api/core/decodedresponse-type): Response metadata plus a body that decoded against a declared struct. - [DecodeFault](/api/core/decodefault-type): A response arrived but could not be read as declared. - [DecodeFaultCode](/api/core/decodefaultcode-type): Codes whose fault carries response metadata but no body. - [defineEventStream](/api/core/defineeventstream): Declare a typed Server-Sent Events endpoint. - [defineRequest](/api/core/definerequest): Declares a typed HTTP request endpoint. - [defineWebSocket](/api/core/definewebsocket): Declare a typed WebSocket endpoint. - [DerivableClient](/api/core/derivableclient-type): Callable root client returned by createClient. - [ERR_ABORTED](/api/core/err-aborted-type): Shared Error sentinel that marks a request as aborted. - [ERR_TIMEOUT](/api/core/err-timeout-type): Shared Error sentinel that marks a request as timed out. - [ErrorMap](/api/core/errormap-type): Optional callback that rewrites a StructIssue message before it is stored. - [EventStreamCloseInfo](/api/core/eventstreamcloseinfo-type): How an SSE stream ended: clean EOF, abort, or an error carrying its fault code. - [EventStreamData](/api/core/eventstreamdata-type): Union of parsed SSE events inferred from an EventStructs map. - [EventStreamDefinition](/api/core/eventstreamdefinition-type): Contract that describes an SSE endpoint for defineEventStream. - [EventStreamEndpoint](/api/core/eventstreamendpoint-type): Operation returned by defineEventStream. - [EventStreamExecuteOptions](/api/core/eventstreamexecuteoptions-type): SSE field of RequestOptions. HTTP progress and WebSocket fields are ignored. - [EventStreamFaultCode](/api/core/eventstreamfaultcode-type): Fault codes an event stream can end with, drawn from the one shared FaultCode namespace. - [EventStreamHandle](/api/core/eventstreamhandle-type): Open SSE stream: iterate events, read open metadata, and close early. - [EventStreamOpenInfo](/api/core/eventstreamopeninfo-type): Metadata available once an SSE response has opened. - [EventStreamRequestShape](/api/core/eventstreamrequestshape-type): Request shape an SSE builder returns: the same fields as HttpRequestShape for method M and path P. - [EventStructs](/api/core/eventstructs-type): Map from SSE event names to the structs that decode their data. - [Fault](/api/core/fault-type): Union of every failure an operation can return, discriminated by code. - [FaultClass](/api/core/faultclass-type): Extracts the class prefix from a fault code: the segment before its first _. - [FaultCode](/api/core/faultcode-type): Every failure Defjs reports, as one closed set of codes. - [FaultOf](/api/core/faultof-type): Any failure returned by an operation, expressed by its decoded error-body type. - [FetchHandle](/api/core/fetchhandle-type): Fetch-compatible function used as an HTTP or SSE handle. - [fetchHandler](/api/core/fetchhandler): Default HTTP transport: perform httpRequest with fetch and return an HttpResponse. - [FlattenedStructError](/api/core/flattenedstructerror-type): Flat field and form error bags returned by StructError.flatten(). - [FormattedStructError](/api/core/formattedstructerror-type): Nested error tree returned by StructError.format(). - [HttpAwaitResult](/api/core/httpawaitresult-type): Await-result tuple for an HTTP call: success is [null, data, response], and failure is [fault, undefined, undefined]. - [HttpExecuteOptions](/api/core/httpexecuteoptions-type): HTTP fields read from RequestOptions for one call. - [HttpInterceptor](/api/core/httpinterceptor-type): Tagged HTTP interceptor accepted by client interceptor options. - [HttpInterceptorNext](/api/core/httpinterceptornext-type): Continuation that runs the rest of the HTTP interceptor chain, or the handler. - [HttpMeta](/api/core/httpmeta-type): Response metadata, available whenever a response reached the client. - [HttpProgressEvent](/api/core/httpprogressevent-type): Progress snapshot passed to upload and download callbacks. - [HttpProgressFn](/api/core/httpprogressfn-type): Callback invoked as request bytes are uploaded or response bytes are downloaded. - [HttpRequest](/api/core/httprequest-type): Normalized outgoing HTTP request seen by transports, handlers, interceptors, and fetchHandler after the builder runs. - [HttpRequestShape](/api/core/httprequestshape-type): Request shape an HTTP builder returns: path, query, headers, and body. - [HttpResponse](/api/core/httpresponse-type): Wire-shape HTTP response that transports produce and interceptors accept. - [HttpResponseType](/api/core/httpresponsetype-type): Representation used to read an HTTP body before struct validation. - [HttpStatusFault](/api/core/httpstatusfault-type): Fault for a non-2xx response, typed by the declared error struct. - [HttpStatusFaultOf](/api/core/httpstatusfaultof-type): Non-2xx fault expressed by its decoded body type instead of the struct that produced it. - [Infer](/api/core/infer-type): Infers the parsed output type of a struct, as an alias of the internal output brand. - [Interceptor](/api/core/interceptor-type): Any tagged interceptor accepted by client interceptor options. - [InterceptorFn](/api/core/interceptorfn-type): HTTP interceptor function: may inspect or modify the request, then call next. - [isAbortCause](/api/core/isabortcause): Whether cause is caller cancellation, across Core copies and platform abort errors. - [isTimeoutCause](/api/core/istimeoutcause): Whether cause is a timeout, across Core copies and platform timeout errors. - [makeResponse](/api/core/makeresponse): Builds an HttpResponse without a network call, for interceptors that short-circuit next and for tests. - [MakeResponseOptions](/api/core/makeresponseoptions-type): Fields accepted by makeResponse when building a synthetic HttpResponse, for example in interceptors. - [ManualSocketCloseReason](/api/core/manualsocketclosereason-type): Close code and reason recorded when a session is closed with session.close. - [ObjectStruct](/api/core/objectstruct-type): Object-shaped struct type produced by struct.object(shape). - [ParseResult](/api/core/parseresult-type): Error-first tuple returned by struct.parse. - [PreflightFault](/api/core/preflightfault-type): A failure that may have happened before any response existed. - [PreflightFaultCode](/api/core/preflightfaultcode-type): Codes whose fault may never have reached a response. - [QuerySerializer](/api/core/queryserializer-type): Serializes an encoded query object into a query string. - [RequestDefinition](/api/core/requestdefinition-type): Contract for an HTTP endpoint: method, path, optional input, and the structs that decode its bodies. - [RequestEndpoint](/api/core/requestendpoint-type): Operation returned by defineRequest. - [RequestErrorData](/api/core/requesterrordata-type): Decoded error body for the declared error struct, or undefined when none is declared. - [RequestOptions](/api/core/requestoptions-type): Flat per-call options. Each protocol reads the fields it understands and ignores the rest. - [RequestSuccessData](/api/core/requestsuccessdata-type): Decoded success body for the declared output struct, or undefined when none is declared. - [SocketAwaitResult](/api/core/socketawaitresult-type): Await-result tuple from opening a WebSocket. - [SocketLifecycleOutcome](/api/core/socketlifecycleoutcome-type): The outcome of a single connect attempt, not the final result of the session. - [SSEHandler](/api/core/ssehandler-type): Terminal next function an SSE interceptor receives; it opens an event stream for the request. - [SSEInterceptor](/api/core/sseinterceptor-type): Tagged SSE interceptor for client option lists, accepted by withInterceptors. - [SSEInterceptorFn](/api/core/sseinterceptorfn-type): SSE interceptor function: may inspect, modify, or replace the request, then call next. - [StreamAwaitResult](/api/core/streamawaitresult-type): Await-result tuple from opening an SSE stream. - [struct.any](/api/core/struct-any): Struct that accepts any value except null and undefined, without validation. - [struct.array](/api/core/struct-array): Struct that parses an array with one item struct. - [struct.arrayBuffer](/api/core/struct-arraybuffer): Struct that accepts an ArrayBuffer. - [struct.bigint](/api/core/struct-bigint): Struct that accepts a bigint or a bigint string and outputs a bigint. - [struct.blob](/api/core/struct-blob): Struct that accepts a Blob. - [struct.boolean](/api/core/struct-boolean): Struct that accepts boolean values. - [struct.date](/api/core/struct-date): Struct that accepts a Date, timestamp, or date string and outputs a Date. - [struct.discriminatedUnion](/api/core/struct-discriminatedunion): Struct that picks one object struct by the value of a tag field. - [struct.enum](/api/core/struct-enum): Struct that accepts one value from a list of strings or from the values of an object. - [struct.file](/api/core/struct-file): Struct that accepts a File. - [struct.formData](/api/core/struct-formdata): Object struct that is encoded as multipart FormData when it is the request body. - [struct.intersection](/api/core/struct-intersection): Struct that requires a value to satisfy every given struct. - [struct.literal](/api/core/struct-literal): Struct that accepts exactly one boolean, null, number, or string value. - [struct.null](/api/core/struct-null): Struct that accepts only null. - [struct.number](/api/core/struct-number): Struct that accepts number values except NaN. - [struct.object](/api/core/struct-object): Struct that parses a plain object with a fixed set of fields. - [struct.or](/api/core/struct-or): Struct that accepts a value matching any one of several structs. - [struct.parse](/api/core/struct-parse): Parses an unknown value with a struct and returns an error-first tuple. - [struct.record](/api/core/struct-record): Struct that parses an object with string keys and one value struct. - [struct.string](/api/core/struct-string): Struct that accepts string values. - [STRUCT](/api/core/struct-symbol-type): Type-only export of the internal enumerable tag key on objects produced while parsing endpoint input, used by the outbound encoder. - [struct.tuple](/api/core/struct-tuple): Struct that parses a fixed-length array with one struct per position. - [Struct](/api/core/struct-type): Public struct contract: input and output types, modifier methods, and the _struct type brand. - [struct.unknown](/api/core/struct-unknown): Struct that accepts any value except null and undefined, typed as unknown. - [struct.urlencoded](/api/core/struct-urlencoded): Object struct that is encoded as an URL-encoded form when it is the request body. - [struct](/api/core/struct): Facade object for building protocol-boundary structs and parsing values with its constructors and struct.parse. - [StructError](/api/core/structerror-type): Error returned by a failed struct parse, aggregating one or more StructIssues and their formatters. - [StructInput](/api/core/structinput-type): Type helper that extracts the accepted input type of a struct. - [StructIssue](/api/core/structissue-type): A single validation failure produced while parsing a struct. - [StructLike](/api/core/structlike-type): Minimal structural brand carried by every struct instance. - [StructMethods](/api/core/structmethods-type): Chainable modifiers available on every Struct instance. - [UseRequestConfig](/api/core/userequestconfig-type): HTTP fields of RequestOptions: progress callbacks and signal. - [UseWebSocketConfig](/api/core/usewebsocketconfig-type): WebSocket fields of RequestOptions, plus signal. - [WebSocketCloseInfo](/api/core/websocketcloseinfo-type): Logical terminal outcome of a WebSocket session. - [WebSocketConnectionInfo](/api/core/websocketconnectioninfo-type): Connection metadata for the current WebSocket generation. - [WebSocketDefinition](/api/core/websocketdefinition-type): Contract object passed to defineWebSocket. - [WebSocketEndpoint](/api/core/websocketendpoint-type): Operation returned by defineWebSocket. - [WebSocketExecuteOptions](/api/core/websocketexecuteoptions-type): WebSocket fields read from RequestOptions for one call. - [WebSocketHandle](/api/core/websockethandle-type): Minimal WebSocket instance surface used by the client transport. - [WebSocketHandleConstructor](/api/core/websockethandleconstructor-type): Constructor type accepted by withWebSocketHandle. - [WebSocketHandler](/api/core/websockethandler-type): Terminal next function a WebSocket interceptor receives; it opens a session for the request. - [WebSocketHeartbeatConfig](/api/core/websocketheartbeatconfig-type): Heartbeat ping and acknowledgement settings for a live WebSocket session. - [WebSocketIncomingData](/api/core/websocketincomingdata-type): Decoded type of a received WebSocket message. - [WebSocketInterceptor](/api/core/websocketinterceptor-type): Tagged WebSocket interceptor for client option lists, accepted by withInterceptors. - [WebSocketInterceptorFn](/api/core/websocketinterceptorfn-type): WebSocket interceptor function: may inspect, modify, or replace the request, then call next. - [WebSocketOutgoingData](/api/core/websocketoutgoingdata-type): Type accepted by WebSocket session send. - [WebSocketRequestShape](/api/core/websocketrequestshape-type): Request shape the builder of a WebSocketDefinition may return, where P is the endpoint path. - [WebSocketSession](/api/core/websocketsession-type): Typed WebSocket session: send and receive messages, observe state, and close. - [WebSocketSessionLike](/api/core/websocketsessionlike-type): Minimal WebSocket session surface that interceptors see. - [WebSocketState](/api/core/websocketstate-type): Lifecycle state of a managed WebSocket session. - [withCredentials](/api/core/withcredentials): Sets whether HTTP and SSE requests include credentials. - [withEndpoint](/api/core/withendpoint): Sets the valid absolute base URL prepended to relative request paths. - [withHeaders](/api/core/withheaders): Sets static default headers for HTTP and SSE requests built by this client. - [withHTTPHandle](/api/core/withhttphandle): Replaces the Fetch-compatible function used for HTTP requests. - [withInterceptors](/api/core/withinterceptors): Appends interceptors to the client interceptor chain. - [withQuerySerializer](/api/core/withqueryserializer): Replaces query encoding for HTTP, SSE, and WebSocket requests. - [withSSEHandle](/api/core/withssehandle): Replaces the Fetch-compatible function used to open SSE event streams. - [withSSEOnInvalidEvent](/api/core/withsseoninvalidevent): Observes SSE events that have no matching event struct or fail validation. - [withSSEReconnect](/api/core/withssereconnect): Configures automatic reconnection after an SSE stream fails. - [withWebSocketBeforeConnect](/api/core/withwebsocketbeforeconnect): Runs a hook before the initial WebSocket connect and before every reconnect. - [withWebSocketHandle](/api/core/withwebsockethandle): Replaces the WebSocket constructor used for socket connections. - [withWebSocketHeartbeat](/api/core/withwebsocketheartbeat): Enables WebSocket heartbeat messages with optional acknowledgement detection. - [withWebSocketProtocols](/api/core/withwebsocketprotocols): Sets the WebSocket subprotocols offered during the handshake. - [withWebSocketReconnect](/api/core/withwebsocketreconnect): Configures automatic reconnection when the socket closes for any reason other than a manual session.close(). - [withXSRF](/api/core/withxsrf): Enables XSRF cookie-to-header token forwarding for HTTP requests. - OpenTelemetry Server - [OpenTelemetryServerHttpOptions](/api/opentelemetry-server/opentelemetryserverhttpoptions-type): Options for the HTTP transport — the shared options with an HttpResponse in responseHook. - [OpenTelemetryServerOptions](/api/opentelemetry-server/opentelemetryserveroptions-type): Options for withOpenTelemetryServer: tracer, meter, logger, propagator, and per-transport settings. - [OpenTelemetryServerSSEOptions](/api/opentelemetry-server/opentelemetryserversseoptions-type): Options for the SSE transport — the shared options with the stream handle in responseHook. - [OpenTelemetryServerTransportOptions](/api/opentelemetry-server/opentelemetryservertransportoptions-type): Shared per-transport OpenTelemetry client options: whether the transport is enabled and its span hooks, generic over the response type. - [OpenTelemetryServerWebSocketOptions](/api/opentelemetry-server/opentelemetryserverwebsocketoptions-type): Options for the WebSocket transport — the shared options plus queryPropagation. - [withOpenTelemetryServer](/api/opentelemetry-server/withopentelemetryserver): Client option that installs outbound OpenTelemetry interceptors for HTTP, SSE, and WebSocket. - React - [ClientProvider](/api/react/clientprovider-type): Provide a Defjs client to React descendants via context. - [ClientProviderProps](/api/react/clientproviderprops-type): Props of ClientProvider: the required client and optional children. - [useClient](/api/react/useclient): React Hook that returns an explicit Defjs client or the nearest ClientProvider. - Vue - [createClientPlugin](/api/vue/createclientplugin): Create a Vue plugin that provides an existing Defjs client via HTTP_CLIENT. - [HTTP_CLIENT](/api/vue/http-client): Vue injection key for the Defjs DerivableClient provided by createClientPlugin. - [injectClient](/api/vue/injectclient): Vue composable that injects the Defjs client for a key, defaulting to HTTP_CLIENT.