Published foldkit API declarations for route.
./route
@wsagency/wseffect-foldkit · MIT · source · MIT license · WS-AGENCY-NOTICE · THIRD-PARTY-NOTICES
This entry point is published in @wsagency/wseffect-foldkit@0.1.0-rc.1. Import it from the package subpath shown below; the signatures and documentation are read from the installed package declarations.
import * as Wseffect from '@wsagency/wseffect-foldkit/route'
Exported declarations
Biparser
A bidirectional parser that can both parse URL segments into a value
and print a value back to URL segments.
export type Biparser<A> = {
parse: (segments: ReadonlyArray<string>, search?: string) => Effect.Effect<ParseResult<A>, ParseError>;
print: (value: A, state: PrintState) => Effect.Effect<PrintState, ParseError>;
};
defineRouteUnion
Declares every application Route in one object. Each key is a tag, and its
value lists the fields parsed from the URL.
The result is both a Schema and the `AppRoute` namespace. Each variant is a
callable Schema, so `AppRoute.Person` works with `mapTo` and
`parseUrlWithFallback`, while `AppRoute.Person({ personId: 42 })` constructs
a value.
Use `match` to handle every Route, `matchOrElse` to handle selected Routes
with a fallback, `guards` or `isAnyOf` to check selected tags, and `subset`
when another Schema accepts only some Routes. A subset includes only the
tags named in the call. Adding a Route to `AppRoute` does not change an
existing subset.
Routers remain separate. A Route is the parsed value; a Router describes the
URL that produces it.
A tag cannot use a name already owned by the union, such as `make`, `match`,
`matchOrElse`, `cases`, `ast`, `members`, or `subset`. TypeScript rejects
these names, and untyped calls throw an error.
export declare function defineRouteUnion<const CasesByTag extends Record<string, Schema.Struct.Fields>>(casesByTag: CasesByTag & ValidateVariantNames<CasesByTag>): RouteUnion<CasesByTag>;
ExtendableBiparser
A `Biparser` that can still be extended with `slash`. Terminal parsers
(`query`, `rest`) do not qualify, since nothing can follow them in
the path.
export type ExtendableBiparser<A> = Biparser<A> & {
readonly __terminal?: never;
readonly 'Cannot use slash after a terminal parser - nothing can follow query or rest'?: never;
};
int
Creates a parser that captures a URL segment as a named integer field.
Fails if the segment is not a valid integer.
int: <K extends string>(name: K) => Biparser<Record<K, number>>
literal
Creates a parser that matches an exact URL path segment.
literal: (segment: string) => Biparser<{}>
mapTo
Converts a `Biparser` into a `Router` by mapping parsed values to a
tagged type constructor.
The resulting `Router` can both parse URLs into tagged route values and
build URLs from route payloads.
mapTo: {
<T>(appRouteConstructor: {
make: () => T;
}): (parser: Biparser<{}>) => Router<T>;
<A, T>(appRouteConstructor: {
make: (data: A) => T;
}): (parser: Biparser<A>) => Router<T>;
}
oneOf
Combines multiple parsers, trying each in order until one matches the
entire path.
A parser only matches when it consumes every segment, so a route never
shadows a longer route that shares its prefix. When several parsers
fully match the same URL, the first one wins.
Returns a `Parser` (parse-only) since the union of different route
shapes cannot provide a single unified print function.
oneOf: <Parsers extends ReadonlyArray<ParserInput>>(...parsers: Parsers) => Parser<InferParsed<Parsers[number]>>
param
Creates a parser for a dynamic URL segment with custom parse and print functions.
param: <A>(label: string, parse: (segment: string) => Effect.Effect<A, ParseError>, print: (value: A) => string) => Biparser<A>
ParseError
Error type for route parsing failures.
Includes optional `expected`, `actual`, and `position` fields for
diagnostic context when a URL segment does not match.
export declare class ParseError extends ParseError_base<{
readonly message: string;
readonly expected?: string;
readonly actual?: string;
readonly position?: number;
}> {
}
Parser
A parse-only parser with no print/build capabilities.
Returned by `oneOf`, which combines multiple parsers whose print
types may differ and therefore cannot be unified into a single `Biparser`.
export type Parser<A> = {
parse: (segments: ReadonlyArray<string>, search?: string) => Effect.Effect<ParseResult<A>, ParseError>;
};
ParseResult
The result of parsing: a tuple of the parsed value and remaining URL segments.
export type ParseResult<A> = [A, ReadonlyArray<string>];
parseUrlWithFallback
Parses a URL against a parser, falling back to a not-found route if no
parser matches.
parseUrlWithFallback: <A, B>(parser: Parser<A>, notFoundRouteConstructor: {
make: (data: {
path: string;
}) => B;
}) => (url: Url) => A | B
query
Adds query parameter parsing to a `Biparser` using an Effect `Schema`.
Produces a `TerminalParser` that cannot be extended with `slash`,
since query parameters must appear at the end of a route definition.
query: <A, I extends Record.ReadonlyRecord<string, unknown>>(schema: Schema.Codec<A, I>) => <B extends Record<string, unknown>>(parser: Biparser<B>) => TerminalParser<B & A>
rest
Creates a parser that captures all remaining URL segments as a named
non-empty array field.
Requires at least one remaining segment. A bare prefix like `/files`
does not match; give it its own route alongside the rest route.
A rest route also matches every URL that a more specific route under
the same prefix accepts, so in `oneOf` the specific route must come
first.
Nothing can follow `rest` in the path, so the result is a
`TerminalParser`. It can still be extended with `query`.
rest: <K extends string>(name: K) => TerminalParser<Record<K, Array.NonEmptyReadonlyArray<string>>>
restString
Creates a parser that captures all remaining URL segments as a single
named string field, preserving the slashes between them.
Where `rest` yields a `NonEmptyArray` of segments, `restString` rejoins
the tail into one raw path string, so a value that itself contains both
slashes and dots, like a repository-relative file path
`documents/taxes/2024.pdf`, round-trips through the bidirectional router
as `{ path: string }` route data.
Requires at least one remaining segment. A bare prefix like `/vault`
does not match; give it its own route alongside the restString route.
A restString route also matches every URL that a more specific route under
the same prefix accepts, so in `oneOf` the specific route must come first.
Printing requires a normalized path: non-empty, with no leading,
trailing, or repeated slashes. Any other value would build a URL that
parses back differently, so printing fails instead of building it.
Nothing can follow `restString` in the path, so the result is a
`TerminalParser`. It can still be extended with `query`.
restString: <K extends string>(name: K) => TerminalParser<Record<K, string>>
root
A parser that matches the root path with no remaining segments.
Succeeds only when the URL path is exactly `/`.
root: Biparser<{}>
Router
A parser with a `build` method that can reconstruct URLs from parsed values.
Created by applying `mapTo` to a `Biparser`, binding it to a tagged
type constructor so parsed values carry a discriminant tag and URLs can be
built from tag payloads.
Routers are callable — `homeRouter()` or `personRouter({ id: 42 })` —
and also expose `.build` as an alias and `.parse` for URL matching.
export type Router<A> = BuildFn<A> & {
parse: (segments: ReadonlyArray<string>, search?: string) => Effect.Effect<ParseResult<A>, ParseError>;
build: BuildFn<A>;
};
RouteUnion
The Schema returned by `defineRouteUnion`. It has the same constructors and
helpers as `TaggedUnion`, with a Route-specific name for public signatures.
export type RouteUnion<CasesByTag extends Record<string, Schema.Struct.Fields>> = TaggedUnion<CasesByTag>;
schemaSegment
Creates a parser that captures a URL segment and decodes it through an
Effect `Schema`, producing a named field of the schema's decoded type.
Decodes the raw segment when parsing and encodes the value back when
printing, so branded ids, refined strings, and string-literal unions
round-trip through the route. The decoded type flows straight into the
route value, so a model carries `UserId` rather than a bare `string`.
The schema's encoded form must be a single URL segment string. For shapes
that span multiple segments or live in the query string, use `rest` or
`query`.
schemaSegment: <K extends string, A, I extends string>(name: K, schema: Schema.Codec<A, I>) => Biparser<Record<K, A>>
slash
Composes two `Biparser`s sequentially, combining their parsed values.
Cannot be used after a terminal parser (`query` or `rest`).
Composing with a terminal second parser yields a `TerminalParser`,
so terminality survives the composition.
slash: {
<A extends Record<string, unknown>, B extends Record<string, unknown>>(parserB: TerminalParser<A>): (parserA: ExtendableBiparser<B>) => TerminalParser<B & A>;
<A extends Record<string, unknown>, B extends Record<string, unknown>>(parserB: Biparser<A>): (parserA: ExtendableBiparser<B>) => Biparser<B & A>;
}
string
Creates a parser that captures a URL segment as a named string field.
string: <K extends string>(name: K) => Biparser<Record<K, string>>
TerminalParser
A `Biparser` that has been terminated (e.g. by `query` or `rest`)
and cannot be extended with `slash`.
export type TerminalParser<A> = Biparser<A> & {
readonly __terminal: true;
};
Transition
import { Option } from 'effect';
/** A route change: where the application was and where it is now.
* `maybePreviousRoute` is `None` on the first render (a cold load), which
* {@link isEntering} treats as an entry. Build one with {@link coldLoad}
* in `init` and with {@link make} wherever the application handles its
* ChangedUrl Message, then hand it to per-cache step functions so `init`
* and navigation share one loading policy. */
export type Transition<Route> = Readonly<{
maybePreviousRoute: Option.Option<Route>;
nextRoute: Route;
}>;
/** Builds the {@link Transition} for an in-app navigation, from the route
* the Model still holds to the route the new URL parsed to. Arguments
* read in travel order: previous first, next second. */
export declare const make: <Route>(previousRoute: Route, nextRoute: Route) => Transition<Route>;
/** Builds the {@link Transition} for a cold load (a direct visit, a
* bookmark, a reload). There is no previous route, so {@link isEntering}
* counts the transition as an entry. */
export declare const coldLoad: <Route>(nextRoute: Route) => Transition<Route>;
/** The route a transition entered, whichever route that was:
* `Some(nextRoute)` when the next route's tag differs from the previous
* route's (a cold load counts as an entry), `None` when the transition
* stayed within one route, for example between two ids of one detail
* route. Match on the result to dispatch entry Commands for many routes
* in one place. For a single named route, {@link entered} narrows to its
* tag and {@link isEntering} is the plain predicate form. */
export declare const enteredAny: <Route extends Readonly<{
_tag: string;
}>>({ maybePreviousRoute, nextRoute, }: Transition<Route>) => Option.Option<Route>;
/** The route a transition entered, narrowed to the given tag: `Some` of
* the entered route when this transition entered it, and `None`
* otherwise. The entry Command for a detail route usually needs the
* route's payload, and this returns it typed. {@link enteredAny} is the
* form that answers for every route at once. */
export declare const entered: <Route extends Readonly<{
_tag: string;
}>, Tag extends Route['_tag']>(transition: Transition<Route>, routeTag: Tag) => Option.Option<Extract<Route, {
_tag: Tag;
}>>;
/** The route a transition left, whichever route that was:
* `Some(previousRoute)` when the previous route's tag differs from the
* next route's, `None` on a cold load or when the transition stayed
* within one route. For one-shot Commands on the way out, saving a
* draft, recording that a visit ended. Things that live while a route is
* active, listeners, timers, handles, belong to a Subscription or
* ManagedResource condition on the Model instead, which also ends them
* when the route state disappears for reasons other than navigation.
* {@link exited} narrows to a single tag. */
export declare const exitedAny: <Route extends Readonly<{
_tag: string;
}>>({ maybePreviousRoute, nextRoute, }: Transition<Route>) => Option.Option<Route>;
/** The route a transition left, narrowed to the given tag: `Some` of the
* exited route when this transition left it, and `None` otherwise.
* {@link exitedAny} is the form that answers for every route at once. */
export declare const exited: <Route extends Readonly<{
_tag: string;
}>, Tag extends Route['_tag']>(transition: Transition<Route>, routeTag: Tag) => Option.Option<Extract<Route, {
_tag: Tag;
}>>;
/** Both sides of a within-route navigation: `Some` of the previous and
* next routes, narrowed to the given tag, when the transition stayed on
* that route, and `None` when it entered it, left it, or never touched
* it. A cold load stays nowhere. For reacting to payload changes within
* one route, a detail id, a search text, when the previous value
* matters; when it does not, the ChangedUrl handler already has the next
* route. There is no tagless counterpart to this the way
* {@link enteredAny} answers for {@link entered}: without a tag the two
* sides of a stay could not narrow to the same route variant together,
* so matching on one would leave the other typed as the whole union. */
export declare const stayed: <Route extends Readonly<{
_tag: string;
}>, Tag extends Route['_tag']>(transition: Transition<Route>, routeTag: Tag) => Option.Option<Readonly<{
previousRoute: Extract<Route, {
_tag: Tag;
}>;
nextRoute: Extract<Route, {
_tag: Tag;
}>;
}>>;
/** Predicate for "this transition entered the given route": the next
* route carries the tag and the previous route did not (a cold load
* counts as an entry). Navigating within the same route, for example
* between two ids of one detail route, is not an entry. The boolean
* view of {@link entered}: when the entry Command needs the route's
* payload, use that instead. The route union is inferred from the
* transition argument, so the tag is checked against the union's
* tags. */
export declare const isEntering: <Route extends Readonly<{
_tag: string;
}>, Tag extends Route['_tag']>(transition: Transition<Route>, routeTag: Tag) => boolean;