@onrails/pattern 0.3.2 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assert.d.cts +24 -0
- package/dist/assert.d.ts +24 -0
- package/dist/exhaustive.d.cts +23 -0
- package/dist/exhaustive.d.ts +23 -0
- package/dist/index.cjs +10 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -329
- package/dist/index.d.ts +6 -329
- package/dist/index.js +10 -12
- package/dist/index.js.map +1 -1
- package/dist/match.d.cts +247 -0
- package/dist/match.d.ts +247 -0
- package/dist/narrow.d.cts +7 -0
- package/dist/narrow.d.ts +7 -0
- package/dist/tag.d.cts +2 -3
- package/dist/tag.d.ts +2 -3
- package/dist/when.d.cts +26 -0
- package/dist/when.d.ts +26 -0
- package/package.json +19 -9
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Use in `default` branches (or after manual narrowing) to assert a union has
|
|
3
|
+
* been fully handled. If every case is handled, `value` is `never` and the call
|
|
4
|
+
* type-checks; an unhandled case makes `value` non-`never`, surfacing a compile
|
|
5
|
+
* error. Always throws at runtime.
|
|
6
|
+
*
|
|
7
|
+
* @param value - the value that should be unreachable (typed `never`)
|
|
8
|
+
* @param message - error message prefix; defaults to `"Unreachable"`
|
|
9
|
+
* @throws always — the branch is meant to be unreachable
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };
|
|
14
|
+
*
|
|
15
|
+
* function area(shape: Shape): number {
|
|
16
|
+
* switch (shape.kind) {
|
|
17
|
+
* case "circle": return Math.PI * shape.r ** 2;
|
|
18
|
+
* case "square": return shape.s ** 2;
|
|
19
|
+
* default: return assertNever(shape); // type error if a case is added
|
|
20
|
+
* }
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare const assertNever: (value: never, message?: string) => never;
|
package/dist/assert.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Use in `default` branches (or after manual narrowing) to assert a union has
|
|
3
|
+
* been fully handled. If every case is handled, `value` is `never` and the call
|
|
4
|
+
* type-checks; an unhandled case makes `value` non-`never`, surfacing a compile
|
|
5
|
+
* error. Always throws at runtime.
|
|
6
|
+
*
|
|
7
|
+
* @param value - the value that should be unreachable (typed `never`)
|
|
8
|
+
* @param message - error message prefix; defaults to `"Unreachable"`
|
|
9
|
+
* @throws always — the branch is meant to be unreachable
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };
|
|
14
|
+
*
|
|
15
|
+
* function area(shape: Shape): number {
|
|
16
|
+
* switch (shape.kind) {
|
|
17
|
+
* case "circle": return Math.PI * shape.r ** 2;
|
|
18
|
+
* case "square": return shape.s ** 2;
|
|
19
|
+
* default: return assertNever(shape); // type error if a case is added
|
|
20
|
+
* }
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare const assertNever: (value: never, message?: string) => never;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { GuardTarget } from "./narrow.js";
|
|
2
|
+
/**
|
|
3
|
+
* Union members of `T` ruled out by pattern `P`.
|
|
4
|
+
* Boolean guards (non-predicates) do not advance exhaustiveness — use `when(isX)` or `.otherwise()`.
|
|
5
|
+
*/
|
|
6
|
+
export type ExhaustMatched<T, P> = P extends (input: T) => boolean ? [GuardTarget<P>] extends [never] ? never : Extract<T, GuardTarget<P>> : Extract<T, P>;
|
|
7
|
+
/** Union of cases already handled by prior branches. */
|
|
8
|
+
export type HandledUnion<Handled extends readonly unknown[]> = Handled[number];
|
|
9
|
+
/** Input cases not yet covered by `.with` / `.withOneOf` / `.withEither`. */
|
|
10
|
+
export type RemainingCases<T, Handled extends readonly unknown[]> = Exclude<T, HandledUnion<Handled>>;
|
|
11
|
+
/** `true` when every member of `T` appears in `Handled`, otherwise `false`. */
|
|
12
|
+
export type IsExhaustive<T, Handled extends readonly unknown[]> = [
|
|
13
|
+
RemainingCases<T, Handled>
|
|
14
|
+
] extends [never] ? true : false;
|
|
15
|
+
/** `.exhaustive()` shape: the value `R` when an input was given, else a `(input: T) => R` matcher. */
|
|
16
|
+
export type ExhaustiveOutput<R, HasInput extends boolean, T> = HasInput extends true ? R : (input: T) => R;
|
|
17
|
+
/** Returned by `.exhaustive()` when union cases are still missing (compile-time error). */
|
|
18
|
+
export type NonExhaustiveError<Remaining> = {
|
|
19
|
+
readonly __nonExhaustive: "Add .with() branches for remaining cases";
|
|
20
|
+
readonly remaining: Remaining;
|
|
21
|
+
};
|
|
22
|
+
/** `.exhaustive()` return type — `NonExhaustiveError` when cases are missing. */
|
|
23
|
+
export type ExhaustiveResult<T, Handled extends readonly unknown[], R, HasInput extends boolean> = IsExhaustive<T, Handled> extends true ? ExhaustiveOutput<R, HasInput, T> : NonExhaustiveError<RemainingCases<T, Handled>>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { GuardTarget } from "./narrow.js";
|
|
2
|
+
/**
|
|
3
|
+
* Union members of `T` ruled out by pattern `P`.
|
|
4
|
+
* Boolean guards (non-predicates) do not advance exhaustiveness — use `when(isX)` or `.otherwise()`.
|
|
5
|
+
*/
|
|
6
|
+
export type ExhaustMatched<T, P> = P extends (input: T) => boolean ? [GuardTarget<P>] extends [never] ? never : Extract<T, GuardTarget<P>> : Extract<T, P>;
|
|
7
|
+
/** Union of cases already handled by prior branches. */
|
|
8
|
+
export type HandledUnion<Handled extends readonly unknown[]> = Handled[number];
|
|
9
|
+
/** Input cases not yet covered by `.with` / `.withOneOf` / `.withEither`. */
|
|
10
|
+
export type RemainingCases<T, Handled extends readonly unknown[]> = Exclude<T, HandledUnion<Handled>>;
|
|
11
|
+
/** `true` when every member of `T` appears in `Handled`, otherwise `false`. */
|
|
12
|
+
export type IsExhaustive<T, Handled extends readonly unknown[]> = [
|
|
13
|
+
RemainingCases<T, Handled>
|
|
14
|
+
] extends [never] ? true : false;
|
|
15
|
+
/** `.exhaustive()` shape: the value `R` when an input was given, else a `(input: T) => R` matcher. */
|
|
16
|
+
export type ExhaustiveOutput<R, HasInput extends boolean, T> = HasInput extends true ? R : (input: T) => R;
|
|
17
|
+
/** Returned by `.exhaustive()` when union cases are still missing (compile-time error). */
|
|
18
|
+
export type NonExhaustiveError<Remaining> = {
|
|
19
|
+
readonly __nonExhaustive: "Add .with() branches for remaining cases";
|
|
20
|
+
readonly remaining: Remaining;
|
|
21
|
+
};
|
|
22
|
+
/** `.exhaustive()` return type — `NonExhaustiveError` when cases are missing. */
|
|
23
|
+
export type ExhaustiveResult<T, Handled extends readonly unknown[], R, HasInput extends boolean> = IsExhaustive<T, Handled> extends true ? ExhaustiveOutput<R, HasInput, T> : NonExhaustiveError<RemainingCases<T, Handled>>;
|
package/dist/index.cjs
CHANGED
|
@@ -27,15 +27,13 @@ var matches = (input, pattern) => {
|
|
|
27
27
|
}
|
|
28
28
|
return true;
|
|
29
29
|
};
|
|
30
|
-
var NO_MATCH = /* @__PURE__ */ Symbol("@onrails/pattern/no-match");
|
|
31
30
|
var NO_INPUT = /* @__PURE__ */ Symbol("@onrails/pattern/no-input");
|
|
32
|
-
var
|
|
33
|
-
for (
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
}
|
|
31
|
+
var findCase = (input, cases) => {
|
|
32
|
+
for (let i = 0; i < cases.length; i++) {
|
|
33
|
+
const c = cases[i];
|
|
34
|
+
if (c.test(input)) return c;
|
|
37
35
|
}
|
|
38
|
-
return
|
|
36
|
+
return null;
|
|
39
37
|
};
|
|
40
38
|
var caseForPatterns = (patterns, handler) => ({
|
|
41
39
|
test: (input) => patterns.some((pattern) => matches(input, pattern)),
|
|
@@ -190,11 +188,11 @@ var MatchBuilder = class _MatchBuilder {
|
|
|
190
188
|
if (value === NO_INPUT) {
|
|
191
189
|
throw new Error("match.run: no input value");
|
|
192
190
|
}
|
|
193
|
-
const
|
|
194
|
-
if (
|
|
191
|
+
const c = findCase(value, this.cases);
|
|
192
|
+
if (c === null) {
|
|
195
193
|
throw new Error("Non-exhaustive match: no case matched input");
|
|
196
194
|
}
|
|
197
|
-
return
|
|
195
|
+
return c.run(value);
|
|
198
196
|
}
|
|
199
197
|
/**
|
|
200
198
|
* Settle the match with a compile-time exhaustiveness guarantee. Only
|
|
@@ -247,8 +245,8 @@ var MatchBuilder = class _MatchBuilder {
|
|
|
247
245
|
*/
|
|
248
246
|
otherwise(handler) {
|
|
249
247
|
const runWithFallback = (value) => {
|
|
250
|
-
const
|
|
251
|
-
return
|
|
248
|
+
const c = findCase(value, this.cases);
|
|
249
|
+
return c === null ? handler(value) : c.run(value);
|
|
252
250
|
};
|
|
253
251
|
return this.input === NO_INPUT ? runWithFallback : runWithFallback(this.input);
|
|
254
252
|
}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/assert.ts","../src/match.ts","../src/tag.ts","../src/when.ts"],"names":[],"mappings":";;;AAuBO,IAAM,WAAA,GAAc,CAAC,KAAA,EAAc,OAAA,GAAU,aAAA,KAAyB;AAC3E,EAAA,MAAM,IAAI,MAAM,CAAA,EAAG,OAAO,KAAK,MAAA,CAAO,KAAK,CAAC,CAAA,CAAE,CAAA;AAChD;;;ACUA,IAAM,OAAA,GAAU,CAAI,OAAA,KAClB,OAAO,OAAA,KAAY,UAAA;AAErB,IAAM,kBAAkB,CAAC,OAAA,KACvB,OAAO,OAAA,KAAY,YAAY,OAAA,KAAY,IAAA;AAE7C,IAAM,OAAA,GAAU,CAAI,KAAA,EAAU,OAAA,KAAiC;AAC7D,EAAA,IAAI,OAAA,CAAQ,OAAO,CAAA,EAAG;AACpB,IAAA,OAAO,QAAQ,KAAK,CAAA;AAAA,EACtB;AACA,EAAA,IAAI,CAAC,eAAA,CA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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBA,UAAU,OAAA,EAAuE;AAC/E,IAAA,MAAM,eAAA,GAAkB,CAAC,KAAA,KAAgB;AACvC,MAAA,MAAM,GAAA,GAAM,QAAA,CAAS,KAAA,EAAO,IAAA,CAAK,KAAK,CAAA;AACtC,MAAA,OAAO,GAAA,KAAQ,QAAA,GAAW,OAAA,CAAQ,KAAK,CAAA,GAAK,GAAA;AAAA,IAC9C,CAAA;AAEA,IAAA,OACE,KAAK,KAAA,KAAU,QAAA,GAAW,eAAA,GAAkB,eAAA,CAAgB,KAAK,KAAK,CAAA;AAAA,EAE1E;AACF;AA2BO,SAAS,SACX,KAAA,EAC8B;AACjC,EAAA,OAAO,KAAA,CAAM,MAAA,KAAW,CAAA,GACpB,IAAI,aAAgC,EAAC,EAAG,KAAA,CAAM,CAAC,CAAC,CAAA,GAChD,IAAI,YAAA,CAAgC,IAAI,QAAQ,CAAA;AACtD;;;AC7XO,IAAM,QAAA,GAAW,CAAsB,KAAA,EAAU,QAAA,KAAmC;AACzF,EAAA,MAAM,MAAM,KAAA,CAAM,IAAA;AAClB,EAAA,MAAM,OAAA,GAAU,SAAS,GAAG,CAAA;AAC5B,EAAA,OAAO,QAAQ,KAAyC,CAAA;AAC1D;;;ACLO,SAAS,KAAQ,KAAA,EAA0C;AAChE,EAAA,OAAO,KAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * Use in `default` branches (or after manual narrowing) to assert a union has\n * been fully handled. If every case is handled, `value` is `never` and the call\n * type-checks; an unhandled case makes `value` non-`never`, surfacing a compile\n * error. Always throws at runtime.\n *\n * @param value - the value that should be unreachable (typed `never`)\n * @param message - error message prefix; defaults to `\"Unreachable\"`\n * @throws always — the branch is meant to be unreachable\n *\n * @example\n * ```ts\n * type Shape = { kind: \"circle\"; r: number } | { kind: \"square\"; s: number };\n *\n * function area(shape: Shape): number {\n * switch (shape.kind) {\n * case \"circle\": return Math.PI * shape.r ** 2;\n * case \"square\": return shape.s ** 2;\n * default: return assertNever(shape); // type error if a case is added\n * }\n * }\n * ```\n */\nexport const assertNever = (value: never, message = \"Unreachable\"): never => {\n throw new Error(`${message}: ${String(value)}`);\n};\n","import type { ExhaustiveResult, ExhaustMatched } from \"./exhaustive.js\";\nimport type { Narrow, NarrowUnion } from \"./narrow.js\";\n\n/**\n * A pattern that matches a value of type `T`. One of:\n *\n * - **Literal** — a primitive (`\"a\"`, `42`, `true`) matched by `===`.\n * - **Object pattern** — a `Partial<T>` of shallow key/value pairs that\n * must all match by strict equality. Only available when `T` is an\n * object type.\n * - **Guard** — a function `(input: T) => boolean`. Type predicates\n * (`(x): x is U`) narrow the handler input via {@link Narrow}.\n *\n * @example\n * ```ts\n * type Event = { kind: \"click\"; x: number; y: number } | { kind: \"key\"; code: string };\n *\n * const p1: Pattern<Event> = { kind: \"click\" }; // object pattern\n * const p2: Pattern<Event> = (e) => e.kind === \"key\"; // guard\n * ```\n */\nexport type Pattern<T> = T | ObjectPattern<T> | PatternGuard<T>;\n\n// Shallow partial of `T`; restricted to object types so primitive `T`\n// (e.g. `number | string`) does not pick up `Record<string, unknown>`\n// as a candidate pattern and pollute `Narrow<T, P>` via distribution.\ntype ObjectPattern<T> = T extends object ? Partial<T> : never;\n\ntype PatternGuard<T> = (input: T) => boolean;\n\ntype Case<T, R> = {\n readonly test: (input: T) => boolean;\n readonly run: (input: T) => R;\n};\n\nconst isGuard = <T>(pattern: Pattern<T>): pattern is PatternGuard<T> =>\n typeof pattern === \"function\";\n\nconst isPatternObject = (pattern: unknown): pattern is Record<string, unknown> =>\n typeof pattern === \"object\" && pattern !== null;\n\nconst matches = <T>(input: T, pattern: Pattern<T>): boolean => {\n if (isGuard(pattern)) {\n return pattern(input);\n }\n if (!isPatternObject(pattern)) {\n return input === pattern;\n }\n if (typeof input !== \"object\" || input === null) {\n return false;\n }\n const record = input as Record<string, unknown>;\n const patternRecord = pattern as Record<string, unknown>;\n for (const key of Object.keys(patternRecord)) {\n if (record[key] !== patternRecord[key]) {\n return false;\n }\n }\n return true;\n};\n\n// Sentinel for \"no case matched\". Distinct from a handler legitimately\n// returning `undefined` (e.g. side-effect-only handlers), which would\n// otherwise be misreported as non-exhaustive.\nconst NO_MATCH = Symbol(\"@onrails/pattern/no-match\");\ntype NoMatch = typeof NO_MATCH;\n\n// Sentinel for \"curried matcher, no captured input\". Distinct from a\n// data-first `match(undefined)` / `match(null)`, which must run immediately\n// like any other value instead of silently degrading to curried mode.\nconst NO_INPUT = Symbol(\"@onrails/pattern/no-input\");\ntype NoInput = typeof NO_INPUT;\n\nconst runCases = <T, R>(input: T, cases: readonly Case<T, R>[]): R | NoMatch => {\n for (const c of cases) {\n if (c.test(input)) {\n return c.run(input);\n }\n }\n return NO_MATCH;\n};\n\nconst caseForPatterns = <T, R>(\n patterns: readonly Pattern<T>[],\n handler: (input: T) => R,\n): Case<T, R> => ({\n test: (input) => patterns.some((pattern) => matches(input, pattern)),\n run: handler,\n});\n\n// Result-type accumulator: stays at `R` when the result type is locked\n// (after `returnType<R>()`), otherwise widens with each `.with`.\ntype NextResult<Locked extends boolean, R, R2> = Locked extends true ? R : R | R2;\n\n// Handler return-type constraint: when locked, every handler must return `R`;\n// when open, the handler can return any type and the result widens to include it.\ntype HandlerReturn<Locked extends boolean, R, R2> = Locked extends true ? R : R2;\n\n/**\n * Fluent builder for {@link match}. Tracks the handled cases at the type\n * level so `.exhaustive()` only compiles when every union member is covered.\n *\n * The `Locked` phantom flag (set via `.returnType<R>()`) constrains every\n * subsequent handler to return `R`, useful when branch return-type\n * inference would widen to a union narrower than the target slot\n * (e.g. `ReactNode`, an API DTO).\n *\n * @example\n * ```ts\n * const describe = match<Event>()\n * .with({ kind: \"click\" }, (e) => `click @ ${e.x},${e.y}`)\n * .with({ kind: \"key\" }, (e) => `key ${e.code}`)\n * .exhaustive();\n * ```\n */\nexport class MatchBuilder<\n T,\n R = never,\n HasInput extends boolean = false,\n Handled extends readonly unknown[] = [],\n Locked extends boolean = false,\n> {\n /**\n * Construct a builder directly. Prefer the {@link match} factory — the\n * constructor exists so internal combinators can thread accumulated `cases`,\n * the optional captured `input`, and the phantom `_handled` tuple.\n */\n constructor(\n private readonly cases: readonly Case<T, unknown>[],\n // No default: `= NO_INPUT` would swallow a data-first `undefined` input,\n // because JS applies parameter defaults to explicitly-passed undefined.\n private readonly input: T | NoInput,\n /** Phantom tuple of handled cases — only its compile-time contents matter. */\n readonly _handled: Handled = [] as unknown as Handled,\n ) {}\n\n /** Appends a runtime case plus a phantom `H` entry on the handled tuple. */\n private addCase<R2, H>(\n next: Case<T, unknown>,\n ): MatchBuilder<T, NextResult<Locked, R, R2>, HasInput, readonly [...Handled, H], Locked> {\n return new MatchBuilder(\n [...this.cases, next],\n this.input,\n // Safe: _handled is a phantom tuple — only its type-level contents matter.\n this._handled as unknown as readonly [...Handled, H],\n );\n }\n\n /**\n * Add a case: when `input` satisfies `pattern`, run `handler` on the narrowed\n * value. The pattern may be a literal, a shallow object pattern, or a guard\n * ({@link Pattern}); a type-predicate guard narrows the handler input. Each\n * `.with` advances compile-time exhaustiveness tracking so `.exhaustive()`\n * knows which union members remain.\n *\n * @param pattern - literal, object pattern, or guard to test against\n * @param handler - run on the narrowed input when the pattern matches\n * @returns a builder with this case appended\n *\n * @example\n * ```ts\n * type Event =\n * | { type: \"message\"; content: string }\n * | { type: \"error\"; message: string }\n * | { type: \"done\" };\n *\n * const summary = match({ type: \"message\", content: \"hi\" } as Event)\n * .with({ type: \"message\" }, (e) => e.content) // e: { type: \"message\"; content: string }\n * .with({ type: \"error\" }, (e) => e.message)\n * .with({ type: \"done\" }, () => \"—\")\n * .exhaustive(); // \"hi\"\n * ```\n */\n with<const P extends Pattern<T>, R2>(\n pattern: P,\n handler: (input: Narrow<T, P>) => HandlerReturn<Locked, R, R2>,\n ): MatchBuilder<\n T,\n NextResult<Locked, R, R2>,\n HasInput,\n readonly [...Handled, ExhaustMatched<T, P>],\n Locked\n > {\n return this.addCase<R2, ExhaustMatched<T, P>>({\n test: (input) => matches(input, pattern),\n run: handler as (input: T) => unknown,\n });\n }\n\n /**\n * One handler for several patterns (OR). The handler input is the union of\n * the members narrowed by each pattern, and all of them are marked handled\n * for exhaustiveness.\n *\n * @param patterns - patterns to test; any match runs `handler`\n * @param handler - run on the union of narrowed members\n * @returns a builder with the shared case appended\n *\n * @example\n * ```ts\n * type Job =\n * | { kind: \"queued\"; id: string }\n * | { kind: \"running\"; id: string }\n * | { kind: \"done\"; ok: boolean };\n *\n * const status = match({ kind: \"running\", id: \"j1\" } as Job)\n * .withOneOf([{ kind: \"queued\" }, { kind: \"running\" }], (j) => j.id) // j: queued | running\n * .with({ kind: \"done\" }, (j) => (j.ok ? \"yes\" : \"no\"))\n * .exhaustive(); // \"j1\"\n * ```\n */\n withOneOf<const Ps extends readonly Pattern<T>[], R2>(\n patterns: Ps,\n handler: (input: NarrowUnion<T, Ps>) => HandlerReturn<Locked, R, R2>,\n ): MatchBuilder<\n T,\n NextResult<Locked, R, R2>,\n HasInput,\n readonly [...Handled, NarrowUnion<T, Ps>],\n Locked\n > {\n return this.addCase<R2, NarrowUnion<T, Ps>>(\n caseForPatterns(patterns, handler as (input: T) => unknown),\n );\n }\n\n /**\n * {@link withOneOf} for exactly two patterns — sugar that avoids the array.\n *\n * @param pattern1 - first pattern\n * @param pattern2 - second pattern\n * @param handler - run on the union of the two narrowed members\n * @returns a builder with the shared case appended\n *\n * @example\n * ```ts\n * type Provider = \"ollama\" | \"openrouter\";\n *\n * const pick = match<Provider>()\n * .withEither(\"ollama\", \"openrouter\", (p) => p) // p: \"ollama\" | \"openrouter\"\n * .exhaustive();\n * pick(\"ollama\"); // \"ollama\"\n * ```\n */\n withEither<const P1 extends Pattern<T>, const P2 extends Pattern<T>, R2>(\n pattern1: P1,\n pattern2: P2,\n handler: (input: NarrowUnion<T, readonly [P1, P2]>) => HandlerReturn<Locked, R, R2>,\n ): MatchBuilder<\n T,\n NextResult<Locked, R, R2>,\n HasInput,\n readonly [...Handled, NarrowUnion<T, readonly [P1, P2]>],\n Locked\n > {\n return this.withOneOf([pattern1, pattern2], handler);\n }\n\n /**\n * Lock the result type. All subsequent `.with()` handlers must return `R2`.\n * Useful when branch return-type inference widens to a union narrower than\n * the slot the match feeds into (e.g. `ReactNode`).\n *\n * Also the fix for literal-widening: when a handler returns an object whose\n * field is a union literal, inference widens it (e.g. `{ mode: \"native\" }`\n * becomes `{ mode: string }`, breaking a `Mode` union). Lock the target type\n * instead of sprinkling `as const`:\n *\n * @example\n * ```ts\n * type State = { mode: \"compat\" | \"native\" };\n * const next = match(flag)\n * .returnType<State>() // handlers now checked against State\n * .with(\"--native\", () => ({ mode: \"native\" })) // no `as const` needed\n * .otherwise(() => state);\n * ```\n */\n returnType<R2>(): MatchBuilder<T, R2, HasInput, Handled, true> {\n return new MatchBuilder<T, R2, HasInput, Handled, true>(this.cases, this.input, this._handled);\n }\n\n /**\n * Run the accumulated cases now, without a compile-time exhaustiveness check.\n * Uses the value passed to {@link match} (data-first), or the value passed to\n * `run` (curried). Throws `\"Non-exhaustive match\"` if no case matches at\n * runtime — prefer {@link exhaustive} when the input is a closed union, or\n * {@link otherwise} for an explicit fallback.\n *\n * @param input - the value to match when the builder was created curried\n * @returns the matched handler's result\n * @throws if no case matches the input\n *\n * @example\n * ```ts\n * type Event = { type: \"error\"; message: string } | { type: \"done\" };\n *\n * const msg = match({ type: \"error\", message: \"x\" } as Event)\n * .with({ type: \"error\" }, (e) => e.message)\n * .run({ type: \"error\", message: \"net\" }); // \"net\"\n * ```\n */\n run(...input: readonly [input: T] | readonly []): R {\n const value = input.length === 1 ? input[0] : this.input;\n if (value === NO_INPUT) {\n throw new Error(\"match.run: no input value\");\n }\n const out = runCases(value, this.cases);\n if (out === NO_MATCH) {\n throw new Error(\"Non-exhaustive match: no case matched input\");\n }\n return out as R;\n }\n\n /**\n * Settle the match with a compile-time exhaustiveness guarantee. Only\n * type-checks when every member of `T` has been handled; otherwise the return\n * type becomes {@link NonExhaustiveError}, surfacing the missing cases as a\n * type error. Returns the result directly when data-first ({@link match}\n * called with a value), or a reusable `(input: T) => R` matcher when curried.\n *\n * @returns the result (data-first) or a matcher function (curried)\n *\n * @example\n * ```ts\n * type Event =\n * | { type: \"message\"; content: string }\n * | { type: \"error\"; message: string }\n * | { type: \"done\" };\n *\n * // Curried — reusable matcher; omitting a `.with` would be a type error.\n * const describe = match<Event>()\n * .with({ type: \"message\" }, (e) => e.content)\n * .with({ type: \"error\" }, (e) => `! ${e.message}`)\n * .with({ type: \"done\" }, () => \"done\")\n * .exhaustive();\n * describe({ type: \"done\" }); // \"done\"\n * ```\n */\n exhaustive(): ExhaustiveResult<T, Handled, R, HasInput> {\n // Safe: HasInput is true exactly when match(value) captured an input.\n return (\n this.input === NO_INPUT ? (value: T) => this.run(value) : this.run()\n ) as ExhaustiveResult<T, Handled, R, HasInput>;\n }\n\n /**\n * Settle the match with a catch-all fallback, dropping the exhaustiveness\n * requirement — `handler` runs (on the full input type) when no case matched.\n * Returns the result directly when data-first, or a reusable matcher when\n * curried.\n *\n * @param handler - fallback run on the input when no prior case matched\n * @returns the result (data-first) or a matcher function (curried)\n *\n * @example\n * ```ts\n * type Event =\n * | { type: \"message\"; content: string }\n * | { type: \"error\"; message: string }\n * | { type: \"done\" };\n *\n * const len = match({ type: \"done\" } as Event)\n * .with({ type: \"message\" }, (e) => e.content.length)\n * .otherwise(() => -1); // -1\n * ```\n */\n otherwise(handler: (input: T) => R): HasInput extends true ? R : (input: T) => R {\n const runWithFallback = (value: T): R => {\n const out = runCases(value, this.cases);\n return out === NO_MATCH ? handler(value) : (out as R);\n };\n // Safe: HasInput is true exactly when match(value) captured an input.\n return (\n this.input === NO_INPUT ? runWithFallback : runWithFallback(this.input)\n ) as HasInput extends true ? R : (input: T) => R;\n }\n}\n\n/**\n * Start a pattern-matching expression. Two call shapes:\n *\n * - `match(value)` — data-first; subsequent `.exhaustive()` or\n * `.otherwise(fn)` runs immediately against `value`.\n * - `match<T>()` — curried; subsequent `.exhaustive()` returns a function\n * `(value: T) => R` for use in `pipe(...)` or as a reusable matcher.\n *\n * @example\n * ```ts\n * // Data-first\n * const out = match({ kind: \"click\", x: 1, y: 2 } as Event)\n * .with({ kind: \"click\" }, (e) => e.x + e.y)\n * .with({ kind: \"key\" }, () => -1)\n * .exhaustive();\n *\n * // Curried — build a reusable matcher\n * const describe = match<Event>()\n * .with({ kind: \"click\" }, (e) => `click @ ${e.x},${e.y}`)\n * .with({ kind: \"key\" }, (e) => `key ${e.code}`)\n * .exhaustive();\n * ```\n */\nexport function match<T>(input: T): MatchBuilder<T, never, true>;\nexport function match<T = never>(): MatchBuilder<T, never, false>;\nexport function match<T>(\n ...input: readonly [input: T] | readonly []\n): MatchBuilder<T, never, boolean> {\n return input.length === 1\n ? new MatchBuilder<T, never, boolean>([], input[0])\n : new MatchBuilder<T, never, boolean>([], NO_INPUT);\n}\n","type Tagged = { readonly _tag: string };\n\ntype TagHandlers<T extends Tagged, R> = {\n [K in T[\"_tag\"]]: (value: Extract<T, { _tag: K }>) => R;\n};\n\n/**\n * Exhaustive match on `_tag` — for `@onrails/result` / `@onrails/maybe` style\n * unions. The `handlers` object must supply one branch per `_tag`, and each\n * handler receives the member narrowed to its tag.\n *\n * @param value - a tagged union value to dispatch on\n * @param handlers - one handler per `_tag`, keyed by tag\n * @returns the result of the matched handler\n *\n * @example\n * ```ts\n * import { err, ok, type Result } from \"@onrails/result\";\n *\n * const label = (r: Result<number, string>) =>\n * matchTag(r, {\n * Ok: (v) => `ok:${v.value}`, // v: Ok<number>\n * Err: (e) => `err:${e.error}`, // e: Err<string>\n * });\n * label(ok(1)); // \"ok:1\"\n * label(err(\"x\")); // \"err:x\"\n * ```\n */\nexport const matchTag = <T extends Tagged, R>(value: T, handlers: TagHandlers<T, R>): R => {\n const tag = value._tag as T[\"_tag\"];\n const handler = handlers[tag] as (value: Extract<T, { _tag: typeof tag }>) => R;\n return handler(value as Extract<T, { _tag: typeof tag }>);\n};\n","import type { Pattern } from \"./match.js\";\n\n/**\n * Guard pattern for {@link match}.with.\n *\n * Accepts plain boolean guards (`(x) => x.length > 0`) or TS type-predicate\n * guards (`(x): x is Foo => ...`). For type predicates, the matched handler's\n * input is narrowed to the predicate's target type via {@link Narrow}.\n *\n * Note: a plain boolean guard does not advance exhaustiveness tracking — pair\n * it with `.otherwise()`, or use a type predicate to narrow the union.\n *\n * @param guard - boolean or type-predicate guard function\n * @returns the guard, usable as a {@link Pattern} in `.with`\n *\n * @example\n * ```ts\n * const sign = match<number>()\n * .with(when((n: number) => n < 0), () => \"neg\")\n * .with(when((n: number) => n >= 0), () => \"non-neg\")\n * .exhaustive();\n * sign(-1); // \"neg\"\n * sign(0); // \"non-neg\"\n * ```\n */\nexport function when<T, U extends T>(guard: (input: T) => input is U): (input: T) => input is U;\nexport function when<T>(guard: (input: T) => boolean): Pattern<T>;\nexport function when<T>(guard: (input: T) => boolean): Pattern<T> {\n return guard;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/assert.ts","../src/match.ts","../src/tag.ts","../src/when.ts"],"names":[],"mappings":";;;AAuBO,IAAM,WAAA,GAAc,CAAC,KAAA,EAAc,OAAA,GAAU,aAAA,KAAyB;AAC3E,EAAA,MAAM,IAAI,MAAM,CAAA,EAAG,OAAO,KAAK,MAAA,CAAO,KAAK,CAAC,CAAA,CAAE,CAAA;AAChD;;;ACUA,IAAM,OAAA,GAAU,CAAI,OAAA,KAClB,OAAO,OAAA,KAAY,UAAA;AAErB,IAAM,kBAAkB,CAAC,OAAA,KACvB,OAAO,OAAA,KAAY,YAAY,OAAA,KAAY,IAAA;AAE7C,IAAM,OAAA,GAAU,CAAI,KAAA,EAAU,OAAA,KAAiC;AAC7D,EAAA,IAAI,OAAA,CAAQ,OAAO,CAAA,EAAG;AACpB,IAAA,OAAO,QAAQ,KAAK,CAAA;AAAA,EACtB;AACA,EAAA,IAAI,CAAC,eAAA,CAAgB,OAAO,CAAA,EAAG;AAC7B,IAAA,OAAO,KA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AAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBA,UAAU,OAAA,EAAuE;AAC/E,IAAA,MAAM,eAAA,GAAkB,CAAC,KAAA,KAAgB;AACvC,MAAA,MAAM,CAAA,GAAI,QAAA,CAAS,KAAA,EAAO,IAAA,CAAK,KAAK,CAAA;AAEpC,MAAA,OAAO,MAAM,IAAA,GAAO,OAAA,CAAQ,KAAK,CAAA,GAAK,CAAA,CAAE,IAAI,KAAK,CAAA;AAAA,IACnD,CAAA;AAEA,IAAA,OACE,KAAK,KAAA,KAAU,QAAA,GAAW,eAAA,GAAkB,eAAA,CAAgB,KAAK,KAAK,CAAA;AAAA,EAE1E;AACF;AA2BO,SAAS,SACX,KAAA,EAC8B;AACjC,EAAA,OAAO,KAAA,CAAM,MAAA,KAAW,CAAA,GACpB,IAAI,aAAgC,EAAC,EAAG,KAAA,CAAM,CAAC,CAAC,CAAA,GAChD,IAAI,YAAA,CAAgC,IAAI,QAAQ,CAAA;AACtD;;;AC7XO,IAAM,QAAA,GAAW,CAAsB,KAAA,EAAU,QAAA,KAAmC;AACzF,EAAA,MAAM,MAAM,KAAA,CAAM,IAAA;AAClB,EAAA,MAAM,OAAA,GAAU,SAAS,GAAG,CAAA;AAC5B,EAAA,OAAO,QAAQ,KAAyC,CAAA;AAC1D;;;ACLO,SAAS,KAAQ,KAAA,EAA0C;AAChE,EAAA,OAAO,KAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * Use in `default` branches (or after manual narrowing) to assert a union has\n * been fully handled. If every case is handled, `value` is `never` and the call\n * type-checks; an unhandled case makes `value` non-`never`, surfacing a compile\n * error. Always throws at runtime.\n *\n * @param value - the value that should be unreachable (typed `never`)\n * @param message - error message prefix; defaults to `\"Unreachable\"`\n * @throws always — the branch is meant to be unreachable\n *\n * @example\n * ```ts\n * type Shape = { kind: \"circle\"; r: number } | { kind: \"square\"; s: number };\n *\n * function area(shape: Shape): number {\n * switch (shape.kind) {\n * case \"circle\": return Math.PI * shape.r ** 2;\n * case \"square\": return shape.s ** 2;\n * default: return assertNever(shape); // type error if a case is added\n * }\n * }\n * ```\n */\nexport const assertNever = (value: never, message = \"Unreachable\"): never => {\n throw new Error(`${message}: ${String(value)}`);\n};\n","import type { ExhaustiveResult, ExhaustMatched } from \"./exhaustive.js\";\nimport type { Narrow, NarrowUnion } from \"./narrow.js\";\n\n/**\n * A pattern that matches a value of type `T`. One of:\n *\n * - **Literal** — a primitive (`\"a\"`, `42`, `true`) matched by `===`.\n * - **Object pattern** — a `Partial<T>` of shallow key/value pairs that\n * must all match by strict equality. Only available when `T` is an\n * object type.\n * - **Guard** — a function `(input: T) => boolean`. Type predicates\n * (`(x): x is U`) narrow the handler input via {@link Narrow}.\n *\n * @example\n * ```ts\n * type Event = { kind: \"click\"; x: number; y: number } | { kind: \"key\"; code: string };\n *\n * const p1: Pattern<Event> = { kind: \"click\" }; // object pattern\n * const p2: Pattern<Event> = (e) => e.kind === \"key\"; // guard\n * ```\n */\nexport type Pattern<T> = T | ObjectPattern<T> | PatternGuard<T>;\n\n// Shallow partial of `T`; restricted to object types so primitive `T`\n// (e.g. `number | string`) does not pick up `Record<string, unknown>`\n// as a candidate pattern and pollute `Narrow<T, P>` via distribution.\ntype ObjectPattern<T> = T extends object ? Partial<T> : never;\n\ntype PatternGuard<T> = (input: T) => boolean;\n\ntype Case<T, R> = {\n readonly test: (input: T) => boolean;\n readonly run: (input: T) => R;\n};\n\nconst isGuard = <T>(pattern: Pattern<T>): pattern is PatternGuard<T> =>\n typeof pattern === \"function\";\n\nconst isPatternObject = (pattern: unknown): pattern is Record<string, unknown> =>\n typeof pattern === \"object\" && pattern !== null;\n\nconst matches = <T>(input: T, pattern: Pattern<T>): boolean => {\n if (isGuard(pattern)) {\n return pattern(input);\n }\n if (!isPatternObject(pattern)) {\n return input === pattern;\n }\n if (typeof input !== \"object\" || input === null) {\n return false;\n }\n const record = input as Record<string, unknown>;\n const patternRecord = pattern as Record<string, unknown>;\n for (const key of Object.keys(patternRecord)) {\n if (record[key] !== patternRecord[key]) {\n return false;\n }\n }\n return true;\n};\n\n// Sentinel for \"curried matcher, no captured input\". Distinct from a\n// data-first `match(undefined)` / `match(null)`, which must run immediately\n// like any other value instead of silently degrading to curried mode.\nconst NO_INPUT = Symbol(\"@onrails/pattern/no-input\");\ntype NoInput = typeof NO_INPUT;\n\n// Returns the matched case, not its result, so the caller invokes `run`\n// itself in tail position (ES2015 PTC) — needed for constant-stack\n// recursive handlers, e.g. compiled alang `switch` loops on JSC. Index\n// loop, not `for..of`: a `return` inside `for..of` runs IteratorClose\n// after the call returns, disqualifying it from tail position.\nconst findCase = <T, R>(input: T, cases: readonly Case<T, R>[]): Case<T, R> | null => {\n for (let i = 0; i < cases.length; i++) {\n const c = cases[i] as Case<T, R>;\n if (c.test(input)) return c;\n }\n return null;\n};\n\nconst caseForPatterns = <T, R>(\n patterns: readonly Pattern<T>[],\n handler: (input: T) => R,\n): Case<T, R> => ({\n test: (input) => patterns.some((pattern) => matches(input, pattern)),\n run: handler,\n});\n\n// Result-type accumulator: stays at `R` when the result type is locked\n// (after `returnType<R>()`), otherwise widens with each `.with`.\ntype NextResult<Locked extends boolean, R, R2> = Locked extends true ? R : R | R2;\n\n// Handler return-type constraint: when locked, every handler must return `R`;\n// when open, the handler can return any type and the result widens to include it.\ntype HandlerReturn<Locked extends boolean, R, R2> = Locked extends true ? R : R2;\n\n/**\n * Fluent builder for {@link match}. Tracks the handled cases at the type\n * level so `.exhaustive()` only compiles when every union member is covered.\n *\n * The `Locked` phantom flag (set via `.returnType<R>()`) constrains every\n * subsequent handler to return `R`, useful when branch return-type\n * inference would widen to a union narrower than the target slot\n * (e.g. `ReactNode`, an API DTO).\n *\n * @example\n * ```ts\n * const describe = match<Event>()\n * .with({ kind: \"click\" }, (e) => `click @ ${e.x},${e.y}`)\n * .with({ kind: \"key\" }, (e) => `key ${e.code}`)\n * .exhaustive();\n * ```\n */\nexport class MatchBuilder<\n T,\n R = never,\n HasInput extends boolean = false,\n Handled extends readonly unknown[] = [],\n Locked extends boolean = false,\n> {\n /**\n * Construct a builder directly. Prefer the {@link match} factory — the\n * constructor exists so internal combinators can thread accumulated `cases`,\n * the optional captured `input`, and the phantom `_handled` tuple.\n */\n constructor(\n private readonly cases: readonly Case<T, unknown>[],\n // No default: `= NO_INPUT` would swallow a data-first `undefined` input,\n // because JS applies parameter defaults to explicitly-passed undefined.\n private readonly input: T | NoInput,\n /** Phantom tuple of handled cases — only its compile-time contents matter. */\n readonly _handled: Handled = [] as unknown as Handled,\n ) {}\n\n /** Appends a runtime case plus a phantom `H` entry on the handled tuple. */\n private addCase<R2, H>(\n next: Case<T, unknown>,\n ): MatchBuilder<T, NextResult<Locked, R, R2>, HasInput, readonly [...Handled, H], Locked> {\n return new MatchBuilder(\n [...this.cases, next],\n this.input,\n // Safe: _handled is a phantom tuple — only its type-level contents matter.\n this._handled as unknown as readonly [...Handled, H],\n );\n }\n\n /**\n * Add a case: when `input` satisfies `pattern`, run `handler` on the narrowed\n * value. The pattern may be a literal, a shallow object pattern, or a guard\n * ({@link Pattern}); a type-predicate guard narrows the handler input. Each\n * `.with` advances compile-time exhaustiveness tracking so `.exhaustive()`\n * knows which union members remain.\n *\n * @param pattern - literal, object pattern, or guard to test against\n * @param handler - run on the narrowed input when the pattern matches\n * @returns a builder with this case appended\n *\n * @example\n * ```ts\n * type Event =\n * | { type: \"message\"; content: string }\n * | { type: \"error\"; message: string }\n * | { type: \"done\" };\n *\n * const summary = match({ type: \"message\", content: \"hi\" } as Event)\n * .with({ type: \"message\" }, (e) => e.content) // e: { type: \"message\"; content: string }\n * .with({ type: \"error\" }, (e) => e.message)\n * .with({ type: \"done\" }, () => \"—\")\n * .exhaustive(); // \"hi\"\n * ```\n */\n with<const P extends Pattern<T>, R2>(\n pattern: P,\n handler: (input: Narrow<T, P>) => HandlerReturn<Locked, R, R2>,\n ): MatchBuilder<\n T,\n NextResult<Locked, R, R2>,\n HasInput,\n readonly [...Handled, ExhaustMatched<T, P>],\n Locked\n > {\n return this.addCase<R2, ExhaustMatched<T, P>>({\n test: (input) => matches(input, pattern),\n run: handler as (input: T) => unknown,\n });\n }\n\n /**\n * One handler for several patterns (OR). The handler input is the union of\n * the members narrowed by each pattern, and all of them are marked handled\n * for exhaustiveness.\n *\n * @param patterns - patterns to test; any match runs `handler`\n * @param handler - run on the union of narrowed members\n * @returns a builder with the shared case appended\n *\n * @example\n * ```ts\n * type Job =\n * | { kind: \"queued\"; id: string }\n * | { kind: \"running\"; id: string }\n * | { kind: \"done\"; ok: boolean };\n *\n * const status = match({ kind: \"running\", id: \"j1\" } as Job)\n * .withOneOf([{ kind: \"queued\" }, { kind: \"running\" }], (j) => j.id) // j: queued | running\n * .with({ kind: \"done\" }, (j) => (j.ok ? \"yes\" : \"no\"))\n * .exhaustive(); // \"j1\"\n * ```\n */\n withOneOf<const Ps extends readonly Pattern<T>[], R2>(\n patterns: Ps,\n handler: (input: NarrowUnion<T, Ps>) => HandlerReturn<Locked, R, R2>,\n ): MatchBuilder<\n T,\n NextResult<Locked, R, R2>,\n HasInput,\n readonly [...Handled, NarrowUnion<T, Ps>],\n Locked\n > {\n return this.addCase<R2, NarrowUnion<T, Ps>>(\n caseForPatterns(patterns, handler as (input: T) => unknown),\n );\n }\n\n /**\n * {@link withOneOf} for exactly two patterns — sugar that avoids the array.\n *\n * @param pattern1 - first pattern\n * @param pattern2 - second pattern\n * @param handler - run on the union of the two narrowed members\n * @returns a builder with the shared case appended\n *\n * @example\n * ```ts\n * type Provider = \"ollama\" | \"openrouter\";\n *\n * const pick = match<Provider>()\n * .withEither(\"ollama\", \"openrouter\", (p) => p) // p: \"ollama\" | \"openrouter\"\n * .exhaustive();\n * pick(\"ollama\"); // \"ollama\"\n * ```\n */\n withEither<const P1 extends Pattern<T>, const P2 extends Pattern<T>, R2>(\n pattern1: P1,\n pattern2: P2,\n handler: (input: NarrowUnion<T, readonly [P1, P2]>) => HandlerReturn<Locked, R, R2>,\n ): MatchBuilder<\n T,\n NextResult<Locked, R, R2>,\n HasInput,\n readonly [...Handled, NarrowUnion<T, readonly [P1, P2]>],\n Locked\n > {\n return this.withOneOf([pattern1, pattern2], handler);\n }\n\n /**\n * Lock the result type. All subsequent `.with()` handlers must return `R2`.\n * Useful when branch return-type inference widens to a union narrower than\n * the slot the match feeds into (e.g. `ReactNode`).\n *\n * Also the fix for literal-widening: when a handler returns an object whose\n * field is a union literal, inference widens it (e.g. `{ mode: \"native\" }`\n * becomes `{ mode: string }`, breaking a `Mode` union). Lock the target type\n * instead of sprinkling `as const`:\n *\n * @example\n * ```ts\n * type State = { mode: \"compat\" | \"native\" };\n * const next = match(flag)\n * .returnType<State>() // handlers now checked against State\n * .with(\"--native\", () => ({ mode: \"native\" })) // no `as const` needed\n * .otherwise(() => state);\n * ```\n */\n returnType<R2>(): MatchBuilder<T, R2, HasInput, Handled, true> {\n return new MatchBuilder<T, R2, HasInput, Handled, true>(this.cases, this.input, this._handled);\n }\n\n /**\n * Run the accumulated cases now, without a compile-time exhaustiveness check.\n * Uses the value passed to {@link match} (data-first), or the value passed to\n * `run` (curried). Throws `\"Non-exhaustive match\"` if no case matches at\n * runtime — prefer {@link exhaustive} when the input is a closed union, or\n * {@link otherwise} for an explicit fallback.\n *\n * @param input - the value to match when the builder was created curried\n * @returns the matched handler's result\n * @throws if no case matches the input\n *\n * @example\n * ```ts\n * type Event = { type: \"error\"; message: string } | { type: \"done\" };\n *\n * const msg = match({ type: \"error\", message: \"x\" } as Event)\n * .with({ type: \"error\" }, (e) => e.message)\n * .run({ type: \"error\", message: \"net\" }); // \"net\"\n * ```\n */\n run(...input: readonly [input: T] | readonly []): R {\n const value = input.length === 1 ? input[0] : this.input;\n if (value === NO_INPUT) {\n throw new Error(\"match.run: no input value\");\n }\n const c = findCase(value, this.cases);\n if (c === null) {\n throw new Error(\"Non-exhaustive match: no case matched input\");\n }\n // Tail call: recursive handlers run in constant stack (see findCase).\n return c.run(value) as R;\n }\n\n /**\n * Settle the match with a compile-time exhaustiveness guarantee. Only\n * type-checks when every member of `T` has been handled; otherwise the return\n * type becomes {@link NonExhaustiveError}, surfacing the missing cases as a\n * type error. Returns the result directly when data-first ({@link match}\n * called with a value), or a reusable `(input: T) => R` matcher when curried.\n *\n * @returns the result (data-first) or a matcher function (curried)\n *\n * @example\n * ```ts\n * type Event =\n * | { type: \"message\"; content: string }\n * | { type: \"error\"; message: string }\n * | { type: \"done\" };\n *\n * // Curried — reusable matcher; omitting a `.with` would be a type error.\n * const describe = match<Event>()\n * .with({ type: \"message\" }, (e) => e.content)\n * .with({ type: \"error\" }, (e) => `! ${e.message}`)\n * .with({ type: \"done\" }, () => \"done\")\n * .exhaustive();\n * describe({ type: \"done\" }); // \"done\"\n * ```\n */\n exhaustive(): ExhaustiveResult<T, Handled, R, HasInput> {\n // Safe: HasInput is true exactly when match(value) captured an input.\n return (\n this.input === NO_INPUT ? (value: T) => this.run(value) : this.run()\n ) as ExhaustiveResult<T, Handled, R, HasInput>;\n }\n\n /**\n * Settle the match with a catch-all fallback, dropping the exhaustiveness\n * requirement — `handler` runs (on the full input type) when no case matched.\n * Returns the result directly when data-first, or a reusable matcher when\n * curried.\n *\n * @param handler - fallback run on the input when no prior case matched\n * @returns the result (data-first) or a matcher function (curried)\n *\n * @example\n * ```ts\n * type Event =\n * | { type: \"message\"; content: string }\n * | { type: \"error\"; message: string }\n * | { type: \"done\" };\n *\n * const len = match({ type: \"done\" } as Event)\n * .with({ type: \"message\" }, (e) => e.content.length)\n * .otherwise(() => -1); // -1\n * ```\n */\n otherwise(handler: (input: T) => R): HasInput extends true ? R : (input: T) => R {\n const runWithFallback = (value: T): R => {\n const c = findCase(value, this.cases);\n // Both branches are tail calls (see findCase).\n return c === null ? handler(value) : (c.run(value) as R);\n };\n // Safe: HasInput is true exactly when match(value) captured an input.\n return (\n this.input === NO_INPUT ? runWithFallback : runWithFallback(this.input)\n ) as HasInput extends true ? R : (input: T) => R;\n }\n}\n\n/**\n * Start a pattern-matching expression. Two call shapes:\n *\n * - `match(value)` — data-first; subsequent `.exhaustive()` or\n * `.otherwise(fn)` runs immediately against `value`.\n * - `match<T>()` — curried; subsequent `.exhaustive()` returns a function\n * `(value: T) => R` for use in `pipe(...)` or as a reusable matcher.\n *\n * @example\n * ```ts\n * // Data-first\n * const out = match({ kind: \"click\", x: 1, y: 2 } as Event)\n * .with({ kind: \"click\" }, (e) => e.x + e.y)\n * .with({ kind: \"key\" }, () => -1)\n * .exhaustive();\n *\n * // Curried — build a reusable matcher\n * const describe = match<Event>()\n * .with({ kind: \"click\" }, (e) => `click @ ${e.x},${e.y}`)\n * .with({ kind: \"key\" }, (e) => `key ${e.code}`)\n * .exhaustive();\n * ```\n */\nexport function match<T>(input: T): MatchBuilder<T, never, true>;\nexport function match<T = never>(): MatchBuilder<T, never, false>;\nexport function match<T>(\n ...input: readonly [input: T] | readonly []\n): MatchBuilder<T, never, boolean> {\n return input.length === 1\n ? new MatchBuilder<T, never, boolean>([], input[0])\n : new MatchBuilder<T, never, boolean>([], NO_INPUT);\n}\n","type Tagged = { readonly _tag: string };\n\ntype TagHandlers<T extends Tagged, R> = {\n [K in T[\"_tag\"]]: (value: Extract<T, { _tag: K }>) => R;\n};\n\n/**\n * Exhaustive match on `_tag` — for `@onrails/result` / `@onrails/maybe` style\n * unions. The `handlers` object must supply one branch per `_tag`, and each\n * handler receives the member narrowed to its tag.\n *\n * @param value - a tagged union value to dispatch on\n * @param handlers - one handler per `_tag`, keyed by tag\n * @returns the result of the matched handler\n *\n * @example\n * ```ts\n * import { err, ok, type Result } from \"@onrails/result\";\n *\n * const label = (r: Result<number, string>) =>\n * matchTag(r, {\n * Ok: (v) => `ok:${v.value}`, // v: Ok<number>\n * Err: (e) => `err:${e.error}`, // e: Err<string>\n * });\n * label(ok(1)); // \"ok:1\"\n * label(err(\"x\")); // \"err:x\"\n * ```\n */\nexport const matchTag = <T extends Tagged, R>(value: T, handlers: TagHandlers<T, R>): R => {\n const tag = value._tag as T[\"_tag\"];\n const handler = handlers[tag] as (value: Extract<T, { _tag: typeof tag }>) => R;\n return handler(value as Extract<T, { _tag: typeof tag }>);\n};\n","import type { Pattern } from \"./match.js\";\n\n/**\n * Guard pattern for {@link match}.with.\n *\n * Accepts plain boolean guards (`(x) => x.length > 0`) or TS type-predicate\n * guards (`(x): x is Foo => ...`). For type predicates, the matched handler's\n * input is narrowed to the predicate's target type via {@link Narrow}.\n *\n * Note: a plain boolean guard does not advance exhaustiveness tracking — pair\n * it with `.otherwise()`, or use a type predicate to narrow the union.\n *\n * @param guard - boolean or type-predicate guard function\n * @returns the guard, usable as a {@link Pattern} in `.with`\n *\n * @example\n * ```ts\n * const sign = match<number>()\n * .with(when((n: number) => n < 0), () => \"neg\")\n * .with(when((n: number) => n >= 0), () => \"non-neg\")\n * .exhaustive();\n * sign(-1); // \"neg\"\n * sign(0); // \"non-neg\"\n * ```\n */\nexport function when<T, U extends T>(guard: (input: T) => input is U): (input: T) => input is U;\nexport function when<T>(guard: (input: T) => boolean): Pattern<T>;\nexport function when<T>(guard: (input: T) => boolean): Pattern<T> {\n return guard;\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,329 +1,6 @@
|
|
|
1
|
-
export {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
* error. Always throws at runtime.
|
|
8
|
-
*
|
|
9
|
-
* @param value - the value that should be unreachable (typed `never`)
|
|
10
|
-
* @param message - error message prefix; defaults to `"Unreachable"`
|
|
11
|
-
* @throws always — the branch is meant to be unreachable
|
|
12
|
-
*
|
|
13
|
-
* @example
|
|
14
|
-
* ```ts
|
|
15
|
-
* type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };
|
|
16
|
-
*
|
|
17
|
-
* function area(shape: Shape): number {
|
|
18
|
-
* switch (shape.kind) {
|
|
19
|
-
* case "circle": return Math.PI * shape.r ** 2;
|
|
20
|
-
* case "square": return shape.s ** 2;
|
|
21
|
-
* default: return assertNever(shape); // type error if a case is added
|
|
22
|
-
* }
|
|
23
|
-
* }
|
|
24
|
-
* ```
|
|
25
|
-
*/
|
|
26
|
-
declare const assertNever: (value: never, message?: string) => never;
|
|
27
|
-
|
|
28
|
-
type GuardTarget<F> = F extends (input: any) => input is infer U ? U : never;
|
|
29
|
-
type NarrowObject<T, P> = [Extract<T, P>] extends [never] ? T & P : Extract<T, P>;
|
|
30
|
-
/** Union of members narrowed by each pattern in `Ps` (multi-branch handlers). */
|
|
31
|
-
type NarrowUnion<T, Ps extends readonly unknown[]> = Narrow<T, Ps[number]>;
|
|
32
|
-
/** Narrows `input` when `pattern` is a shallow object, literal discriminant, or type predicate. */
|
|
33
|
-
type Narrow<T, P> = P extends (input: T) => boolean ? [GuardTarget<P>] extends [never] ? T : NarrowObject<T, GuardTarget<P>> : P extends Record<string, unknown> ? NarrowObject<T, P> : T extends P ? Extract<T, P> : T;
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Union members of `T` ruled out by pattern `P`.
|
|
37
|
-
* Boolean guards (non-predicates) do not advance exhaustiveness — use `when(isX)` or `.otherwise()`.
|
|
38
|
-
*/
|
|
39
|
-
type ExhaustMatched<T, P> = P extends (input: T) => boolean ? [GuardTarget<P>] extends [never] ? never : Extract<T, GuardTarget<P>> : Extract<T, P>;
|
|
40
|
-
/** Union of cases already handled by prior branches. */
|
|
41
|
-
type HandledUnion<Handled extends readonly unknown[]> = Handled[number];
|
|
42
|
-
/** Input cases not yet covered by `.with` / `.withOneOf` / `.withEither`. */
|
|
43
|
-
type RemainingCases<T, Handled extends readonly unknown[]> = Exclude<T, HandledUnion<Handled>>;
|
|
44
|
-
/** `true` when every member of `T` appears in `Handled`, otherwise `false`. */
|
|
45
|
-
type IsExhaustive<T, Handled extends readonly unknown[]> = [
|
|
46
|
-
RemainingCases<T, Handled>
|
|
47
|
-
] extends [never] ? true : false;
|
|
48
|
-
/** `.exhaustive()` shape: the value `R` when an input was given, else a `(input: T) => R` matcher. */
|
|
49
|
-
type ExhaustiveOutput<R, HasInput extends boolean, T> = HasInput extends true ? R : (input: T) => R;
|
|
50
|
-
/** Returned by `.exhaustive()` when union cases are still missing (compile-time error). */
|
|
51
|
-
type NonExhaustiveError<Remaining> = {
|
|
52
|
-
readonly __nonExhaustive: "Add .with() branches for remaining cases";
|
|
53
|
-
readonly remaining: Remaining;
|
|
54
|
-
};
|
|
55
|
-
/** `.exhaustive()` return type — `NonExhaustiveError` when cases are missing. */
|
|
56
|
-
type ExhaustiveResult<T, Handled extends readonly unknown[], R, HasInput extends boolean> = IsExhaustive<T, Handled> extends true ? ExhaustiveOutput<R, HasInput, T> : NonExhaustiveError<RemainingCases<T, Handled>>;
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* A pattern that matches a value of type `T`. One of:
|
|
60
|
-
*
|
|
61
|
-
* - **Literal** — a primitive (`"a"`, `42`, `true`) matched by `===`.
|
|
62
|
-
* - **Object pattern** — a `Partial<T>` of shallow key/value pairs that
|
|
63
|
-
* must all match by strict equality. Only available when `T` is an
|
|
64
|
-
* object type.
|
|
65
|
-
* - **Guard** — a function `(input: T) => boolean`. Type predicates
|
|
66
|
-
* (`(x): x is U`) narrow the handler input via {@link Narrow}.
|
|
67
|
-
*
|
|
68
|
-
* @example
|
|
69
|
-
* ```ts
|
|
70
|
-
* type Event = { kind: "click"; x: number; y: number } | { kind: "key"; code: string };
|
|
71
|
-
*
|
|
72
|
-
* const p1: Pattern<Event> = { kind: "click" }; // object pattern
|
|
73
|
-
* const p2: Pattern<Event> = (e) => e.kind === "key"; // guard
|
|
74
|
-
* ```
|
|
75
|
-
*/
|
|
76
|
-
type Pattern<T> = T | ObjectPattern<T> | PatternGuard<T>;
|
|
77
|
-
type ObjectPattern<T> = T extends object ? Partial<T> : never;
|
|
78
|
-
type PatternGuard<T> = (input: T) => boolean;
|
|
79
|
-
type Case<T, R> = {
|
|
80
|
-
readonly test: (input: T) => boolean;
|
|
81
|
-
readonly run: (input: T) => R;
|
|
82
|
-
};
|
|
83
|
-
declare const NO_INPUT: unique symbol;
|
|
84
|
-
type NoInput = typeof NO_INPUT;
|
|
85
|
-
type NextResult<Locked extends boolean, R, R2> = Locked extends true ? R : R | R2;
|
|
86
|
-
type HandlerReturn<Locked extends boolean, R, R2> = Locked extends true ? R : R2;
|
|
87
|
-
/**
|
|
88
|
-
* Fluent builder for {@link match}. Tracks the handled cases at the type
|
|
89
|
-
* level so `.exhaustive()` only compiles when every union member is covered.
|
|
90
|
-
*
|
|
91
|
-
* The `Locked` phantom flag (set via `.returnType<R>()`) constrains every
|
|
92
|
-
* subsequent handler to return `R`, useful when branch return-type
|
|
93
|
-
* inference would widen to a union narrower than the target slot
|
|
94
|
-
* (e.g. `ReactNode`, an API DTO).
|
|
95
|
-
*
|
|
96
|
-
* @example
|
|
97
|
-
* ```ts
|
|
98
|
-
* const describe = match<Event>()
|
|
99
|
-
* .with({ kind: "click" }, (e) => `click @ ${e.x},${e.y}`)
|
|
100
|
-
* .with({ kind: "key" }, (e) => `key ${e.code}`)
|
|
101
|
-
* .exhaustive();
|
|
102
|
-
* ```
|
|
103
|
-
*/
|
|
104
|
-
declare class MatchBuilder<T, R = never, HasInput extends boolean = false, Handled extends readonly unknown[] = [], Locked extends boolean = false> {
|
|
105
|
-
private readonly cases;
|
|
106
|
-
private readonly input;
|
|
107
|
-
/** Phantom tuple of handled cases — only its compile-time contents matter. */
|
|
108
|
-
readonly _handled: Handled;
|
|
109
|
-
/**
|
|
110
|
-
* Construct a builder directly. Prefer the {@link match} factory — the
|
|
111
|
-
* constructor exists so internal combinators can thread accumulated `cases`,
|
|
112
|
-
* the optional captured `input`, and the phantom `_handled` tuple.
|
|
113
|
-
*/
|
|
114
|
-
constructor(cases: readonly Case<T, unknown>[], input: T | NoInput,
|
|
115
|
-
/** Phantom tuple of handled cases — only its compile-time contents matter. */
|
|
116
|
-
_handled?: Handled);
|
|
117
|
-
/** Appends a runtime case plus a phantom `H` entry on the handled tuple. */
|
|
118
|
-
private addCase;
|
|
119
|
-
/**
|
|
120
|
-
* Add a case: when `input` satisfies `pattern`, run `handler` on the narrowed
|
|
121
|
-
* value. The pattern may be a literal, a shallow object pattern, or a guard
|
|
122
|
-
* ({@link Pattern}); a type-predicate guard narrows the handler input. Each
|
|
123
|
-
* `.with` advances compile-time exhaustiveness tracking so `.exhaustive()`
|
|
124
|
-
* knows which union members remain.
|
|
125
|
-
*
|
|
126
|
-
* @param pattern - literal, object pattern, or guard to test against
|
|
127
|
-
* @param handler - run on the narrowed input when the pattern matches
|
|
128
|
-
* @returns a builder with this case appended
|
|
129
|
-
*
|
|
130
|
-
* @example
|
|
131
|
-
* ```ts
|
|
132
|
-
* type Event =
|
|
133
|
-
* | { type: "message"; content: string }
|
|
134
|
-
* | { type: "error"; message: string }
|
|
135
|
-
* | { type: "done" };
|
|
136
|
-
*
|
|
137
|
-
* const summary = match({ type: "message", content: "hi" } as Event)
|
|
138
|
-
* .with({ type: "message" }, (e) => e.content) // e: { type: "message"; content: string }
|
|
139
|
-
* .with({ type: "error" }, (e) => e.message)
|
|
140
|
-
* .with({ type: "done" }, () => "—")
|
|
141
|
-
* .exhaustive(); // "hi"
|
|
142
|
-
* ```
|
|
143
|
-
*/
|
|
144
|
-
with<const P extends Pattern<T>, R2>(pattern: P, handler: (input: Narrow<T, P>) => HandlerReturn<Locked, R, R2>): MatchBuilder<T, NextResult<Locked, R, R2>, HasInput, readonly [...Handled, ExhaustMatched<T, P>], Locked>;
|
|
145
|
-
/**
|
|
146
|
-
* One handler for several patterns (OR). The handler input is the union of
|
|
147
|
-
* the members narrowed by each pattern, and all of them are marked handled
|
|
148
|
-
* for exhaustiveness.
|
|
149
|
-
*
|
|
150
|
-
* @param patterns - patterns to test; any match runs `handler`
|
|
151
|
-
* @param handler - run on the union of narrowed members
|
|
152
|
-
* @returns a builder with the shared case appended
|
|
153
|
-
*
|
|
154
|
-
* @example
|
|
155
|
-
* ```ts
|
|
156
|
-
* type Job =
|
|
157
|
-
* | { kind: "queued"; id: string }
|
|
158
|
-
* | { kind: "running"; id: string }
|
|
159
|
-
* | { kind: "done"; ok: boolean };
|
|
160
|
-
*
|
|
161
|
-
* const status = match({ kind: "running", id: "j1" } as Job)
|
|
162
|
-
* .withOneOf([{ kind: "queued" }, { kind: "running" }], (j) => j.id) // j: queued | running
|
|
163
|
-
* .with({ kind: "done" }, (j) => (j.ok ? "yes" : "no"))
|
|
164
|
-
* .exhaustive(); // "j1"
|
|
165
|
-
* ```
|
|
166
|
-
*/
|
|
167
|
-
withOneOf<const Ps extends readonly Pattern<T>[], R2>(patterns: Ps, handler: (input: NarrowUnion<T, Ps>) => HandlerReturn<Locked, R, R2>): MatchBuilder<T, NextResult<Locked, R, R2>, HasInput, readonly [...Handled, NarrowUnion<T, Ps>], Locked>;
|
|
168
|
-
/**
|
|
169
|
-
* {@link withOneOf} for exactly two patterns — sugar that avoids the array.
|
|
170
|
-
*
|
|
171
|
-
* @param pattern1 - first pattern
|
|
172
|
-
* @param pattern2 - second pattern
|
|
173
|
-
* @param handler - run on the union of the two narrowed members
|
|
174
|
-
* @returns a builder with the shared case appended
|
|
175
|
-
*
|
|
176
|
-
* @example
|
|
177
|
-
* ```ts
|
|
178
|
-
* type Provider = "ollama" | "openrouter";
|
|
179
|
-
*
|
|
180
|
-
* const pick = match<Provider>()
|
|
181
|
-
* .withEither("ollama", "openrouter", (p) => p) // p: "ollama" | "openrouter"
|
|
182
|
-
* .exhaustive();
|
|
183
|
-
* pick("ollama"); // "ollama"
|
|
184
|
-
* ```
|
|
185
|
-
*/
|
|
186
|
-
withEither<const P1 extends Pattern<T>, const P2 extends Pattern<T>, R2>(pattern1: P1, pattern2: P2, handler: (input: NarrowUnion<T, readonly [P1, P2]>) => HandlerReturn<Locked, R, R2>): MatchBuilder<T, NextResult<Locked, R, R2>, HasInput, readonly [...Handled, NarrowUnion<T, readonly [P1, P2]>], Locked>;
|
|
187
|
-
/**
|
|
188
|
-
* Lock the result type. All subsequent `.with()` handlers must return `R2`.
|
|
189
|
-
* Useful when branch return-type inference widens to a union narrower than
|
|
190
|
-
* the slot the match feeds into (e.g. `ReactNode`).
|
|
191
|
-
*
|
|
192
|
-
* Also the fix for literal-widening: when a handler returns an object whose
|
|
193
|
-
* field is a union literal, inference widens it (e.g. `{ mode: "native" }`
|
|
194
|
-
* becomes `{ mode: string }`, breaking a `Mode` union). Lock the target type
|
|
195
|
-
* instead of sprinkling `as const`:
|
|
196
|
-
*
|
|
197
|
-
* @example
|
|
198
|
-
* ```ts
|
|
199
|
-
* type State = { mode: "compat" | "native" };
|
|
200
|
-
* const next = match(flag)
|
|
201
|
-
* .returnType<State>() // handlers now checked against State
|
|
202
|
-
* .with("--native", () => ({ mode: "native" })) // no `as const` needed
|
|
203
|
-
* .otherwise(() => state);
|
|
204
|
-
* ```
|
|
205
|
-
*/
|
|
206
|
-
returnType<R2>(): MatchBuilder<T, R2, HasInput, Handled, true>;
|
|
207
|
-
/**
|
|
208
|
-
* Run the accumulated cases now, without a compile-time exhaustiveness check.
|
|
209
|
-
* Uses the value passed to {@link match} (data-first), or the value passed to
|
|
210
|
-
* `run` (curried). Throws `"Non-exhaustive match"` if no case matches at
|
|
211
|
-
* runtime — prefer {@link exhaustive} when the input is a closed union, or
|
|
212
|
-
* {@link otherwise} for an explicit fallback.
|
|
213
|
-
*
|
|
214
|
-
* @param input - the value to match when the builder was created curried
|
|
215
|
-
* @returns the matched handler's result
|
|
216
|
-
* @throws if no case matches the input
|
|
217
|
-
*
|
|
218
|
-
* @example
|
|
219
|
-
* ```ts
|
|
220
|
-
* type Event = { type: "error"; message: string } | { type: "done" };
|
|
221
|
-
*
|
|
222
|
-
* const msg = match({ type: "error", message: "x" } as Event)
|
|
223
|
-
* .with({ type: "error" }, (e) => e.message)
|
|
224
|
-
* .run({ type: "error", message: "net" }); // "net"
|
|
225
|
-
* ```
|
|
226
|
-
*/
|
|
227
|
-
run(...input: readonly [input: T] | readonly []): R;
|
|
228
|
-
/**
|
|
229
|
-
* Settle the match with a compile-time exhaustiveness guarantee. Only
|
|
230
|
-
* type-checks when every member of `T` has been handled; otherwise the return
|
|
231
|
-
* type becomes {@link NonExhaustiveError}, surfacing the missing cases as a
|
|
232
|
-
* type error. Returns the result directly when data-first ({@link match}
|
|
233
|
-
* called with a value), or a reusable `(input: T) => R` matcher when curried.
|
|
234
|
-
*
|
|
235
|
-
* @returns the result (data-first) or a matcher function (curried)
|
|
236
|
-
*
|
|
237
|
-
* @example
|
|
238
|
-
* ```ts
|
|
239
|
-
* type Event =
|
|
240
|
-
* | { type: "message"; content: string }
|
|
241
|
-
* | { type: "error"; message: string }
|
|
242
|
-
* | { type: "done" };
|
|
243
|
-
*
|
|
244
|
-
* // Curried — reusable matcher; omitting a `.with` would be a type error.
|
|
245
|
-
* const describe = match<Event>()
|
|
246
|
-
* .with({ type: "message" }, (e) => e.content)
|
|
247
|
-
* .with({ type: "error" }, (e) => `! ${e.message}`)
|
|
248
|
-
* .with({ type: "done" }, () => "done")
|
|
249
|
-
* .exhaustive();
|
|
250
|
-
* describe({ type: "done" }); // "done"
|
|
251
|
-
* ```
|
|
252
|
-
*/
|
|
253
|
-
exhaustive(): ExhaustiveResult<T, Handled, R, HasInput>;
|
|
254
|
-
/**
|
|
255
|
-
* Settle the match with a catch-all fallback, dropping the exhaustiveness
|
|
256
|
-
* requirement — `handler` runs (on the full input type) when no case matched.
|
|
257
|
-
* Returns the result directly when data-first, or a reusable matcher when
|
|
258
|
-
* curried.
|
|
259
|
-
*
|
|
260
|
-
* @param handler - fallback run on the input when no prior case matched
|
|
261
|
-
* @returns the result (data-first) or a matcher function (curried)
|
|
262
|
-
*
|
|
263
|
-
* @example
|
|
264
|
-
* ```ts
|
|
265
|
-
* type Event =
|
|
266
|
-
* | { type: "message"; content: string }
|
|
267
|
-
* | { type: "error"; message: string }
|
|
268
|
-
* | { type: "done" };
|
|
269
|
-
*
|
|
270
|
-
* const len = match({ type: "done" } as Event)
|
|
271
|
-
* .with({ type: "message" }, (e) => e.content.length)
|
|
272
|
-
* .otherwise(() => -1); // -1
|
|
273
|
-
* ```
|
|
274
|
-
*/
|
|
275
|
-
otherwise(handler: (input: T) => R): HasInput extends true ? R : (input: T) => R;
|
|
276
|
-
}
|
|
277
|
-
/**
|
|
278
|
-
* Start a pattern-matching expression. Two call shapes:
|
|
279
|
-
*
|
|
280
|
-
* - `match(value)` — data-first; subsequent `.exhaustive()` or
|
|
281
|
-
* `.otherwise(fn)` runs immediately against `value`.
|
|
282
|
-
* - `match<T>()` — curried; subsequent `.exhaustive()` returns a function
|
|
283
|
-
* `(value: T) => R` for use in `pipe(...)` or as a reusable matcher.
|
|
284
|
-
*
|
|
285
|
-
* @example
|
|
286
|
-
* ```ts
|
|
287
|
-
* // Data-first
|
|
288
|
-
* const out = match({ kind: "click", x: 1, y: 2 } as Event)
|
|
289
|
-
* .with({ kind: "click" }, (e) => e.x + e.y)
|
|
290
|
-
* .with({ kind: "key" }, () => -1)
|
|
291
|
-
* .exhaustive();
|
|
292
|
-
*
|
|
293
|
-
* // Curried — build a reusable matcher
|
|
294
|
-
* const describe = match<Event>()
|
|
295
|
-
* .with({ kind: "click" }, (e) => `click @ ${e.x},${e.y}`)
|
|
296
|
-
* .with({ kind: "key" }, (e) => `key ${e.code}`)
|
|
297
|
-
* .exhaustive();
|
|
298
|
-
* ```
|
|
299
|
-
*/
|
|
300
|
-
declare function match<T>(input: T): MatchBuilder<T, never, true>;
|
|
301
|
-
declare function match<T = never>(): MatchBuilder<T, never, false>;
|
|
302
|
-
|
|
303
|
-
/**
|
|
304
|
-
* Guard pattern for {@link match}.with.
|
|
305
|
-
*
|
|
306
|
-
* Accepts plain boolean guards (`(x) => x.length > 0`) or TS type-predicate
|
|
307
|
-
* guards (`(x): x is Foo => ...`). For type predicates, the matched handler's
|
|
308
|
-
* input is narrowed to the predicate's target type via {@link Narrow}.
|
|
309
|
-
*
|
|
310
|
-
* Note: a plain boolean guard does not advance exhaustiveness tracking — pair
|
|
311
|
-
* it with `.otherwise()`, or use a type predicate to narrow the union.
|
|
312
|
-
*
|
|
313
|
-
* @param guard - boolean or type-predicate guard function
|
|
314
|
-
* @returns the guard, usable as a {@link Pattern} in `.with`
|
|
315
|
-
*
|
|
316
|
-
* @example
|
|
317
|
-
* ```ts
|
|
318
|
-
* const sign = match<number>()
|
|
319
|
-
* .with(when((n: number) => n < 0), () => "neg")
|
|
320
|
-
* .with(when((n: number) => n >= 0), () => "non-neg")
|
|
321
|
-
* .exhaustive();
|
|
322
|
-
* sign(-1); // "neg"
|
|
323
|
-
* sign(0); // "non-neg"
|
|
324
|
-
* ```
|
|
325
|
-
*/
|
|
326
|
-
declare function when<T, U extends T>(guard: (input: T) => input is U): (input: T) => input is U;
|
|
327
|
-
declare function when<T>(guard: (input: T) => boolean): Pattern<T>;
|
|
328
|
-
|
|
329
|
-
export { type ExhaustMatched, type ExhaustiveResult, type HandledUnion, type IsExhaustive, MatchBuilder, type Narrow, type NarrowUnion, type NonExhaustiveError, type Pattern, type RemainingCases, assertNever, match, when };
|
|
1
|
+
export { assertNever } from "./assert.js";
|
|
2
|
+
export type { ExhaustiveResult, ExhaustMatched, HandledUnion, IsExhaustive, NonExhaustiveError, RemainingCases, } from "./exhaustive.js";
|
|
3
|
+
export { MatchBuilder, match, type Pattern } from "./match.js";
|
|
4
|
+
export type { Narrow, NarrowUnion } from "./narrow.js";
|
|
5
|
+
export { matchTag } from "./tag.js";
|
|
6
|
+
export { when } from "./when.js";
|