boxlang-express 0.2.27
Released .
- Request helpers (
models/Request.bx, newmodels/Negotiator.bx): the parts of Express'sreqthat a ported handler reaches for first and had to be hand-rolled fromreq.headersuntil now.req.accepts()andreq.acceptsLanguages()pick from the types or languages you offer by the client'sqweights, returningfalsewhen none is acceptable.req.is()matches the request's ownContent-Type, including wildcards,+json-style suffixes and theurlencoded/multipartshorthands. The rules follow the npmnegotiatorandtype-ispackages, minus media-type parameters other thanq.req.is()returnsfalse, notnull, for a request with no body.req.xhr, andreq.subdomainswithapp.set( "subdomain offset", n ).req.baseUrl(models/Router.bx): the mount path of the router or path-scoped middleware handling the request. A mounted router had no way to learn where it was mounted, so it couldn't build a link to itself without the prefix hard-coded.- No
req.fresh/req.staleyet — they only mean something onceres.send()/res.json()set anETag, which they don't.
- Response helpers (
models/Response.bx):res.clearCookie(), plusdomainandexpiresoptions onres.cookie()— withoutdomaina cookie scoped to a parent domain could be neither set nor cleared.res.vary()adds toVaryinstead of replacing it.boxExpressCors()now uses it, so itsVary: Originno longer overwrites aVaryset earlier in the chain. A hand-written fakerespassed to the CORS middleware in a unit test needs avary()method.res.format()dispatches onAccept, setsContent-TypeandVary: Accept, and answers406when nothing matches. Pass an ordered struct ([ ... ]): a plain{ ... }has no key order to fall back on when the client has no preference.res.get(),res.append(),res.location(),res.links(),res.attachment(),res.set( { ... } )for several headers at once, and an extension shorthand forres.type( "json" ).res.append()joins values into one comma-separated line (a line each forSet-Cookie) sores.get()still returns the whole value.
- Timeouts and size limits (
models/BoxExpress.bx,models/HttpBridge.bx, newmodels/RequestWatchdog.bx; see docs/limits.md). Until now the only bounds on a request were the body parsers' own limits and the accept backlog.app.set( "requestTimeoutMs", n )answers503when a handler hasn't started its response in time;req.setTimeout( ms )changes or removes it for one request. Off by default. The handler's thread is interrupted and sends the503itself — the watchdog never writes to the response, because Undertow's exchange isn't safe to write from a second thread while the handler may be using it. The trade-off is that a handler which never blocks isn't stopped. Error-handling middleware doesn't run for a timeout; a handler that catches the interruption can checkreq.timedOut. A response that has already started (SSE, a file download) is never cut off.app.set( "maxBodySize", bytes )answers413before any handler runs, onContent-Lengthalone when there is one. Off by default, so upgrading can't start rejecting uploads. This is enforced in BoxExpress rather than with Undertow'sMAX_ENTITY_SIZE, which was tried first: it answered an oversized request with a500, or dropped the connection with no response for a chunked one, and printed a stack trace either way. A chunked body is read into memory up to the cap to measure it.headerTimeoutMsdefaults to 60 s. Before, a client that never finished sending its headers was held open indefinitely (measured against 0.2.26: still open after 75 s).maxHeaderSizedefaults to 64 KB, down from Undertow's 1 MB; a request over it gets a400. Raise it if you send unusually large headers.keepAliveTimeoutMsmakes the idle keep-alive timeout configurable. Its default, 60 s, is what Undertow already did.
- Text and raw body parsers (
models/middleware/BodyParsers.bx, newbifs/boxExpressText.bx,bifs/boxExpressRaw.bx; see docs/middleware.md):boxExpressText()puts atext/plainbody onreq.bodyas a string, decoded with the charset the request names (415for one the JVM can't decode).boxExpressRaw()puts anapplication/octet-streambody there as the exact bytes.- All four parsers take a
typeoption — the same patterns asreq.is(), an array, or a function — soboxExpressJSON( { type: [ "json", "+json" ] } )parsesapplication/vnd.api+json. With notype,json()andurlencoded()match exactly as before. - All four take a
verify( req, res, bodyBytes )option, called with the bytes as received before they're parsed; throwing answers403. This is what a webhook signature check needs: the signature covers the sender's exact bytes, which re-serializing parsed JSON doesn't reproduce, and before this the only way to see them was to skip the parser and readreq.bodyStream()by hand. - A parser now skips a request an earlier parser, or
boxExpressUpload(), already handled. The body stream can only be read once, so a second parser was reading nothing — harmless while no two parsers could match the same request, but a catch-alltype: "*/*"would have replaced a parsedreq.bodywith an empty one.
- Signed cookies (new
models/CookieSigner.bx,models/Request.bx,models/Response.bx):app.set( "cookie secret", secret ), thenres.cookie( name, value, { signed: true } )andreq.signedCookies. A cookie that fails verification reads asfalseand, like every signed cookie, is removed fromreq.cookies, so a forged value can't be read as a plain one. An array of secrets signs with the first and verifies with all, for rotation. The format iscookie-parser's, byte for byte (checked against Node's own HMAC output), so an Express app with the same secret reads these cookies and vice versa. Noj:JSON cookies. Setting a secret changes nothing for an app that doesn't sign: only values startings:are affected. - View layouts and partials (
models/Response.bx; see docs/views.md):app.set( "view layout", name )wraps everyres.render()in a layout view, which gets the rendered view asdata.body. The view runs first, so it can set a title or anything else ondatafor the layout to read.layoutin the render data (orres.locals) picks another layout for one render, orfalsefor none.partial( view, data )renders another view inline, with the caller's data plus its own. Until now every view had to include its own header and footer.layoutis now a reserved key in render data. - Access log (
models/HttpBridge.bx, newmodels/AccessLog.bx; see docs/observability.md):app.set( "log", "access" )or"json"logs each request when it's answered, with status, duration and bytes sent; a function receives the entry instead. The default (true) is unchanged — a line on arrival — which can't say how a request went, and getting status and duration meant writing logging middleware aroundres.getStatusCode(). The logged path leaves out the query string. An invalid"log"value now throws atapp.set(). The timeout log line no longer prints the query string either. - Binary WebSocket sends (
models/WebSocketConnection.bx):connection.sendBinary( bytes ), andconnection.send()sends a binary frame when handed abyte[]. A connection could receive binary messages (onBinary()) but only ever answer in text. - Cron schedules (new
models/CronExpression.bx,models/Scheduler.bx; see docs/scheduler.md):app.schedule( "0 2 * * *", callback )runs a job at clock times. Five fields or six with seconds, ranges, lists, steps, month and weekday names,@daily-style shorthands, andoptions.timezone. An interval can't say "every night at 2" — the first run lands wherever the process happened to start. Cron parsing was left out of the first scheduler on purpose as a separable feature; this is it. A cron job is driven by a one-shot timer re-armed after each run, since the gap between fire times isn't constant. A malformed expression, or one that can never fire, throws atschedule(). - Middleware for WebSocket upgrades (
models/BoxExpress.bx, newmodels/adapters/WsUpgradeMiddleware.bx; see docs/websockets.md):app.ws( path, handler, { use: [ ... ] } )runs ordinary middleware against the upgrade request. The socket opens only if they all callnext(); one that responds refuses the upgrade. The handler receives the request as a second argument and asconnection.req. Authenticating a socket used to mean re-reading the session cookie fromconnection.cookiesand looking the session up by hand. Opt-in per route rather than running theapp.use()chain, which would let an app's catch-all 404 handler answer every upgrade. - Path patterns (
models/Router.bx; see docs/routing.md): a param can carry a regex constraint (/users/:id(\d+)), share a segment with literal text or other params (/flights/:from-:to,/api/v:version,/files/:name(.+).json), and a trailing*namecaptures the rest of the path. A route that needed a numeric id had to accept anything and reject it in the handler. A segment that is only:nameis parsed as before, so/:user-idis still one param. A literal colon inside a path segment (/time/12:30) is now read as the start of a param, and a segment starting with*is a named wildcard. A wildcard or optional param is still final-segment only. - Request validation (new
models/middleware/Validate.bx,bifs/boxExpressValidate.bx; see docs/validation.md):boxExpressValidate( schema )checksreq.body,req.queryandreq.paramsbefore the handler runs, converts values to the declared types, fills defaults, and answers400listing every problem.req.validholds only the fields the schema names, so it can be passed to a model without a client slipping extra fields in. Types cover strings, numbers, booleans, email, URL, UUID, ISO dates, arrays and nested structs, with avalidatefunction for anything else. A schema with an unknown type or rule name throws at registration. - One MIME table (new
models/MimeTypes.bx):res.sendFile()andboxExpressStatic()each had their own, and they disagreed —sendFile()sent.avif,.ttf,.otf,.ogg,.mapand.webmanifestasapplication/octet-stream, static files did the same for.csvand.zip. Both now use the union, which also gains.md,.yaml/.yml,.wavand.text.