@shadow-js/dusk/server
The 298 exports of @shadow-js/dusk/server: 96 functions, 9 classes, 139 interfaces, 28 types, 25 consts and 1 component.
Everything @shadow-js/dusk/server exports, from the TSDoc of its entry point.
Functions#
absoluteUrl: A full, absolute URL for a path: the base ismetadataBasewhen given, else the origin of the request (or of the origin string or URL passed).addressKey: The key a rate limiter should use for an address.after: Runstaskafter the response has been sent.all: Passes when every guard passes, in order.any: Passes when at least one guard passes.apiHandler: Builds an API handler with validated input and a typed context.apiRoute: Defines an API route module.bindServerFn: Gives a server function the id and url the build assigned to it.buildCsp: Builds the header value.cacheData: Caches the result of an async function under a key, for the handler of the current request.cachedFetch: Fetches a public GET URL through the data cache (see the file comment).cacheTags: Tags the page that is being rendered, so a later revalidateTag with one of the tags discards it.chainHead: The head tags and JSON-LD blocks of a resolved chain.chainRoutesOf: The routes of a rendered chain that the metadata reads, outermost first, from matches and their specs.checkCsrf: Decides whether a request may change state.checkFraming: Checks the headers that frame the body.checkRedirectTarget: Validates a redirect target and returns the string to put inLocation, or the error that explains why it is not allowed.compileHostRules: Compiles host patterns into a predicate.createCookieSigner: Creates a signer.createDataCache: Creates a data cache over a store.createEventLog: Creates a bounded event log.createFetch: Wraps a handler as the{ fetch(request, env, ctx) }module that Workers, Vercel and Netlify expect.createHandler: Creates the request handler: the singlefetch(Request) => Responsecontract that adapters, the dev server, the test client and prerendering all call.createKey: Creates a typed key forevent.set/event.get.createKeyValueCacheStore: A CacheStore over a Redis-like client.createKvCacheStore: The ISR page cache over a KV store.createKvRateLimitStore: Token buckets over a KV store.createKvSessionStore: Sessions over a KV store.createMemoryCacheStore: An in-process cache store: a Map kept in least-recently-used order, bounded bymaxEntries.createMemoryKVStore: The in-process store: a bounded least-recently-used table of JSON text.createMemoryRateLimitStore: A bounded in-memory store: at mostmaxKeysbuckets, least recently used evicted first, so a flood of distinct keys cannot grow memory.createMemorySessionStore: An in-memory session store for development and single-process servers.createRateLimiter: Creates a rate limiter.createSessionManager: Creates a session manager: signed id cookie, server-side data, idle and absolute lifetimes, periodic id rotation, explicitregenerate()against fixation.defaultCspDirectives: The strict defaults: same-origin everything, scripts only from this origin or with the nonce, no plugins, no framing, no foreign form targets.defineEnv: Describes the environment of the app.defineGuard: Identity helper that types a reusable guard.defineLocals: Declares a typed group of locals with defaults.draftMode: Whether draft mode is on for the current request (its cookie verifies with the secret).encodeFrame: Encodes one frame the server sends: a single final frame, unmasked, with the shortest length encoding.executeServerFn: Runs a server function definition: validation, middleware, then the handler.fail: Makes a failure result.file: A file answer: the bytes (or aBlob) with the headers a download needs, and the conditional and range requests answered from the request.formatSseEvent: Formats one event as the bytes of the stream:retry,id,event, then onedataline per line of the payload, then the blank line that ends the event.formToObject: Converts form data to a plain object.geoOf: The geo a platform reported for a request.getLocals: The locals of the request being handled.getRequestEvent: The event of the request being handled.html: An HTML response (text/html; charset=utf-8).isFailure: True for a value fail made (or one that has its shape, after the wire).isJsonContentType: True when aContent-Typeheader names JSON (application/json,application/*+json).isStandardSchema: True whenvaluehas the Standard Schema shape.json: A JSON response.limitBody: Returns a request whose body errors with BodyTooLargeError as soon as more thanmaxBodyByteshave been read.manifestJson: The text of a web app manifest: compact JSON (as Next writes it) with the display mode and every address checked.manifestRoute: An API route handler that serves the web app manifest.mergeHandlerOptions: Merges the handler options of the file (baked) with the entry's (user).normalizeIp: Normalizes an IP address: IPv4 stays as is, IPv6 is written in full lower-case groups, and an IPv4-mapped IPv6 address (::ffff:1.2.3.4) becomes the IPv4 address.normalizeOrigins: Normalizes origins toscheme://host[:port]form.parseCookies: Parses aCookieheader.parseJsonSafe: Parses JSON from untrusted input and rejects what could pollute a prototype later: a__proto__key anywhere, aconstructororprototypekey holding an object, and nesting deeper than 64 levels.platformHost: Builds the host object passed tohandler.fetch.readFormLimited: Reads amultipart/form-dataorapplication/x-www-form-urlencodedbody and checks its entries against the form caps: the number of fields and of files, the size of a file, the size of a text field and the total of the text fields.readJson: Reads and parses a JSON request body safely (see parseJsonSafe).readJsonLimited: Reads and parses a JSON request body safely (see parseJsonSafe), never more thanmaxBytes.readTextLimited: Reads a request body as text, never more thanmaxBytes(a smaller limit than the handler's, for endpoints that accept less).resolveChain: Resolves a matched chain, outermost route first.resolveClientAddress: Chooses the client address.resolveRedirectTarget: Like checkRedirectTarget, but throws.revalidatePath: Discards the cached page at a path, so the next request renders it again.revalidateTag: Discards every cached page indexed under a tag.rewrite: Returns a rewrite answer for middleware:return rewrite("/internal/path").robotsRoute: An API route handler that servesrobots.txt.robotsTxt: The text ofrobots.txt, written as Next writes it:User-Agentlines, the rules, a blank line after each group, then theHostline and oneSitemapline per file.runtimeEnvironment: The environment of a runtime that has noprocess.envof its own (Deno-based edge runtimes):Deno.envwhen it exists, elseprocess.env, elseundefined.runWithEvent: Runscallbackwitheventas the current request event.safeImageFetch: Creates afetchthat only connects to addressesrefuseallows.secureHeaderEntries: The headers added to every response, as name-value pairs, for the given options.serializeCookie: Builds aSet-Cookievalue.serverFn: Defines a server function.serverOptionsFromConfig: The handler options a baked configuration stands for.setFlash: Sets a value that the next page shows once, read withuseFlash()on the page.sharpProcessor: A processor that resizes and converts raster images withsharp.signIn: Signs a visitor in: gives the session a new id first, then storesvaluesin it.sitemapIndexRoute: An API route handler that serves the sitemap index of several sitemaps.sitemapIndexXml: The index file of several sitemaps (generateSitemaps): one<sitemap>per file, laid out likesitemapXml.sitemapRoute: An API route handler that servessitemap.xmlfrom a function of the request event.sitemapXml: The XML of one sitemap file, written as Next writes it: one element per line, the namespaces in Next's order, a final newline.text: A plain text response (text/plain; charset=utf-8).timing: Measuresfnundernamefor the request that is running (getRequestEvent().timing.measure): the same asevent.timing.measure, for code that has no event at hand.tryGetRequestEvent: The event of the request being handled, orundefinedoutside a request or where the runtime has noAsyncLocalStorage.useRequestLocals: Same as getLocals, named for use inside a loader or a server function body.validate: Validatesvaluewith a Standard Schema.validateRouting: Validates the declarative routing and compiles every pattern.waitUntil: Keepspromiserunning after the response is sent.xmlEscape: XML text escaping for element content and attribute values.
Classes#
BodyTooLargeError: Thrown while a request body is read when it grows past the limit.DuskError: Error with a stable diagnostic code, for conditions the caller can fix.EnvError: Thrown at startup when the environment does not match its schema.FrameReader: Reads the frames a peer sends.RedirectBlockedError: Thrown when a redirect target is not allowed (an open-redirect attempt or a misconfiguration).RequestTimeoutError: Thrown by the handler when the request outlives its time budget.SseOverflowError: A consumer fell so far behind that the stream was closed.ValidationError: Thrown when input does not pass its schema.WebSocketProtocolError: A protocol violation: the connection is closed withcode.
Interfaces#
AbsoluteUrlOptions: Options of absoluteUrl.ActionFailure: A failure returned by a server function with fail: the call succeeded and answers with a status and data (typically field problems) for the page to show.ApiContext: What a validated API handler receives.ApiHandlerOptions: Options of apiHandler.ApiModule: The module of an API route: HTTP-method exports and no default export.BakedServerConfig: The server part of the configuration.BooleanField: A boolean variable:true/false,1/0,yes/no,on/off.BucketSpec: Parameters of one token bucket.CacheDataOptions: Options ofcacheData.CachedFetchInit: The parts ofRequestInitthatcachedFetchaccepts (no body, no credentials).CachedFetchOptions: Options ofcachedFetch: the same lifetimes and tags.CacheEntry: One cached page.CacheLifeProfile: The three lifetimes of a profile, in seconds.CacheOptions: Handler options of the cache.CacheStore: The storage interface of the ISR cache.ChainContext: Request values the generator functions receive.ChainRoute: Exports of one matched route that the metadata API reads.ContextKey: A typed key of the per-request context.CookieJar: The cookies of one request: what arrived and what to send back.CookieOptions: Attributes of a cookie.CookieSigner: Signs and verifies cookie values with HMAC-SHA-256.CorsOptions: Options ofsecurity.cors.CounterLike: A counter, with the OpenTelemetryCounter.addsignature.CreateFetchOptions: Options of createFetch.CspOptions: Options of the Content-Security-Policy builder.CsrfContext: Inputs of checkCsrf that do not come from the request.CsrfDecision: Result of checkCsrf.CsrfOptions: Options of the CSRF check.DataCache: The data cache of one handler.DataCacheOptions: Options of createDataCache.DefinedLocals: A typed set of locals with defaults.DocumentAttributes: Attributes of the<html>element.DocumentOptions: Options of the generated document.DuskFeature: A feature object.DuskHandler: What createHandler returns: the Handler plus the validated environment and the SPA shell used by@shadow-js/dusk/static.DuskLocals: Request-scoped values that middleware, guards, loaders and server functions share.DuskRuntimeManifest: The runtime manifest the build emits for the server entry.EnumField: A variable that is one of a fixed set.EnvIssue: One invalid variable.EnvOptions: Options of defineEnv.EnvSchema: A validated environment description.ErrorBody: Context the helpers of the server use to describe a thrown value.ErrorInfo: Context of a reported error.EventLog: A bounded log of sent events, for replaying what a reconnecting client missed.EventTiming:event.timing: records your own metrics for theServer-Timingheader and for theonTimingshook.FetchModule: The module shape a platform expects: a Webfetch.FileOptions: Options of file.FramingProblem: A problem with the framing headers of a request, with the status to answer.GeoInfo: Where the visitor is, as the platform reports it.Handler: The fetch handler: the single contract every adapter bridges to.HandlerOptions: Options of createHandler.HistogramLike: A histogram, with the OpenTelemetryHistogram.recordsignature.ImageProcessor: Turns a source into the requested width, quality and format.ImageProcessorInput: What a processor is asked to do.ImagesOptions: Options of the image endpoint.ImageSource: An image as the optimizer holds it.InstrumentationModule: The modulesrc/instrumentation.tsexports.KeyValueCacheStoreOptions: Options of createKeyValueCacheStore.KeyValueClient: The subset of a Redis-like client the key-value adapter uses.KvCacheStoreOptions: Options of createKvCacheStore.KVListOptions: Options oflist.KVListPage: One page of keys.KVStore: The key-value store.KVWriteOptions: Options ofsetandincrement.LimitsOptions: Limits applied before any application code runs.LoggedEvent: One event kept by an EventLog.Manifest: The web app manifest.ManifestIcon: An icon of the web app manifest.MemoryCacheStoreOptions: Options of createMemoryCacheStore.MemoryKVStoreOptions: Options of createMemoryKVStore.MemoryRateLimitStoreOptions: Options of createMemoryRateLimitStore.MemorySessionStoreOptions: Options of createMemorySessionStore.MessageWebSocketInput: Message events supplied by a native WebSocket runtime.MessageWebSocketSink: A runtime that exposes complete WebSocket messages and owns their framing.MetadataResponseOptions: Options of the response helpers.MetricsLike: The subset of the OpenTelemetry MetricsMeterthat Dusk uses: passmetrics.getMeter("my-app")of@opentelemetry/api, or any object with the two methods.MiddlewareModule: A module of server middleware that is loaded on demand.NumberField: A numeric variable.ParsedEnv: The validated variables.PlatformInit: What a platform adds to a request.RateLimitDecision: Result of taking tokens from a bucket.RateLimiter: A token-bucket rate limiter.RateLimiterOptions: Options of createRateLimiter.RateLimitMiddlewareOptions: Options of the rate limit middleware.RateLimitStore: Where bucket state lives.RedirectPolicy: What decides which redirects are allowed.RequestErrorContext: WhatonRequestandonRequestErrorlearn about the request.RequestEvent: The state of one request.RequestTimings: What theonTimingshook learns about one finished request.ResolvedAddress: One resolved address.ResolvedChain: The merged result of a chain.RewriteOptions: Options of rewrite.RobotsConfig: The robots file.RobotsRule: One robots group: the agents it applies to, and its rules.RouteInfo: Which kind of route answered a request.RouteMiddlewareManifest: The server-only middleware of the routes, as the build emits it.RouteRule: The settings of one route rule.RoutingConfig: The whole declarative routing.SafeImageFetchOptions: Options of safeImageFetch.SecureHeadersOptions: Options of the secure response headers.SecurityOptions: Security settings.ServerFn: A server function: callable on the server like a normal async function, and callable from the client through the RPC endpoint once the build registers it.ServerFnCallOptions: Options of one server function call.ServerFnContext: What a server function middleware receives: the request event and the (validated) input.ServerFnDefinition: A server function as the build output registers it.ServerFnOptions: Options of serverFn.ServerFnRateLimit: // Kept apart fromrate-limit.tsso that defining a server function does not pull the limiter (and the address // parser it uses) into a bundle that only callsserverFn.ServerTimingOptions: TheserverTimingoption as an object.Session: The session of one request.SessionManager: Loads sessions and saves them after the request.SessionOptions: Options of createSessionManager.SessionRecord: What a store keeps for one session.SessionStore: Where sessions live.SharpProcessorOptions: Options of sharpProcessor.SitemapEntry: One URL of a sitemap.SitemapImage: An image of a sitemap entry (Google's image extension).SitemapIndexEntry: One sitemap of a site with several (generateSitemaps).SitemapVideo: A video of a sitemap entry (Google's video extension).SpanLike: A span, with the OpenTelemetry method names.SseMessage: One event to send.SseStream: What a stream handler gets: the way to send, the request'sLast-Event-ID, and the signal that aborts when the client disconnects or the stream is closed.StandardSchemaV1: The Standard Schema v1 interface (https://standardschema.dev), inlined so that Zod, Valibot, ArkType and any other conforming library work without a dependency on any of them.StandardSchemaV1Issue: One problem found by a schema.StandardSchemaV1Props: The~standardmember of a StandardSchemaV1.StreamingServerFnOptions: Options of an AsyncIterable server function; streaming excludes forms, batches and cached answers.StreamModule: The handlers a stream route module exports:SSE(server-sent events) andWS(WebSocket).StreamOptions: Limits of the stream routes.StringField: A text variable.TracerLike: A tracer with the OpenTelemetrystartActiveSpanshape.TrustProxyOptions: How the client address is derived.UrlField: A URL variable; the value is the normalized href.ValidationIssue: One validation issue as sent to the client.WaitUntilContext: The execution context of a Workers-stylefetch(request, env, ctx).WebSocketConnection: One open connection, as the handlers see it.WebSocketHandlers: The handlers of a WebSocket route.WebSocketInput: What the transport feeds to a connection.WebSocketLimits: Limits of a connection.WebSocketModule: The stream module a route file exportsWSfrom: the handlers, as `export const WS = { ...WebSocketSink: Where the connection writes its frames: the transport of the runtime.
Types#
ApiHandler: A handler of one HTTP method of an API route.ApiResult: What an API route handler may return.AppComponent: The root component of the app.CacheControlOption: The option, as written.CacheLifePreset: The built-in profile names.ChainErrorHandler: Called with an error a metadata function threw, and the route it belongs to.ChangeFrequency:changefreqvalues of the sitemap protocol.CsrfReason: Why a request was accepted or rejected.EnvField: A variable description.EnvShape: Variable name to description.EnvSource: Where variables are read from.ErrorPhase: Where an error was caught.FeatureName: The names of the features.FormLimitsOptions: The caps a form read is held to: the app'ssecurity.limits.form, then the route's overrides.GeoPlatform: The platforms whose geo the adapter entries read (see geoOf).Guard: A guard: a check that runs before a server function's input is validated or its handler runs, and before an API route method's body is read.HttpMethod: HTTP methods the handler dispatches.InferInput: The input type of a schema.InferOutput: The output type of a schema.Middleware: Middleware: runs around the rest of the request.Next: Continues the middleware chain.ServerFnMiddleware: Middleware of a server function.ServerFnRateLimitOption: WhatserverFn({ rateLimit })accepts: a limiter, or a limiter with a caller key and a cost.SharpFactory: Creates an instance from the encoded bytes of an image.SseHandler: A stream route's handler: `export function SSE(event, stream) { ...StandardSchemaV1Result: Result of validating: a value, or issues.UpgradeDecision: The answer to a WebSocket upgrade: refused with a response, or accepted.WsEvent: One thing a client sent.
Constants#
CACHE_LIFE_PRESETS: The built-in profiles.COOKIE_LIMITS: Limits of the cookie code.DEFAULT_LIMITS: Default limits.DEPLOYMENT_HEADER: The request header that carries the client's deployment id.DEPLOYMENT_MISMATCH: The error code of a refused call.hasAsyncContext: True when this runtime can track the request event acrossawait.ISSUE_LIMITS: Limits on the validation issues sent to a client.JSON_LIMITS: Limits of the JSON helpers.MAX_CSP_LENGTH: Longest header the builder accepts, in characters.MAX_SITEMAP_ALTERNATES: Most language alternates one sitemap URL may list.MAX_SITEMAP_BYTES: Largest sitemap file in UTF-8 bytes (the protocol's limit, 50 MiB).MAX_SITEMAP_IMAGES: Most images one sitemap URL may list (Google's limit).MAX_SITEMAP_TEXT: Longest title, caption, description, tag or language code, in characters.MAX_SITEMAP_URLS: Largest sitemap a single file may hold (the protocol's limit).MAX_SITEMAP_VIDEO_TAGS: Most<video:tag>elements one video may list (Google's limit).MAX_VIDEO_DURATION: Longest video duration in seconds (Google's limit, 8 hours).MIN_SECRET_LENGTH: Shortest accepted signing secret, in characters.NONCE_TOKEN: Token to write where the per-request nonce goes:"{nonce}".NOOP_TRACER: The tracer when none is given: it runs the work and records nothing.passthroughProcessor: Never transforms: every request gets the source as it is.ROUTER_PAYLOAD_ID: Id of the element that carries the router's hydration data.RPC_HEADER: The request header every client call must send.RPC_PREFIX: Path (below the base) under which server functions are served.svgProcessor: SVG is a vector format: the source is served as it is at any width.WS_CLOSE: Close codes the server uses (RFC 6455 section 7.4.1).
components#
DEFAULT_PERMISSIONS_POLICY: DefaultPermissions-Policy: powerful features off unless the app opts in.