Repository navigation
Releases
Releases · simoalanne/rest-rpc
v0.8.1
v0.8.0
server:
- Add
createToolsFromRoutes(), which turns a route tree into tools shaped like MCP tools: a definition and acallfunction, to register with an MCP server or an agent framework. Tool calls run through the routes' validation and middleware without HTTP.mergeTools()merges tools into two, one that finds tools and one that calls a tool by name, so a model can use every route of a large API. (7496228)
v0.7.0
core:
isDefinedError()takes an optional second argument, a client route or tree or a route or route tree, and narrows the error to their defined errors. A caught error isunknown, soisDefinedError(error)narrows it only toRouteError, andisDefinedError(error, client.posts.create)now types itscodeanddatafor that route, or for every route of a tree. The argument is only read for its type. (c04340d)
core:
- Add
contractFromJson<typeof router>(json), which types a contract thatextractContract()wrote to JSON as the route tree it was extracted from, so it no longer needs anas unknown ascast. It throws aTypeErrorwhen the value doesn't have the shape of an extracted contract. (c04340d)
core:
- Remove the
timeoutMsclient option. A timeout is now an interceptor, which decides what the time covers, such as only the wait for the response or the body too: (f341bac)
core:
- The client passes fetch options to
fetchas its second argument when the client'sfetchOptionsor the call set any, the way the globalfetchtakes them. Options aRequestdoesn't keep, such as ones a runtime or framework adds tofetch, now reach it instead of being dropped. A customfetchreceives them too, andFetchLiketakes them as an optional second parameter. Calls without fetch options still callfetch(request). (c04340d)
core, server:
acceptandauthorizationheader parameters are left out likecontent-type, since OpenAPI ignores them. Usesecurityfor credentials.
core, server:
createOpenApiDocument()needs no options.info.titledefaults to"API"andinfo.versionto"0.0.0".info,servers,tagsandexternalDocsaccept any other fields of their OpenAPI objects, such ascontactorlicenseininfo, and copy them to the document as they are. The document's other top-level fields,security,externalDocsandx-extensions, are now copied to the document likeservers,componentsandtags. (c04340d)
core, server:
- A parameter's or response header's
descriptionanddeprecatedare set on the parameter or header itself, and response headers are markedrequiredwhen their schema requires them.
core, server:
- Every path segment is documented as a parameter, as a string when the params schema doesn't convert it, so documents without a schema converter stay valid.
core, server:
- Type the
pathof an intercepted route as always set. Client and server interceptors receive the path resolved from the route tree, also for routes that take their path from their key, soroute.pathno longer needs anundefinedcheck. (c04340d)
core, server, tanstack-query:
- Add a
defaultcondition next toimportin each package'sexports, so resolvers that don't use theimportcondition, such as some bundler plugins, find the entry points. (c04340d)
server:
implement()rejects a contract tree whose top-level keys includeuseor$contextwith a type error. The implementer's methods use those names, so such a route or group used to be replaced by the method. (c04340d)
server:
implement()requires a contract route to define its responses. A contract route without.response()has no handler to infer its response from, so its handler used to accept any value and the client typed the call asnever. Itshandler()is now a type error that says to add.response(), which can be a response without a body, such as.response({ status: 204 }). (c04340d)
server:
- A defined response or error without a headers schema sends the headers the handler and middleware set. They used to be dropped, so a
content-typeset withrespond(), or a header such ascache-controladded by middleware, was not sent on routes that define their responses. With a headers schema, its output is still what's sent, so a schema that strips unknown keys sends only the headers it declares. (c04340d)
tanstack-query:
key()returns the key that matches every query of the utils, of a group or of a route, prefix included, such asqueryClient.invalidateQueries({ queryKey: queryUtils.posts.key() }).keyis reserved, so a client tree with a route or group namedkeyis a type error.
tanstack-query:
prefixstarts every query and mutation key of the utils. Query keys hold the route and its request, so a value the client sends with every request that changes the response, such as a locale inglobalHeaders, can be added to the keys withcreateTanstackQueryUtils(client, { prefix: ["locale", locale] }).
tanstack-query:
queryOptions()andinfiniteQueryOptions()with a request are accepted byuseSuspenseQuery()anduseSuspenseInfiniteQuery(). TheirqueryFnwas typed as possiblyskipToken, which the suspense hooks reject. Options with askipTokenrequest keep that type, so the suspense hooks still reject them. (c04340d)
tanstack-query:
- Add a
prefixoption tocreateTanstackQueryUtils()and akey()util on every node of the util tree. (c04340d)
v0.6.0
core, server:
- Custom codecs take precedence over the built-in ones for every media type they match, patterns included. A codec such as
bodyCodec(/.*/, ...)now also handlesapplication/json,application/x-www-form-urlencodedandmultipart/form-data, which used to stay with the built-in codecs because they list them as strings. Within the custom codecs, a media type listed as a string is still selected before patterns. (bddf9bc)
core, server:
- Rename the client types to match the other
Clienttypes:ApiClientForis nowClientFor,ApiClientOptionsis nowCreateClientOptions, andApiClientRouteValueis nowClientRouteValue. (f150152)
core, server:
- Server-Sent Events and error responses never use body codecs, on either side. The server writes event streams without passing them through the codecs, and the client reads error bodies with the built-in codecs only, so a custom codec that matches
application/json, such as a catch-all pattern, no longer breaks defined errors. (bddf9bc)
core, server:
- Throw
BodySerializationErrorfrom the built-in codecs'serializefor a value they don't encode. It extendsTypeErrorand carries themediaTypethe value was serialized for, the value kinds the codecexpected, and the kind of value itreceived. The JSON codec still throws the errors ofJSON.stringify. (bddf9bc)
server:
- Accept
FormDatarequest bodies without a declared content type. A route whose headers schema declares nocontent-typenow decodesmultipart/form-dataas well as JSON, soroute.body(type<FormData>())works with a client that sendsFormDataand nocontent-typeheader, which Fetch sets with the generated boundary. Such routes no longer answer multipart requests with415, so a route that shouldn't takeFormDatarejects it with its body schema. (0e5ba74)
tanstack-query:
- Add a
fetchfunction to each route's TanStack Query utils that calls the underlying client route directly (aae3fd4)
v0.5.0
core:
- Show a client call's resolved response, such as
{ status: 200; body: Post; ... }, on hover in editors instead of an internalClientResponseEntrytype. (34a29eb)
core, server:
- Export the built-in body codecs from
@rest-rpc/coreand@rest-rpc/serverasjsonCodec,urlEncodedCodec,formDataCodec,textCodecandbinaryCodec, so a custom codec can call one for the values it doesn't handle. Their operations are both defined and typed with what they return, such asPromise<FormData>fromformDataCodec.deserialize(). (3d6507c)
server:
- Accept handlers that only throw, such as a stub that throws a defined
NOT_IMPLEMENTEDerror, without a return type annotation. (d3b9f08)
server:
- Re-export the rest of
@rest-rpc/coreexceptroutefrom@rest-rpc/server, so server code and its tests import only@rest-rpc/server:clientInterceptor(),extractContract()and theAbsolutePath,ApiClientFor,ApiClientRouteValue,BodyDeserializer,BodySerializer,BuiltInBodyCodec,ClientHeaders,ClientInterceptor,Contract,FetchLike,FetchOptions,IncomingBody,InferClientStreamData,ResponseOptions,RouteDefinitionandSseResponsetypes. (5deb097)
server:
- Remove
createLocalClient()and theLocalClienttype. To call an app in process with the same behavior as over HTTP, such as in tests, pass itsfetchtocreateClient(routes, { fetch: app.fetch }).createClientandApiClientOptionsare now exported from@rest-rpc/servertoo. To call one route without HTTP, usecall(). (99c0b66)
server:
- Run interceptors for
OPTIONSrequests toapp.routes, asapp.fetchdoes, so an interceptor answers CORS preflights when Bun servesapp.routeswithoutapp.fetch. Bun answered them with its own404before. A preflight no interceptor answers is sentNOT_FOUND. (b38ff78)
v0.4.0
core:
BodyValuetypes the chunks of streams a serializer returns, asReadableStream<Uint8Array>orAsyncIterable<string | Uint8Array>. Other chunks already failed when the response was sent, after its headers, and are now a type error in custom codecs. (7e3354b)
core:
- A
.response()for a status the route already defines is a type error. So is a.response()status outside 200 to 299. Before, both only threw when the route was defined. (1b88943)
core:
- An error response without a string
code, such as a proxy's error page, rejects with anErrorwhosecauseholds the response as the client received it: its status, headers, cookies and decoded body. Before, only the status was kept, in the message. (30ef141)
core:
- OpenAPI documents a defined request body as required. Before,
requestBody.requiredwas never set, so generated SDKs made every body optional. (1b88943)
core:
- OpenAPI documents array query parameters as
name[]withstyle: formandexplode: true, the way the client sends them and the server reads them. (c56f8b6)
core:
- Replace the client's
baseUrloption withoriginandmountPath, which are both optional. A browser app served from the same origin as its routes needs no options, andmountPathis the same as the server's. Outside browsers, a call withoutoriginrejects with aTypeError. A trailing slash oforiginis ignored, and anoriginwith a path throws aTypeErrorwhen the client is created. MigratebaseUrl: "https://api.example.com/api"toorigin: "https://api.example.com", mountPath: "/api". (81f58db)
core, server:
errorResponse()from@rest-rpc/serverandwriteErrorResponse()from@rest-rpc/server/nodesend the response of aRouteError, which clients decode as one, such as from a rate limit interceptor.
core, server:
- A
serializedBody()without acontent-typeheader is sent with the selected content type, on the client and the server. Before, the runtime chose one from the body, such astext/plain;charset=UTF-8for a string, which could contradict the route's content type. AFormDatabody is always sent with themultipart/form-datacontent type the runtime generates with its boundary, so the default multipart codec returns it as is instead of wrapping it inserializedBody(). (7e3354b)
core, server:
- A Fetch
Responsea handler returns is sent as it is, after middleware, without response validation or codecs, on Fetch and Node. Middleware receives it as the body of the envelopenext()resolves to, with its status, headers and cookies, and the envelope's fields are sent..response(raw())declares such a route, such as in a contract, and must be the route's only response. OpenAPI documents it as a default response..static(new Response(...))sends a clone for every request, andrespond()rejects aResponsebody. (f86a7c5)
core, server:
- A Fetch interceptor may call
next()with another request for the matched route to read, or more than once, and receives the runtime's arguments after the request, such as Cloudflare'senv, asargs. A Node interceptor sets headers on theServerResponsebefore callingnext().
core, server:
- Add interceptors: functions around everything an app or a client does for a request, for API key checks, logging, error reporting, metrics, retries or CORS. Pass them as
interceptorstocreateApp, typed withinterceptor()from@rest-rpc/server, or@rest-rpc/server/nodefor the NodecreateApp, and tocreateClient, typed withclientInterceptor(). They run first to last and see every response, error responses included. (81f58db)
core, server:
- Body codecs receive headers instead of a content type:
serialize(value, headers)gets the outgoing headers with the selectedcontent-type, anddeserialize(body, headers)the received ones, with lowercase names. Headers a codec returns withserializedBody()replace the handler's and the call's,content-typeparameters included, so a codec can add a filename tocontent-disposition. Before, a handler's headers won over them. The client chooses a request's format from itscontent-typewherever it is set, the call's overadditionalHeadersoverglobalHeaders. Before, acontent-typein either was ignored and the body sent as JSON, althoughglobalHeadersmade the route's header optional. A Node request body can be read once, and a second read rejects as on Fetch instead of returning the same body or hanging. (011d62f)
core, server:
- Content types are
content-typeheaders instead of their own concept, and a body is JSON unless that header says otherwise. A route accepts the request content types its headers schema declares and answers others with415, and the client states the content type in the call's headers. A defined response declares its content type in its headers schema, and an inferred one sends the header passed torespond()..body()and.response()take a schema, and a stream response takessse(schema). Media type records, thecontentTypeoption ofrespond(), thecontentTypeof handler arguments, client calls and results, and theBodyContent,KnownBodyContentType,MediaTypeandResponseContentDefinitiontypes are removed. AFormDatabody is always sent asmultipart/form-data, and OpenAPI reads content types from the declaredcontent-typeheader. (0699974)
core, server:
- Make server-sent events usable behind proxies and with other data formats. The client parses event streams following the SSE spec: LF, CRLF and CR line endings, an optional space after the colon, multi-line data, persisted ids and digit-only
retryvalues. Stream responses are sent withcache-control: no-cacheby default, so proxies don't cache or buffer them.sseFormat()and thesse: { format }option on the server and the client set the data format of events, JSON by default. The server'ssseoption also takeskeepAliveandinitialComment, whichrespond(stream, { sse })overrides per stream. (eb281e2)
core, server:
- On the client, they receive the Fetch
Requestand the called route, before the response is decoded.
core, server:
- On the server, they receive every request, including ones that match no route, except those a route completed with
.static()serves.routeis the matched route's definition, with its path andmeta, orundefinedwhen no route matches.next()resolves with every response,RouteErrors included, and rejects only with other thrown values, such as anErrora handler throws, which the app sends asINTERNAL_SERVER_ERRORwhen nothing catches it. A Node app also sends it when its interceptors finish without a response.
core, server:
- Params, query and headers schemas accept any object input, and header values passed to
respond(),globalHeadersandadditionalHeadersaccept any value, all sent withString()as documented. Before, their inputs had to be strings, numbers or booleans, soz.coerce.number()needed<number>to compile. A promise inglobalHeadersis awaited, like the result of a provider function.ClientHeaderValueandRequestScalarare removed, andClientHeadersisRecord<string, unknown>. (8f0be69)
server:
.static()rejects arespond()result with a promise body, which is not awaited, like it rejects a promise value. (350882a)
server:
- Interceptors'
next()rejects with every error thrown after it,RouteErrors included, with the status,dataand headers they're sent with, andNOT_FOUNDfor unmatched requests. Interceptors send errors by throwing.errorResponse()andwriteErrorResponse()take any thrown value and are what the app sends with, so an interceptor catching with them turns errors into responses for the ones before it.onError()creates an interceptor that reports errors, response bodies that fail while they stream included.createRouteHandlersandcreateCatchAllHandlertakeinterceptorstoo. (30f9ad3)
server:
- Parsed query strings are objects without a prototype, so a
__proto__[]key is an ordinary key instead of replacing the object's prototype, and fields the query doesn't contain read asundefinedinstead of inherited values such as an array'slength. (1b88943)
server:
- Remove the
onErrorroute option and thenotFoundoption of bothcreateApps. Report errors from an interceptor instead, wherenext()rejects with them, and send a custom response for unmatched requests from an interceptor, which receives noroutefor them. (aa81df2)
server:
- The Node adapter streams
Blobresponse bodies, such as fromfs.openAsBlob(), instead of reading each into memory, and sends their size ascontent-length. Static routes with aBlobbody stream it for each response too. (7e3354b)
server:
- The Node adapter streams
FormDataresponse bodies instead of reading each into memory, files included. They are sent without acontent-length. ([7e3354b](h...
v0.3.0
core:
- The client passes response bodies to codecs directly. A response body that fails while it is read now rejects like a body that cannot be decoded, with the read error as
cause. (da819aa)
core:
- The client skips event stream frames without data, such as keepalive comments, and drops an incomplete last frame, instead of ending the stream with an error. (da819aa)
core, server:
serializedBody()takes itsheadersas a plain object of header names and values instead of any FetchHeadersInit, andSerializedBody.headersis that object with lowercase names instead of a FetchHeaders. Replacenew Headers(...)or header tuples passed to it with an object, and read the headers of a serialized body asserialized.headers["content-type"]instead of withget(). (64804e5)
core, server:
- A
mountPaththat ends with a slash, such as/api/, now serves the routes like/api, instead of responding to every request with anINTERNAL_SERVER_ERROR. A.prefix()that ends with a slash is now a type error instead of a runtime error. (da819aa)
core, server:
- A body's content type now always replaces a
content-typepassed in headers. Before, a passed header could override it, including the content type and multipart boundary the runtime sets forFormData. Routes with inferred responses now typecontentTypein client results as the received lowercase base media type, such astext/csvfortext/csv; charset=utf-8. On routes with defined responses,respond()usescontentTypeas given, so a value that is not one of the defined media types throws. (da819aa)
core, server:
- Body deserializers receive an
IncomingBodyand the complete content type, asdeserialize(body, contentType), like serializers receive the content type.IncomingBodyhastext(),json(),arrayBuffer(),blob()andbody, which Fetch requests and responses already have, so codecs that only use these work unchanged. Codecs that call otherRequestorResponsemembers, such asformData(), must read the body with these instead, such asnew Response(await body.arrayBuffer(), { headers: { "content-type": contentType } }).formData(). A codec used only on one side can no longer treat its source as aRequestorResponse. (64804e5)
server:
compileRoutesis renamedcreateRouteHandlers, and its options typeCompileRoutesOptionsis renamedCreateRouteHandlersOptions.createCatchAllHandlernow takes the route tree and the same options instead of compiled routes, in both@rest-rpc/serverand@rest-rpc/server/node: replacecreateCatchAllHandler(compileRoutes(routes, options))withcreateCatchAllHandler(routes, options). (64804e5)
server:
onErrorreceives a thrown defined error as it was thrown, instead of a copy with the defined status, validateddataand headers, and the thrown error ascause. Itscauseis now the one passed when throwing, soerrors.CODE({ cause })reachesonErroraserror.cause. The response still uses the definition. Anew RouteError(code)for a code the route defines keeps its own status inonError, which defaults to 400, while the defined status is sent. Defined errors with synchronous schemas are now resolved without a promise, and errors received fromcall()and the local client have nocause, like errors received over HTTP. (64804e5)
server:
serveandServeOptionsare removed from@rest-rpc/server/node. It now exportscreateApp, which takes the route tree and returns a request listener forhttp.createServer(), so the server is started and configured with Node's own API: replaceserve(createApp(routes, options), { port })withcreateServer(createApp(routes, options)).listen(port), importingcreateAppfrom@rest-rpc/server/node. Itscontextfunction receives theIncomingMessage, andnotFoundwrites to theServerResponseand keeps the default response when it writes nothing. (64804e5)
server:
- Reject functions passed to
.static()in types, which accepted them on routes without defined responses although static values are not called. Type errors now say why a promise, function or stream is not a valid static value instead of reporting a barenever. Static routes no longer check at runtime for values that bypass the types. (05ab0d0)
server:
- Serve
createApproutes registered with Bun's native router through one promise per request instead of nested async wrappers, which lowers per-request overhead. (359e26f)
server:
- The Node handlers from
@rest-rpc/server/noderead the Node request and write the Node response directly, instead of converting them to a FetchRequestandResponse, which lowers per-request overhead.onErrorpassed to them now receives theIncomingMessageinstead of a FetchRequest. Stream responses send their headers before the first item on Node. (64804e5)
v0.2.0
core:
InferClientRequest,InferClientResponse,InferClientError, andInferClientStreamDataaccept the type of a client route function or client tree, such astypeof client.todos.get, in addition to routes. Request types inferred from a client already make headers that itsglobalHeadersprovides optional. (36640ac)
core, server:
- Add
cookiestorespond()options, middleware responses and thrown errors. Each value is sent as its ownSet-Cookieheader. Fetch client results andRouteErrors have the received values ascookiesinstead of a joinedset-cookieheader. Browsers hideSet-Cookiefromfetch, socookiesis empty there. (a3b6a2a)
core, server:
- Header names with uppercase letters are a type error in
.headers(), response and errorheadersschemas,routeError()andrespond()headers. Received header names are lowercase, so those names never matched: required request headers failed validation, optional ones were alwaysundefined, and response headers were typed but missing on the client.globalHeadersandadditionalHeadersare not checked. (a3b6a2a)
core, server:
- Path params are written only as
:name.{name}segments are no longer params, and theparamSyntaxcompile option is removed: compiled paths keep:name, and OpenAPI documents still use{name}. (9a1a7da)
core, server, tanstack-query:
- Client calls may omit a
queryorheadersobject without required fields, abodywhose schema acceptsundefinedon routes with one body media type, and a request without required fields. Before, only headers could be omitted, and only inside a passed request. TanStack Queryrequestoptions and the local client follow the same rules, and local calls receive an omittedqueryorheadersas{}, as over HTTP. (0948a36)
server:
- Add
.static(value), which completes a route with the same response for every request, serialized once when the routes are compiled. Compiled Fetch routes have it asstaticResponse, andApp.routesentries are a function or thatResponse. (dfe3e97)