@backendkit-labs/result 0.1.2 → 0.2.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/LICENSE ADDED
@@ -0,0 +1,184 @@
1
+  Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and the Work's derivative works.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and subsequently
61
+ incorporated within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or contributory
82
+ patent infringement, then any patent licenses granted to You under
83
+ this License for that Work shall terminate as of the date such
84
+ litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, and
120
+ distribute Your modifications, or for such Derivative Works as a
121
+ whole, subject to the terms and conditions of this License.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any warranties or conditions
141
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
142
+ PARTICULAR PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or exemplary damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or all other
155
+ commercial damages or losses), even if such Contributor has been
156
+ advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may act only
163
+ on Your own behalf and on Your sole responsibility, not on behalf
164
+ of any other Contributor, and only if You agree to indemnify,
165
+ defend, and hold each Contributor harmless for any liability
166
+ incurred by, or claims asserted against, such Contributor by reason
167
+ of your accepting any such warranty or additional liability.
168
+
169
+ END OF TERMS AND CONDITIONS
170
+
171
+ Copyright 2024-2026 Mairon Cuello / BackendKit Labs
172
+
173
+ Licensed under the Apache License, Version 2.0 (the "License");
174
+ you may not use this file except in compliance with the License.
175
+ You may obtain a copy of the License at
176
+
177
+ http://www.apache.org/licenses/LICENSE-2.0
178
+
179
+ Unless required by applicable law or agreed to in writing, software
180
+ distributed under the License is distributed on an "AS IS" BASIS,
181
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
182
+ See the License for the specific language governing permissions and
183
+ limitations under the License.
184
+
package/README.md CHANGED
@@ -1,9 +1,10 @@
1
1
  # @backendkit-labs/result
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/@backendkit-labs/result?style=flat-square&color=cb3837)](https://www.npmjs.com/package/@backendkit-labs/result)
4
- [![CI](https://img.shields.io/github/actions/workflow/status/backendkit-dev/backendkit-monorepo/ci.yml?style=flat-square&label=CI)](https://github.com/backendkit-dev/backendkit-monorepo/actions/workflows/ci.yml)
4
+ [![CI](https://img.shields.io/github/actions/workflow/status/BackendKit-labs/backendkit-monorepo/ci.yml?style=flat-square&label=CI)](https://github.com/BackendKit-labs/backendkit-monorepo/actions/workflows/ci.yml)
5
5
  [![License](https://img.shields.io/npm/l/@backendkit-labs/result?style=flat-square)](LICENSE)
6
6
  [![Node](https://img.shields.io/node/v/@backendkit-labs/result?style=flat-square)](package.json)
7
+ [![Docs](https://img.shields.io/badge/docs-backendkitlabs.dev-4f7eff?style=flat-square)](https://backendkitlabs.dev/docs/result/)
7
8
 
8
9
  > Type-safe Result monad for Node.js. Generic error types, observability, resilience, and optional NestJS integration. Zero runtime dependencies.
9
10
 
@@ -46,6 +47,65 @@ npm install @nestjs/common @nestjs/core rxjs
46
47
 
47
48
  ---
48
49
 
50
+ ## TypeScript Configuration
51
+
52
+ ### Subpath exports (`/nestjs`)
53
+
54
+ This package uses the `exports` field in `package.json` to expose the `/nestjs` subpath. TypeScript's ability to resolve it depends on the `moduleResolution` setting in your `tsconfig.json`.
55
+
56
+ **Modern resolution (recommended) — no extra config needed:**
57
+
58
+ ```json
59
+ {
60
+ "compilerOptions": {
61
+ "moduleResolution": "bundler"
62
+ }
63
+ }
64
+ ```
65
+
66
+ `"bundler"`, `"node16"`, and `"nodenext"` all understand the `exports` field natively. This is the recommended setting for any project using a bundler or NestJS on TypeScript ≥ 5.
67
+
68
+ **Legacy resolution (`"node"`) — add a `paths` alias:**
69
+
70
+ NestJS projects generated before ~2024 default to `"moduleResolution": "node"`, which ignores the `exports` field. Add an explicit alias so TypeScript can find the types:
71
+
72
+ ```json
73
+ {
74
+ "compilerOptions": {
75
+ "moduleResolution": "node",
76
+ "paths": {
77
+ "@backendkit-labs/result/nestjs": [
78
+ "./node_modules/@backendkit-labs/result/dist/nestjs/index"
79
+ ]
80
+ }
81
+ }
82
+ }
83
+ ```
84
+
85
+ > **Why?** The `"node"` resolver was designed before subpath exports existed and only reads `main`/`types` at the package root — it ignores the `exports` map entirely. The `paths` alias manually points TypeScript to the correct `.d.ts` file.
86
+
87
+ ### NestJS decorator support
88
+
89
+ ```json
90
+ {
91
+ "compilerOptions": {
92
+ "experimentalDecorators": true,
93
+ "emitDecoratorMetadata": true
94
+ }
95
+ }
96
+ ```
97
+
98
+ And import `reflect-metadata` once at application startup:
99
+
100
+ ```typescript
101
+ // main.ts
102
+ import 'reflect-metadata';
103
+ ```
104
+
105
+ > NestJS CLI scaffolds these automatically. You only need to verify them if setting up a project manually.
106
+
107
+ ---
108
+
49
109
  ## Quick Start
50
110
 
51
111
  ```typescript
@@ -1149,4 +1209,4 @@ The core is a pure TypeScript library with no runtime dependencies. The NestJS l
1149
1209
 
1150
1210
  ## License
1151
1211
 
1152
- MIT — [BackendKit Labs](https://github.com/backendkit-dev)
1212
+ Apache-2.0 — [BackendKit Labs](https://github.com/BackendKit-labs)
package/dist/index.cjs CHANGED
@@ -61,6 +61,7 @@ function toUndefined(result) {
61
61
 
62
62
  // src/result/resilience.ts
63
63
  async function retry(fn, options) {
64
+ if (options.attempts < 1) throw new Error("retry() attempts must be at least 1");
64
65
  let last;
65
66
  for (let attempt = 1; attempt <= options.attempts; attempt++) {
66
67
  last = await fn();
@@ -73,6 +74,7 @@ async function retry(fn, options) {
73
74
  return last;
74
75
  }
75
76
  async function retryWithBackoff(fn, options) {
77
+ if (options.attempts < 1) throw new Error("retryWithBackoff() attempts must be at least 1");
76
78
  let last;
77
79
  for (let attempt = 1; attempt <= options.attempts; attempt++) {
78
80
  last = await fn();
@@ -85,10 +87,15 @@ async function retryWithBackoff(fn, options) {
85
87
  return last;
86
88
  }
87
89
  async function withTimeout(fn, ms, timeoutError) {
88
- const timer = new Promise(
89
- (resolve) => setTimeout(() => resolve(chunkGCGL2Y6D_cjs.fail(timeoutError)), ms)
90
- );
91
- return Promise.race([fn(), timer]);
90
+ let timerId;
91
+ const timer = new Promise((resolve) => {
92
+ timerId = setTimeout(() => resolve(chunkGCGL2Y6D_cjs.fail(timeoutError)), ms);
93
+ });
94
+ try {
95
+ return await Promise.race([fn(), timer]);
96
+ } finally {
97
+ clearTimeout(timerId);
98
+ }
92
99
  }
93
100
  function computeBackoffDelay(attempt, options) {
94
101
  const base = (options.delayMs ?? 100) * Math.pow(2, attempt - 1);
@@ -113,6 +120,7 @@ function all(results) {
113
120
  return chunkGCGL2Y6D_cjs.ok(values);
114
121
  }
115
122
  async function any(operations) {
123
+ if (operations.length === 0) throw new Error("any() requires at least one operation");
116
124
  let last;
117
125
  for (const op of operations) {
118
126
  last = await op();
@@ -121,7 +129,10 @@ async function any(operations) {
121
129
  return last;
122
130
  }
123
131
  async function parallel(operations, options) {
124
- const concurrency = options?.concurrency ?? operations.length;
132
+ if (options?.concurrency !== void 0 && options.concurrency < 1) {
133
+ throw new Error("parallel() concurrency must be at least 1");
134
+ }
135
+ const concurrency = options?.concurrency ?? (operations.length || 1);
125
136
  const results = [];
126
137
  for (let i = 0; i < operations.length; i += concurrency) {
127
138
  const batch = await Promise.all(operations.slice(i, i + concurrency).map((op) => op()));
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/result/operations.ts","../src/result/resilience.ts","../src/result/combinators.ts","../src/result/flow.ts"],"names":["ok","fail","isRich"],"mappings":";;;;;AAMO,SAAS,GAAA,CAAa,QAAsB,EAAA,EAAmC;AACpF,EAAA,OAAO,OAAO,EAAA,GAAKA,oBAAA,CAAG,GAAG,MAAA,CAAO,KAAK,CAAC,CAAA,GAAI,MAAA;AAC5C;AAGO,SAAS,QAAA,CAAkB,QAAsB,EAAA,EAAmC;AACzF,EAAA,OAAO,OAAO,EAAA,GAAK,MAAA,GAASC,uBAAK,EAAA,CAAG,MAAA,CAAO,KAAK,CAAC,CAAA;AACnD;AAGO,SAAS,OAAA,CACd,QACA,EAAA,EACc;AACd,EAAA,OAAO,MAAA,CAAO,EAAA,GAAK,EAAA,CAAG,MAAA,CAAO,KAAK,CAAA,GAAI,MAAA;AACxC;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,KAAK,CAAC,CAAC,CAAA;AAAA,EAC5C;AAAA;AAAA,EAGA,MAAS,QAAA,EAA6D;AACpE,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAA,GAChB,QAAA,CAAS,EAAA,CAAG,IAAA,CAAK,OAAA,CAAQ,KAAK,CAAA,GAC9B,QAAA,CAAS,IAAA,CAAK,IAAA,CAAK,QAAQ,KAAK,CAAA;AAAA,EACtC;AAAA;AAAA,EAGA,SAAA,GAA0B;AACxB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAA,GAAkC;AAChC,IAAA,IAAI,CAACE,yBAAO,IAAA,CAAK,OAAO,GAAG,MAAM,IAAI,MAAM,4BAA4B,CAAA;AACvE,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA,EAEA,IAAA,GAAkB;AAAE,IAAA,OAAO,KAAK,OAAA,CAAQ,EAAA;AAAA,EAAI;AAAA,EAC5C,MAAA,GAAkB;AAAE,IAAA,OAAO,CAAC,KAAK,OAAA,CAAQ,EAAA;AAAA,EAAI;AAC/C","file":"index.cjs","sourcesContent":["import type { Result } from './types.js';\nimport { ok, fail } from './constructors.js';\n\n// ── Transformations ────────────────────────────────────────────────────────\n\n/** Maps the success value. Passes failures through unchanged. */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return result.ok ? ok(fn(result.value)) : result;\n}\n\n/** Maps the error value. Passes successes through unchanged. */\nexport function mapError<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return result.ok ? result : fail(fn(result.error));\n}\n\n/** Monadic bind — chains a Result-returning function on success. */\nexport function flatMap<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, E>,\n): Result<U, E> {\n return result.ok ? fn(result.value) : result;\n}\n\n/** Async variant of `flatMap`. */\nexport async function flatMapAsync<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Promise<Result<U, E>>,\n): Promise<Result<U, E>> {\n return result.ok ? fn(result.value) : Promise.resolve(result);\n}\n\n/** Async variant of `map`. */\nexport async function mapAsync<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Promise<U>,\n): Promise<Result<U, E>> {\n if (!result.ok) return Promise.resolve(result);\n return ok(await fn(result.value));\n}\n\n// ── Pattern matching ───────────────────────────────────────────────────────\n\n/**\n * Exhaustive pattern match over both branches.\n *\n * @example\n * const msg = match(result, {\n * ok: (user) => `Welcome, ${user.name}`,\n * fail: (error) => `Error: ${error.message}`,\n * });\n */\nexport function match<T, E, R>(\n result: Result<T, E>,\n handlers: { ok: (value: T) => R; fail: (error: E) => R },\n): R {\n return result.ok ? handlers.ok(result.value) : handlers.fail(result.error);\n}\n\n/** Alias for `match` — familiar to fp-ts / Scala users. */\nexport const fold = match;\n\n// ── Side effects ───────────────────────────────────────────────────────────\n\n/** Runs a side effect on the success value; returns the result unchanged. */\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> {\n if (result.ok) fn(result.value);\n return result;\n}\n\n/** Runs a side effect on the error value; returns the result unchanged. */\nexport function tapError<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> {\n if (!result.ok) fn(result.error);\n return result;\n}\n\n// ── Unwrapping ─────────────────────────────────────────────────────────────\n\n/** Extracts the value or throws the error (re-thrown as-is if it's an Error, wrapped otherwise). */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (result.ok) return result.value;\n throw result.error instanceof Error ? result.error : new Error(String(result.error));\n}\n\n/** Extracts the error or throws if the result is Ok. */\nexport function unwrapError<T, E>(result: Result<T, E>): E {\n if (!result.ok) return result.error;\n throw new Error('Called unwrapError on an Ok result');\n}\n\n/** Extracts the value or returns `defaultValue` on failure. */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n return result.ok ? result.value : defaultValue;\n}\n\n/** Extracts the value or computes a fallback from the error. */\nexport function unwrapOrElse<T, E>(result: Result<T, E>, fn: (error: E) => T): T {\n return result.ok ? result.value : fn(result.error);\n}\n\n/** Extracts the value or throws with a custom `message`. */\nexport function expect<T, E>(result: Result<T, E>, message: string): T {\n if (result.ok) return result.value;\n throw new Error(message);\n}\n\n// ── Conversion ─────────────────────────────────────────────────────────────\n\n/** Converts to a Promise — resolves on Ok, rejects on Fail. */\nexport function toPromise<T, E>(result: Result<T, E>): Promise<T> {\n return result.ok ? Promise.resolve(result.value) : Promise.reject(result.error);\n}\n\n/** Returns the value or `null` on failure. */\nexport function toNullable<T, E>(result: Result<T, E>): T | null {\n return result.ok ? result.value : null;\n}\n\n/** Returns the value or `undefined` on failure. */\nexport function toUndefined<T, E>(result: Result<T, E>): T | undefined {\n return result.ok ? result.value : undefined;\n}\n","import type { Result } from './types.js';\nimport { fail } from './constructors.js';\n\nexport interface RetryOptions<E> {\n /** Maximum number of attempts (including the first). */\n attempts: number;\n /** Fixed delay in ms between attempts. Default: 0 */\n delayMs?: number;\n /** Return false to stop retrying early based on the error. */\n shouldRetry?: (error: E, attempt: number) => boolean;\n /** Called before each retry with the previous error and attempt number. */\n onRetry?: (error: E, attempt: number) => void;\n}\n\nexport interface BackoffOptions<E> extends RetryOptions<E> {\n /** Cap for the computed backoff delay. Default: 30_000 */\n maxDelayMs?: number;\n /**\n * Adds random noise to the backoff delay to avoid thundering herd when\n * multiple instances retry simultaneously.\n *\n * - `true` → full jitter: delay = random(0, computedDelay)\n * - `number` → partial jitter: delay ± (computedDelay * factor), clamped to [0, maxDelayMs]\n * e.g. 0.25 adds ±25% noise\n * - `false` → no jitter (default)\n */\n jitter?: boolean | number;\n}\n\n/**\n * Retries a Result-returning function up to `options.attempts` times with\n * an optional fixed delay between attempts.\n *\n * @example\n * const result = await retry(() => run(() => callApi()), {\n * attempts: 3,\n * delayMs: 500,\n * shouldRetry: (err) => err.code === 'ECONNRESET',\n * });\n */\nexport async function retry<T, E = Error>(\n fn: () => Promise<Result<T, E>>,\n options: RetryOptions<E>,\n): Promise<Result<T, E>> {\n let last!: Result<T, E>;\n\n for (let attempt = 1; attempt <= options.attempts; attempt++) {\n last = await fn();\n if (last.ok) return last;\n if (attempt === options.attempts) break;\n if (options.shouldRetry && !options.shouldRetry(last.error, attempt)) break;\n options.onRetry?.(last.error, attempt);\n if (options.delayMs) await sleep(options.delayMs);\n }\n\n return last;\n}\n\n/**\n * Like `retry()` but uses exponential backoff: delay doubles on each attempt,\n * capped at `maxDelayMs`.\n *\n * @example\n * const result = await retryWithBackoff(() => run(() => callApi()), {\n * attempts: 4,\n * delayMs: 100, // 100ms → 200ms → 400ms\n * maxDelayMs: 1_000,\n * });\n */\nexport async function retryWithBackoff<T, E = Error>(\n fn: () => Promise<Result<T, E>>,\n options: BackoffOptions<E>,\n): Promise<Result<T, E>> {\n let last!: Result<T, E>;\n\n for (let attempt = 1; attempt <= options.attempts; attempt++) {\n last = await fn();\n if (last.ok) return last;\n if (attempt === options.attempts) break;\n if (options.shouldRetry && !options.shouldRetry(last.error, attempt)) break;\n options.onRetry?.(last.error, attempt);\n await sleep(computeBackoffDelay(attempt, options));\n }\n\n return last;\n}\n\n/**\n * Races a Result-returning function against a timeout.\n * Returns `fail(timeoutError)` if `ms` elapses before the function resolves.\n *\n * @example\n * const result = await withTimeout(\n * () => run(() => fetchData()),\n * 5_000,\n * new TimeoutError('fetchData timed out'),\n * );\n */\nexport async function withTimeout<T, E>(\n fn: () => Promise<Result<T, E>>,\n ms: number,\n timeoutError: E,\n): Promise<Result<T, E>> {\n const timer = new Promise<Result<T, E>>(resolve =>\n setTimeout(() => resolve(fail<T, E>(timeoutError)), ms),\n );\n return Promise.race([fn(), timer]);\n}\n\nfunction computeBackoffDelay<E>(attempt: number, options: BackoffOptions<E>): number {\n const base = (options.delayMs ?? 100) * Math.pow(2, attempt - 1);\n const capped = Math.min(base, options.maxDelayMs ?? 30_000);\n const { jitter } = options;\n\n if (!jitter) return capped;\n\n if (jitter === true) {\n // Full jitter: uniform random in [0, capped] — maximises spread across instances\n return Math.random() * capped;\n }\n\n // Partial jitter: ± (capped * factor), stays within [0, maxDelayMs]\n const noise = (Math.random() * 2 - 1) * capped * jitter;\n return Math.max(0, Math.min(capped + noise, options.maxDelayMs ?? 30_000));\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise(r => setTimeout(r, ms));\n","import type { Result } from './types.js';\nimport { ok } from './constructors.js';\n\n/**\n * Returns `ok([...values])` if every result succeeds, or the first `fail` encountered.\n *\n * @example\n * const result = all([findUser(id), findAccount(id)]);\n * // Result<[User, Account], Error>\n */\nexport function all<T, E>(results: Result<T, E>[]): Result<T[], E> {\n const values: T[] = [];\n for (const r of results) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values);\n}\n\n/**\n * Returns the first successful result from a list of async operations,\n * tried sequentially. Returns the last failure if all fail.\n *\n * @example\n * const result = await any([\n * () => run(() => primaryCache.get(key)),\n * () => run(() => database.find(key)),\n * ]);\n */\nexport async function any<T, E>(\n operations: (() => Promise<Result<T, E>>)[],\n): Promise<Result<T, E>> {\n let last!: Result<T, E>;\n for (const op of operations) {\n last = await op();\n if (last.ok) return last;\n }\n return last;\n}\n\nexport interface ParallelOptions {\n /** Max number of operations running concurrently. Default: all at once. */\n concurrency?: number;\n}\n\n/**\n * Runs operations concurrently (optionally throttled by `concurrency`).\n * Returns `ok([...values])` if all succeed, or the first failure.\n *\n * @example\n * const result = await parallel(\n * userIds.map(id => () => run(() => fetchUser(id))),\n * { concurrency: 5 },\n * );\n */\nexport async function parallel<T, E>(\n operations: (() => Promise<Result<T, E>>)[],\n options?: ParallelOptions,\n): Promise<Result<T[], E>> {\n const concurrency = options?.concurrency ?? operations.length;\n const results: Result<T, E>[] = [];\n\n for (let i = 0; i < operations.length; i += concurrency) {\n const batch = await Promise.all(operations.slice(i, i + concurrency).map(op => op()));\n results.push(...batch);\n }\n\n return all(results);\n}\n\n/**\n * Splits an array of Results into `[successValues, errorValues]`.\n *\n * @example\n * const [users, errors] = partition(results);\n */\nexport function partition<T, E>(results: Result<T, E>[]): [T[], E[]] {\n const values: T[] = [];\n const errors: E[] = [];\n for (const r of results) {\n if (r.ok) values.push(r.value);\n else errors.push(r.error);\n }\n return [values, errors];\n}\n\n/**\n * Extracts only the success values, silently discarding failures.\n *\n * @example\n * const users = collect(results); // User[]\n */\nexport function collect<T, E>(results: Result<T, E>[]): T[] {\n return results\n .filter((r): r is Extract<Result<T, E>, { ok: true }> => r.ok)\n .map(r => r.value);\n}\n\n/**\n * Maps each item through a Result-returning function, collecting all successes\n * into an array or short-circuiting on the first failure.\n *\n * @example\n * const result = traverse(ids, id => fromNullable(cache.get(id), 'not-found'));\n */\nexport function traverse<T, U, E>(\n items: T[],\n fn: (item: T) => Result<U, E>,\n): Result<U[], E> {\n return all(items.map(fn));\n}\n\n// ── Typed tuple combinators ────────────────────────────────────────────────\n\n/** Combines two Results into a tuple. Short-circuits on first failure. */\nexport function combine2<A, B, E>(\n r1: Result<A, E>,\n r2: Result<B, E>,\n): Result<[A, B], E> {\n if (!r1.ok) return r1;\n if (!r2.ok) return r2;\n return ok([r1.value, r2.value]);\n}\n\n/** Combines three Results into a typed tuple. Short-circuits on first failure. */\nexport function combine3<A, B, C, E>(\n r1: Result<A, E>,\n r2: Result<B, E>,\n r3: Result<C, E>,\n): Result<[A, B, C], E> {\n if (!r1.ok) return r1;\n if (!r2.ok) return r2;\n if (!r3.ok) return r3;\n return ok([r1.value, r2.value, r3.value]);\n}\n","import type { Result, RichResult } from './types.js';\nimport { ok, fail } from './constructors.js';\nimport { isRich } from './guards.js';\n\n/**\n * Fluent pipeline wrapper around `Result<T, E>`.\n * Operations short-circuit on failure — subsequent transforms are skipped.\n *\n * @example\n * const price = Flow.from(findProduct(id))\n * .map(p => p.price)\n * .filter(price => price > 0, new Error('Price must be positive'))\n * .map(price => price * taxRate)\n * .getResult();\n */\nexport class Flow<T, E = Error> {\n private constructor(private readonly _result: Result<T, E>) {}\n\n /** Start a pipeline from an existing Result. */\n static from<T, E>(result: Result<T, E>): Flow<T, E> {\n return new Flow(result);\n }\n\n /** Start an empty pipeline (value is `undefined`). */\n static start(): Flow<void, never> {\n return new Flow(ok(undefined));\n }\n\n /** Maps the success value. Skipped on failure. */\n map<U>(fn: (value: T) => U): Flow<U, E> {\n if (!this._result.ok) return new Flow<U, E>(this._result as unknown as Result<U, E>);\n return new Flow(ok(fn(this._result.value)));\n }\n\n /** Maps the error value. Skipped on success. */\n mapError<F>(fn: (error: E) => F): Flow<T, F> {\n if (this._result.ok) return new Flow<T, F>(this._result as unknown as Result<T, F>);\n return new Flow(fail(fn(this._result.error)));\n }\n\n /** Chains a Result-returning function. Skipped on failure. */\n flatMap<U>(fn: (value: T) => Result<U, E>): Flow<U, E> {\n if (!this._result.ok) return new Flow<U, E>(this._result as unknown as Result<U, E>);\n return new Flow(fn(this._result.value));\n }\n\n /** Filters the success value. Becomes `fail(error)` if predicate is false. */\n filter(pred: (value: T) => boolean, error: E): Flow<T, E> {\n if (!this._result.ok) return this;\n return pred(this._result.value) ? this : new Flow(fail(error));\n }\n\n /** Runs a side effect on success; returns `this` unchanged. */\n tap(fn: (value: T) => void): this {\n if (this._result.ok) fn(this._result.value);\n return this;\n }\n\n /** Runs a side effect on failure; returns `this` unchanged. */\n tapError(fn: (error: E) => void): this {\n if (!this._result.ok) fn(this._result.error);\n return this;\n }\n\n /**\n * Recovers from a failure by computing a new success value.\n * Skipped if already Ok.\n */\n recover(fn: (error: E) => T): Flow<T, never> {\n if (this._result.ok) return new Flow<T, never>(this._result as unknown as Result<T, never>);\n return new Flow(ok(fn(this._result.error)));\n }\n\n /** Exhaustive pattern match — always produces a value. */\n match<R>(handlers: { ok: (value: T) => R; fail: (error: E) => R }): R {\n return this._result.ok\n ? handlers.ok(this._result.value)\n : handlers.fail(this._result.error);\n }\n\n /** Returns the underlying `Result<T, E>`. */\n getResult(): Result<T, E> {\n return this._result;\n }\n\n /**\n * Returns the underlying result as `RichResult<T, E>` if it was created by `track()`.\n * Throws if the result has no observability metadata.\n */\n getRichResult(): RichResult<T, E> {\n if (!isRich(this._result)) throw new Error('Result is not a RichResult');\n return this._result;\n }\n\n isOk(): boolean { return this._result.ok; }\n isFail(): boolean { return !this._result.ok; }\n}\n"]}
1
+ {"version":3,"sources":["../src/result/operations.ts","../src/result/resilience.ts","../src/result/combinators.ts","../src/result/flow.ts"],"names":["ok","fail","isRich"],"mappings":";;;;;AAMO,SAAS,GAAA,CAAa,QAAsB,EAAA,EAAmC;AACpF,EAAA,OAAO,OAAO,EAAA,GAAKA,oBAAA,CAAG,GAAG,MAAA,CAAO,KAAK,CAAC,CAAA,GAAI,MAAA;AAC5C;AAGO,SAAS,QAAA,CAAkB,QAAsB,EAAA,EAAmC;AACzF,EAAA,OAAO,OAAO,EAAA,GAAK,MAAA,GAASC,uBAAK,EAAA,CAAG,MAAA,CAAO,KAAK,CAAC,CAAA;AACnD;AAGO,SAAS,OAAA,CACd,QACA,EAAA,EACc;AACd,EAAA,OAAO,MAAA,CAAO,EAAA,GAAK,EAAA,CAAG,MAAA,CAAO,KAAK,CAAA,GAAI,MAAA;AACxC;AAGA,eAAsB,YAAA,CACpB,QACA,EAAA,EACuB;AACvB,EAAA,OAAO,MAAA,CAAO,KAAK,EAAA,CAAG,MAAA,CAAO,KAAK,CAAA,GAAI,OAAA,CAAQ,QAAQ,MAAM,CAAA;AAC9D;AAGA,eAAsB,QAAA,CACpB,QACA,EAAA,EACuB;AACvB,EAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,OAAO,OAAA,CAAQ,QAAQ,MAAM,CAAA;AAC7C,EAAA,OAAOD,oBAAA,CAAG,MAAM,EAAA,CAAG,MAAA,CAAO,KAAK,CAAC,CAAA;AAClC;AAaO,SAAS,KAAA,CACd,QACA,QAAA,EACG;AACH,EAAA,OAAO,MAAA,CAAO,EAAA,GAAK,QAAA,CAAS,EAAA,CAAG,MAAA,CAAO,KAAK,CAAA,GAAI,QAAA,CAAS,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC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,OAAA,CAAQ,KAAK,CAAC,CAAC,CAAA;AAAA,EAC5C;AAAA;AAAA,EAGA,MAAS,QAAA,EAA6D;AACpE,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAA,GAChB,QAAA,CAAS,EAAA,CAAG,IAAA,CAAK,OAAA,CAAQ,KAAK,CAAA,GAC9B,QAAA,CAAS,IAAA,CAAK,IAAA,CAAK,QAAQ,KAAK,CAAA;AAAA,EACtC;AAAA;AAAA,EAGA,SAAA,GAA0B;AACxB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAA,GAAkC;AAChC,IAAA,IAAI,CAACE,yBAAO,IAAA,CAAK,OAAO,GAAG,MAAM,IAAI,MAAM,4BAA4B,CAAA;AACvE,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA,EAEA,IAAA,GAAkB;AAAE,IAAA,OAAO,KAAK,OAAA,CAAQ,EAAA;AAAA,EAAI;AAAA,EAC5C,MAAA,GAAkB;AAAE,IAAA,OAAO,CAAC,KAAK,OAAA,CAAQ,EAAA;AAAA,EAAI;AAC/C","file":"index.cjs","sourcesContent":["import type { Result } from './types.js';\nimport { ok, fail } from './constructors.js';\n\n// ── Transformations ────────────────────────────────────────────────────────\n\n/** Maps the success value. Passes failures through unchanged. */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return result.ok ? ok(fn(result.value)) : result;\n}\n\n/** Maps the error value. Passes successes through unchanged. */\nexport function mapError<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return result.ok ? result : fail(fn(result.error));\n}\n\n/** Monadic bind — chains a Result-returning function on success. */\nexport function flatMap<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, E>,\n): Result<U, E> {\n return result.ok ? fn(result.value) : result;\n}\n\n/** Async variant of `flatMap`. */\nexport async function flatMapAsync<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Promise<Result<U, E>>,\n): Promise<Result<U, E>> {\n return result.ok ? fn(result.value) : Promise.resolve(result);\n}\n\n/** Async variant of `map`. */\nexport async function mapAsync<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Promise<U>,\n): Promise<Result<U, E>> {\n if (!result.ok) return Promise.resolve(result);\n return ok(await fn(result.value));\n}\n\n// ── Pattern matching ───────────────────────────────────────────────────────\n\n/**\n * Exhaustive pattern match over both branches.\n *\n * @example\n * const msg = match(result, {\n * ok: (user) => `Welcome, ${user.name}`,\n * fail: (error) => `Error: ${error.message}`,\n * });\n */\nexport function match<T, E, R>(\n result: Result<T, E>,\n handlers: { ok: (value: T) => R; fail: (error: E) => R },\n): R {\n return result.ok ? handlers.ok(result.value) : handlers.fail(result.error);\n}\n\n/** Alias for `match` — familiar to fp-ts / Scala users. */\nexport const fold = match;\n\n// ── Side effects ───────────────────────────────────────────────────────────\n\n/** Runs a side effect on the success value; returns the result unchanged. */\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> {\n if (result.ok) fn(result.value);\n return result;\n}\n\n/** Runs a side effect on the error value; returns the result unchanged. */\nexport function tapError<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> {\n if (!result.ok) fn(result.error);\n return result;\n}\n\n// ── Unwrapping ─────────────────────────────────────────────────────────────\n\n/** Extracts the value or throws the error (re-thrown as-is if it's an Error, wrapped otherwise). */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (result.ok) return result.value;\n throw result.error instanceof Error ? result.error : new Error(String(result.error));\n}\n\n/** Extracts the error or throws if the result is Ok. */\nexport function unwrapError<T, E>(result: Result<T, E>): E {\n if (!result.ok) return result.error;\n throw new Error('Called unwrapError on an Ok result');\n}\n\n/** Extracts the value or returns `defaultValue` on failure. */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n return result.ok ? result.value : defaultValue;\n}\n\n/** Extracts the value or computes a fallback from the error. */\nexport function unwrapOrElse<T, E>(result: Result<T, E>, fn: (error: E) => T): T {\n return result.ok ? result.value : fn(result.error);\n}\n\n/** Extracts the value or throws with a custom `message`. */\nexport function expect<T, E>(result: Result<T, E>, message: string): T {\n if (result.ok) return result.value;\n throw new Error(message);\n}\n\n// ── Conversion ─────────────────────────────────────────────────────────────\n\n/** Converts to a Promise — resolves on Ok, rejects on Fail. */\nexport function toPromise<T, E>(result: Result<T, E>): Promise<T> {\n return result.ok ? Promise.resolve(result.value) : Promise.reject(result.error);\n}\n\n/** Returns the value or `null` on failure. */\nexport function toNullable<T, E>(result: Result<T, E>): T | null {\n return result.ok ? result.value : null;\n}\n\n/** Returns the value or `undefined` on failure. */\nexport function toUndefined<T, E>(result: Result<T, E>): T | undefined {\n return result.ok ? result.value : undefined;\n}\n","import type { Result } from './types.js';\nimport { fail } from './constructors.js';\n\nexport interface RetryOptions<E> {\n /** Maximum number of attempts (including the first). */\n attempts: number;\n /** Fixed delay in ms between attempts. Default: 0 */\n delayMs?: number;\n /** Return false to stop retrying early based on the error. */\n shouldRetry?: (error: E, attempt: number) => boolean;\n /** Called before each retry with the previous error and attempt number. */\n onRetry?: (error: E, attempt: number) => void;\n}\n\nexport interface BackoffOptions<E> extends RetryOptions<E> {\n /** Cap for the computed backoff delay. Default: 30_000 */\n maxDelayMs?: number;\n /**\n * Adds random noise to the backoff delay to avoid thundering herd when\n * multiple instances retry simultaneously.\n *\n * - `true` → full jitter: delay = random(0, computedDelay)\n * - `number` → partial jitter: delay ± (computedDelay * factor), clamped to [0, maxDelayMs]\n * e.g. 0.25 adds ±25% noise\n * - `false` → no jitter (default)\n */\n jitter?: boolean | number;\n}\n\n/**\n * Retries a Result-returning function up to `options.attempts` times with\n * an optional fixed delay between attempts.\n *\n * @example\n * const result = await retry(() => run(() => callApi()), {\n * attempts: 3,\n * delayMs: 500,\n * shouldRetry: (err) => err.code === 'ECONNRESET',\n * });\n */\nexport async function retry<T, E = Error>(\n fn: () => Promise<Result<T, E>>,\n options: RetryOptions<E>,\n): Promise<Result<T, E>> {\n if (options.attempts < 1) throw new Error('retry() attempts must be at least 1');\n let last!: Result<T, E>;\n\n for (let attempt = 1; attempt <= options.attempts; attempt++) {\n last = await fn();\n if (last.ok) return last;\n if (attempt === options.attempts) break;\n if (options.shouldRetry && !options.shouldRetry(last.error, attempt)) break;\n options.onRetry?.(last.error, attempt);\n if (options.delayMs) await sleep(options.delayMs);\n }\n\n return last;\n}\n\n/**\n * Like `retry()` but uses exponential backoff: delay doubles on each attempt,\n * capped at `maxDelayMs`.\n *\n * @example\n * const result = await retryWithBackoff(() => run(() => callApi()), {\n * attempts: 4,\n * delayMs: 100, // 100ms → 200ms → 400ms\n * maxDelayMs: 1_000,\n * });\n */\nexport async function retryWithBackoff<T, E = Error>(\n fn: () => Promise<Result<T, E>>,\n options: BackoffOptions<E>,\n): Promise<Result<T, E>> {\n if (options.attempts < 1) throw new Error('retryWithBackoff() attempts must be at least 1');\n let last!: Result<T, E>;\n\n for (let attempt = 1; attempt <= options.attempts; attempt++) {\n last = await fn();\n if (last.ok) return last;\n if (attempt === options.attempts) break;\n if (options.shouldRetry && !options.shouldRetry(last.error, attempt)) break;\n options.onRetry?.(last.error, attempt);\n await sleep(computeBackoffDelay(attempt, options));\n }\n\n return last;\n}\n\n/**\n * Races a Result-returning function against a timeout.\n * Returns `fail(timeoutError)` if `ms` elapses before the function resolves.\n *\n * @example\n * const result = await withTimeout(\n * () => run(() => fetchData()),\n * 5_000,\n * new TimeoutError('fetchData timed out'),\n * );\n */\nexport async function withTimeout<T, E>(\n fn: () => Promise<Result<T, E>>,\n ms: number,\n timeoutError: E,\n): Promise<Result<T, E>> {\n let timerId!: ReturnType<typeof setTimeout>;\n const timer = new Promise<Result<T, E>>(resolve => {\n timerId = setTimeout(() => resolve(fail<T, E>(timeoutError)), ms);\n });\n try {\n return await Promise.race([fn(), timer]);\n } finally {\n clearTimeout(timerId);\n }\n}\n\nfunction computeBackoffDelay<E>(attempt: number, options: BackoffOptions<E>): number {\n const base = (options.delayMs ?? 100) * Math.pow(2, attempt - 1);\n const capped = Math.min(base, options.maxDelayMs ?? 30_000);\n const { jitter } = options;\n\n if (!jitter) return capped;\n\n if (jitter === true) {\n // Full jitter: uniform random in [0, capped] — maximises spread across instances\n return Math.random() * capped;\n }\n\n // Partial jitter: ± (capped * factor), stays within [0, maxDelayMs]\n const noise = (Math.random() * 2 - 1) * capped * jitter;\n return Math.max(0, Math.min(capped + noise, options.maxDelayMs ?? 30_000));\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise(r => setTimeout(r, ms));\n","import type { Result } from './types.js';\nimport { ok } from './constructors.js';\n\n/**\n * Returns `ok([...values])` if every result succeeds, or the first `fail` encountered.\n *\n * @example\n * const result = all([findUser(id), findAccount(id)]);\n * // Result<[User, Account], Error>\n */\nexport function all<T, E>(results: Result<T, E>[]): Result<T[], E> {\n const values: T[] = [];\n for (const r of results) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values);\n}\n\n/**\n * Returns the first successful result from a list of async operations,\n * tried sequentially. Returns the last failure if all fail.\n *\n * @example\n * const result = await any([\n * () => run(() => primaryCache.get(key)),\n * () => run(() => database.find(key)),\n * ]);\n */\nexport async function any<T, E>(\n operations: (() => Promise<Result<T, E>>)[],\n): Promise<Result<T, E>> {\n if (operations.length === 0) throw new Error('any() requires at least one operation');\n let last!: Result<T, E>;\n for (const op of operations) {\n last = await op();\n if (last.ok) return last;\n }\n return last;\n}\n\nexport interface ParallelOptions {\n /** Max number of operations running concurrently. Default: all at once. */\n concurrency?: number;\n}\n\n/**\n * Runs operations concurrently (optionally throttled by `concurrency`).\n * Returns `ok([...values])` if all succeed, or the first failure.\n *\n * @example\n * const result = await parallel(\n * userIds.map(id => () => run(() => fetchUser(id))),\n * { concurrency: 5 },\n * );\n */\nexport async function parallel<T, E>(\n operations: (() => Promise<Result<T, E>>)[],\n options?: ParallelOptions,\n): Promise<Result<T[], E>> {\n if (options?.concurrency !== undefined && options.concurrency < 1) {\n throw new Error('parallel() concurrency must be at least 1');\n }\n const concurrency = options?.concurrency ?? (operations.length || 1);\n const results: Result<T, E>[] = [];\n\n for (let i = 0; i < operations.length; i += concurrency) {\n const batch = await Promise.all(operations.slice(i, i + concurrency).map(op => op()));\n results.push(...batch);\n }\n\n return all(results);\n}\n\n/**\n * Splits an array of Results into `[successValues, errorValues]`.\n *\n * @example\n * const [users, errors] = partition(results);\n */\nexport function partition<T, E>(results: Result<T, E>[]): [T[], E[]] {\n const values: T[] = [];\n const errors: E[] = [];\n for (const r of results) {\n if (r.ok) values.push(r.value);\n else errors.push(r.error);\n }\n return [values, errors];\n}\n\n/**\n * Extracts only the success values, silently discarding failures.\n *\n * @example\n * const users = collect(results); // User[]\n */\nexport function collect<T, E>(results: Result<T, E>[]): T[] {\n return results\n .filter((r): r is Extract<Result<T, E>, { ok: true }> => r.ok)\n .map(r => r.value);\n}\n\n/**\n * Maps each item through a Result-returning function, collecting all successes\n * into an array or short-circuiting on the first failure.\n *\n * @example\n * const result = traverse(ids, id => fromNullable(cache.get(id), 'not-found'));\n */\nexport function traverse<T, U, E>(\n items: T[],\n fn: (item: T) => Result<U, E>,\n): Result<U[], E> {\n return all(items.map(fn));\n}\n\n// ── Typed tuple combinators ────────────────────────────────────────────────\n\n/** Combines two Results into a tuple. Short-circuits on first failure. */\nexport function combine2<A, B, E>(\n r1: Result<A, E>,\n r2: Result<B, E>,\n): Result<[A, B], E> {\n if (!r1.ok) return r1;\n if (!r2.ok) return r2;\n return ok([r1.value, r2.value]);\n}\n\n/** Combines three Results into a typed tuple. Short-circuits on first failure. */\nexport function combine3<A, B, C, E>(\n r1: Result<A, E>,\n r2: Result<B, E>,\n r3: Result<C, E>,\n): Result<[A, B, C], E> {\n if (!r1.ok) return r1;\n if (!r2.ok) return r2;\n if (!r3.ok) return r3;\n return ok([r1.value, r2.value, r3.value]);\n}\n","import type { Result, RichResult } from './types.js';\nimport { ok, fail } from './constructors.js';\nimport { isRich } from './guards.js';\n\n/**\n * Fluent pipeline wrapper around `Result<T, E>`.\n * Operations short-circuit on failure — subsequent transforms are skipped.\n *\n * @example\n * const price = Flow.from(findProduct(id))\n * .map(p => p.price)\n * .filter(price => price > 0, new Error('Price must be positive'))\n * .map(price => price * taxRate)\n * .getResult();\n */\nexport class Flow<T, E = Error> {\n private constructor(private readonly _result: Result<T, E>) {}\n\n /** Start a pipeline from an existing Result. */\n static from<T, E>(result: Result<T, E>): Flow<T, E> {\n return new Flow(result);\n }\n\n /** Start an empty pipeline (value is `undefined`). */\n static start(): Flow<void, never> {\n return new Flow(ok(undefined));\n }\n\n /** Maps the success value. Skipped on failure. */\n map<U>(fn: (value: T) => U): Flow<U, E> {\n if (!this._result.ok) return new Flow<U, E>(this._result as unknown as Result<U, E>);\n return new Flow(ok(fn(this._result.value)));\n }\n\n /** Maps the error value. Skipped on success. */\n mapError<F>(fn: (error: E) => F): Flow<T, F> {\n if (this._result.ok) return new Flow<T, F>(this._result as unknown as Result<T, F>);\n return new Flow(fail(fn(this._result.error)));\n }\n\n /** Chains a Result-returning function. Skipped on failure. */\n flatMap<U>(fn: (value: T) => Result<U, E>): Flow<U, E> {\n if (!this._result.ok) return new Flow<U, E>(this._result as unknown as Result<U, E>);\n return new Flow(fn(this._result.value));\n }\n\n /** Filters the success value. Becomes `fail(error)` if predicate is false. */\n filter(pred: (value: T) => boolean, error: E): Flow<T, E> {\n if (!this._result.ok) return this;\n return pred(this._result.value) ? this : new Flow(fail(error));\n }\n\n /** Runs a side effect on success; returns `this` unchanged. */\n tap(fn: (value: T) => void): this {\n if (this._result.ok) fn(this._result.value);\n return this;\n }\n\n /** Runs a side effect on failure; returns `this` unchanged. */\n tapError(fn: (error: E) => void): this {\n if (!this._result.ok) fn(this._result.error);\n return this;\n }\n\n /**\n * Recovers from a failure by computing a new success value.\n * Skipped if already Ok.\n */\n recover(fn: (error: E) => T): Flow<T, never> {\n if (this._result.ok) return new Flow<T, never>(this._result as unknown as Result<T, never>);\n return new Flow(ok(fn(this._result.error)));\n }\n\n /** Exhaustive pattern match — always produces a value. */\n match<R>(handlers: { ok: (value: T) => R; fail: (error: E) => R }): R {\n return this._result.ok\n ? handlers.ok(this._result.value)\n : handlers.fail(this._result.error);\n }\n\n /** Returns the underlying `Result<T, E>`. */\n getResult(): Result<T, E> {\n return this._result;\n }\n\n /**\n * Returns the underlying result as `RichResult<T, E>` if it was created by `track()`.\n * Throws if the result has no observability metadata.\n */\n getRichResult(): RichResult<T, E> {\n if (!isRich(this._result)) throw new Error('Result is not a RichResult');\n return this._result;\n }\n\n isOk(): boolean { return this._result.ok; }\n isFail(): boolean { return !this._result.ok; }\n}\n"]}
package/dist/index.js CHANGED
@@ -60,6 +60,7 @@ function toUndefined(result) {
60
60
 
61
61
  // src/result/resilience.ts
62
62
  async function retry(fn, options) {
63
+ if (options.attempts < 1) throw new Error("retry() attempts must be at least 1");
63
64
  let last;
64
65
  for (let attempt = 1; attempt <= options.attempts; attempt++) {
65
66
  last = await fn();
@@ -72,6 +73,7 @@ async function retry(fn, options) {
72
73
  return last;
73
74
  }
74
75
  async function retryWithBackoff(fn, options) {
76
+ if (options.attempts < 1) throw new Error("retryWithBackoff() attempts must be at least 1");
75
77
  let last;
76
78
  for (let attempt = 1; attempt <= options.attempts; attempt++) {
77
79
  last = await fn();
@@ -84,10 +86,15 @@ async function retryWithBackoff(fn, options) {
84
86
  return last;
85
87
  }
86
88
  async function withTimeout(fn, ms, timeoutError) {
87
- const timer = new Promise(
88
- (resolve) => setTimeout(() => resolve(fail(timeoutError)), ms)
89
- );
90
- return Promise.race([fn(), timer]);
89
+ let timerId;
90
+ const timer = new Promise((resolve) => {
91
+ timerId = setTimeout(() => resolve(fail(timeoutError)), ms);
92
+ });
93
+ try {
94
+ return await Promise.race([fn(), timer]);
95
+ } finally {
96
+ clearTimeout(timerId);
97
+ }
91
98
  }
92
99
  function computeBackoffDelay(attempt, options) {
93
100
  const base = (options.delayMs ?? 100) * Math.pow(2, attempt - 1);
@@ -112,6 +119,7 @@ function all(results) {
112
119
  return ok(values);
113
120
  }
114
121
  async function any(operations) {
122
+ if (operations.length === 0) throw new Error("any() requires at least one operation");
115
123
  let last;
116
124
  for (const op of operations) {
117
125
  last = await op();
@@ -120,7 +128,10 @@ async function any(operations) {
120
128
  return last;
121
129
  }
122
130
  async function parallel(operations, options) {
123
- const concurrency = options?.concurrency ?? operations.length;
131
+ if (options?.concurrency !== void 0 && options.concurrency < 1) {
132
+ throw new Error("parallel() concurrency must be at least 1");
133
+ }
134
+ const concurrency = options?.concurrency ?? (operations.length || 1);
124
135
  const results = [];
125
136
  for (let i = 0; i < operations.length; i += concurrency) {
126
137
  const batch = await Promise.all(operations.slice(i, i + concurrency).map((op) => op()));
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/result/operations.ts","../src/result/resilience.ts","../src/result/combinators.ts","../src/result/flow.ts"],"names":[],"mappings":";;;;AAMO,SAAS,GAAA,CAAa,QAAsB,EAAA,EAAmC;AACpF,EAAA,OAAO,OAAO,EAAA,GAAK,EAAA,CAAG,GAAG,MAAA,CAAO,KAAK,CAAC,CAAA,GAAI,MAAA;AAC5C;AAGO,SAAS,QAAA,CAAkB,QAAsB,EAAA,EAAmC;AACzF,EAAA,OAAO,OAAO,EAAA,GAAK,MAAA,GAAS,KAAK,EAAA,CAAG,MAAA,CAAO,KAAK,CAAC,CAAA;AACnD;AAGO,SAAS,OAAA,CACd,QACA,EAAA,EACc;AACd,EAAA,OAAO,MAAA,CAAO,EAAA,GAAK,EAAA,CAAG,MAAA,CAAO,KAAK,CAAA,GAAI,MAAA;AACxC;AAGA,eAAsB,YAAA,CACpB,QACA,EAAA,EACuB;AACvB,EAAA,OAAO,MAAA,CAAO,KAAK,EAAA,CAAG,MAAA,CAAO,KAAK,CAAA,GAAI,OAAA,CAAQ,QAAQ,MAAM,CAAA;AAC9D;AAGA,eAAsB,QAAA,CACpB,QACA,EAAA,EACuB;AACvB,EAAA,IAAI,CAAC,MAAA,CAAO,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,EACtC;AAAA;AAAA,EAGA,SAAA,GAA0B;AACxB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAA,GAAkC;AAChC,IAAA,IAAI,CAAC,OAAO,IAAA,CAAK,OAAO,GAAG,MAAM,IAAI,MAAM,4BAA4B,CAAA;AACvE,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA,EAEA,IAAA,GAAkB;AAAE,IAAA,OAAO,KAAK,OAAA,CAAQ,EAAA;AAAA,EAAI;AAAA,EAC5C,MAAA,GAAkB;AAAE,IAAA,OAAO,CAAC,KAAK,OAAA,CAAQ,EAAA;AAAA,EAAI;AAC/C","file":"index.js","sourcesContent":["import type { Result } from './types.js';\nimport { ok, fail } from './constructors.js';\n\n// ── Transformations ────────────────────────────────────────────────────────\n\n/** Maps the success value. Passes failures through unchanged. */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return result.ok ? ok(fn(result.value)) : result;\n}\n\n/** Maps the error value. Passes successes through unchanged. */\nexport function mapError<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return result.ok ? result : fail(fn(result.error));\n}\n\n/** Monadic bind — chains a Result-returning function on success. */\nexport function flatMap<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, E>,\n): Result<U, E> {\n return result.ok ? fn(result.value) : result;\n}\n\n/** Async variant of `flatMap`. */\nexport async function flatMapAsync<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Promise<Result<U, E>>,\n): Promise<Result<U, E>> {\n return result.ok ? fn(result.value) : Promise.resolve(result);\n}\n\n/** Async variant of `map`. */\nexport async function mapAsync<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Promise<U>,\n): Promise<Result<U, E>> {\n if (!result.ok) return Promise.resolve(result);\n return ok(await fn(result.value));\n}\n\n// ── Pattern matching ───────────────────────────────────────────────────────\n\n/**\n * Exhaustive pattern match over both branches.\n *\n * @example\n * const msg = match(result, {\n * ok: (user) => `Welcome, ${user.name}`,\n * fail: (error) => `Error: ${error.message}`,\n * });\n */\nexport function match<T, E, R>(\n result: Result<T, E>,\n handlers: { ok: (value: T) => R; fail: (error: E) => R },\n): R {\n return result.ok ? handlers.ok(result.value) : handlers.fail(result.error);\n}\n\n/** Alias for `match` — familiar to fp-ts / Scala users. */\nexport const fold = match;\n\n// ── Side effects ───────────────────────────────────────────────────────────\n\n/** Runs a side effect on the success value; returns the result unchanged. */\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> {\n if (result.ok) fn(result.value);\n return result;\n}\n\n/** Runs a side effect on the error value; returns the result unchanged. */\nexport function tapError<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> {\n if (!result.ok) fn(result.error);\n return result;\n}\n\n// ── Unwrapping ─────────────────────────────────────────────────────────────\n\n/** Extracts the value or throws the error (re-thrown as-is if it's an Error, wrapped otherwise). */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (result.ok) return result.value;\n throw result.error instanceof Error ? result.error : new Error(String(result.error));\n}\n\n/** Extracts the error or throws if the result is Ok. */\nexport function unwrapError<T, E>(result: Result<T, E>): E {\n if (!result.ok) return result.error;\n throw new Error('Called unwrapError on an Ok result');\n}\n\n/** Extracts the value or returns `defaultValue` on failure. */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n return result.ok ? result.value : defaultValue;\n}\n\n/** Extracts the value or computes a fallback from the error. */\nexport function unwrapOrElse<T, E>(result: Result<T, E>, fn: (error: E) => T): T {\n return result.ok ? result.value : fn(result.error);\n}\n\n/** Extracts the value or throws with a custom `message`. */\nexport function expect<T, E>(result: Result<T, E>, message: string): T {\n if (result.ok) return result.value;\n throw new Error(message);\n}\n\n// ── Conversion ─────────────────────────────────────────────────────────────\n\n/** Converts to a Promise — resolves on Ok, rejects on Fail. */\nexport function toPromise<T, E>(result: Result<T, E>): Promise<T> {\n return result.ok ? Promise.resolve(result.value) : Promise.reject(result.error);\n}\n\n/** Returns the value or `null` on failure. */\nexport function toNullable<T, E>(result: Result<T, E>): T | null {\n return result.ok ? result.value : null;\n}\n\n/** Returns the value or `undefined` on failure. */\nexport function toUndefined<T, E>(result: Result<T, E>): T | undefined {\n return result.ok ? result.value : undefined;\n}\n","import type { Result } from './types.js';\nimport { fail } from './constructors.js';\n\nexport interface RetryOptions<E> {\n /** Maximum number of attempts (including the first). */\n attempts: number;\n /** Fixed delay in ms between attempts. Default: 0 */\n delayMs?: number;\n /** Return false to stop retrying early based on the error. */\n shouldRetry?: (error: E, attempt: number) => boolean;\n /** Called before each retry with the previous error and attempt number. */\n onRetry?: (error: E, attempt: number) => void;\n}\n\nexport interface BackoffOptions<E> extends RetryOptions<E> {\n /** Cap for the computed backoff delay. Default: 30_000 */\n maxDelayMs?: number;\n /**\n * Adds random noise to the backoff delay to avoid thundering herd when\n * multiple instances retry simultaneously.\n *\n * - `true` → full jitter: delay = random(0, computedDelay)\n * - `number` → partial jitter: delay ± (computedDelay * factor), clamped to [0, maxDelayMs]\n * e.g. 0.25 adds ±25% noise\n * - `false` → no jitter (default)\n */\n jitter?: boolean | number;\n}\n\n/**\n * Retries a Result-returning function up to `options.attempts` times with\n * an optional fixed delay between attempts.\n *\n * @example\n * const result = await retry(() => run(() => callApi()), {\n * attempts: 3,\n * delayMs: 500,\n * shouldRetry: (err) => err.code === 'ECONNRESET',\n * });\n */\nexport async function retry<T, E = Error>(\n fn: () => Promise<Result<T, E>>,\n options: RetryOptions<E>,\n): Promise<Result<T, E>> {\n let last!: Result<T, E>;\n\n for (let attempt = 1; attempt <= options.attempts; attempt++) {\n last = await fn();\n if (last.ok) return last;\n if (attempt === options.attempts) break;\n if (options.shouldRetry && !options.shouldRetry(last.error, attempt)) break;\n options.onRetry?.(last.error, attempt);\n if (options.delayMs) await sleep(options.delayMs);\n }\n\n return last;\n}\n\n/**\n * Like `retry()` but uses exponential backoff: delay doubles on each attempt,\n * capped at `maxDelayMs`.\n *\n * @example\n * const result = await retryWithBackoff(() => run(() => callApi()), {\n * attempts: 4,\n * delayMs: 100, // 100ms → 200ms → 400ms\n * maxDelayMs: 1_000,\n * });\n */\nexport async function retryWithBackoff<T, E = Error>(\n fn: () => Promise<Result<T, E>>,\n options: BackoffOptions<E>,\n): Promise<Result<T, E>> {\n let last!: Result<T, E>;\n\n for (let attempt = 1; attempt <= options.attempts; attempt++) {\n last = await fn();\n if (last.ok) return last;\n if (attempt === options.attempts) break;\n if (options.shouldRetry && !options.shouldRetry(last.error, attempt)) break;\n options.onRetry?.(last.error, attempt);\n await sleep(computeBackoffDelay(attempt, options));\n }\n\n return last;\n}\n\n/**\n * Races a Result-returning function against a timeout.\n * Returns `fail(timeoutError)` if `ms` elapses before the function resolves.\n *\n * @example\n * const result = await withTimeout(\n * () => run(() => fetchData()),\n * 5_000,\n * new TimeoutError('fetchData timed out'),\n * );\n */\nexport async function withTimeout<T, E>(\n fn: () => Promise<Result<T, E>>,\n ms: number,\n timeoutError: E,\n): Promise<Result<T, E>> {\n const timer = new Promise<Result<T, E>>(resolve =>\n setTimeout(() => resolve(fail<T, E>(timeoutError)), ms),\n );\n return Promise.race([fn(), timer]);\n}\n\nfunction computeBackoffDelay<E>(attempt: number, options: BackoffOptions<E>): number {\n const base = (options.delayMs ?? 100) * Math.pow(2, attempt - 1);\n const capped = Math.min(base, options.maxDelayMs ?? 30_000);\n const { jitter } = options;\n\n if (!jitter) return capped;\n\n if (jitter === true) {\n // Full jitter: uniform random in [0, capped] — maximises spread across instances\n return Math.random() * capped;\n }\n\n // Partial jitter: ± (capped * factor), stays within [0, maxDelayMs]\n const noise = (Math.random() * 2 - 1) * capped * jitter;\n return Math.max(0, Math.min(capped + noise, options.maxDelayMs ?? 30_000));\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise(r => setTimeout(r, ms));\n","import type { Result } from './types.js';\nimport { ok } from './constructors.js';\n\n/**\n * Returns `ok([...values])` if every result succeeds, or the first `fail` encountered.\n *\n * @example\n * const result = all([findUser(id), findAccount(id)]);\n * // Result<[User, Account], Error>\n */\nexport function all<T, E>(results: Result<T, E>[]): Result<T[], E> {\n const values: T[] = [];\n for (const r of results) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values);\n}\n\n/**\n * Returns the first successful result from a list of async operations,\n * tried sequentially. Returns the last failure if all fail.\n *\n * @example\n * const result = await any([\n * () => run(() => primaryCache.get(key)),\n * () => run(() => database.find(key)),\n * ]);\n */\nexport async function any<T, E>(\n operations: (() => Promise<Result<T, E>>)[],\n): Promise<Result<T, E>> {\n let last!: Result<T, E>;\n for (const op of operations) {\n last = await op();\n if (last.ok) return last;\n }\n return last;\n}\n\nexport interface ParallelOptions {\n /** Max number of operations running concurrently. Default: all at once. */\n concurrency?: number;\n}\n\n/**\n * Runs operations concurrently (optionally throttled by `concurrency`).\n * Returns `ok([...values])` if all succeed, or the first failure.\n *\n * @example\n * const result = await parallel(\n * userIds.map(id => () => run(() => fetchUser(id))),\n * { concurrency: 5 },\n * );\n */\nexport async function parallel<T, E>(\n operations: (() => Promise<Result<T, E>>)[],\n options?: ParallelOptions,\n): Promise<Result<T[], E>> {\n const concurrency = options?.concurrency ?? operations.length;\n const results: Result<T, E>[] = [];\n\n for (let i = 0; i < operations.length; i += concurrency) {\n const batch = await Promise.all(operations.slice(i, i + concurrency).map(op => op()));\n results.push(...batch);\n }\n\n return all(results);\n}\n\n/**\n * Splits an array of Results into `[successValues, errorValues]`.\n *\n * @example\n * const [users, errors] = partition(results);\n */\nexport function partition<T, E>(results: Result<T, E>[]): [T[], E[]] {\n const values: T[] = [];\n const errors: E[] = [];\n for (const r of results) {\n if (r.ok) values.push(r.value);\n else errors.push(r.error);\n }\n return [values, errors];\n}\n\n/**\n * Extracts only the success values, silently discarding failures.\n *\n * @example\n * const users = collect(results); // User[]\n */\nexport function collect<T, E>(results: Result<T, E>[]): T[] {\n return results\n .filter((r): r is Extract<Result<T, E>, { ok: true }> => r.ok)\n .map(r => r.value);\n}\n\n/**\n * Maps each item through a Result-returning function, collecting all successes\n * into an array or short-circuiting on the first failure.\n *\n * @example\n * const result = traverse(ids, id => fromNullable(cache.get(id), 'not-found'));\n */\nexport function traverse<T, U, E>(\n items: T[],\n fn: (item: T) => Result<U, E>,\n): Result<U[], E> {\n return all(items.map(fn));\n}\n\n// ── Typed tuple combinators ────────────────────────────────────────────────\n\n/** Combines two Results into a tuple. Short-circuits on first failure. */\nexport function combine2<A, B, E>(\n r1: Result<A, E>,\n r2: Result<B, E>,\n): Result<[A, B], E> {\n if (!r1.ok) return r1;\n if (!r2.ok) return r2;\n return ok([r1.value, r2.value]);\n}\n\n/** Combines three Results into a typed tuple. Short-circuits on first failure. */\nexport function combine3<A, B, C, E>(\n r1: Result<A, E>,\n r2: Result<B, E>,\n r3: Result<C, E>,\n): Result<[A, B, C], E> {\n if (!r1.ok) return r1;\n if (!r2.ok) return r2;\n if (!r3.ok) return r3;\n return ok([r1.value, r2.value, r3.value]);\n}\n","import type { Result, RichResult } from './types.js';\nimport { ok, fail } from './constructors.js';\nimport { isRich } from './guards.js';\n\n/**\n * Fluent pipeline wrapper around `Result<T, E>`.\n * Operations short-circuit on failure — subsequent transforms are skipped.\n *\n * @example\n * const price = Flow.from(findProduct(id))\n * .map(p => p.price)\n * .filter(price => price > 0, new Error('Price must be positive'))\n * .map(price => price * taxRate)\n * .getResult();\n */\nexport class Flow<T, E = Error> {\n private constructor(private readonly _result: Result<T, E>) {}\n\n /** Start a pipeline from an existing Result. */\n static from<T, E>(result: Result<T, E>): Flow<T, E> {\n return new Flow(result);\n }\n\n /** Start an empty pipeline (value is `undefined`). */\n static start(): Flow<void, never> {\n return new Flow(ok(undefined));\n }\n\n /** Maps the success value. Skipped on failure. */\n map<U>(fn: (value: T) => U): Flow<U, E> {\n if (!this._result.ok) return new Flow<U, E>(this._result as unknown as Result<U, E>);\n return new Flow(ok(fn(this._result.value)));\n }\n\n /** Maps the error value. Skipped on success. */\n mapError<F>(fn: (error: E) => F): Flow<T, F> {\n if (this._result.ok) return new Flow<T, F>(this._result as unknown as Result<T, F>);\n return new Flow(fail(fn(this._result.error)));\n }\n\n /** Chains a Result-returning function. Skipped on failure. */\n flatMap<U>(fn: (value: T) => Result<U, E>): Flow<U, E> {\n if (!this._result.ok) return new Flow<U, E>(this._result as unknown as Result<U, E>);\n return new Flow(fn(this._result.value));\n }\n\n /** Filters the success value. Becomes `fail(error)` if predicate is false. */\n filter(pred: (value: T) => boolean, error: E): Flow<T, E> {\n if (!this._result.ok) return this;\n return pred(this._result.value) ? this : new Flow(fail(error));\n }\n\n /** Runs a side effect on success; returns `this` unchanged. */\n tap(fn: (value: T) => void): this {\n if (this._result.ok) fn(this._result.value);\n return this;\n }\n\n /** Runs a side effect on failure; returns `this` unchanged. */\n tapError(fn: (error: E) => void): this {\n if (!this._result.ok) fn(this._result.error);\n return this;\n }\n\n /**\n * Recovers from a failure by computing a new success value.\n * Skipped if already Ok.\n */\n recover(fn: (error: E) => T): Flow<T, never> {\n if (this._result.ok) return new Flow<T, never>(this._result as unknown as Result<T, never>);\n return new Flow(ok(fn(this._result.error)));\n }\n\n /** Exhaustive pattern match — always produces a value. */\n match<R>(handlers: { ok: (value: T) => R; fail: (error: E) => R }): R {\n return this._result.ok\n ? handlers.ok(this._result.value)\n : handlers.fail(this._result.error);\n }\n\n /** Returns the underlying `Result<T, E>`. */\n getResult(): Result<T, E> {\n return this._result;\n }\n\n /**\n * Returns the underlying result as `RichResult<T, E>` if it was created by `track()`.\n * Throws if the result has no observability metadata.\n */\n getRichResult(): RichResult<T, E> {\n if (!isRich(this._result)) throw new Error('Result is not a RichResult');\n return this._result;\n }\n\n isOk(): boolean { return this._result.ok; }\n isFail(): boolean { return !this._result.ok; }\n}\n"]}
1
+ {"version":3,"sources":["../src/result/operations.ts","../src/result/resilience.ts","../src/result/combinators.ts","../src/result/flow.ts"],"names":[],"mappings":";;;;AAMO,SAAS,GAAA,CAAa,QAAsB,EAAA,EAA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GAA0B;AACxB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAA,GAAkC;AAChC,IAAA,IAAI,CAAC,OAAO,IAAA,CAAK,OAAO,GAAG,MAAM,IAAI,MAAM,4BAA4B,CAAA;AACvE,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA,EAEA,IAAA,GAAkB;AAAE,IAAA,OAAO,KAAK,OAAA,CAAQ,EAAA;AAAA,EAAI;AAAA,EAC5C,MAAA,GAAkB;AAAE,IAAA,OAAO,CAAC,KAAK,OAAA,CAAQ,EAAA;AAAA,EAAI;AAC/C","file":"index.js","sourcesContent":["import type { Result } from './types.js';\nimport { ok, fail } from './constructors.js';\n\n// ── Transformations ────────────────────────────────────────────────────────\n\n/** Maps the success value. Passes failures through unchanged. */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return result.ok ? ok(fn(result.value)) : result;\n}\n\n/** Maps the error value. Passes successes through unchanged. */\nexport function mapError<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return result.ok ? result : fail(fn(result.error));\n}\n\n/** Monadic bind — chains a Result-returning function on success. */\nexport function flatMap<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, E>,\n): Result<U, E> {\n return result.ok ? fn(result.value) : result;\n}\n\n/** Async variant of `flatMap`. */\nexport async function flatMapAsync<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Promise<Result<U, E>>,\n): Promise<Result<U, E>> {\n return result.ok ? fn(result.value) : Promise.resolve(result);\n}\n\n/** Async variant of `map`. */\nexport async function mapAsync<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Promise<U>,\n): Promise<Result<U, E>> {\n if (!result.ok) return Promise.resolve(result);\n return ok(await fn(result.value));\n}\n\n// ── Pattern matching ───────────────────────────────────────────────────────\n\n/**\n * Exhaustive pattern match over both branches.\n *\n * @example\n * const msg = match(result, {\n * ok: (user) => `Welcome, ${user.name}`,\n * fail: (error) => `Error: ${error.message}`,\n * });\n */\nexport function match<T, E, R>(\n result: Result<T, E>,\n handlers: { ok: (value: T) => R; fail: (error: E) => R },\n): R {\n return result.ok ? handlers.ok(result.value) : handlers.fail(result.error);\n}\n\n/** Alias for `match` — familiar to fp-ts / Scala users. */\nexport const fold = match;\n\n// ── Side effects ───────────────────────────────────────────────────────────\n\n/** Runs a side effect on the success value; returns the result unchanged. */\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> {\n if (result.ok) fn(result.value);\n return result;\n}\n\n/** Runs a side effect on the error value; returns the result unchanged. */\nexport function tapError<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> {\n if (!result.ok) fn(result.error);\n return result;\n}\n\n// ── Unwrapping ─────────────────────────────────────────────────────────────\n\n/** Extracts the value or throws the error (re-thrown as-is if it's an Error, wrapped otherwise). */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (result.ok) return result.value;\n throw result.error instanceof Error ? result.error : new Error(String(result.error));\n}\n\n/** Extracts the error or throws if the result is Ok. */\nexport function unwrapError<T, E>(result: Result<T, E>): E {\n if (!result.ok) return result.error;\n throw new Error('Called unwrapError on an Ok result');\n}\n\n/** Extracts the value or returns `defaultValue` on failure. */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n return result.ok ? result.value : defaultValue;\n}\n\n/** Extracts the value or computes a fallback from the error. */\nexport function unwrapOrElse<T, E>(result: Result<T, E>, fn: (error: E) => T): T {\n return result.ok ? result.value : fn(result.error);\n}\n\n/** Extracts the value or throws with a custom `message`. */\nexport function expect<T, E>(result: Result<T, E>, message: string): T {\n if (result.ok) return result.value;\n throw new Error(message);\n}\n\n// ── Conversion ─────────────────────────────────────────────────────────────\n\n/** Converts to a Promise — resolves on Ok, rejects on Fail. */\nexport function toPromise<T, E>(result: Result<T, E>): Promise<T> {\n return result.ok ? Promise.resolve(result.value) : Promise.reject(result.error);\n}\n\n/** Returns the value or `null` on failure. */\nexport function toNullable<T, E>(result: Result<T, E>): T | null {\n return result.ok ? result.value : null;\n}\n\n/** Returns the value or `undefined` on failure. */\nexport function toUndefined<T, E>(result: Result<T, E>): T | undefined {\n return result.ok ? result.value : undefined;\n}\n","import type { Result } from './types.js';\nimport { fail } from './constructors.js';\n\nexport interface RetryOptions<E> {\n /** Maximum number of attempts (including the first). */\n attempts: number;\n /** Fixed delay in ms between attempts. Default: 0 */\n delayMs?: number;\n /** Return false to stop retrying early based on the error. */\n shouldRetry?: (error: E, attempt: number) => boolean;\n /** Called before each retry with the previous error and attempt number. */\n onRetry?: (error: E, attempt: number) => void;\n}\n\nexport interface BackoffOptions<E> extends RetryOptions<E> {\n /** Cap for the computed backoff delay. Default: 30_000 */\n maxDelayMs?: number;\n /**\n * Adds random noise to the backoff delay to avoid thundering herd when\n * multiple instances retry simultaneously.\n *\n * - `true` → full jitter: delay = random(0, computedDelay)\n * - `number` → partial jitter: delay ± (computedDelay * factor), clamped to [0, maxDelayMs]\n * e.g. 0.25 adds ±25% noise\n * - `false` → no jitter (default)\n */\n jitter?: boolean | number;\n}\n\n/**\n * Retries a Result-returning function up to `options.attempts` times with\n * an optional fixed delay between attempts.\n *\n * @example\n * const result = await retry(() => run(() => callApi()), {\n * attempts: 3,\n * delayMs: 500,\n * shouldRetry: (err) => err.code === 'ECONNRESET',\n * });\n */\nexport async function retry<T, E = Error>(\n fn: () => Promise<Result<T, E>>,\n options: RetryOptions<E>,\n): Promise<Result<T, E>> {\n if (options.attempts < 1) throw new Error('retry() attempts must be at least 1');\n let last!: Result<T, E>;\n\n for (let attempt = 1; attempt <= options.attempts; attempt++) {\n last = await fn();\n if (last.ok) return last;\n if (attempt === options.attempts) break;\n if (options.shouldRetry && !options.shouldRetry(last.error, attempt)) break;\n options.onRetry?.(last.error, attempt);\n if (options.delayMs) await sleep(options.delayMs);\n }\n\n return last;\n}\n\n/**\n * Like `retry()` but uses exponential backoff: delay doubles on each attempt,\n * capped at `maxDelayMs`.\n *\n * @example\n * const result = await retryWithBackoff(() => run(() => callApi()), {\n * attempts: 4,\n * delayMs: 100, // 100ms → 200ms → 400ms\n * maxDelayMs: 1_000,\n * });\n */\nexport async function retryWithBackoff<T, E = Error>(\n fn: () => Promise<Result<T, E>>,\n options: BackoffOptions<E>,\n): Promise<Result<T, E>> {\n if (options.attempts < 1) throw new Error('retryWithBackoff() attempts must be at least 1');\n let last!: Result<T, E>;\n\n for (let attempt = 1; attempt <= options.attempts; attempt++) {\n last = await fn();\n if (last.ok) return last;\n if (attempt === options.attempts) break;\n if (options.shouldRetry && !options.shouldRetry(last.error, attempt)) break;\n options.onRetry?.(last.error, attempt);\n await sleep(computeBackoffDelay(attempt, options));\n }\n\n return last;\n}\n\n/**\n * Races a Result-returning function against a timeout.\n * Returns `fail(timeoutError)` if `ms` elapses before the function resolves.\n *\n * @example\n * const result = await withTimeout(\n * () => run(() => fetchData()),\n * 5_000,\n * new TimeoutError('fetchData timed out'),\n * );\n */\nexport async function withTimeout<T, E>(\n fn: () => Promise<Result<T, E>>,\n ms: number,\n timeoutError: E,\n): Promise<Result<T, E>> {\n let timerId!: ReturnType<typeof setTimeout>;\n const timer = new Promise<Result<T, E>>(resolve => {\n timerId = setTimeout(() => resolve(fail<T, E>(timeoutError)), ms);\n });\n try {\n return await Promise.race([fn(), timer]);\n } finally {\n clearTimeout(timerId);\n }\n}\n\nfunction computeBackoffDelay<E>(attempt: number, options: BackoffOptions<E>): number {\n const base = (options.delayMs ?? 100) * Math.pow(2, attempt - 1);\n const capped = Math.min(base, options.maxDelayMs ?? 30_000);\n const { jitter } = options;\n\n if (!jitter) return capped;\n\n if (jitter === true) {\n // Full jitter: uniform random in [0, capped] — maximises spread across instances\n return Math.random() * capped;\n }\n\n // Partial jitter: ± (capped * factor), stays within [0, maxDelayMs]\n const noise = (Math.random() * 2 - 1) * capped * jitter;\n return Math.max(0, Math.min(capped + noise, options.maxDelayMs ?? 30_000));\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise(r => setTimeout(r, ms));\n","import type { Result } from './types.js';\nimport { ok } from './constructors.js';\n\n/**\n * Returns `ok([...values])` if every result succeeds, or the first `fail` encountered.\n *\n * @example\n * const result = all([findUser(id), findAccount(id)]);\n * // Result<[User, Account], Error>\n */\nexport function all<T, E>(results: Result<T, E>[]): Result<T[], E> {\n const values: T[] = [];\n for (const r of results) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values);\n}\n\n/**\n * Returns the first successful result from a list of async operations,\n * tried sequentially. Returns the last failure if all fail.\n *\n * @example\n * const result = await any([\n * () => run(() => primaryCache.get(key)),\n * () => run(() => database.find(key)),\n * ]);\n */\nexport async function any<T, E>(\n operations: (() => Promise<Result<T, E>>)[],\n): Promise<Result<T, E>> {\n if (operations.length === 0) throw new Error('any() requires at least one operation');\n let last!: Result<T, E>;\n for (const op of operations) {\n last = await op();\n if (last.ok) return last;\n }\n return last;\n}\n\nexport interface ParallelOptions {\n /** Max number of operations running concurrently. Default: all at once. */\n concurrency?: number;\n}\n\n/**\n * Runs operations concurrently (optionally throttled by `concurrency`).\n * Returns `ok([...values])` if all succeed, or the first failure.\n *\n * @example\n * const result = await parallel(\n * userIds.map(id => () => run(() => fetchUser(id))),\n * { concurrency: 5 },\n * );\n */\nexport async function parallel<T, E>(\n operations: (() => Promise<Result<T, E>>)[],\n options?: ParallelOptions,\n): Promise<Result<T[], E>> {\n if (options?.concurrency !== undefined && options.concurrency < 1) {\n throw new Error('parallel() concurrency must be at least 1');\n }\n const concurrency = options?.concurrency ?? (operations.length || 1);\n const results: Result<T, E>[] = [];\n\n for (let i = 0; i < operations.length; i += concurrency) {\n const batch = await Promise.all(operations.slice(i, i + concurrency).map(op => op()));\n results.push(...batch);\n }\n\n return all(results);\n}\n\n/**\n * Splits an array of Results into `[successValues, errorValues]`.\n *\n * @example\n * const [users, errors] = partition(results);\n */\nexport function partition<T, E>(results: Result<T, E>[]): [T[], E[]] {\n const values: T[] = [];\n const errors: E[] = [];\n for (const r of results) {\n if (r.ok) values.push(r.value);\n else errors.push(r.error);\n }\n return [values, errors];\n}\n\n/**\n * Extracts only the success values, silently discarding failures.\n *\n * @example\n * const users = collect(results); // User[]\n */\nexport function collect<T, E>(results: Result<T, E>[]): T[] {\n return results\n .filter((r): r is Extract<Result<T, E>, { ok: true }> => r.ok)\n .map(r => r.value);\n}\n\n/**\n * Maps each item through a Result-returning function, collecting all successes\n * into an array or short-circuiting on the first failure.\n *\n * @example\n * const result = traverse(ids, id => fromNullable(cache.get(id), 'not-found'));\n */\nexport function traverse<T, U, E>(\n items: T[],\n fn: (item: T) => Result<U, E>,\n): Result<U[], E> {\n return all(items.map(fn));\n}\n\n// ── Typed tuple combinators ────────────────────────────────────────────────\n\n/** Combines two Results into a tuple. Short-circuits on first failure. */\nexport function combine2<A, B, E>(\n r1: Result<A, E>,\n r2: Result<B, E>,\n): Result<[A, B], E> {\n if (!r1.ok) return r1;\n if (!r2.ok) return r2;\n return ok([r1.value, r2.value]);\n}\n\n/** Combines three Results into a typed tuple. Short-circuits on first failure. */\nexport function combine3<A, B, C, E>(\n r1: Result<A, E>,\n r2: Result<B, E>,\n r3: Result<C, E>,\n): Result<[A, B, C], E> {\n if (!r1.ok) return r1;\n if (!r2.ok) return r2;\n if (!r3.ok) return r3;\n return ok([r1.value, r2.value, r3.value]);\n}\n","import type { Result, RichResult } from './types.js';\nimport { ok, fail } from './constructors.js';\nimport { isRich } from './guards.js';\n\n/**\n * Fluent pipeline wrapper around `Result<T, E>`.\n * Operations short-circuit on failure — subsequent transforms are skipped.\n *\n * @example\n * const price = Flow.from(findProduct(id))\n * .map(p => p.price)\n * .filter(price => price > 0, new Error('Price must be positive'))\n * .map(price => price * taxRate)\n * .getResult();\n */\nexport class Flow<T, E = Error> {\n private constructor(private readonly _result: Result<T, E>) {}\n\n /** Start a pipeline from an existing Result. */\n static from<T, E>(result: Result<T, E>): Flow<T, E> {\n return new Flow(result);\n }\n\n /** Start an empty pipeline (value is `undefined`). */\n static start(): Flow<void, never> {\n return new Flow(ok(undefined));\n }\n\n /** Maps the success value. Skipped on failure. */\n map<U>(fn: (value: T) => U): Flow<U, E> {\n if (!this._result.ok) return new Flow<U, E>(this._result as unknown as Result<U, E>);\n return new Flow(ok(fn(this._result.value)));\n }\n\n /** Maps the error value. Skipped on success. */\n mapError<F>(fn: (error: E) => F): Flow<T, F> {\n if (this._result.ok) return new Flow<T, F>(this._result as unknown as Result<T, F>);\n return new Flow(fail(fn(this._result.error)));\n }\n\n /** Chains a Result-returning function. Skipped on failure. */\n flatMap<U>(fn: (value: T) => Result<U, E>): Flow<U, E> {\n if (!this._result.ok) return new Flow<U, E>(this._result as unknown as Result<U, E>);\n return new Flow(fn(this._result.value));\n }\n\n /** Filters the success value. Becomes `fail(error)` if predicate is false. */\n filter(pred: (value: T) => boolean, error: E): Flow<T, E> {\n if (!this._result.ok) return this;\n return pred(this._result.value) ? this : new Flow(fail(error));\n }\n\n /** Runs a side effect on success; returns `this` unchanged. */\n tap(fn: (value: T) => void): this {\n if (this._result.ok) fn(this._result.value);\n return this;\n }\n\n /** Runs a side effect on failure; returns `this` unchanged. */\n tapError(fn: (error: E) => void): this {\n if (!this._result.ok) fn(this._result.error);\n return this;\n }\n\n /**\n * Recovers from a failure by computing a new success value.\n * Skipped if already Ok.\n */\n recover(fn: (error: E) => T): Flow<T, never> {\n if (this._result.ok) return new Flow<T, never>(this._result as unknown as Result<T, never>);\n return new Flow(ok(fn(this._result.error)));\n }\n\n /** Exhaustive pattern match — always produces a value. */\n match<R>(handlers: { ok: (value: T) => R; fail: (error: E) => R }): R {\n return this._result.ok\n ? handlers.ok(this._result.value)\n : handlers.fail(this._result.error);\n }\n\n /** Returns the underlying `Result<T, E>`. */\n getResult(): Result<T, E> {\n return this._result;\n }\n\n /**\n * Returns the underlying result as `RichResult<T, E>` if it was created by `track()`.\n * Throws if the result has no observability metadata.\n */\n getRichResult(): RichResult<T, E> {\n if (!isRich(this._result)) throw new Error('Result is not a RichResult');\n return this._result;\n }\n\n isOk(): boolean { return this._result.ok; }\n isFail(): boolean { return !this._result.ok; }\n}\n"]}
package/package.json CHANGED
@@ -1,71 +1,97 @@
1
- {
2
- "name": "@backendkit-labs/result",
3
- "version": "0.1.2",
4
- "description": "Type-safe Result monad for Node.js — generic error types, observability, resilience, and optional NestJS integration",
5
- "type": "module",
6
- "main": "./dist/index.cjs",
7
- "module": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
9
- "exports": {
10
- ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.cjs"
14
- },
15
- "./nestjs": {
16
- "types": "./dist/nestjs/index.d.ts",
17
- "import": "./dist/nestjs/index.js",
18
- "require": "./dist/nestjs/index.cjs"
19
- }
20
- },
21
- "files": ["dist", "README.md", "LICENSE"],
22
- "scripts": {
23
- "build": "tsup",
24
- "dev": "tsup --watch",
25
- "test": "vitest run",
26
- "test:watch": "vitest",
27
- "test:coverage": "vitest run --coverage",
28
- "typecheck": "tsc --noEmit",
29
- "lint": "eslint src/",
30
- "prepublishOnly": "npm run build && npm run test && npm run lint"
31
- },
32
- "keywords": [
33
- "result", "either", "monad", "error-handling",
34
- "functional", "railway", "nestjs", "typescript", "node"
35
- ],
36
- "author": "Mairon José Cuello Martínez",
37
- "license": "MIT",
38
- "homepage": "https://github.com/backendkit-dev/backendkit-monorepo/tree/master/packages/result#readme",
39
- "repository": {
40
- "type": "git",
41
- "url": "git+https://github.com/backendkit-dev/backendkit-monorepo.git",
42
- "directory": "packages/result"
43
- },
44
- "bugs": { "url": "https://github.com/backendkit-dev/backendkit-monorepo/issues" },
45
- "publishConfig": { "access": "public" },
46
- "sideEffects": false,
47
- "engines": { "node": ">=18" },
48
- "peerDependencies": {
49
- "@nestjs/common": ">=10.0.0",
50
- "@nestjs/core": ">=10.0.0",
51
- "rxjs": ">=7.0.0"
52
- },
53
- "peerDependenciesMeta": {
54
- "@nestjs/common": { "optional": true },
55
- "@nestjs/core": { "optional": true },
56
- "rxjs": { "optional": true }
57
- },
58
- "devDependencies": {
59
- "@eslint/js": "^9.39.4",
60
- "@nestjs/common": "^10.0.0",
61
- "@nestjs/core": "^10.0.0",
62
- "@types/node": "^22.0.0",
63
- "eslint": "^9.0.0",
64
- "reflect-metadata": "^0.2.0",
65
- "rxjs": "^7.8.0",
66
- "tsup": "^8.0.0",
67
- "typescript": "^5.5.0",
68
- "typescript-eslint": "^8.59.3",
69
- "vitest": "^2.0.0"
70
- }
71
- }
1
+ {
2
+ "name": "@backendkit-labs/result",
3
+ "version": "0.2.0",
4
+ "license": "Apache-2.0",
5
+ "author": {
6
+ "name": "BackendKit Labs",
7
+ "email": "hello@backendkitlabs.dev"
8
+ },
9
+ "description": "Type-safe Result monad for Node.js — generic error types, observability, resilience, and optional NestJS integration",
10
+ "type": "module",
11
+ "main": "./dist/index.cjs",
12
+ "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js",
18
+ "require": "./dist/index.cjs"
19
+ },
20
+ "./nestjs": {
21
+ "types": "./dist/nestjs/index.d.ts",
22
+ "import": "./dist/nestjs/index.js",
23
+ "require": "./dist/nestjs/index.cjs"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "scripts": {
32
+ "build": "tsup",
33
+ "dev": "tsup --watch",
34
+ "test": "vitest run",
35
+ "test:watch": "vitest",
36
+ "test:coverage": "vitest run --coverage",
37
+ "typecheck": "tsc --noEmit",
38
+ "lint": "eslint src/",
39
+ "prepublishOnly": "npm run build && npm run test && npm run lint"
40
+ },
41
+ "keywords": [
42
+ "result",
43
+ "either",
44
+ "monad",
45
+ "error-handling",
46
+ "functional",
47
+ "railway",
48
+ "nestjs",
49
+ "typescript",
50
+ "node"
51
+ ],
52
+ "homepage": "https://backendkitlabs.dev/docs/result/",
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "git+https://github.com/BackendKit-labs/backendkit-monorepo.git",
56
+ "directory": "packages/result"
57
+ },
58
+ "bugs": {
59
+ "url": "https://github.com/BackendKit-labs/backendkit-monorepo/issues"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ },
64
+ "sideEffects": false,
65
+ "engines": {
66
+ "node": ">=18"
67
+ },
68
+ "peerDependencies": {
69
+ "@nestjs/common": ">=10.0.0",
70
+ "@nestjs/core": ">=10.0.0",
71
+ "rxjs": ">=7.0.0"
72
+ },
73
+ "peerDependenciesMeta": {
74
+ "@nestjs/common": {
75
+ "optional": true
76
+ },
77
+ "@nestjs/core": {
78
+ "optional": true
79
+ },
80
+ "rxjs": {
81
+ "optional": true
82
+ }
83
+ },
84
+ "devDependencies": {
85
+ "@eslint/js": "^9.39.4",
86
+ "@nestjs/common": "^10.0.0",
87
+ "@nestjs/core": "^10.0.0",
88
+ "@types/node": "^22.0.0",
89
+ "eslint": "^9.0.0",
90
+ "reflect-metadata": "^0.2.0",
91
+ "rxjs": "^7.8.0",
92
+ "tsup": "^8.0.0",
93
+ "typescript": "^5.5.0",
94
+ "typescript-eslint": "^8.59.3",
95
+ "vitest": "^2.0.0"
96
+ }
97
+ }