@noego/trust 0.2.0 → 0.3.0

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/README.md CHANGED
@@ -24,6 +24,41 @@ const loaded = Result.try(() => JSON.parse(text), () => ({ kind: 'bad_json' }) a
24
24
  const fetched = await Result.tryAsync(() => client.get(url), (cause) => toHttpError(cause));
25
25
  ```
26
26
 
27
+ ## Handling a failure: return it or decide it
28
+
29
+ Rules:
30
+
31
+ 1. A failure is an object with a literal `kind`: `{ kind: 'NotFound', id }`.
32
+ 2. On failure either `return r` (pass it up) or `decide` it. Nothing else may stop a failure.
33
+ 3. A `decide` handler returns a value (never `undefined`/`void`); that value says what replaced the failure.
34
+ 4. Leave fallible functions' return types inferred so the failure kinds flow to the caller.
35
+ 5. A thrown error from outside code becomes a named failure in `Result.try` / `Result.tryAsync`.
36
+
37
+ ```ts
38
+ import { Result } from '@noego/trust';
39
+
40
+ async function lookup(id: number) {
41
+ const found = await Result.tryAsync(
42
+ () => db.find(id),
43
+ (cause) => ({ kind: 'ConnectionFailed', cause }),
44
+ );
45
+ if (!found.ok) return found;
46
+ return found.value ? Result.ok(found.value) : Result.err({ kind: 'NotFound', id });
47
+ }
48
+
49
+ const r = await lookup(7);
50
+ // NotFound becomes a guest value; ConnectionFailed stays a failure in the type.
51
+ const user = Result.decide(r, { NotFound: () => GUEST });
52
+ if (!user.ok) return user; // Err<{ kind: 'ConnectionFailed'; ... }>
53
+ ```
54
+
55
+ `Result.translate(r, { NotFound: (f) => ({ kind: 'Missing', id: f.id }) })` turns one failure into another.
56
+ Handlers and mappers are synchronous: async handlers are not supported.
57
+
58
+ ### Breaking in 0.3.0
59
+
60
+ An inline `err({ kind: ... })` now keeps its literal kind, so a callback returning several different failures no longer collapses to `{ kind: string }`. Give the receiving function a union type, or let it infer the callback's whole return type.
61
+
27
62
  ## Lint: `@noego/trust/eslint`
28
63
 
29
64
  Rules (typed linting required for `untrusted-call-must-return-result`):
package/dist/index.cjs CHANGED
@@ -21,8 +21,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
23
  Result: () => Result,
24
+ decide: () => decide,
24
25
  err: () => err,
25
26
  ok: () => ok,
27
+ translate: () => translate,
26
28
  tryResult: () => tryResult,
27
29
  tryResultAsync: () => tryResultAsync
28
30
  });
@@ -47,12 +49,28 @@ async function tryResultAsync(fn, onError) {
47
49
  return err(onError(cause));
48
50
  }
49
51
  }
50
- var Result = { ok, err, try: tryResult, tryAsync: tryResultAsync };
52
+ function pick(table, kind) {
53
+ if (typeof kind !== "string" || !Object.prototype.hasOwnProperty.call(table, kind)) return void 0;
54
+ return table[kind];
55
+ }
56
+ function decide(result, handlers) {
57
+ if (result.ok) return result;
58
+ const handler = pick(handlers, result.error?.kind);
59
+ return handler === void 0 ? result : ok(handler(result.error));
60
+ }
61
+ function translate(result, mappers) {
62
+ if (result.ok) return result;
63
+ const mapper = pick(mappers, result.error?.kind);
64
+ return mapper === void 0 ? result : err(mapper(result.error));
65
+ }
66
+ var Result = { ok, err, try: tryResult, tryAsync: tryResultAsync, decide, translate };
51
67
  // Annotate the CommonJS export names for ESM import in node:
52
68
  0 && (module.exports = {
53
69
  Result,
70
+ decide,
54
71
  err,
55
72
  ok,
73
+ translate,
56
74
  tryResult,
57
75
  tryResultAsync
58
76
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Closed result primitive: expected failures are values, not exceptions.\n *\n * `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no\n * imports so it is safe in any bundle (Node, Electron main, renderer, browser).\n *\n * The `@noego/trust/eslint` rules recognise these declarations by identity (not by\n * name): a call whose declared return type is a `Result` from this module is\n * trusted, and a `catch` is accepted when it returns an `Err` from this module.\n */\nexport type Ok<T> = { readonly ok: true; readonly value: T };\nexport type Err<E> = { readonly ok: false; readonly error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/** Wraps a success value. */\nexport function ok<T>(value: T): Ok<T> {\n return { ok: true, value };\n}\n\n/** Wraps a failure value. Pass a typed error, not a raw caught value. */\nexport function err<E>(error: E): Err<E> {\n return { ok: false, error };\n}\n\n/**\n * Runs `fn` and converts anything it throws into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E> {\n try {\n return ok(fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/**\n * Awaits `fn` and converts a throw or rejection into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport async function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>> {\n try {\n return ok(await fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/** Namespace form: `Result.ok`, `Result.err`, `Result.try`, `Result.tryAsync`. */\nexport const Result: {\n readonly ok: typeof ok;\n readonly err: typeof err;\n readonly try: typeof tryResult;\n readonly tryAsync: typeof tryResultAsync;\n} = { ok, err, try: tryResult, tryAsync: tryResultAsync };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeO,SAAS,GAAM,OAAiB;AACrC,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;AAGO,SAAS,IAAO,OAAkB;AACvC,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;AAMO,SAAS,UAAgB,IAAa,SAA8C;AACzF,MAAI;AACF,WAAO,GAAG,GAAG,CAAC;AAAA,EAChB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAMA,eAAsB,eACpB,IACA,SACuB;AACvB,MAAI;AACF,WAAO,GAAG,MAAM,GAAG,CAAC;AAAA,EACtB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAGO,IAAM,SAKT,EAAE,IAAI,KAAK,KAAK,WAAW,UAAU,eAAe;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Closed result primitive: expected failures are values, not exceptions.\n *\n * `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no\n * imports so it is safe in any bundle (Node, Electron main, renderer, browser).\n *\n * The `@noego/trust/eslint` rules recognise these declarations by identity (not by\n * name): a call whose declared return type is a `Result` from this module is\n * trusted, and a `catch` is accepted when it returns an `Err` from this module.\n */\nexport type Ok<T> = { readonly ok: true; readonly value: T };\nexport type Err<E> = { readonly ok: false; readonly error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/** Wraps a success value. */\nexport function ok<T>(value: T): Ok<T> {\n return { ok: true, value };\n}\n\n/**\n * Wraps a failure value. Pass a typed error, not a raw caught value.\n *\n * The first overload keeps a literal `kind` for inline failures (`err({ kind: 'X' })`\n * gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection. `E` itself is\n * still a plain type parameter, so a declared `Result` return type sets it and other\n * literal fields keep their declared union types. The second overload covers\n * arguments that cannot meet the intersection (generic, unknown, null, undefined).\n */\nexport function err<E, K extends string = string>(error: E & { readonly kind?: K }): Err<E>;\nexport function err<E>(error: E): Err<E>;\nexport function err<E>(error: E): Err<E> {\n return { ok: false, error };\n}\n\n/**\n * Runs `fn` and converts anything it throws into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResult<T, E, K extends string = string>(\n fn: () => T,\n onError: (cause: unknown) => E & { readonly kind?: K },\n): Result<T, E>;\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E>;\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E> {\n try {\n return ok(fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/**\n * Awaits `fn` and converts a throw or rejection into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResultAsync<T, E, K extends string = string>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E & { readonly kind?: K },\n): Promise<Result<T, E>>;\nexport function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>>;\nexport async function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>> {\n try {\n return ok(await fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/** A failure is an object with a literal `kind` plus any fields. */\nexport type Failure<K extends string = string, Fields extends object = {}> = { readonly kind: K } & Readonly<Fields>;\n\ntype KindsOf<E> = E extends { readonly kind: infer K extends string } ? K : never;\ntype ErrorOf<R> = R extends Err<infer E> ? E : never;\ntype OkOf<R> = R extends Ok<infer T> ? T : never;\ntype CannotFail = { readonly __trust: 'decide needs a result that can fail (it has no Err member)' };\ntype BadFailure = { readonly __trust: 'every failure needs a string `kind` (string and Error are not failures)' };\ntype NeedsLiteralKind = { readonly __trust: 'a translate mapper must return an object with a literal string kind' };\n\ntype FailureGuard<R> = [ErrorOf<R>] extends [never]\n ? CannotFail\n : [ErrorOf<R>] extends [{ readonly kind: string }]\n ? unknown\n : BadFailure;\n\ntype HandlerBase<E, H> = { [K in keyof H]: K extends KindsOf<E> ? {} | null : never };\ntype HandlerFns<E, H> = {\n [K in keyof H]-?: (failure: Extract<E, { readonly kind: K }>) => H[K];\n};\ntype LiteralKind = '' | (string & {});\ntype MapperBase<E, M> = { [K in keyof M]: K extends KindsOf<E> ? { readonly kind: LiteralKind } : never };\ntype MapperFns<E, M> = {\n [K in keyof M]-?: (failure: Extract<E, { readonly kind: K }>) => M[K];\n};\ntype KindCheck<M> = [\n { [K in keyof M]-?: M[K] extends { readonly kind: infer Kd } ? (string extends Kd ? 1 : never) : 1 }[keyof M],\n] extends [never]\n ? []\n : [problem: NeedsLiteralKind];\n\ntype Remaining<E, H> = Exclude<E, { readonly kind: keyof H & string }>;\ntype Decided<R, H> = [Remaining<ErrorOf<R>, H>] extends [never]\n ? Ok<OkOf<R> | H[keyof H]>\n : Ok<OkOf<R> | H[keyof H]> | Err<Remaining<ErrorOf<R>, H>>;\ntype Translated<R, M> = Ok<OkOf<R>> | Err<M[keyof M] | Remaining<ErrorOf<R>, M>>;\n\nfunction pick(table: object, kind: unknown): ((failure: unknown) => unknown) | undefined {\n if (typeof kind !== 'string' || !Object.prototype.hasOwnProperty.call(table, kind)) return undefined;\n return (table as Record<string, (failure: unknown) => unknown>)[kind];\n}\n\n/**\n * The only place a failure may stop: a failure whose kind has a handler becomes\n * `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous.\n */\nexport function decide<R extends Result<unknown, unknown>, H extends HandlerBase<ErrorOf<R>, H>>(\n result: R & FailureGuard<R>,\n handlers: HandlerFns<ErrorOf<R>, H>,\n): Decided<R, H>;\nexport function decide(result: Result<unknown, unknown>, handlers: object): unknown {\n if (result.ok) return result;\n const handler = pick(handlers, (result.error as { kind?: unknown } | null)?.kind);\n return handler === undefined ? result : ok(handler(result.error));\n}\n\n/** Turns failures into different failures; unmapped failures and successes pass through untouched. */\nexport function translate<R extends Result<unknown, unknown>, M extends MapperBase<ErrorOf<R>, M>>(\n result: R & FailureGuard<R>,\n mappers: MapperFns<ErrorOf<R>, M>,\n ...check: KindCheck<M>\n): Translated<R, M>;\nexport function translate(result: Result<unknown, unknown>, mappers: object): unknown {\n if (result.ok) return result;\n const mapper = pick(mappers, (result.error as { kind?: unknown } | null)?.kind);\n return mapper === undefined ? result : err(mapper(result.error));\n}\n\n/** Namespace form: `Result.ok`, `Result.err`, `Result.try`, `Result.tryAsync`, `Result.decide`, `Result.translate`. */\nexport const Result: {\n readonly ok: typeof ok;\n readonly err: typeof err;\n readonly try: typeof tryResult;\n readonly tryAsync: typeof tryResultAsync;\n readonly decide: typeof decide;\n readonly translate: typeof translate;\n} = { ok, err, try: tryResult, tryAsync: tryResultAsync, decide, translate };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeO,SAAS,GAAM,OAAiB;AACrC,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;AAaO,SAAS,IAAO,OAAkB;AACvC,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;AAWO,SAAS,UAAgB,IAAa,SAA8C;AACzF,MAAI;AACF,WAAO,GAAG,GAAG,CAAC;AAAA,EAChB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAcA,eAAsB,eACpB,IACA,SACuB;AACvB,MAAI;AACF,WAAO,GAAG,MAAM,GAAG,CAAC;AAAA,EACtB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAuCA,SAAS,KAAK,OAAe,MAA4D;AACvF,MAAI,OAAO,SAAS,YAAY,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,IAAI,EAAG,QAAO;AAC3F,SAAQ,MAAwD,IAAI;AACtE;AAUO,SAAS,OAAO,QAAkC,UAA2B;AAClF,MAAI,OAAO,GAAI,QAAO;AACtB,QAAM,UAAU,KAAK,UAAW,OAAO,OAAqC,IAAI;AAChF,SAAO,YAAY,SAAY,SAAS,GAAG,QAAQ,OAAO,KAAK,CAAC;AAClE;AAQO,SAAS,UAAU,QAAkC,SAA0B;AACpF,MAAI,OAAO,GAAI,QAAO;AACtB,QAAM,SAAS,KAAK,SAAU,OAAO,OAAqC,IAAI;AAC9E,SAAO,WAAW,SAAY,SAAS,IAAI,OAAO,OAAO,KAAK,CAAC;AACjE;AAGO,IAAM,SAOT,EAAE,IAAI,KAAK,KAAK,WAAW,UAAU,gBAAgB,QAAQ,UAAU;","names":[]}
package/dist/index.d.cts CHANGED
@@ -18,25 +18,103 @@ type Err<E> = {
18
18
  };
19
19
  /** Wraps a success value. */
20
20
  declare function ok<T>(value: T): Ok<T>;
21
- /** Wraps a failure value. Pass a typed error, not a raw caught value. */
21
+ /**
22
+ * Wraps a failure value. Pass a typed error, not a raw caught value.
23
+ *
24
+ * The first overload keeps a literal `kind` for inline failures (`err({ kind: 'X' })`
25
+ * gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection. `E` itself is
26
+ * still a plain type parameter, so a declared `Result` return type sets it and other
27
+ * literal fields keep their declared union types. The second overload covers
28
+ * arguments that cannot meet the intersection (generic, unknown, null, undefined).
29
+ */
30
+ declare function err<E, K extends string = string>(error: E & {
31
+ readonly kind?: K;
32
+ }): Err<E>;
22
33
  declare function err<E>(error: E): Err<E>;
23
34
  /**
24
35
  * Runs `fn` and converts anything it throws into `Err` via `onError`.
25
36
  * Calls made directly inside `fn` count as guarded for the trust lint rules.
26
37
  */
38
+ declare function tryResult<T, E, K extends string = string>(fn: () => T, onError: (cause: unknown) => E & {
39
+ readonly kind?: K;
40
+ }): Result<T, E>;
27
41
  declare function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E>;
28
42
  /**
29
43
  * Awaits `fn` and converts a throw or rejection into `Err` via `onError`.
30
44
  * Calls made directly inside `fn` count as guarded for the trust lint rules.
31
45
  */
46
+ declare function tryResultAsync<T, E, K extends string = string>(fn: () => T | PromiseLike<T>, onError: (cause: unknown) => E & {
47
+ readonly kind?: K;
48
+ }): Promise<Result<T, E>>;
32
49
  declare function tryResultAsync<T, E>(fn: () => T | PromiseLike<T>, onError: (cause: unknown) => E): Promise<Result<T, E>>;
50
+ /** A failure is an object with a literal `kind` plus any fields. */
51
+ type Failure<K extends string = string, Fields extends object = {}> = {
52
+ readonly kind: K;
53
+ } & Readonly<Fields>;
54
+ type KindsOf<E> = E extends {
55
+ readonly kind: infer K extends string;
56
+ } ? K : never;
57
+ type ErrorOf<R> = R extends Err<infer E> ? E : never;
58
+ type OkOf<R> = R extends Ok<infer T> ? T : never;
59
+ type CannotFail = {
60
+ readonly __trust: 'decide needs a result that can fail (it has no Err member)';
61
+ };
62
+ type BadFailure = {
63
+ readonly __trust: 'every failure needs a string `kind` (string and Error are not failures)';
64
+ };
65
+ type NeedsLiteralKind = {
66
+ readonly __trust: 'a translate mapper must return an object with a literal string kind';
67
+ };
68
+ type FailureGuard<R> = [ErrorOf<R>] extends [never] ? CannotFail : [ErrorOf<R>] extends [{
69
+ readonly kind: string;
70
+ }] ? unknown : BadFailure;
71
+ type HandlerBase<E, H> = {
72
+ [K in keyof H]: K extends KindsOf<E> ? {} | null : never;
73
+ };
74
+ type HandlerFns<E, H> = {
75
+ [K in keyof H]-?: (failure: Extract<E, {
76
+ readonly kind: K;
77
+ }>) => H[K];
78
+ };
79
+ type LiteralKind = '' | (string & {});
80
+ type MapperBase<E, M> = {
81
+ [K in keyof M]: K extends KindsOf<E> ? {
82
+ readonly kind: LiteralKind;
83
+ } : never;
84
+ };
85
+ type MapperFns<E, M> = {
86
+ [K in keyof M]-?: (failure: Extract<E, {
87
+ readonly kind: K;
88
+ }>) => M[K];
89
+ };
90
+ type KindCheck<M> = [
91
+ {
92
+ [K in keyof M]-?: M[K] extends {
93
+ readonly kind: infer Kd;
94
+ } ? (string extends Kd ? 1 : never) : 1;
95
+ }[keyof M]
96
+ ] extends [never] ? [] : [problem: NeedsLiteralKind];
97
+ type Remaining<E, H> = Exclude<E, {
98
+ readonly kind: keyof H & string;
99
+ }>;
100
+ type Decided<R, H> = [Remaining<ErrorOf<R>, H>] extends [never] ? Ok<OkOf<R> | H[keyof H]> : Ok<OkOf<R> | H[keyof H]> | Err<Remaining<ErrorOf<R>, H>>;
101
+ type Translated<R, M> = Ok<OkOf<R>> | Err<M[keyof M] | Remaining<ErrorOf<R>, M>>;
102
+ /**
103
+ * The only place a failure may stop: a failure whose kind has a handler becomes
104
+ * `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous.
105
+ */
106
+ declare function decide<R extends Result<unknown, unknown>, H extends HandlerBase<ErrorOf<R>, H>>(result: R & FailureGuard<R>, handlers: HandlerFns<ErrorOf<R>, H>): Decided<R, H>;
107
+ /** Turns failures into different failures; unmapped failures and successes pass through untouched. */
108
+ declare function translate<R extends Result<unknown, unknown>, M extends MapperBase<ErrorOf<R>, M>>(result: R & FailureGuard<R>, mappers: MapperFns<ErrorOf<R>, M>, ...check: KindCheck<M>): Translated<R, M>;
33
109
  type Result<T, E> = Ok<T> | Err<E>;
34
- /** Namespace form: `Result.ok`, `Result.err`, `Result.try`, `Result.tryAsync`. */
110
+ /** Namespace form: `Result.ok`, `Result.err`, `Result.try`, `Result.tryAsync`, `Result.decide`, `Result.translate`. */
35
111
  declare const Result: {
36
112
  readonly ok: typeof ok;
37
113
  readonly err: typeof err;
38
114
  readonly try: typeof tryResult;
39
115
  readonly tryAsync: typeof tryResultAsync;
116
+ readonly decide: typeof decide;
117
+ readonly translate: typeof translate;
40
118
  };
41
119
 
42
- export { type Err, type Ok, Result, err, ok, tryResult, tryResultAsync };
120
+ export { type Err, type Failure, type Ok, Result, decide, err, ok, translate, tryResult, tryResultAsync };
package/dist/index.d.ts CHANGED
@@ -18,25 +18,103 @@ type Err<E> = {
18
18
  };
19
19
  /** Wraps a success value. */
20
20
  declare function ok<T>(value: T): Ok<T>;
21
- /** Wraps a failure value. Pass a typed error, not a raw caught value. */
21
+ /**
22
+ * Wraps a failure value. Pass a typed error, not a raw caught value.
23
+ *
24
+ * The first overload keeps a literal `kind` for inline failures (`err({ kind: 'X' })`
25
+ * gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection. `E` itself is
26
+ * still a plain type parameter, so a declared `Result` return type sets it and other
27
+ * literal fields keep their declared union types. The second overload covers
28
+ * arguments that cannot meet the intersection (generic, unknown, null, undefined).
29
+ */
30
+ declare function err<E, K extends string = string>(error: E & {
31
+ readonly kind?: K;
32
+ }): Err<E>;
22
33
  declare function err<E>(error: E): Err<E>;
23
34
  /**
24
35
  * Runs `fn` and converts anything it throws into `Err` via `onError`.
25
36
  * Calls made directly inside `fn` count as guarded for the trust lint rules.
26
37
  */
38
+ declare function tryResult<T, E, K extends string = string>(fn: () => T, onError: (cause: unknown) => E & {
39
+ readonly kind?: K;
40
+ }): Result<T, E>;
27
41
  declare function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E>;
28
42
  /**
29
43
  * Awaits `fn` and converts a throw or rejection into `Err` via `onError`.
30
44
  * Calls made directly inside `fn` count as guarded for the trust lint rules.
31
45
  */
46
+ declare function tryResultAsync<T, E, K extends string = string>(fn: () => T | PromiseLike<T>, onError: (cause: unknown) => E & {
47
+ readonly kind?: K;
48
+ }): Promise<Result<T, E>>;
32
49
  declare function tryResultAsync<T, E>(fn: () => T | PromiseLike<T>, onError: (cause: unknown) => E): Promise<Result<T, E>>;
50
+ /** A failure is an object with a literal `kind` plus any fields. */
51
+ type Failure<K extends string = string, Fields extends object = {}> = {
52
+ readonly kind: K;
53
+ } & Readonly<Fields>;
54
+ type KindsOf<E> = E extends {
55
+ readonly kind: infer K extends string;
56
+ } ? K : never;
57
+ type ErrorOf<R> = R extends Err<infer E> ? E : never;
58
+ type OkOf<R> = R extends Ok<infer T> ? T : never;
59
+ type CannotFail = {
60
+ readonly __trust: 'decide needs a result that can fail (it has no Err member)';
61
+ };
62
+ type BadFailure = {
63
+ readonly __trust: 'every failure needs a string `kind` (string and Error are not failures)';
64
+ };
65
+ type NeedsLiteralKind = {
66
+ readonly __trust: 'a translate mapper must return an object with a literal string kind';
67
+ };
68
+ type FailureGuard<R> = [ErrorOf<R>] extends [never] ? CannotFail : [ErrorOf<R>] extends [{
69
+ readonly kind: string;
70
+ }] ? unknown : BadFailure;
71
+ type HandlerBase<E, H> = {
72
+ [K in keyof H]: K extends KindsOf<E> ? {} | null : never;
73
+ };
74
+ type HandlerFns<E, H> = {
75
+ [K in keyof H]-?: (failure: Extract<E, {
76
+ readonly kind: K;
77
+ }>) => H[K];
78
+ };
79
+ type LiteralKind = '' | (string & {});
80
+ type MapperBase<E, M> = {
81
+ [K in keyof M]: K extends KindsOf<E> ? {
82
+ readonly kind: LiteralKind;
83
+ } : never;
84
+ };
85
+ type MapperFns<E, M> = {
86
+ [K in keyof M]-?: (failure: Extract<E, {
87
+ readonly kind: K;
88
+ }>) => M[K];
89
+ };
90
+ type KindCheck<M> = [
91
+ {
92
+ [K in keyof M]-?: M[K] extends {
93
+ readonly kind: infer Kd;
94
+ } ? (string extends Kd ? 1 : never) : 1;
95
+ }[keyof M]
96
+ ] extends [never] ? [] : [problem: NeedsLiteralKind];
97
+ type Remaining<E, H> = Exclude<E, {
98
+ readonly kind: keyof H & string;
99
+ }>;
100
+ type Decided<R, H> = [Remaining<ErrorOf<R>, H>] extends [never] ? Ok<OkOf<R> | H[keyof H]> : Ok<OkOf<R> | H[keyof H]> | Err<Remaining<ErrorOf<R>, H>>;
101
+ type Translated<R, M> = Ok<OkOf<R>> | Err<M[keyof M] | Remaining<ErrorOf<R>, M>>;
102
+ /**
103
+ * The only place a failure may stop: a failure whose kind has a handler becomes
104
+ * `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous.
105
+ */
106
+ declare function decide<R extends Result<unknown, unknown>, H extends HandlerBase<ErrorOf<R>, H>>(result: R & FailureGuard<R>, handlers: HandlerFns<ErrorOf<R>, H>): Decided<R, H>;
107
+ /** Turns failures into different failures; unmapped failures and successes pass through untouched. */
108
+ declare function translate<R extends Result<unknown, unknown>, M extends MapperBase<ErrorOf<R>, M>>(result: R & FailureGuard<R>, mappers: MapperFns<ErrorOf<R>, M>, ...check: KindCheck<M>): Translated<R, M>;
33
109
  type Result<T, E> = Ok<T> | Err<E>;
34
- /** Namespace form: `Result.ok`, `Result.err`, `Result.try`, `Result.tryAsync`. */
110
+ /** Namespace form: `Result.ok`, `Result.err`, `Result.try`, `Result.tryAsync`, `Result.decide`, `Result.translate`. */
35
111
  declare const Result: {
36
112
  readonly ok: typeof ok;
37
113
  readonly err: typeof err;
38
114
  readonly try: typeof tryResult;
39
115
  readonly tryAsync: typeof tryResultAsync;
116
+ readonly decide: typeof decide;
117
+ readonly translate: typeof translate;
40
118
  };
41
119
 
42
- export { type Err, type Ok, Result, err, ok, tryResult, tryResultAsync };
120
+ export { type Err, type Failure, type Ok, Result, decide, err, ok, translate, tryResult, tryResultAsync };
package/dist/index.js CHANGED
@@ -19,11 +19,27 @@ async function tryResultAsync(fn, onError) {
19
19
  return err(onError(cause));
20
20
  }
21
21
  }
22
- var Result = { ok, err, try: tryResult, tryAsync: tryResultAsync };
22
+ function pick(table, kind) {
23
+ if (typeof kind !== "string" || !Object.prototype.hasOwnProperty.call(table, kind)) return void 0;
24
+ return table[kind];
25
+ }
26
+ function decide(result, handlers) {
27
+ if (result.ok) return result;
28
+ const handler = pick(handlers, result.error?.kind);
29
+ return handler === void 0 ? result : ok(handler(result.error));
30
+ }
31
+ function translate(result, mappers) {
32
+ if (result.ok) return result;
33
+ const mapper = pick(mappers, result.error?.kind);
34
+ return mapper === void 0 ? result : err(mapper(result.error));
35
+ }
36
+ var Result = { ok, err, try: tryResult, tryAsync: tryResultAsync, decide, translate };
23
37
  export {
24
38
  Result,
39
+ decide,
25
40
  err,
26
41
  ok,
42
+ translate,
27
43
  tryResult,
28
44
  tryResultAsync
29
45
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Closed result primitive: expected failures are values, not exceptions.\n *\n * `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no\n * imports so it is safe in any bundle (Node, Electron main, renderer, browser).\n *\n * The `@noego/trust/eslint` rules recognise these declarations by identity (not by\n * name): a call whose declared return type is a `Result` from this module is\n * trusted, and a `catch` is accepted when it returns an `Err` from this module.\n */\nexport type Ok<T> = { readonly ok: true; readonly value: T };\nexport type Err<E> = { readonly ok: false; readonly error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/** Wraps a success value. */\nexport function ok<T>(value: T): Ok<T> {\n return { ok: true, value };\n}\n\n/** Wraps a failure value. Pass a typed error, not a raw caught value. */\nexport function err<E>(error: E): Err<E> {\n return { ok: false, error };\n}\n\n/**\n * Runs `fn` and converts anything it throws into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E> {\n try {\n return ok(fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/**\n * Awaits `fn` and converts a throw or rejection into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport async function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>> {\n try {\n return ok(await fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/** Namespace form: `Result.ok`, `Result.err`, `Result.try`, `Result.tryAsync`. */\nexport const Result: {\n readonly ok: typeof ok;\n readonly err: typeof err;\n readonly try: typeof tryResult;\n readonly tryAsync: typeof tryResultAsync;\n} = { ok, err, try: tryResult, tryAsync: tryResultAsync };\n"],"mappings":";AAeO,SAAS,GAAM,OAAiB;AACrC,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;AAGO,SAAS,IAAO,OAAkB;AACvC,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;AAMO,SAAS,UAAgB,IAAa,SAA8C;AACzF,MAAI;AACF,WAAO,GAAG,GAAG,CAAC;AAAA,EAChB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAMA,eAAsB,eACpB,IACA,SACuB;AACvB,MAAI;AACF,WAAO,GAAG,MAAM,GAAG,CAAC;AAAA,EACtB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAGO,IAAM,SAKT,EAAE,IAAI,KAAK,KAAK,WAAW,UAAU,eAAe;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Closed result primitive: expected failures are values, not exceptions.\n *\n * `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no\n * imports so it is safe in any bundle (Node, Electron main, renderer, browser).\n *\n * The `@noego/trust/eslint` rules recognise these declarations by identity (not by\n * name): a call whose declared return type is a `Result` from this module is\n * trusted, and a `catch` is accepted when it returns an `Err` from this module.\n */\nexport type Ok<T> = { readonly ok: true; readonly value: T };\nexport type Err<E> = { readonly ok: false; readonly error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/** Wraps a success value. */\nexport function ok<T>(value: T): Ok<T> {\n return { ok: true, value };\n}\n\n/**\n * Wraps a failure value. Pass a typed error, not a raw caught value.\n *\n * The first overload keeps a literal `kind` for inline failures (`err({ kind: 'X' })`\n * gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection. `E` itself is\n * still a plain type parameter, so a declared `Result` return type sets it and other\n * literal fields keep their declared union types. The second overload covers\n * arguments that cannot meet the intersection (generic, unknown, null, undefined).\n */\nexport function err<E, K extends string = string>(error: E & { readonly kind?: K }): Err<E>;\nexport function err<E>(error: E): Err<E>;\nexport function err<E>(error: E): Err<E> {\n return { ok: false, error };\n}\n\n/**\n * Runs `fn` and converts anything it throws into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResult<T, E, K extends string = string>(\n fn: () => T,\n onError: (cause: unknown) => E & { readonly kind?: K },\n): Result<T, E>;\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E>;\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E> {\n try {\n return ok(fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/**\n * Awaits `fn` and converts a throw or rejection into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResultAsync<T, E, K extends string = string>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E & { readonly kind?: K },\n): Promise<Result<T, E>>;\nexport function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>>;\nexport async function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>> {\n try {\n return ok(await fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/** A failure is an object with a literal `kind` plus any fields. */\nexport type Failure<K extends string = string, Fields extends object = {}> = { readonly kind: K } & Readonly<Fields>;\n\ntype KindsOf<E> = E extends { readonly kind: infer K extends string } ? K : never;\ntype ErrorOf<R> = R extends Err<infer E> ? E : never;\ntype OkOf<R> = R extends Ok<infer T> ? T : never;\ntype CannotFail = { readonly __trust: 'decide needs a result that can fail (it has no Err member)' };\ntype BadFailure = { readonly __trust: 'every failure needs a string `kind` (string and Error are not failures)' };\ntype NeedsLiteralKind = { readonly __trust: 'a translate mapper must return an object with a literal string kind' };\n\ntype FailureGuard<R> = [ErrorOf<R>] extends [never]\n ? CannotFail\n : [ErrorOf<R>] extends [{ readonly kind: string }]\n ? unknown\n : BadFailure;\n\ntype HandlerBase<E, H> = { [K in keyof H]: K extends KindsOf<E> ? {} | null : never };\ntype HandlerFns<E, H> = {\n [K in keyof H]-?: (failure: Extract<E, { readonly kind: K }>) => H[K];\n};\ntype LiteralKind = '' | (string & {});\ntype MapperBase<E, M> = { [K in keyof M]: K extends KindsOf<E> ? { readonly kind: LiteralKind } : never };\ntype MapperFns<E, M> = {\n [K in keyof M]-?: (failure: Extract<E, { readonly kind: K }>) => M[K];\n};\ntype KindCheck<M> = [\n { [K in keyof M]-?: M[K] extends { readonly kind: infer Kd } ? (string extends Kd ? 1 : never) : 1 }[keyof M],\n] extends [never]\n ? []\n : [problem: NeedsLiteralKind];\n\ntype Remaining<E, H> = Exclude<E, { readonly kind: keyof H & string }>;\ntype Decided<R, H> = [Remaining<ErrorOf<R>, H>] extends [never]\n ? Ok<OkOf<R> | H[keyof H]>\n : Ok<OkOf<R> | H[keyof H]> | Err<Remaining<ErrorOf<R>, H>>;\ntype Translated<R, M> = Ok<OkOf<R>> | Err<M[keyof M] | Remaining<ErrorOf<R>, M>>;\n\nfunction pick(table: object, kind: unknown): ((failure: unknown) => unknown) | undefined {\n if (typeof kind !== 'string' || !Object.prototype.hasOwnProperty.call(table, kind)) return undefined;\n return (table as Record<string, (failure: unknown) => unknown>)[kind];\n}\n\n/**\n * The only place a failure may stop: a failure whose kind has a handler becomes\n * `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous.\n */\nexport function decide<R extends Result<unknown, unknown>, H extends HandlerBase<ErrorOf<R>, H>>(\n result: R & FailureGuard<R>,\n handlers: HandlerFns<ErrorOf<R>, H>,\n): Decided<R, H>;\nexport function decide(result: Result<unknown, unknown>, handlers: object): unknown {\n if (result.ok) return result;\n const handler = pick(handlers, (result.error as { kind?: unknown } | null)?.kind);\n return handler === undefined ? result : ok(handler(result.error));\n}\n\n/** Turns failures into different failures; unmapped failures and successes pass through untouched. */\nexport function translate<R extends Result<unknown, unknown>, M extends MapperBase<ErrorOf<R>, M>>(\n result: R & FailureGuard<R>,\n mappers: MapperFns<ErrorOf<R>, M>,\n ...check: KindCheck<M>\n): Translated<R, M>;\nexport function translate(result: Result<unknown, unknown>, mappers: object): unknown {\n if (result.ok) return result;\n const mapper = pick(mappers, (result.error as { kind?: unknown } | null)?.kind);\n return mapper === undefined ? result : err(mapper(result.error));\n}\n\n/** Namespace form: `Result.ok`, `Result.err`, `Result.try`, `Result.tryAsync`, `Result.decide`, `Result.translate`. */\nexport const Result: {\n readonly ok: typeof ok;\n readonly err: typeof err;\n readonly try: typeof tryResult;\n readonly tryAsync: typeof tryResultAsync;\n readonly decide: typeof decide;\n readonly translate: typeof translate;\n} = { ok, err, try: tryResult, tryAsync: tryResultAsync, decide, translate };\n"],"mappings":";AAeO,SAAS,GAAM,OAAiB;AACrC,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;AAaO,SAAS,IAAO,OAAkB;AACvC,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;AAWO,SAAS,UAAgB,IAAa,SAA8C;AACzF,MAAI;AACF,WAAO,GAAG,GAAG,CAAC;AAAA,EAChB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAcA,eAAsB,eACpB,IACA,SACuB;AACvB,MAAI;AACF,WAAO,GAAG,MAAM,GAAG,CAAC;AAAA,EACtB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAuCA,SAAS,KAAK,OAAe,MAA4D;AACvF,MAAI,OAAO,SAAS,YAAY,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,IAAI,EAAG,QAAO;AAC3F,SAAQ,MAAwD,IAAI;AACtE;AAUO,SAAS,OAAO,QAAkC,UAA2B;AAClF,MAAI,OAAO,GAAI,QAAO;AACtB,QAAM,UAAU,KAAK,UAAW,OAAO,OAAqC,IAAI;AAChF,SAAO,YAAY,SAAY,SAAS,GAAG,QAAQ,OAAO,KAAK,CAAC;AAClE;AAQO,SAAS,UAAU,QAAkC,SAA0B;AACpF,MAAI,OAAO,GAAI,QAAO;AACtB,QAAM,SAAS,KAAK,SAAU,OAAO,OAAqC,IAAI;AAC9E,SAAO,WAAW,SAAY,SAAS,IAAI,OAAO,OAAO,KAAK,CAAC;AACjE;AAGO,IAAM,SAOT,EAAE,IAAI,KAAK,KAAK,WAAW,UAAU,gBAAgB,QAAQ,UAAU;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/trust",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Result type plus type-aware ESLint rules that make failure handling explicit: untrusted calls and throws must be caught locally and returned as Result.err.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",