@onrails/result 0.1.3 → 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.
Files changed (68) hide show
  1. package/DESIGN.md +2 -2
  2. package/README.md +0 -3
  3. package/RECIPES.md +16 -15
  4. package/dist/$.cjs +40 -0
  5. package/dist/$.cjs.map +1 -0
  6. package/dist/$.js +36 -0
  7. package/dist/$.js.map +1 -0
  8. package/dist/_.d.cts +2 -0
  9. package/dist/_.d.ts +2 -0
  10. package/dist/async-1fIhfzFu.d.ts +290 -0
  11. package/dist/async-u8U5P2EH.d.cts +290 -0
  12. package/dist/compat/neverthrow.cjs +234 -50
  13. package/dist/compat/neverthrow.cjs.map +1 -1
  14. package/dist/compat/neverthrow.d.cts +2 -2
  15. package/dist/compat/neverthrow.d.ts +2 -2
  16. package/dist/compat/neverthrow.js +231 -47
  17. package/dist/compat/neverthrow.js.map +1 -1
  18. package/dist/extra.cjs +1 -24
  19. package/dist/extra.cjs.map +1 -1
  20. package/dist/extra.d.cts +3 -9
  21. package/dist/extra.d.ts +3 -9
  22. package/dist/extra.js +2 -24
  23. package/dist/extra.js.map +1 -1
  24. package/dist/fluent.cjs +0 -2
  25. package/dist/fluent.cjs.map +1 -1
  26. package/dist/fluent.d.cts +2 -6
  27. package/dist/fluent.d.ts +2 -6
  28. package/dist/fluent.js +0 -2
  29. package/dist/fluent.js.map +1 -1
  30. package/dist/index.cjs +226 -47
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +174 -51
  33. package/dist/index.d.ts +174 -51
  34. package/dist/index.js +227 -44
  35. package/dist/index.js.map +1 -1
  36. package/dist/interop.cjs +209 -23
  37. package/dist/interop.cjs.map +1 -1
  38. package/dist/interop.d.cts +60 -10
  39. package/dist/interop.d.ts +60 -10
  40. package/dist/interop.js +209 -23
  41. package/dist/interop.js.map +1 -1
  42. package/dist/pipe.cjs.map +1 -1
  43. package/dist/pipe.d.cts +7 -5
  44. package/dist/pipe.d.ts +7 -5
  45. package/dist/pipe.js.map +1 -1
  46. package/dist/railway.cjs +205 -24
  47. package/dist/railway.cjs.map +1 -1
  48. package/dist/railway.d.cts +20 -3
  49. package/dist/railway.d.ts +20 -3
  50. package/dist/railway.js +205 -25
  51. package/dist/railway.js.map +1 -1
  52. package/dist/try-gen.cjs.map +1 -1
  53. package/dist/try-gen.d.cts +29 -3
  54. package/dist/try-gen.d.ts +29 -3
  55. package/dist/try-gen.js.map +1 -1
  56. package/dist/types-BQ9vv0nD.d.cts +55 -0
  57. package/dist/types-BQ9vv0nD.d.ts +55 -0
  58. package/dist/validation.cjs.map +1 -1
  59. package/dist/validation.d.cts +1 -1
  60. package/dist/validation.d.ts +1 -1
  61. package/dist/validation.js.map +1 -1
  62. package/package.json +10 -3
  63. package/skills/railway-do-notation/SKILL.md +436 -0
  64. package/skills/result-composition/SKILL.md +325 -0
  65. package/dist/async-CH8Cs8KE.d.cts +0 -161
  66. package/dist/async-DKISqIBc.d.ts +0 -161
  67. package/dist/types-C2Dp1d5J.d.cts +0 -21
  68. package/dist/types-C2Dp1d5J.d.ts +0 -21
package/dist/interop.js CHANGED
@@ -60,9 +60,32 @@ var ResultAsync = class _ResultAsync {
60
60
  }
61
61
  run;
62
62
  promise = null;
63
+ /**
64
+ * Lifts an already-settled sync {@link Result} into a {@link ResultAsync}.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const ra = ResultAsync.fromResult(ok(42)); // ResultAsync<number, never>
69
+ * ```
70
+ */
63
71
  static fromResult(result) {
64
72
  return new _ResultAsync(async () => result);
65
73
  }
74
+ /**
75
+ * Wraps a `PromiseLike<T>` that may reject. Rejections pass through `onReject`
76
+ * to become a typed `Err`; resolution becomes `Ok<T>`.
77
+ *
78
+ * @param promise - the promise to wrap
79
+ * @param onReject - maps a rejection reason to the `Err` channel
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * const body = ResultAsync.fromPromise(
84
+ * fetch(url).then((r) => r.text()),
85
+ * (e): NetError => ({ kind: "net", cause: String(e) }),
86
+ * );
87
+ * ```
88
+ */
66
89
  static fromPromise(promise, onReject) {
67
90
  return new _ResultAsync(async () => {
68
91
  try {
@@ -72,12 +95,29 @@ var ResultAsync = class _ResultAsync {
72
95
  }
73
96
  });
74
97
  }
98
+ /**
99
+ * Wraps a `PromiseLike<T>` that is **guaranteed not to reject**, skipping the
100
+ * `onReject` mapper. Use only when rejection is provably impossible.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * const now = ResultAsync.fromSafePromise(Promise.resolve(Date.now()));
105
+ * ```
106
+ */
75
107
  static fromSafePromise(promise) {
76
108
  return new _ResultAsync(async () => ok(await promise));
77
109
  }
78
110
  /**
79
- * Defers work until {@link resolve}. Unlike {@link fromPromise}, nothing runs
80
- * until the `ResultAsync` is resolved (e.g. by `combineTuple` / `combineTupleParallel`).
111
+ * Defers work until {@link resolve}. Unlike {@link fromPromise}, the factory
112
+ * does not run until the `ResultAsync` is resolved (e.g. by `combineTuple` /
113
+ * `combineTupleParallel`). The factory runs at most once — `resolve` memoizes.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * const insert = ResultAsync.defer(() => db.orders.insert(row));
118
+ * // nothing has run yet
119
+ * const r = await insert; // factory runs exactly once here
120
+ * ```
81
121
  */
82
122
  static defer(fn) {
83
123
  return new _ResultAsync(fn);
@@ -85,14 +125,42 @@ var ResultAsync = class _ResultAsync {
85
125
  static ok(value) {
86
126
  return new _ResultAsync(async () => ok(value));
87
127
  }
128
+ /**
129
+ * Lifts an error into an `Err` async result.
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * const r = ResultAsync.err({ kind: "not_found" as const });
134
+ * ```
135
+ */
88
136
  static err(error) {
89
137
  return new _ResultAsync(async () => err(error));
90
138
  }
91
- /** @see {@link fromAsync} from `@onrails/result/interop` */
139
+ /**
140
+ * Lifts an existing `Promise<Result<T, E>>` (e.g. from interop code) into a
141
+ * {@link ResultAsync}, auto-flattening one level of double-wrapping. A thrown
142
+ * defect is routed through `onDefect`, defaulting to {@link UnexpectedError}.
143
+ *
144
+ * @param promise - a promise that already yields a `Result`
145
+ * @param onDefect - maps an unexpected throw to the `Err` channel
146
+ * @see {@link fromAsync} from `@onrails/result/interop`
147
+ */
92
148
  static fromResultPromise(promise, onDefect) {
93
149
  const mapDefect = onDefect ?? ((error) => new UnexpectedError("Unexpected async defect", error));
94
150
  return new _ResultAsync(() => liftPromiseResult(promise, mapDefect));
95
151
  }
152
+ /**
153
+ * Combines a homogeneous array of async results into one. Resolves
154
+ * **sequentially** in input order, short-circuiting on the first `Err`.
155
+ * For heterogeneous tuples that preserve per-index types, use
156
+ * {@link combineTuple}; for wall-clock overlap, {@link combineTupleParallel}.
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * const all = ResultAsync.combine([loadA(), loadB(), loadC()]);
161
+ * // ResultAsync<Item[], LoadError>
162
+ * ```
163
+ */
96
164
  static combine(results) {
97
165
  return new _ResultAsync(async () => {
98
166
  const values = [];
@@ -106,6 +174,23 @@ var ResultAsync = class _ResultAsync {
106
174
  return ok(values);
107
175
  });
108
176
  }
177
+ /**
178
+ * Heterogeneous async tuple combine — resolves branches **sequentially**
179
+ * (left-to-right), returning the first `Err` in input order. Preserves each
180
+ * branch's `Ok` type by position, so the result destructures type-safely.
181
+ * This is the canonical sequential async combine (replaces the former
182
+ * `sequenceTupleAsync`).
183
+ *
184
+ * @example
185
+ * ```ts
186
+ * const combined = ResultAsync.combineTuple([loadCfg(), loadCatalog()] as const);
187
+ * // ResultAsync<readonly [Cfg, Catalog], CfgError | CatalogError>
188
+ * const r = await combined;
189
+ * if (isOk(r)) {
190
+ * const [cfg, catalog] = r.value; // typed per position
191
+ * }
192
+ * ```
193
+ */
109
194
  static combineTuple(results) {
110
195
  return _ResultAsync.combine(
111
196
  results
@@ -114,18 +199,55 @@ var ResultAsync = class _ResultAsync {
114
199
  /**
115
200
  * Like {@link combineTuple}, but starts every branch before awaiting (wall-clock
116
201
  * parallel for independent IO). On failure, returns the first `Err` in input order.
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * // independent IO — overlap them
206
+ * const combined = ResultAsync.combineTupleParallel([
207
+ * loadProfile(id),
208
+ * loadMetrics(id),
209
+ * ] as const);
210
+ * ```
117
211
  */
118
212
  static combineTupleParallel(results) {
119
213
  return new _ResultAsync(
120
214
  async () => sequenceSettled(await Promise.all(results.map((ra) => ra.resolve())))
121
215
  );
122
216
  }
217
+ /**
218
+ * Transforms the `Ok` value, passing `Err` through unchanged.
219
+ *
220
+ * @example
221
+ * ```ts
222
+ * ResultAsync.ok(2).map((n) => n * 3); // ResultAsync<number> → Ok 6
223
+ * ```
224
+ */
123
225
  map(fn) {
124
226
  return new _ResultAsync(async () => map(await this.resolve(), fn));
125
227
  }
228
+ /**
229
+ * Transforms the `Err` value, passing `Ok` through unchanged — useful for
230
+ * unifying heterogeneous failures into one app-level union.
231
+ *
232
+ * @example
233
+ * ```ts
234
+ * load(id).mapErr((e): AppError => ({ kind: "load", cause: e }));
235
+ * ```
236
+ */
126
237
  mapErr(fn) {
127
238
  return new _ResultAsync(async () => mapErr(await this.resolve(), fn));
128
239
  }
240
+ /**
241
+ * Canonical bind — chains a step that itself returns a `ResultAsync` or sync
242
+ * `Result`, short-circuiting on `Err`. Error types accumulate (`E | F`).
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * authenticate(req)
247
+ * .flatMap((user) => loadProfile(user.id)) // ResultAsync
248
+ * .flatMap((p) => validate(p)); // sync Result also accepted
249
+ * ```
250
+ */
129
251
  flatMap(fn) {
130
252
  return new _ResultAsync(async () => {
131
253
  const first = await this.resolve();
@@ -142,16 +264,28 @@ var ResultAsync = class _ResultAsync {
142
264
  return isCompatLike(next) ? next.inner : next;
143
265
  });
144
266
  }
267
+ /**
268
+ * neverthrow-compat alias of {@link flatMap}. Kept as the documented compat
269
+ * tier; prefer `flatMap` in new code.
270
+ *
271
+ * @example
272
+ * ```ts
273
+ * authenticate(req).andThen((user) => loadProfile(user.id));
274
+ * ```
275
+ */
145
276
  andThen(fn) {
146
277
  return this.flatMap(fn);
147
278
  }
148
279
  /**
149
- * Alias for {@link flatMap}.
150
- * @deprecated Use {@link flatMap} or keep/use compat {@link andThen} instead.
280
+ * Error-channel bind — runs `fn` only on `Err`, swapping in a recovery
281
+ * `ResultAsync` or sync `Result`. `Ok` passes through. The mirror of
282
+ * {@link flatMap} on the error track.
283
+ *
284
+ * @example
285
+ * ```ts
286
+ * loadFromCache(id).recover(() => loadFromOrigin(id));
287
+ * ```
151
288
  */
152
- chain(fn) {
153
- return this.flatMap(fn);
154
- }
155
289
  recover(fn) {
156
290
  return new _ResultAsync(async () => {
157
291
  const first = await this.resolve();
@@ -162,9 +296,27 @@ var ResultAsync = class _ResultAsync {
162
296
  return next instanceof _ResultAsync ? next.resolve() : next;
163
297
  });
164
298
  }
299
+ /**
300
+ * neverthrow-compat alias of {@link recover}. Kept as the documented compat
301
+ * tier; prefer `recover` in new code.
302
+ *
303
+ * @example
304
+ * ```ts
305
+ * loadFromCache(id).orElse(() => loadFromOrigin(id));
306
+ * ```
307
+ */
165
308
  orElse(fn) {
166
309
  return this.recover(fn);
167
310
  }
311
+ /**
312
+ * Runs a side effect on the `Ok` value and passes the result through
313
+ * unchanged; a no-op on `Err`. Mirrors {@link tapErr}.
314
+ *
315
+ * @example
316
+ * ```ts
317
+ * saveUser(u).tap((saved) => analytics.track("user_saved", saved.id));
318
+ * ```
319
+ */
168
320
  tap(fn) {
169
321
  return new _ResultAsync(async () => {
170
322
  const result = await this.resolve();
@@ -174,6 +326,15 @@ var ResultAsync = class _ResultAsync {
174
326
  return result;
175
327
  });
176
328
  }
329
+ /**
330
+ * Runs a side effect on the `Err` value and passes the result through
331
+ * unchanged; a no-op on `Ok`. The error-track mirror of {@link tap}.
332
+ *
333
+ * @example
334
+ * ```ts
335
+ * saveUser(u).tapErr((e) => logger.warn("save failed", e));
336
+ * ```
337
+ */
177
338
  tapErr(fn) {
178
339
  return new _ResultAsync(async () => {
179
340
  const result = await this.resolve();
@@ -183,28 +344,49 @@ var ResultAsync = class _ResultAsync {
183
344
  return result;
184
345
  });
185
346
  }
186
- unwrapOr(defaultValue) {
187
- return this.resolve().then((result) => isErr(result) ? defaultValue : result.value);
188
- }
189
347
  /**
190
- * @deprecated Await the ResultAsync and narrow with {@link isOk} — this method
191
- * re-executes deferred factories and cannot narrow.
348
+ * Settles to the `Ok` value, or `defaultValue` if `Err`. Terminal — returns a
349
+ * plain `Promise`, not a `ResultAsync`.
350
+ *
351
+ * @example
352
+ * ```ts
353
+ * const profile = await loadProfile(id).unwrapOr(guestProfile);
354
+ * ```
192
355
  */
193
- isOk() {
194
- return this.resolve().then((result) => !isErr(result));
356
+ unwrapOr(defaultValue) {
357
+ return this.resolve().then((result) => isErr(result) ? defaultValue : result.value);
195
358
  }
196
359
  /**
197
- * @deprecated Await the ResultAsync and narrow with {@link isErr} — this method
198
- * re-executes deferred factories and cannot narrow.
360
+ * Terminal collapse — folds both tracks into a single awaited value. Returns
361
+ * a plain `Promise`, settling the carrier exactly once.
362
+ *
363
+ * @param onOk - handles the `Ok` value
364
+ * @param onErr - handles the `Err` value
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * const status = await save(row).match(
369
+ * () => 200,
370
+ * (e) => (e.kind === "conflict" ? 409 : 500),
371
+ * );
372
+ * ```
199
373
  */
200
- isErr() {
201
- return this.resolve().then((result) => isErr(result));
202
- }
203
374
  match(onOk, onErr) {
204
375
  return this.resolve().then(
205
376
  (result) => isErr(result) ? onErr(result.error) : onOk(result.value)
206
377
  );
207
378
  }
379
+ /**
380
+ * Settles the carrier to a bare sync {@link Result}, memoizing so the
381
+ * underlying factory runs at most once. Prefer `await ra` (the thenable) or
382
+ * {@link match} in app code; use `resolve` when you need the tagged union back.
383
+ *
384
+ * @example
385
+ * ```ts
386
+ * const r = await load(id).resolve(); // Result<Data, LoadError>
387
+ * if (isOk(r)) use(r.value);
388
+ * ```
389
+ */
208
390
  resolve() {
209
391
  if (!this.promise) {
210
392
  this.promise = this.run();
@@ -233,10 +415,14 @@ function isCompatLike(v) {
233
415
 
234
416
  // src/interop.ts
235
417
  var fromResult = (result) => ResultAsync.fromResult(result);
236
- var asyncAfter = (result, fn) => fromResult(result).flatMap(fn);
237
- function fromAsync(fn, onDefect) {
238
- return (...args) => ResultAsync.fromResultPromise(fn(...args), onDefect);
418
+ function asyncAfter(resultOrFn, fn) {
419
+ if (fn === void 0) {
420
+ const f = resultOrFn;
421
+ return (result) => fromResult(result).flatMap(f);
422
+ }
423
+ return fromResult(resultOrFn).flatMap(fn);
239
424
  }
425
+ var fromAsync = (fn, onDefect) => (...args) => ResultAsync.fromResultPromise(fn(...args), onDefect);
240
426
 
241
427
  export { asyncAfter, fromAsync, fromResult };
242
428
  //# sourceMappingURL=interop.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/result.ts","../src/types.ts","../src/async.ts","../src/interop.ts"],"names":[],"mappings":";AAaO,IAAM,EAAA,GAAK,CAAe,KAAA,MAA4B;AAAA,EAC3D,IAAA,EAAM,IAAA;AAAA,EACN;AACF,CAAA,CAAA;AAWO,IAAM,GAAA,GAAM,CAAyB,KAAA,MAA4B;AAAA,EACtE,IAAA,EAAM,KAAA;AAAA,EACN;AACF,CAAA,CAAA;AAYO,IAAM,IAAA,GAAO,CAAO,MAAA,KAA6C,MAAA,CAAO,IAAA,KAAS,IAAA;AAYjF,IAAM,KAAA,GAAQ,CAAO,MAAA,KAA8C,MAAA,CAAO,IAAA,KAAS,KAAA;AAe1F,IAAM,OAAA,GAAU,CAAU,MAAA,EAAsB,EAAA,KAC9C,KAAK,MAAM,CAAA,GAAI,EAAA,CAAG,EAAA,CAAG,OAAO,KAAK,CAAC,CAAA,GAAI,GAAA,CAAI,OAAO,KAAK,CAAA;AAcjD,SAAS,OACX,IAAA,EACM;AACT,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,OAAA,CAAQ,KAAK,CAAC,CAAA,EAAG,IAAA,CA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,QACN,OAAA,IAAW,CAAA,IACX,YAAA,CAAc,CAAA,CAAyB,KAAK,CAAA;AAEhD;;;ACpQO,IAAM,UAAA,GAAa,CAAO,MAAA,KAC/B,WAAA,CAAY,WAAW,MAAM;AAGxB,IAAM,UAAA,GAAa,CACxB,MAAA,EACA,EAAA,KAC0B,WAAW,MAAM,CAAA,CAAE,QAAQ,EAAE;AAMlD,SAAS,SAAA,CACd,IACA,QAAA,EACwE;AACxE,EAAA,OAAO,CAAA,GAAI,SACT,WAAA,CAAY,iBAAA,CAAkB,GAAG,GAAG,IAAI,GAAG,QAAQ,CAAA;AAIvD","file":"interop.js","sourcesContent":["import type { Err, Ok, Result } from \"./types.js\";\n\nexport type { Err, Ok, Result } from \"./types.js\";\n\n/**\n * Lifts a value into the success track.\n *\n * @example\n * ```ts\n * const r = ok(42); // Result<number, never>\n * const typed: Result<number, \"parse\"> = ok(1);\n * ```\n */\nexport const ok = <T, E = never>(value: T): Result<T, E> => ({\n _tag: \"Ok\",\n value,\n});\n\n/**\n * Lifts a value into the error track.\n *\n * @example\n * ```ts\n * const r = err({ kind: \"parse\", message: \"bad json\" });\n * // Result<never, { kind: \"parse\"; message: string }>\n * ```\n */\nexport const err = <T = never, E = unknown>(error: E): Result<T, E> => ({\n _tag: \"Err\",\n error,\n});\n\n/**\n * Type-narrowing predicate: returns `true` when the result is `Ok`.\n *\n * @example\n * ```ts\n * if (isOk(r)) {\n * console.log(r.value); // narrowed to Ok branch\n * }\n * ```\n */\nexport const isOk = <T, E>(result: Result<T, E>): result is Ok<T, E> => result._tag === \"Ok\";\n\n/**\n * Type-narrowing predicate: returns `true` when the result is `Err`.\n *\n * @example\n * ```ts\n * if (isErr(r)) {\n * metrics.inc(\"error\", { kind: r.error.kind });\n * }\n * ```\n */\nexport const isErr = <T, E>(result: Result<T, E>): result is Err<T, E> => result._tag === \"Err\";\n\n/**\n * Fantasy Land `of` — alias of {@link ok}.\n * @deprecated Use {@link ok} instead.\n */\nexport const of = ok;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dual-form helpers — each export accepts either shape:\n// data-first: `map(result, fn)`\n// curried: `map(fn)(result)`\n// Arity at the call site selects the overload.\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst mapImpl = <T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> =>\n isOk(result) ? ok(fn(result.value)) : err(result.error);\n\n/**\n * Transform the `Ok` value, passing `Err` through unchanged. Dual-form:\n * call data-first or curried (for use with {@link pipe}).\n *\n * @example\n * ```ts\n * map(ok(2), (n) => n * 3); // Ok 6 — data-first\n * pipe(ok(\"x\"), map((s) => s.length));// Ok 1 — curried\n * ```\n */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E>;\nexport function map<T, U>(fn: (value: T) => U): <E>(result: Result<T, E>) => Result<U, E>;\nexport function map(\n ...args: [Result<unknown, unknown>, (value: unknown) => unknown] | [(value: unknown) => unknown]\n): unknown {\n if (args.length === 2) return mapImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => mapImpl(result, fn);\n}\n\nconst mapErrImpl = <T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> =>\n isErr(result) ? err(fn(result.error)) : ok(result.value);\n\n/**\n * Transform the `Err` value, passing `Ok` through unchanged. Useful for\n * unifying heterogeneous failure types into one app-level union.\n *\n * @example\n * ```ts\n * type AppError = { kind: \"http\"; status: number } | { kind: \"parse\" };\n * pipe(\n * fetchSync(url), // Result<Body, { status: number }>\n * mapErr((e): AppError => ({ kind: \"http\", status: e.status })),\n * );\n * ```\n */\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F>;\nexport function mapErr<E, F>(fn: (error: E) => F): <T>(result: Result<T, E>) => Result<T, F>;\nexport function mapErr(\n ...args: [Result<unknown, unknown>, (error: unknown) => unknown] | [(error: unknown) => unknown]\n): unknown {\n if (args.length === 2) return mapErrImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => mapErrImpl(result, fn);\n}\n\nconst bimapImpl = <T, U, E, F>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n): Result<U, F> => (isOk(result) ? ok(onOk(result.value)) : err(onErr(result.error)));\n\n/**\n * Transform both tracks at once — `Ok` via `onOk`, `Err` via `onErr`.\n * Equivalent to `mapErr(onErr)(map(onOk)(result))` but in one pass.\n *\n * @example\n * ```ts\n * bimap(parsed, (cfg) => cfg.name, (e) => ({ kind: \"input\", cause: e }));\n * ```\n */\nexport function bimap<T, U, E, F>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n): Result<U, F>;\nexport function bimap<T, U, E, F>(\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n): (result: Result<T, E>) => Result<U, F>;\nexport function bimap(\n ...args:\n | [Result<unknown, unknown>, (value: unknown) => unknown, (error: unknown) => unknown]\n | [(value: unknown) => unknown, (error: unknown) => unknown]\n): unknown {\n if (args.length === 3) return bimapImpl(args[0], args[1], args[2]);\n const [onOk, onErr] = args;\n return (result: Result<unknown, unknown>) => bimapImpl(result, onOk, onErr);\n}\n\nconst flatMapImpl = <T, U, E, F>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, F>,\n): Result<U, E | F> => (isOk(result) ? fn(result.value) : err(result.error));\n\n/**\n * Canonical bind (Fantasy Land `chain`). Chains a Result-returning step,\n * widening the error union to `E | F`. Short-circuits on `Err`.\n *\n * @example\n * ```ts\n * flatMap(parseInput(raw), (data) =>\n * data.id != null ? ok(data) : err({ kind: \"missing_id\" as const }),\n * );\n * // Result<Data, ParseError | { kind: \"missing_id\" }>\n * ```\n */\nexport function flatMap<T, U, E, F>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, F>,\n): Result<U, E | F>;\nexport function flatMap<T, U, F>(\n fn: (value: T) => Result<U, F>,\n): <E>(result: Result<T, E>) => Result<U, E | F>;\nexport function flatMap(\n ...args:\n | [Result<unknown, unknown>, (value: unknown) => Result<unknown, unknown>]\n | [(value: unknown) => Result<unknown, unknown>]\n): unknown {\n if (args.length === 2) return flatMapImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => flatMapImpl(result, fn);\n}\n\nconst recoverImpl = <T, E, F>(\n result: Result<T, E>,\n fn: (error: E) => Result<T, F>,\n): Result<T, F> => (isErr(result) ? fn(result.error) : ok(result.value));\n\n/**\n * Error-track bind — runs `fn` only when the result is `Err`, allowing\n * a failed workflow to recover to `Ok` or remap the failure. Mirror of\n * {@link flatMap} on the error channel.\n *\n * @example\n * ```ts\n * recover(networkResult, (e) =>\n * e.kind === \"rate_limit\" ? ok(cachedBody) : err(e),\n * );\n * ```\n */\nexport function recover<T, E, F>(\n result: Result<T, E>,\n fn: (error: E) => Result<T, F>,\n): Result<T, F>;\nexport function recover<T, E, F>(\n fn: (error: E) => Result<T, F>,\n): (result: Result<T, E>) => Result<T, F>;\nexport function recover(\n ...args:\n | [Result<unknown, unknown>, (error: unknown) => Result<unknown, unknown>]\n | [(error: unknown) => Result<unknown, unknown>]\n): unknown {\n if (args.length === 2) return recoverImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => recoverImpl(result, fn);\n}\n\nconst tapImpl = <T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> => {\n if (isOk(result)) fn(result.value);\n return result;\n};\n\n/**\n * Observe the `Ok` value for side effects (logging, metrics) without\n * changing the carried value. Passes `Err` through untouched.\n *\n * @example\n * ```ts\n * pipe(\n * parseConfig(raw),\n * tap((cfg) => log.info({ msg: \"parsed\", name: cfg.name })),\n * flatMap(validate),\n * );\n * ```\n */\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E>;\nexport function tap<T>(fn: (value: T) => void): <E>(result: Result<T, E>) => Result<T, E>;\nexport function tap(\n ...args: [Result<unknown, unknown>, (value: unknown) => void] | [(value: unknown) => void]\n): unknown {\n if (args.length === 2) return tapImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => tapImpl(result, fn);\n}\n\nconst tapErrImpl = <T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> => {\n if (isErr(result)) fn(result.error);\n return result;\n};\n\n/**\n * Observe the `Err` value for side effects (logging, metrics) without\n * changing the carried error. Passes `Ok` through untouched.\n *\n * @example\n * ```ts\n * pipe(\n * loadUser(id),\n * tapErr((e) => metrics.inc(\"user.load.fail\", { kind: e.kind })),\n * );\n * ```\n */\nexport function tapErr<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E>;\nexport function tapErr<E>(fn: (error: E) => void): <T>(result: Result<T, E>) => Result<T, E>;\nexport function tapErr(\n ...args: [Result<unknown, unknown>, (error: unknown) => void] | [(error: unknown) => void]\n): unknown {\n if (args.length === 2) return tapErrImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => tapErrImpl(result, fn);\n}\n\nconst matchImpl = <T, E, U>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => U,\n): U => (isOk(result) ? onOk(result.value) : onErr(result.error));\n\n/**\n * Terminal collapse — fold both tracks into a single value. Dual-form:\n * 3-args data-first, 2-args curried for {@link pipe}. Returns whatever\n * the handlers return.\n *\n * For files that also import `match` from `ts-pattern`, the\n * collision-free alias {@link matchResult} is identical.\n *\n * @example\n * ```ts\n * const html = match(parsed, (cfg) => render(cfg), (e) => renderError(e));\n * ```\n */\nexport function match<T, E, U>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => U,\n): U;\nexport function match<T, E, U>(\n onOk: (value: T) => U,\n onErr: (error: E) => U,\n): (result: Result<T, E>) => U;\nexport function match(\n ...args:\n | [Result<unknown, unknown>, (value: unknown) => unknown, (error: unknown) => unknown]\n | [(value: unknown) => unknown, (error: unknown) => unknown]\n): unknown {\n if (args.length === 3) return matchImpl(args[0], args[1], args[2]);\n const [onOk, onErr] = args;\n return (result: Result<unknown, unknown>) => matchImpl(result, onOk, onErr);\n}\n\n/**\n * Collision-free alias for files that also import `match` from ts-pattern.\n * @deprecated Namespace import carriers (e.g., `import * as R from \"@onrails/result\"`) and use canonical {@link match} instead.\n */\nexport const matchResult = match;\n\n/**\n * Curried collapse with named slots — escape valve when positional `match`\n * order is unclear at the call site (e.g. when both handlers return the same\n * type and a transposed `match(r, onErr, onOk)` would silently compile).\n * @deprecated Use curried {@link match}(onOk, onErr)(result) instead.\n */\nexport const fold =\n <T, E, U>(handlers: { readonly ok: (value: T) => U; readonly err: (error: E) => U }) =>\n (result: Result<T, E>): U =>\n matchImpl(result, handlers.ok, handlers.err);\n\n/**\n * Returns the `Ok` value, or `defaultValue` when the result is `Err`.\n *\n * @example\n * ```ts\n * unwrapOr(parsedSetting, \"default-value\");\n * ```\n */\nexport const unwrapOr = <T, E>(result: Result<T, E>, defaultValue: T): T =>\n isOk(result) ? result.value : defaultValue;\n\n/**\n * Test/assert helper — throws the original Err value when called on Err.\n *\n * @throws when the result is Err — assertion-tier; use {@link match} / {@link unwrapOr} in business logic.\n * Allowed in `*.spec.ts` / `*.test.ts`; flagged elsewhere by the plugins.\n */\nexport function unwrapOk<T, E>(result: Result<T, E>): T {\n if (isErr(result)) throw result.error;\n return result.value;\n}\n\n/**\n * Test/assert helper — throws TypeError when called on Ok.\n *\n * @throws when the result is Ok — assertion-tier; allowed in `*.spec.ts` / `*.test.ts`; flagged elsewhere by the plugins.\n */\nexport function unwrapErr<T, E>(result: Result<T, E>): E {\n if (isOk(result)) throw new TypeError(\"unwrapErr called on Ok\");\n return result.error;\n}\n\n/** Wrap a throwing sync function — neverthrow `Result.fromThrowable` */\nexport function trySync<A extends readonly unknown[], T, E>(\n fn: (...args: A) => T,\n onThrow: (error: unknown) => E,\n): (...args: A) => Result<T, E>;\nexport function trySync<F extends (...args: never) => unknown, E>(\n fn: F,\n onThrow: (error: unknown) => E,\n): (...args: Parameters<F>) => Result<ReturnType<F>, E>;\nexport function trySync(\n fn: (...args: never) => unknown,\n onThrow: (error: unknown) => unknown,\n): (...args: never) => Result<unknown, unknown> {\n return (...args: never) => {\n try {\n return ok(fn(...args));\n } catch (error) {\n return err(onThrow(error));\n }\n };\n}\n\n/** First failure wins; otherwise collects values in order */\nexport const combine = <T, E>(results: readonly Result<T, E>[]): Result<T[], E> => {\n const values: T[] = [];\n for (const result of results) {\n if (isErr(result)) return err(result.error);\n values.push(result.value);\n }\n return ok(values);\n};\n\n/** Tuple-preserving combine (neverthrow-style) */\nexport const combineTuple = <const R extends readonly Result<unknown, unknown>[]>(\n results: R,\n): CombineTuple<R> =>\n // Runtime identical to combine; the cast restores per-index tuple types.\n combine(results as readonly Result<unknown, unknown>[]) as CombineTuple<R>;\n\ntype _OkValue<R> = R extends { _tag: \"Ok\"; readonly value: infer T } ? T : never;\ntype _ErrValue<R> = R extends { _tag: \"Err\"; readonly error: infer E } ? E : never;\n\ntype CombineTuple<R extends readonly Result<unknown, unknown>[]> = Result<\n { [K in keyof R]: _OkValue<R[K]> },\n { [K in keyof R]: _ErrValue<R[K]> }[number]\n>;\n\n/**\n * Variadic value-first pipe — threads `value` through up to nine unary fns.\n *\n * ```ts\n * pipe(\n * parseConfig(raw),\n * map((cfg) => cfg.name),\n * flatMap((name) => name ? ok(name) : err({ kind: \"empty\" })),\n * tap(log),\n * );\n * ```\n */\nexport function pipe<A>(value: A): A;\nexport function pipe<A, B>(value: A, ab: (a: A) => B): B;\nexport function pipe<A, B, C>(value: A, ab: (a: A) => B, bc: (b: B) => C): C;\nexport function pipe<A, B, C, D>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D;\nexport function pipe<A, B, C, D, E>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): E;\nexport function pipe<A, B, C, D, E, F>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n): F;\nexport function pipe<A, B, C, D, E, F, G>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n): G;\nexport function pipe<A, B, C, D, E, F, G, H>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n): H;\nexport function pipe<A, B, C, D, E, F, G, H, I>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n hi: (h: H) => I,\n): I;\nexport function pipe(value: unknown, ...fns: ReadonlyArray<(x: unknown) => unknown>): unknown {\n let acc = value;\n for (const fn of fns) {\n acc = fn(acc);\n }\n return acc;\n}\n","/** Tagged success/failure — no classes, tree-shake friendly. */\nexport type Result<T, E> =\n | { readonly _tag: \"Ok\"; readonly value: T }\n | { readonly _tag: \"Err\"; readonly error: E };\n\nexport type Ok<T, E = never> = Extract<Result<T, E>, { _tag: \"Ok\" }>;\nexport type Err<T, E> = Extract<Result<T, E>, { _tag: \"Err\" }>;\n\n/** Thrown defect mapped when {@link fromAsync} has no `onDefect` */\nexport class UnexpectedError extends Error {\n constructor(\n message: string,\n override readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"UnexpectedError\";\n }\n}\n","import { err, isErr, map, mapErr, ok } from \"./result.js\";\nimport type { Result } from \"./types.js\";\nimport { UnexpectedError } from \"./types.js\";\n\ntype PromiseFactory<T, E> = () => Promise<Result<T, E>>;\ntype AsyncOk<R> = R extends ResultAsync<infer T, unknown> ? T : never;\ntype AsyncErr<R> = R extends ResultAsync<unknown, infer E> ? E : never;\ntype CombineTupleAsync<R extends readonly ResultAsync<unknown, unknown>[]> = ResultAsync<\n { [K in keyof R]: AsyncOk<R[K]> },\n { [K in keyof R]: AsyncErr<R[K]> }[number]\n>;\n\nconst liftPromiseResult = async <T, E>(\n promise: Promise<Result<T, E>>,\n onDefect: (error: unknown) => E | UnexpectedError,\n): Promise<Result<T, E | UnexpectedError>> => {\n try {\n const result = await promise;\n if (isErr(result)) {\n return result;\n }\n // Auto-flatten one level: Ok<Result<…>> from double-wrapped interop.\n return isResultLike<T, E | UnexpectedError>(result.value) ? result.value : result;\n } catch (error) {\n return err(onDefect(error));\n }\n};\n\n/** Collapses settled results left-to-right, short-circuiting on the first `Err`. */\nconst sequenceSettled = (\n settled: readonly Result<unknown, unknown>[],\n): Result<unknown[], unknown> => {\n const values: unknown[] = [];\n for (const result of settled) {\n if (isErr(result)) {\n return err(result.error);\n }\n values.push(result.value);\n }\n return ok(values);\n};\n\n/**\n * Async result — public API never exposes `Promise<Result<…>>` directly;\n * await via `.resolve()` or `.match()`.\n */\nexport class ResultAsync<T, E> {\n private promise: Promise<Result<T, E>> | null = null;\n\n protected constructor(protected readonly run: PromiseFactory<T, E>) {}\n\n static fromResult<T, E>(result: Result<T, E>): ResultAsync<T, E> {\n return new ResultAsync(async () => result);\n }\n\n static fromPromise<T, E>(\n promise: PromiseLike<T>,\n onReject: (error: unknown) => E,\n ): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n try {\n return ok(await promise);\n } catch (error) {\n return err(onReject(error));\n }\n });\n }\n\n static fromSafePromise<T, E = never>(promise: PromiseLike<T>): ResultAsync<T, E> {\n return new ResultAsync(async () => ok(await promise));\n }\n\n /**\n * Defers work until {@link resolve}. Unlike {@link fromPromise}, nothing runs\n * until the `ResultAsync` is resolved (e.g. by `combineTuple` / `combineTupleParallel`).\n */\n static defer<T, E>(fn: () => Promise<Result<T, E>>): ResultAsync<T, E> {\n return new ResultAsync(fn);\n }\n\n static ok<T>(value: T): ResultAsync<T, never>;\n static ok<T, E>(value: T): ResultAsync<T, E>;\n static ok<T, E = never>(value: T): ResultAsync<T, E> {\n return new ResultAsync(async () => ok(value));\n }\n\n static err<T = never, E = unknown>(error: E): ResultAsync<T, E> {\n return new ResultAsync(async () => err(error));\n }\n\n /** @see {@link fromAsync} from `@onrails/result/interop` */\n static fromResultPromise<T, E>(\n promise: Promise<Result<T, E>>,\n onDefect?: (error: unknown) => E | UnexpectedError,\n ): ResultAsync<T, E | UnexpectedError> {\n const mapDefect =\n onDefect ?? ((error: unknown) => new UnexpectedError(\"Unexpected async defect\", error));\n return new ResultAsync(() => liftPromiseResult(promise, mapDefect));\n }\n\n static combine<T, E>(results: readonly ResultAsync<T, E>[]): ResultAsync<T[], E> {\n return new ResultAsync(async () => {\n const values: T[] = [];\n for (const ra of results) {\n const result = await ra.resolve();\n if (isErr(result)) {\n return err(result.error);\n }\n values.push(result.value);\n }\n return ok(values);\n });\n }\n\n static combineTuple<const R extends readonly ResultAsync<unknown, unknown>[]>(\n results: R,\n ): CombineTupleAsync<R> {\n // Runtime identical to combine; the cast restores per-index tuple types.\n return ResultAsync.combine(\n results as readonly ResultAsync<unknown, unknown>[],\n ) as CombineTupleAsync<R>;\n }\n\n /**\n * Like {@link combineTuple}, but starts every branch before awaiting (wall-clock\n * parallel for independent IO). On failure, returns the first `Err` in input order.\n */\n static combineTupleParallel<const R extends readonly ResultAsync<unknown, unknown>[]>(\n results: R,\n ): CombineTupleAsync<R> {\n // Cast restores per-index tuple types over the untyped sequence core.\n return new ResultAsync(async () =>\n sequenceSettled(await Promise.all(results.map((ra) => ra.resolve()))),\n ) as CombineTupleAsync<R>;\n }\n\n map<U>(fn: (value: T) => U): ResultAsync<U, E> {\n return new ResultAsync(async () => map(await this.resolve(), fn));\n }\n\n mapErr<F>(fn: (error: E) => F): ResultAsync<T, F> {\n return new ResultAsync(async () => mapErr(await this.resolve(), fn));\n }\n\n flatMap<U, F = E>(\n fn: (value: T) => ResultAsync<U, F> | Result<U, F> | { inner: Result<U, F> },\n ): ResultAsync<U, E | F> {\n return new ResultAsync<U, E | F>(async () => {\n const first = await this.resolve();\n if (isErr(first)) {\n return first;\n }\n const next = fn(first.value);\n if (next instanceof ResultAsync) {\n return next.resolve();\n }\n if (isResultLike<U, F>(next)) {\n return next;\n }\n return isCompatLike<U, F>(next) ? next.inner : next;\n });\n }\n\n andThen<U, F = E>(\n fn: (value: T) => ResultAsync<U, F> | Result<U, F> | { inner: Result<U, F> },\n ): ResultAsync<U, E | F> {\n return this.flatMap(fn);\n }\n\n /**\n * Alias for {@link flatMap}.\n * @deprecated Use {@link flatMap} or keep/use compat {@link andThen} instead.\n */\n chain<U, F = E>(\n fn: (value: T) => ResultAsync<U, F> | Result<U, F> | { inner: Result<U, F> },\n ): ResultAsync<U, E | F> {\n return this.flatMap(fn);\n }\n\n recover<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F> {\n return new ResultAsync<T, F>(async () => {\n const first = await this.resolve();\n if (!isErr(first)) {\n return first;\n }\n const next = fn(first.error);\n return next instanceof ResultAsync ? next.resolve() : next;\n });\n }\n\n orElse<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F> {\n return this.recover(fn);\n }\n\n tap(fn: (value: T) => void): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n const result = await this.resolve();\n if (!isErr(result)) {\n fn(result.value);\n }\n return result;\n });\n }\n\n tapErr(fn: (error: E) => void): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n const result = await this.resolve();\n if (isErr(result)) {\n fn(result.error);\n }\n return result;\n });\n }\n\n unwrapOr<U>(defaultValue: U): Promise<T | U> {\n return this.resolve().then((result) => (isErr(result) ? defaultValue : result.value));\n }\n\n /**\n * @deprecated Await the ResultAsync and narrow with {@link isOk} — this method\n * re-executes deferred factories and cannot narrow.\n */\n isOk(): Promise<boolean> {\n return this.resolve().then((result) => !isErr(result));\n }\n\n /**\n * @deprecated Await the ResultAsync and narrow with {@link isErr} — this method\n * re-executes deferred factories and cannot narrow.\n */\n isErr(): Promise<boolean> {\n return this.resolve().then((result) => isErr(result));\n }\n\n match<U1, U2 = U1>(onOk: (value: T) => U1, onErr: (error: E) => U2): Promise<U1 | U2> {\n return this.resolve().then((result) =>\n isErr(result) ? onErr(result.error) : onOk(result.value),\n );\n }\n\n resolve(): Promise<Result<T, E>> {\n if (!this.promise) {\n this.promise = this.run();\n }\n return this.promise;\n }\n\n /**\n * Thenable shim — `await ra` resolves to a bare tagged-union `Result<T, E>`.\n * Narrow with `isOk(r)` / `isErr(r)` to read `.value` / `.error`.\n */\n // biome-ignore lint/suspicious/noThenProperty: makes ResultAsync awaitable\n then<R1 = Result<T, E>, R2 = never>(\n onfulfilled?: ((value: Result<T, E>) => R1 | PromiseLike<R1>) | undefined | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | undefined | null,\n ): Promise<R1 | R2> {\n return this.resolve().then(\n // Safe: without onfulfilled, R1 stays at its Result<T, E> default.\n (r) => (onfulfilled ? onfulfilled(r) : (r as unknown as R1)),\n onrejected ?? undefined,\n );\n }\n}\n\nfunction isResultLike<U, F>(v: unknown): v is Result<U, F> {\n return (\n typeof v === \"object\" &&\n v !== null &&\n \"_tag\" in v &&\n ((v as { _tag: unknown })._tag === \"Ok\" || (v as { _tag: unknown })._tag === \"Err\")\n );\n}\n\nfunction isCompatLike<U, F>(v: unknown): v is { inner: Result<U, F> } {\n return (\n typeof v === \"object\" &&\n v !== null &&\n \"inner\" in v &&\n isResultLike((v as { inner: unknown }).inner)\n );\n}\n\n/**\n * Lifts a value into an `Ok` async result.\n *\n * @example\n * ```ts\n * const r = okAsync(42); // ResultAsync<number, never>\n * ```\n */\nexport const okAsync = ResultAsync.ok;\n\n/**\n * Lifts a value into an `Err` async result.\n *\n * @example\n * ```ts\n * const r = errAsync({ kind: \"not_found\" as const });\n * ```\n */\nexport const errAsync = ResultAsync.err;\n\n/**\n * Wraps a `PromiseLike<T>` into a {@link ResultAsync}. Reject reasons go\n * through `onReject` to become typed `Err`s; success becomes `Ok<T>`.\n *\n * @example\n * ```ts\n * const body = fromPromise(\n * fetch(url).then((r) => r.text()),\n * (e): NetworkError => ({ kind: \"network\", cause: String(e) }),\n * );\n * ```\n */\nexport const fromPromise = ResultAsync.fromPromise;\n\n/**\n * Wraps a `PromiseLike<T>` that **never rejects** into {@link ResultAsync}.\n * Skips the `onReject` mapper. Use only when the promise is provably safe.\n */\nexport const fromSafePromise = ResultAsync.fromSafePromise;\n\n/**\n * Heterogeneous async tuple combine — left-to-right, short-circuit on\n * first `Err` in input order. Preserves tuple positions so destructuring\n * stays type-safe.\n *\n * @example\n * ```ts\n * const combined = sequenceTupleAsync([loadCfg(), loadCatalog()] as const);\n * // ResultAsync<readonly [Cfg, Catalog], CfgError | CatalogError>\n * ```\n * @deprecated Use static {@link ResultAsync.combineTuple} instead.\n */\nexport const sequenceTupleAsync = ResultAsync.combineTuple;\n\n/**\n * Heterogeneous async tuple combine — branches overlap in wall-clock time.\n * Returns the first `Err` in **input** order (not completion order).\n *\n * @example\n * ```ts\n * const combined = parallelTupleAsync([\n * loadProfile(id),\n * loadMetrics(id),\n * loadFlags(id),\n * ] as const);\n * // ResultAsync<readonly [Profile, Metrics, Flags], …>\n * ```\n */\nexport const parallelTupleAsync = ResultAsync.combineTupleParallel;\n\nconst toError = (error: unknown): Error =>\n error instanceof Error ? error : new Error(String(error));\n\n/**\n * Convenience wrapper over {@link fromPromise} with default `Error`\n * normalization. Call without `onReject` to get `ResultAsync<T, Error>`,\n * or pass a custom mapper for a typed error.\n *\n * @example\n * ```ts\n * // Default: rejection → Err(Error)\n * const a = tryAsync(db.users.insert(row));\n *\n * // Custom: typed error\n * const b = tryAsync(db.users.insert(row), (e): DbError => ({\n * kind: \"db\",\n * cause: e,\n * }));\n * ```\n */\nexport function tryAsync<T>(promise: PromiseLike<T>): ResultAsync<T, Error>;\nexport function tryAsync<T, E>(\n promise: PromiseLike<T>,\n onReject: (error: unknown) => E,\n): ResultAsync<T, E>;\nexport function tryAsync<T, E>(\n promise: PromiseLike<T>,\n onReject?: (error: unknown) => E,\n): ResultAsync<T, E | Error> {\n if (onReject) {\n return ResultAsync.fromPromise(promise, onReject);\n }\n return ResultAsync.fromPromise(promise, toError);\n}\n","import { ResultAsync } from \"./async.js\";\nimport type { Result, UnexpectedError } from \"./types.js\";\n\n/** Success type of a {@link Result} or {@link ResultAsync} */\nexport type InferOk<R> = R extends { _tag: \"Ok\"; readonly value: infer T }\n ? T\n : R extends ResultAsync<infer T, unknown>\n ? T\n : never;\n\n/** Error type of a {@link Result} or {@link ResultAsync} */\nexport type InferErr<R> = R extends { _tag: \"Err\"; readonly error: infer E }\n ? E\n : R extends ResultAsync<unknown, infer E>\n ? E\n : never;\n\ntype AnyResult = Result<unknown, unknown>;\n\n/** Lift an already-known sync {@link Result} into {@link ResultAsync}. */\nexport const fromResult = <T, E>(result: Result<T, E>): ResultAsync<T, E> =>\n ResultAsync.fromResult(result);\n\n/** Bind a sync {@link Result} into an async step without widening defects. */\nexport const asyncAfter = <T, U, E, F>(\n result: Result<T, E>,\n fn: (value: T) => ResultAsync<U, F>,\n): ResultAsync<U, E | F> => fromResult(result).flatMap(fn);\n\n/**\n * Lift `(...args) => Promise<Result<T, E>>` to `(...args) => ResultAsync<T, E>`.\n * Catches unexpected promise rejections (defects) via `onDefect` or {@link UnexpectedError}.\n */\nexport function fromAsync<A extends readonly unknown[], R extends AnyResult>(\n fn: (...args: A) => Promise<R>,\n onDefect?: (error: unknown) => InferErr<R> | UnexpectedError,\n): (...args: A) => ResultAsync<InferOk<R>, InferErr<R> | UnexpectedError> {\n return (...args: A) =>\n ResultAsync.fromResultPromise(fn(...args), onDefect) as ResultAsync<\n InferOk<R>,\n InferErr<R> | UnexpectedError\n >;\n}\n"]}
1
+ {"version":3,"sources":["../src/result.ts","../src/types.ts","../src/async.ts","../src/interop.ts"],"names":[],"mappings":";AAaO,IAAM,EAAA,GAAK,CAAe,KAAA,MAA4B;AAAA,EAC3D,IAAA,EAAM,IAAA;AAAA,EACN;AACF,CAAA,CAAA;AAWO,IAAM,GAAA,GAAM,CAAyB,KAAA,MAA4B;AAAA,EACtE,IA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E,OAAO,MAAM,QAAA,IACb,CAAA,KAAM,QACN,OAAA,IAAW,CAAA,IACX,YAAA,CAAc,CAAA,CAAyB,KAAK,CAAA;AAEhD;;;ACpbO,IAAM,UAAA,GAAa,CAAO,MAAA,KAC/B,WAAA,CAAY,WAAW,MAAM;AAmBxB,SAAS,UAAA,CACd,YACA,EAAA,EAC2E;AAC3E,EAAA,IAAI,OAAO,MAAA,EAAW;AACpB,IAAA,MAAM,CAAA,GAAI,UAAA;AACV,IAAA,OAAO,CAAC,MAAA,KAAgD,UAAA,CAAW,MAAM,CAAA,CAAE,QAAQ,CAAC,CAAA;AAAA,EACtF;AACA,EAAA,OAAO,UAAA,CAAW,UAA0B,CAAA,CAAE,OAAA,CAAQ,EAAE,CAAA;AAC1D;AAmBO,IAAM,SAAA,GACX,CACE,EAAA,EACA,QAAA,KAEF,CAAA,GAAI,IAAA,KACF,WAAA,CAAY,iBAAA,CAAkB,EAAA,CAAG,GAAG,IAAI,CAAA,EAAG,QAAQ","file":"interop.js","sourcesContent":["import type { Err, Ok, Result } from \"./types.js\";\n\nexport type { Err, Ok, Result } from \"./types.js\";\n\n/**\n * Lifts a value into the success track.\n *\n * @example\n * ```ts\n * const r = ok(42); // Result<number, never>\n * const typed: Result<number, \"parse\"> = ok(1);\n * ```\n */\nexport const ok = <T, E = never>(value: T): Result<T, E> => ({\n _tag: \"Ok\",\n value,\n});\n\n/**\n * Lifts a value into the error track.\n *\n * @example\n * ```ts\n * const r = err({ kind: \"parse\", message: \"bad json\" });\n * // Result<never, { kind: \"parse\"; message: string }>\n * ```\n */\nexport const err = <T = never, E = unknown>(error: E): Result<T, E> => ({\n _tag: \"Err\",\n error,\n});\n\n/**\n * Type-narrowing predicate: returns `true` when the result is `Ok`.\n *\n * @example\n * ```ts\n * if (isOk(r)) {\n * console.log(r.value); // narrowed to Ok branch\n * }\n * ```\n */\nexport const isOk = <T, E>(result: Result<T, E>): result is Ok<T, E> => result._tag === \"Ok\";\n\n/**\n * Type-narrowing predicate: returns `true` when the result is `Err`.\n *\n * @example\n * ```ts\n * if (isErr(r)) {\n * metrics.inc(\"error\", { kind: r.error.kind });\n * }\n * ```\n */\nexport const isErr = <T, E>(result: Result<T, E>): result is Err<T, E> => result._tag === \"Err\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dual-form helpers — each export accepts either shape:\n// data-first: `map(result, fn)`\n// curried: `map(fn)(result)`\n// Arity at the call site selects the overload.\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst mapImpl = <T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> =>\n isOk(result) ? ok(fn(result.value)) : err(result.error);\n\n/**\n * Transform the `Ok` value, passing `Err` through unchanged. Dual-form:\n * call data-first or curried (for use with {@link pipe}).\n *\n * @example\n * ```ts\n * map(ok(2), (n) => n * 3); // Ok 6 — data-first\n * pipe(ok(\"x\"), map((s) => s.length));// Ok 1 — curried\n * ```\n */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E>;\nexport function map<T, U>(fn: (value: T) => U): <E>(result: Result<T, E>) => Result<U, E>;\nexport function map(\n ...args: [Result<unknown, unknown>, (value: unknown) => unknown] | [(value: unknown) => unknown]\n): unknown {\n if (args.length === 2) return mapImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => mapImpl(result, fn);\n}\n\nconst mapErrImpl = <T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> =>\n isErr(result) ? err(fn(result.error)) : ok(result.value);\n\n/**\n * Transform the `Err` value, passing `Ok` through unchanged. Useful for\n * unifying heterogeneous failure types into one app-level union.\n *\n * @example\n * ```ts\n * type AppError = { kind: \"http\"; status: number } | { kind: \"parse\" };\n * pipe(\n * fetchSync(url), // Result<Body, { status: number }>\n * mapErr((e): AppError => ({ kind: \"http\", status: e.status })),\n * );\n * ```\n */\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F>;\nexport function mapErr<E, F>(fn: (error: E) => F): <T>(result: Result<T, E>) => Result<T, F>;\nexport function mapErr(\n ...args: [Result<unknown, unknown>, (error: unknown) => unknown] | [(error: unknown) => unknown]\n): unknown {\n if (args.length === 2) return mapErrImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => mapErrImpl(result, fn);\n}\n\nconst bimapImpl = <T, U, E, F>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n): Result<U, F> => (isOk(result) ? ok(onOk(result.value)) : err(onErr(result.error)));\n\n/**\n * Transform both tracks at once — `Ok` via `onOk`, `Err` via `onErr`.\n * Equivalent to `mapErr(onErr)(map(onOk)(result))` but in one pass.\n *\n * @example\n * ```ts\n * bimap(parsed, (cfg) => cfg.name, (e) => ({ kind: \"input\", cause: e }));\n * ```\n */\nexport function bimap<T, U, E, F>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n): Result<U, F>;\nexport function bimap<T, U, E, F>(\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n): (result: Result<T, E>) => Result<U, F>;\nexport function bimap(\n ...args:\n | [Result<unknown, unknown>, (value: unknown) => unknown, (error: unknown) => unknown]\n | [(value: unknown) => unknown, (error: unknown) => unknown]\n): unknown {\n if (args.length === 3) return bimapImpl(args[0], args[1], args[2]);\n const [onOk, onErr] = args;\n return (result: Result<unknown, unknown>) => bimapImpl(result, onOk, onErr);\n}\n\nconst flatMapImpl = <T, U, E, F>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, F>,\n): Result<U, E | F> => (isOk(result) ? fn(result.value) : err(result.error));\n\n/**\n * Canonical bind (Fantasy Land `chain`). Chains a Result-returning step,\n * widening the error union to `E | F`. Short-circuits on `Err`.\n *\n * @example\n * ```ts\n * flatMap(parseInput(raw), (data) =>\n * data.id != null ? ok(data) : err({ kind: \"missing_id\" as const }),\n * );\n * // Result<Data, ParseError | { kind: \"missing_id\" }>\n * ```\n */\nexport function flatMap<T, U, E, F>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, F>,\n): Result<U, E | F>;\nexport function flatMap<T, U, F>(\n fn: (value: T) => Result<U, F>,\n): <E>(result: Result<T, E>) => Result<U, E | F>;\nexport function flatMap(\n ...args:\n | [Result<unknown, unknown>, (value: unknown) => Result<unknown, unknown>]\n | [(value: unknown) => Result<unknown, unknown>]\n): unknown {\n if (args.length === 2) return flatMapImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => flatMapImpl(result, fn);\n}\n\nconst recoverImpl = <T, E, F>(\n result: Result<T, E>,\n fn: (error: E) => Result<T, F>,\n): Result<T, F> => (isErr(result) ? fn(result.error) : ok(result.value));\n\n/**\n * Error-track bind — runs `fn` only when the result is `Err`, allowing\n * a failed workflow to recover to `Ok` or remap the failure. Mirror of\n * {@link flatMap} on the error channel.\n *\n * @example\n * ```ts\n * recover(networkResult, (e) =>\n * e.kind === \"rate_limit\" ? ok(cachedBody) : err(e),\n * );\n * ```\n */\nexport function recover<T, E, F>(\n result: Result<T, E>,\n fn: (error: E) => Result<T, F>,\n): Result<T, F>;\nexport function recover<T, E, F>(\n fn: (error: E) => Result<T, F>,\n): (result: Result<T, E>) => Result<T, F>;\nexport function recover(\n ...args:\n | [Result<unknown, unknown>, (error: unknown) => Result<unknown, unknown>]\n | [(error: unknown) => Result<unknown, unknown>]\n): unknown {\n if (args.length === 2) return recoverImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => recoverImpl(result, fn);\n}\n\nconst tapImpl = <T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> => {\n if (isOk(result)) fn(result.value);\n return result;\n};\n\n/**\n * Observe the `Ok` value for side effects (logging, metrics) without\n * changing the carried value. Passes `Err` through untouched.\n *\n * @example\n * ```ts\n * pipe(\n * parseConfig(raw),\n * tap((cfg) => log.info({ msg: \"parsed\", name: cfg.name })),\n * flatMap(validate),\n * );\n * ```\n */\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E>;\nexport function tap<T>(fn: (value: T) => void): <E>(result: Result<T, E>) => Result<T, E>;\nexport function tap(\n ...args: [Result<unknown, unknown>, (value: unknown) => void] | [(value: unknown) => void]\n): unknown {\n if (args.length === 2) return tapImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => tapImpl(result, fn);\n}\n\nconst tapErrImpl = <T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> => {\n if (isErr(result)) fn(result.error);\n return result;\n};\n\n/**\n * Observe the `Err` value for side effects (logging, metrics) without\n * changing the carried error. Passes `Ok` through untouched.\n *\n * @example\n * ```ts\n * pipe(\n * loadUser(id),\n * tapErr((e) => metrics.inc(\"user.load.fail\", { kind: e.kind })),\n * );\n * ```\n */\nexport function tapErr<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E>;\nexport function tapErr<E>(fn: (error: E) => void): <T>(result: Result<T, E>) => Result<T, E>;\nexport function tapErr(\n ...args: [Result<unknown, unknown>, (error: unknown) => void] | [(error: unknown) => void]\n): unknown {\n if (args.length === 2) return tapErrImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => tapErrImpl(result, fn);\n}\n\nconst matchImpl = <T, E, U>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => U,\n): U => (isOk(result) ? onOk(result.value) : onErr(result.error));\n\n/**\n * Terminal collapse — fold both tracks into a single value. Dual-form:\n * 3-args data-first, 2-args curried for {@link pipe}. Returns whatever\n * the handlers return.\n *\n * For files that also import `match` from `ts-pattern`, use a namespace\n * import (`import * as R from \"@onrails/result\"` → `R.match`) to dissolve\n * the collision.\n *\n * @example\n * ```ts\n * const html = match(parsed, (cfg) => render(cfg), (e) => renderError(e));\n * ```\n */\nexport function match<T, E, U>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => U,\n): U;\nexport function match<T, E, U>(\n onOk: (value: T) => U,\n onErr: (error: E) => U,\n): (result: Result<T, E>) => U;\nexport function match(\n ...args:\n | [Result<unknown, unknown>, (value: unknown) => unknown, (error: unknown) => unknown]\n | [(value: unknown) => unknown, (error: unknown) => unknown]\n): unknown {\n if (args.length === 3) return matchImpl(args[0], args[1], args[2]);\n const [onOk, onErr] = args;\n return (result: Result<unknown, unknown>) => matchImpl(result, onOk, onErr);\n}\n\n/**\n * Returns the `Ok` value, or `defaultValue` when the result is `Err`.\n *\n * @example\n * ```ts\n * unwrapOr(parsedSetting, \"default-value\");\n * ```\n */\nexport const unwrapOr = <T, E>(result: Result<T, E>, defaultValue: T): T =>\n isOk(result) ? result.value : defaultValue;\n\n/**\n * Test/assert helper — returns the `Ok` value, or **throws the original `Err`\n * value** when called on an `Err`. This is the assertion tier (RFC 0001 §4):\n * intended for `*.spec.ts` / `*.test.ts`, where throwing fails the test loudly.\n * In business logic prefer {@link match} or {@link unwrapOr}; the lint plugins\n * flag `unwrapOk` outside test files.\n *\n * @returns the unwrapped `Ok` value\n * @throws the carried `Err` value when the result is `Err`\n *\n * @example\n * ```ts\n * // in a *.spec.ts\n * expect(unwrapOk(ok(5))).toBe(5);\n * expect(() => unwrapOk(err(error))).toThrow(error);\n * ```\n */\nexport function unwrapOk<T, E>(result: Result<T, E>): T {\n if (isErr(result)) throw result.error;\n return result.value;\n}\n\n/**\n * Test/assert helper — returns the `Err` value, or **throws a `TypeError`**\n * when called on an `Ok`. Mirror of {@link unwrapOk} on the error track and\n * part of the same assertion tier (RFC 0001 §4): intended for `*.spec.ts` /\n * `*.test.ts`. Prefer {@link match} / {@link unwrapOr} in business logic; the\n * lint plugins flag `unwrapErr` outside test files.\n *\n * @returns the unwrapped `Err` value\n * @throws `TypeError` when the result is `Ok`\n *\n * @example\n * ```ts\n * // in a *.spec.ts\n * expect(unwrapErr(err(\"x\"))).toBe(\"x\");\n * expect(() => unwrapErr(ok(5))).toThrow(TypeError);\n * ```\n */\nexport function unwrapErr<T, E>(result: Result<T, E>): E {\n if (isOk(result)) throw new TypeError(\"unwrapErr called on Ok\");\n return result.error;\n}\n\n/**\n * Wraps a throwing sync function, returning a function that produces a\n * {@link Result} instead of throwing. Thrown errors pass through `onThrow` to\n * become a typed `Err`; a normal return becomes `Ok`. The neverthrow analogue\n * is `Result.fromThrowable`.\n *\n * @param fn - the throwing function to wrap\n * @param onThrow - maps a thrown value to the `Err` channel\n * @returns a function with `fn`'s parameters that returns `Result<ReturnType, E>`\n *\n * @example\n * ```ts\n * type ParseError = { kind: \"parse\"; message: string };\n * const parse = trySync(\n * JSON.parse,\n * (e): ParseError => ({ kind: \"parse\", message: String(e) }),\n * );\n * parse(\"{}\"); // Ok({})\n * parse(\"nope\"); // Err({ kind: \"parse\", … })\n * ```\n */\nexport function trySync<A extends readonly unknown[], T, E>(\n fn: (...args: A) => T,\n onThrow: (error: unknown) => E,\n): (...args: A) => Result<T, E>;\nexport function trySync<F extends (...args: never) => unknown, E>(\n fn: F,\n onThrow: (error: unknown) => E,\n): (...args: Parameters<F>) => Result<ReturnType<F>, E>;\nexport function trySync(\n fn: (...args: never) => unknown,\n onThrow: (error: unknown) => unknown,\n): (...args: never) => Result<unknown, unknown> {\n return (...args: never) => {\n try {\n return ok(fn(...args));\n } catch (error) {\n return err(onThrow(error));\n }\n };\n}\n\n/**\n * Variadic value-first pipe — threads `value` through up to nine unary fns,\n * left-to-right. Use {@link pipe} when you already have a starting value;\n * use {@link flow} to define a reusable composed function with no value yet.\n *\n * @example\n * ```ts\n * pipe(\n * parseConfig(raw),\n * map((cfg) => cfg.name),\n * flatMap((name) => (name ? ok(name) : err({ kind: \"empty\" as const }))),\n * tap(log),\n * );\n * ```\n */\nexport function pipe<A>(value: A): A;\nexport function pipe<A, B>(value: A, ab: (a: A) => B): B;\nexport function pipe<A, B, C>(value: A, ab: (a: A) => B, bc: (b: B) => C): C;\nexport function pipe<A, B, C, D>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D;\nexport function pipe<A, B, C, D, E>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): E;\nexport function pipe<A, B, C, D, E, F>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n): F;\nexport function pipe<A, B, C, D, E, F, G>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n): G;\nexport function pipe<A, B, C, D, E, F, G, H>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n): H;\nexport function pipe<A, B, C, D, E, F, G, H, I>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n hi: (h: H) => I,\n): I;\nexport function pipe(value: unknown, ...fns: ReadonlyArray<(x: unknown) => unknown>): unknown {\n let acc = value;\n for (const fn of fns) {\n acc = fn(acc);\n }\n return acc;\n}\n","/**\n * The core railway type: a tagged union carrying either a success value\n * (`Ok<T>`) or a failure value (`Err<E>`). It is a plain discriminated union\n * on `_tag` — no classes — so it is immutable and tree-shake friendly. Narrow\n * with {@link isOk} / {@link isErr} to read `.value` / `.error`.\n *\n * @typeParam T - the `Ok` value type\n * @typeParam E - the `Err` error type\n *\n * @example\n * ```ts\n * function parse(raw: string): Result<number, \"nan\"> {\n * const n = Number(raw);\n * return Number.isNaN(n) ? err(\"nan\") : ok(n);\n * }\n * ```\n */\nexport type Result<T, E> =\n | { readonly _tag: \"Ok\"; readonly value: T }\n | { readonly _tag: \"Err\"; readonly error: E };\n\n/**\n * The success branch of a {@link Result} — `{ _tag: \"Ok\"; value: T }`.\n * The `E` parameter keeps the type assignable to `Result<T, E>`.\n */\nexport type Ok<T, E = never> = Extract<Result<T, E>, { _tag: \"Ok\" }>;\n\n/**\n * The failure branch of a {@link Result} — `{ _tag: \"Err\"; error: E }`.\n */\nexport type Err<T, E> = Extract<Result<T, E>, { _tag: \"Err\" }>;\n\n/**\n * Error subclass representing an **unexpected** defect — a thrown exception or\n * promise rejection that was not part of the modelled `Err` union. Used as the\n * default mapping when {@link fromAsync} is called without an `onDefect`\n * handler; the original cause is preserved on `.cause`.\n *\n * @example\n * ```ts\n * const defect = new UnexpectedError(\"Unexpected async defect\", caught);\n * defect.cause; // the original thrown value\n * ```\n */\nexport class UnexpectedError extends Error {\n constructor(\n message: string,\n override readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"UnexpectedError\";\n }\n}\n","import { err, isErr, map, mapErr, ok } from \"./result.js\";\nimport type { Result } from \"./types.js\";\nimport { UnexpectedError } from \"./types.js\";\n\ntype PromiseFactory<T, E> = () => Promise<Result<T, E>>;\ntype AsyncOk<R> = R extends ResultAsync<infer T, unknown> ? T : never;\ntype AsyncErr<R> = R extends ResultAsync<unknown, infer E> ? E : never;\ntype CombineTupleAsync<R extends readonly ResultAsync<unknown, unknown>[]> = ResultAsync<\n { [K in keyof R]: AsyncOk<R[K]> },\n { [K in keyof R]: AsyncErr<R[K]> }[number]\n>;\n\nconst liftPromiseResult = async <T, E>(\n promise: Promise<Result<T, E>>,\n onDefect: (error: unknown) => E | UnexpectedError,\n): Promise<Result<T, E | UnexpectedError>> => {\n try {\n const result = await promise;\n if (isErr(result)) {\n return result;\n }\n // Auto-flatten one level: Ok<Result<…>> from double-wrapped interop.\n return isResultLike<T, E | UnexpectedError>(result.value) ? result.value : result;\n } catch (error) {\n return err(onDefect(error));\n }\n};\n\n/** Collapses settled results left-to-right, short-circuiting on the first `Err`. */\nconst sequenceSettled = (\n settled: readonly Result<unknown, unknown>[],\n): Result<unknown[], unknown> => {\n const values: unknown[] = [];\n for (const result of settled) {\n if (isErr(result)) {\n return err(result.error);\n }\n values.push(result.value);\n }\n return ok(values);\n};\n\n/**\n * Async railway carrier. Wraps a deferred `Promise<Result<T, E>>` and exposes\n * the same dual-track transforms as the sync {@link Result} — `map`, `flatMap`,\n * `recover`, `tap`, `match`. The public API never surfaces `Promise<Result<…>>`\n * directly: `await` the instance (it is thenable) or call {@link resolve} /\n * {@link match} to settle it.\n *\n * Construct via the static factories ({@link ok}, {@link err}, {@link fromPromise},\n * {@link defer}, …) rather than `new` — the constructor is `protected`.\n *\n * @typeParam T - the `Ok` value type\n * @typeParam E - the `Err` error type\n *\n * @example\n * ```ts\n * const user = ResultAsync.fromPromise(api.getUser(id), toAppError)\n * .map((u) => u.profile)\n * .recover(() => ResultAsync.ok(guestProfile));\n *\n * const r = await user; // Result<Profile, AppError>\n * ```\n */\nexport class ResultAsync<T, E> {\n private promise: Promise<Result<T, E>> | null = null;\n\n protected constructor(protected readonly run: PromiseFactory<T, E>) {}\n\n /**\n * Lifts an already-settled sync {@link Result} into a {@link ResultAsync}.\n *\n * @example\n * ```ts\n * const ra = ResultAsync.fromResult(ok(42)); // ResultAsync<number, never>\n * ```\n */\n static fromResult<T, E>(result: Result<T, E>): ResultAsync<T, E> {\n return new ResultAsync(async () => result);\n }\n\n /**\n * Wraps a `PromiseLike<T>` that may reject. Rejections pass through `onReject`\n * to become a typed `Err`; resolution becomes `Ok<T>`.\n *\n * @param promise - the promise to wrap\n * @param onReject - maps a rejection reason to the `Err` channel\n *\n * @example\n * ```ts\n * const body = ResultAsync.fromPromise(\n * fetch(url).then((r) => r.text()),\n * (e): NetError => ({ kind: \"net\", cause: String(e) }),\n * );\n * ```\n */\n static fromPromise<T, E>(\n promise: PromiseLike<T>,\n onReject: (error: unknown) => E,\n ): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n try {\n return ok(await promise);\n } catch (error) {\n return err(onReject(error));\n }\n });\n }\n\n /**\n * Wraps a `PromiseLike<T>` that is **guaranteed not to reject**, skipping the\n * `onReject` mapper. Use only when rejection is provably impossible.\n *\n * @example\n * ```ts\n * const now = ResultAsync.fromSafePromise(Promise.resolve(Date.now()));\n * ```\n */\n static fromSafePromise<T, E = never>(promise: PromiseLike<T>): ResultAsync<T, E> {\n return new ResultAsync(async () => ok(await promise));\n }\n\n /**\n * Defers work until {@link resolve}. Unlike {@link fromPromise}, the factory\n * does not run until the `ResultAsync` is resolved (e.g. by `combineTuple` /\n * `combineTupleParallel`). The factory runs at most once — `resolve` memoizes.\n *\n * @example\n * ```ts\n * const insert = ResultAsync.defer(() => db.orders.insert(row));\n * // nothing has run yet\n * const r = await insert; // factory runs exactly once here\n * ```\n */\n static defer<T, E>(fn: () => Promise<Result<T, E>>): ResultAsync<T, E> {\n return new ResultAsync(fn);\n }\n\n /**\n * Lifts a value into an `Ok` async result.\n *\n * @example\n * ```ts\n * const r = ResultAsync.ok(42); // ResultAsync<number, never>\n * ```\n */\n static ok<T>(value: T): ResultAsync<T, never>;\n static ok<T, E>(value: T): ResultAsync<T, E>;\n static ok<T, E = never>(value: T): ResultAsync<T, E> {\n return new ResultAsync(async () => ok(value));\n }\n\n /**\n * Lifts an error into an `Err` async result.\n *\n * @example\n * ```ts\n * const r = ResultAsync.err({ kind: \"not_found\" as const });\n * ```\n */\n static err<T = never, E = unknown>(error: E): ResultAsync<T, E> {\n return new ResultAsync(async () => err(error));\n }\n\n /**\n * Lifts an existing `Promise<Result<T, E>>` (e.g. from interop code) into a\n * {@link ResultAsync}, auto-flattening one level of double-wrapping. A thrown\n * defect is routed through `onDefect`, defaulting to {@link UnexpectedError}.\n *\n * @param promise - a promise that already yields a `Result`\n * @param onDefect - maps an unexpected throw to the `Err` channel\n * @see {@link fromAsync} from `@onrails/result/interop`\n */\n static fromResultPromise<T, E>(\n promise: Promise<Result<T, E>>,\n onDefect?: (error: unknown) => E | UnexpectedError,\n ): ResultAsync<T, E | UnexpectedError> {\n const mapDefect =\n onDefect ?? ((error: unknown) => new UnexpectedError(\"Unexpected async defect\", error));\n return new ResultAsync(() => liftPromiseResult(promise, mapDefect));\n }\n\n /**\n * Combines a homogeneous array of async results into one. Resolves\n * **sequentially** in input order, short-circuiting on the first `Err`.\n * For heterogeneous tuples that preserve per-index types, use\n * {@link combineTuple}; for wall-clock overlap, {@link combineTupleParallel}.\n *\n * @example\n * ```ts\n * const all = ResultAsync.combine([loadA(), loadB(), loadC()]);\n * // ResultAsync<Item[], LoadError>\n * ```\n */\n static combine<T, E>(results: readonly ResultAsync<T, E>[]): ResultAsync<T[], E> {\n return new ResultAsync(async () => {\n const values: T[] = [];\n for (const ra of results) {\n const result = await ra.resolve();\n if (isErr(result)) {\n return err(result.error);\n }\n values.push(result.value);\n }\n return ok(values);\n });\n }\n\n /**\n * Heterogeneous async tuple combine — resolves branches **sequentially**\n * (left-to-right), returning the first `Err` in input order. Preserves each\n * branch's `Ok` type by position, so the result destructures type-safely.\n * This is the canonical sequential async combine (replaces the former\n * `sequenceTupleAsync`).\n *\n * @example\n * ```ts\n * const combined = ResultAsync.combineTuple([loadCfg(), loadCatalog()] as const);\n * // ResultAsync<readonly [Cfg, Catalog], CfgError | CatalogError>\n * const r = await combined;\n * if (isOk(r)) {\n * const [cfg, catalog] = r.value; // typed per position\n * }\n * ```\n */\n static combineTuple<const R extends readonly ResultAsync<unknown, unknown>[]>(\n results: R,\n ): CombineTupleAsync<R> {\n // Runtime identical to combine; the cast restores per-index tuple types.\n return ResultAsync.combine(\n results as readonly ResultAsync<unknown, unknown>[],\n ) as CombineTupleAsync<R>;\n }\n\n /**\n * Like {@link combineTuple}, but starts every branch before awaiting (wall-clock\n * parallel for independent IO). On failure, returns the first `Err` in input order.\n *\n * @example\n * ```ts\n * // independent IO — overlap them\n * const combined = ResultAsync.combineTupleParallel([\n * loadProfile(id),\n * loadMetrics(id),\n * ] as const);\n * ```\n */\n static combineTupleParallel<const R extends readonly ResultAsync<unknown, unknown>[]>(\n results: R,\n ): CombineTupleAsync<R> {\n // Cast restores per-index tuple types over the untyped sequence core.\n return new ResultAsync(async () =>\n sequenceSettled(await Promise.all(results.map((ra) => ra.resolve()))),\n ) as CombineTupleAsync<R>;\n }\n\n /**\n * Transforms the `Ok` value, passing `Err` through unchanged.\n *\n * @example\n * ```ts\n * ResultAsync.ok(2).map((n) => n * 3); // ResultAsync<number> → Ok 6\n * ```\n */\n map<U>(fn: (value: T) => U): ResultAsync<U, E> {\n return new ResultAsync(async () => map(await this.resolve(), fn));\n }\n\n /**\n * Transforms the `Err` value, passing `Ok` through unchanged — useful for\n * unifying heterogeneous failures into one app-level union.\n *\n * @example\n * ```ts\n * load(id).mapErr((e): AppError => ({ kind: \"load\", cause: e }));\n * ```\n */\n mapErr<F>(fn: (error: E) => F): ResultAsync<T, F> {\n return new ResultAsync(async () => mapErr(await this.resolve(), fn));\n }\n\n /**\n * Canonical bind — chains a step that itself returns a `ResultAsync` or sync\n * `Result`, short-circuiting on `Err`. Error types accumulate (`E | F`).\n *\n * @example\n * ```ts\n * authenticate(req)\n * .flatMap((user) => loadProfile(user.id)) // ResultAsync\n * .flatMap((p) => validate(p)); // sync Result also accepted\n * ```\n */\n flatMap<U, F = E>(\n fn: (value: T) => ResultAsync<U, F> | Result<U, F> | { inner: Result<U, F> },\n ): ResultAsync<U, E | F> {\n return new ResultAsync<U, E | F>(async () => {\n const first = await this.resolve();\n if (isErr(first)) {\n return first;\n }\n const next = fn(first.value);\n if (next instanceof ResultAsync) {\n return next.resolve();\n }\n if (isResultLike<U, F>(next)) {\n return next;\n }\n return isCompatLike<U, F>(next) ? next.inner : next;\n });\n }\n\n /**\n * neverthrow-compat alias of {@link flatMap}. Kept as the documented compat\n * tier; prefer `flatMap` in new code.\n *\n * @example\n * ```ts\n * authenticate(req).andThen((user) => loadProfile(user.id));\n * ```\n */\n andThen<U, F = E>(\n fn: (value: T) => ResultAsync<U, F> | Result<U, F> | { inner: Result<U, F> },\n ): ResultAsync<U, E | F> {\n return this.flatMap(fn);\n }\n\n /**\n * Error-channel bind — runs `fn` only on `Err`, swapping in a recovery\n * `ResultAsync` or sync `Result`. `Ok` passes through. The mirror of\n * {@link flatMap} on the error track.\n *\n * @example\n * ```ts\n * loadFromCache(id).recover(() => loadFromOrigin(id));\n * ```\n */\n recover<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F> {\n return new ResultAsync<T, F>(async () => {\n const first = await this.resolve();\n if (!isErr(first)) {\n return first;\n }\n const next = fn(first.error);\n return next instanceof ResultAsync ? next.resolve() : next;\n });\n }\n\n /**\n * neverthrow-compat alias of {@link recover}. Kept as the documented compat\n * tier; prefer `recover` in new code.\n *\n * @example\n * ```ts\n * loadFromCache(id).orElse(() => loadFromOrigin(id));\n * ```\n */\n orElse<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F> {\n return this.recover(fn);\n }\n\n /**\n * Runs a side effect on the `Ok` value and passes the result through\n * unchanged; a no-op on `Err`. Mirrors {@link tapErr}.\n *\n * @example\n * ```ts\n * saveUser(u).tap((saved) => analytics.track(\"user_saved\", saved.id));\n * ```\n */\n tap(fn: (value: T) => void): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n const result = await this.resolve();\n if (!isErr(result)) {\n fn(result.value);\n }\n return result;\n });\n }\n\n /**\n * Runs a side effect on the `Err` value and passes the result through\n * unchanged; a no-op on `Ok`. The error-track mirror of {@link tap}.\n *\n * @example\n * ```ts\n * saveUser(u).tapErr((e) => logger.warn(\"save failed\", e));\n * ```\n */\n tapErr(fn: (error: E) => void): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n const result = await this.resolve();\n if (isErr(result)) {\n fn(result.error);\n }\n return result;\n });\n }\n\n /**\n * Settles to the `Ok` value, or `defaultValue` if `Err`. Terminal — returns a\n * plain `Promise`, not a `ResultAsync`.\n *\n * @example\n * ```ts\n * const profile = await loadProfile(id).unwrapOr(guestProfile);\n * ```\n */\n unwrapOr<U>(defaultValue: U): Promise<T | U> {\n return this.resolve().then((result) => (isErr(result) ? defaultValue : result.value));\n }\n\n /**\n * Terminal collapse — folds both tracks into a single awaited value. Returns\n * a plain `Promise`, settling the carrier exactly once.\n *\n * @param onOk - handles the `Ok` value\n * @param onErr - handles the `Err` value\n *\n * @example\n * ```ts\n * const status = await save(row).match(\n * () => 200,\n * (e) => (e.kind === \"conflict\" ? 409 : 500),\n * );\n * ```\n */\n match<U1, U2 = U1>(onOk: (value: T) => U1, onErr: (error: E) => U2): Promise<U1 | U2> {\n return this.resolve().then((result) =>\n isErr(result) ? onErr(result.error) : onOk(result.value),\n );\n }\n\n /**\n * Settles the carrier to a bare sync {@link Result}, memoizing so the\n * underlying factory runs at most once. Prefer `await ra` (the thenable) or\n * {@link match} in app code; use `resolve` when you need the tagged union back.\n *\n * @example\n * ```ts\n * const r = await load(id).resolve(); // Result<Data, LoadError>\n * if (isOk(r)) use(r.value);\n * ```\n */\n resolve(): Promise<Result<T, E>> {\n if (!this.promise) {\n this.promise = this.run();\n }\n return this.promise;\n }\n\n /**\n * Thenable shim — `await ra` resolves to a bare tagged-union `Result<T, E>`.\n * Narrow with `isOk(r)` / `isErr(r)` to read `.value` / `.error`.\n */\n // biome-ignore lint/suspicious/noThenProperty: makes ResultAsync awaitable\n then<R1 = Result<T, E>, R2 = never>(\n onfulfilled?: ((value: Result<T, E>) => R1 | PromiseLike<R1>) | undefined | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | undefined | null,\n ): Promise<R1 | R2> {\n return this.resolve().then(\n // Safe: without onfulfilled, R1 stays at its Result<T, E> default.\n (r) => (onfulfilled ? onfulfilled(r) : (r as unknown as R1)),\n onrejected ?? undefined,\n );\n }\n}\n\nfunction isResultLike<U, F>(v: unknown): v is Result<U, F> {\n return (\n typeof v === \"object\" &&\n v !== null &&\n \"_tag\" in v &&\n ((v as { _tag: unknown })._tag === \"Ok\" || (v as { _tag: unknown })._tag === \"Err\")\n );\n}\n\nfunction isCompatLike<U, F>(v: unknown): v is { inner: Result<U, F> } {\n return (\n typeof v === \"object\" &&\n v !== null &&\n \"inner\" in v &&\n isResultLike((v as { inner: unknown }).inner)\n );\n}\n\n/**\n * The free-function lift helpers (`okAsync`, `errAsync`, `fromPromise`,\n * `fromSafePromise`, `parallelTupleAsync`, `tryAsync`) live in `./async-lift.ts`\n * and are re-exported from the package index.\n */\n","import { ResultAsync } from \"./async.js\";\nimport type { Result, UnexpectedError } from \"./types.js\";\n\n/**\n * Extracts the `Ok` value type from a {@link Result} or {@link ResultAsync},\n * resolving to `never` for any other type.\n *\n * @example\n * ```ts\n * type T = InferOk<Result<number, string>>; // number\n * type U = InferOk<ResultAsync<User, AppError>>; // User\n * ```\n */\nexport type InferOk<R> = R extends { _tag: \"Ok\"; readonly value: infer T }\n ? T\n : R extends ResultAsync<infer T, unknown>\n ? T\n : never;\n\n/**\n * Extracts the `Err` error type from a {@link Result} or {@link ResultAsync},\n * resolving to `never` for any other type. Mirror of {@link InferOk}.\n *\n * @example\n * ```ts\n * type E = InferErr<Result<number, string>>; // string\n * type F = InferErr<ResultAsync<User, AppError>>; // AppError\n * ```\n */\nexport type InferErr<R> = R extends { _tag: \"Err\"; readonly error: infer E }\n ? E\n : R extends ResultAsync<unknown, infer E>\n ? E\n : never;\n\ntype AnyResult = Result<unknown, unknown>;\n\n/**\n * Lifts an already-settled sync {@link Result} into a {@link ResultAsync}, so\n * it can be chained alongside async steps in a railway.\n *\n * @example\n * ```ts\n * const ra = fromResult(ok(1)); // ResultAsync<number, never>\n * await fromResult(err(error)).resolve(); // Err(error)\n * ```\n */\nexport const fromResult = <T, E>(result: Result<T, E>): ResultAsync<T, E> =>\n ResultAsync.fromResult(result);\n\n/**\n * Bind a sync {@link Result} into an async step without widening defects.\n * Dual-form: data-first for one-shots, data-last (curried) for `pipe`/`flow`.\n *\n * @example\n * ```ts\n * asyncAfter(result, (u) => tryAsync(db.insert(u), toErr)); // data-first\n * asyncAfter((u) => tryAsync(db.insert(u), toErr)); // data-last\n * ```\n */\nexport function asyncAfter<T, U, E, F>(\n result: Result<T, E>,\n fn: (value: T) => ResultAsync<U, F>,\n): ResultAsync<U, E | F>;\nexport function asyncAfter<T, U, F>(\n fn: (value: T) => ResultAsync<U, F>,\n): <E>(result: Result<T, E>) => ResultAsync<U, E | F>;\nexport function asyncAfter<T, U, E, F>(\n resultOrFn: Result<T, E> | ((value: T) => ResultAsync<U, F>),\n fn?: (value: T) => ResultAsync<U, F>,\n): ResultAsync<U, E | F> | ((result: Result<T, E>) => ResultAsync<U, E | F>) {\n if (fn === undefined) {\n const f = resultOrFn as (value: T) => ResultAsync<U, F>;\n return (result: Result<T, E>): ResultAsync<U, E | F> => fromResult(result).flatMap(f);\n }\n return fromResult(resultOrFn as Result<T, E>).flatMap(fn);\n}\n\n/**\n * Lifts a `(...args) => Promise<Result<T, E>>` function (typical of interop or\n * boundary code) into one returning `(...args) => ResultAsync<T, E>`. Expected\n * `Err`s pass through; an unexpected promise rejection (a defect) is routed via\n * `onDefect`, defaulting to {@link UnexpectedError} and widening the error union.\n *\n * @param fn - a function returning a promise that already yields a `Result`\n * @param onDefect - maps an unexpected rejection to the `Err` channel\n *\n * @example\n * ```ts\n * const loadUser = fromAsync(\n * (id: string): Promise<Result<User, NotFound>> => api.getUser(id),\n * );\n * const ra = loadUser(\"u1\"); // ResultAsync<User, NotFound | UnexpectedError>\n * ```\n */\nexport const fromAsync =\n <A extends readonly unknown[], R extends AnyResult>(\n fn: (...args: A) => Promise<R>,\n onDefect?: (error: unknown) => InferErr<R> | UnexpectedError,\n ): ((...args: A) => ResultAsync<InferOk<R>, InferErr<R> | UnexpectedError>) =>\n (...args: A) =>\n ResultAsync.fromResultPromise(fn(...args), onDefect) as ResultAsync<\n InferOk<R>,\n InferErr<R> | UnexpectedError\n >;\n"]}
package/dist/pipe.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pipe.ts"],"names":[],"mappings":";;;AAkEO,SAAS,IAAA,CACd,UACG,IAAA,EAC8B;AACjC,EAAA,OAAO,IAAI,IAAA,KAAoB;AAC7B,IAAA,IAAI,GAAA,GAAM,KAAA,CAAM,GAAG,IAAI,CAAA;AACvB,IAAA,KAAA,MAAW,MAAM,IAAA,EAAM;AACrB,MAAA,GAAA,GAAM,GAAG,GAAG,CAAA;AAAA,IACd;AACA,IAAA,OAAO,GAAA;AAAA,EACT,CAAA;AACF","file":"pipe.cjs","sourcesContent":["/**\n * Variadic point-free composition — left-to-right.\n *\n * ```ts\n * const parseUserName = flow(\n * (raw: string) => parseConfig(raw),\n * map((cfg) => cfg.user),\n * flatMap((u) => u.name ? ok(u.name) : err({ kind: \"missing\" })),\n * );\n *\n * parseUserName(raw); // Result<string, ParseError | { kind: \"missing\" }>\n * ```\n *\n * Use {@link pipe} from `@onrails/result` when you have a starting value;\n * use {@link flow} when you want to define a reusable composed function.\n */\nexport function flow<A extends readonly unknown[], B>(ab: (...a: A) => B): (...a: A) => B;\nexport function flow<A extends readonly unknown[], B, C>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n): (...a: A) => C;\nexport function flow<A extends readonly unknown[], B, C, D>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n): (...a: A) => D;\nexport function flow<A extends readonly unknown[], B, C, D, E>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): (...a: A) => E;\nexport function flow<A extends readonly unknown[], B, C, D, E, F>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n): (...a: A) => F;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n): (...a: A) => G;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n): (...a: A) => H;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n hi: (h: H) => I,\n): (...a: A) => I;\nexport function flow(\n first: (...args: unknown[]) => unknown,\n ...rest: ReadonlyArray<(x: unknown) => unknown>\n): (...args: unknown[]) => unknown {\n return (...args: unknown[]) => {\n let acc = first(...args);\n for (const fn of rest) {\n acc = fn(acc);\n }\n return acc;\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/pipe.ts"],"names":[],"mappings":";;;AAoEO,SAAS,IAAA,CACd,UACG,IAAA,EAC8B;AACjC,EAAA,OAAO,IAAI,IAAA,KAAoB;AAC7B,IAAA,IAAI,GAAA,GAAM,KAAA,CAAM,GAAG,IAAI,CAAA;AACvB,IAAA,KAAA,MAAW,MAAM,IAAA,EAAM;AACrB,MAAA,GAAA,GAAM,GAAG,GAAG,CAAA;AAAA,IACd;AACA,IAAA,OAAO,GAAA;AAAA,EACT,CAAA;AACF","file":"pipe.cjs","sourcesContent":["/**\n * Variadic point-free composition — chains up to nine unary fns left-to-right\n * into one reusable function. The first fn may take multiple arguments; the\n * rest are unary. Use {@link pipe} from `@onrails/result` when you already\n * have a starting value; use {@link flow} to define a reusable composed\n * function with no value yet.\n *\n * @example\n * ```ts\n * const parseUserName = flow(\n * (raw: string) => parseConfig(raw),\n * map((cfg) => cfg.user),\n * flatMap((u) => (u.name ? ok(u.name) : err({ kind: \"missing\" as const }))),\n * );\n *\n * parseUserName(raw); // Result<string, ParseError | { kind: \"missing\" }>\n * ```\n */\nexport function flow<A extends readonly unknown[], B>(ab: (...a: A) => B): (...a: A) => B;\nexport function flow<A extends readonly unknown[], B, C>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n): (...a: A) => C;\nexport function flow<A extends readonly unknown[], B, C, D>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n): (...a: A) => D;\nexport function flow<A extends readonly unknown[], B, C, D, E>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): (...a: A) => E;\nexport function flow<A extends readonly unknown[], B, C, D, E, F>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n): (...a: A) => F;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n): (...a: A) => G;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n): (...a: A) => H;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n hi: (h: H) => I,\n): (...a: A) => I;\nexport function flow(\n first: (...args: unknown[]) => unknown,\n ...rest: ReadonlyArray<(x: unknown) => unknown>\n): (...args: unknown[]) => unknown {\n return (...args: unknown[]) => {\n let acc = first(...args);\n for (const fn of rest) {\n acc = fn(acc);\n }\n return acc;\n };\n}\n"]}
package/dist/pipe.d.cts CHANGED
@@ -1,18 +1,20 @@
1
1
  /**
2
- * Variadic point-free composition — left-to-right.
2
+ * Variadic point-free composition — chains up to nine unary fns left-to-right
3
+ * into one reusable function. The first fn may take multiple arguments; the
4
+ * rest are unary. Use {@link pipe} from `@onrails/result` when you already
5
+ * have a starting value; use {@link flow} to define a reusable composed
6
+ * function with no value yet.
3
7
  *
8
+ * @example
4
9
  * ```ts
5
10
  * const parseUserName = flow(
6
11
  * (raw: string) => parseConfig(raw),
7
12
  * map((cfg) => cfg.user),
8
- * flatMap((u) => u.name ? ok(u.name) : err({ kind: "missing" })),
13
+ * flatMap((u) => (u.name ? ok(u.name) : err({ kind: "missing" as const }))),
9
14
  * );
10
15
  *
11
16
  * parseUserName(raw); // Result<string, ParseError | { kind: "missing" }>
12
17
  * ```
13
- *
14
- * Use {@link pipe} from `@onrails/result` when you have a starting value;
15
- * use {@link flow} when you want to define a reusable composed function.
16
18
  */
17
19
  declare function flow<A extends readonly unknown[], B>(ab: (...a: A) => B): (...a: A) => B;
18
20
  declare function flow<A extends readonly unknown[], B, C>(ab: (...a: A) => B, bc: (b: B) => C): (...a: A) => C;
package/dist/pipe.d.ts CHANGED
@@ -1,18 +1,20 @@
1
1
  /**
2
- * Variadic point-free composition — left-to-right.
2
+ * Variadic point-free composition — chains up to nine unary fns left-to-right
3
+ * into one reusable function. The first fn may take multiple arguments; the
4
+ * rest are unary. Use {@link pipe} from `@onrails/result` when you already
5
+ * have a starting value; use {@link flow} to define a reusable composed
6
+ * function with no value yet.
3
7
  *
8
+ * @example
4
9
  * ```ts
5
10
  * const parseUserName = flow(
6
11
  * (raw: string) => parseConfig(raw),
7
12
  * map((cfg) => cfg.user),
8
- * flatMap((u) => u.name ? ok(u.name) : err({ kind: "missing" })),
13
+ * flatMap((u) => (u.name ? ok(u.name) : err({ kind: "missing" as const }))),
9
14
  * );
10
15
  *
11
16
  * parseUserName(raw); // Result<string, ParseError | { kind: "missing" }>
12
17
  * ```
13
- *
14
- * Use {@link pipe} from `@onrails/result` when you have a starting value;
15
- * use {@link flow} when you want to define a reusable composed function.
16
18
  */
17
19
  declare function flow<A extends readonly unknown[], B>(ab: (...a: A) => B): (...a: A) => B;
18
20
  declare function flow<A extends readonly unknown[], B, C>(ab: (...a: A) => B, bc: (b: B) => C): (...a: A) => C;
package/dist/pipe.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pipe.ts"],"names":[],"mappings":";AAkEO,SAAS,IAAA,CACd,UACG,IAAA,EAC8B;AACjC,EAAA,OAAO,IAAI,IAAA,KAAoB;AAC7B,IAAA,IAAI,GAAA,GAAM,KAAA,CAAM,GAAG,IAAI,CAAA;AACvB,IAAA,KAAA,MAAW,MAAM,IAAA,EAAM;AACrB,MAAA,GAAA,GAAM,GAAG,GAAG,CAAA;AAAA,IACd;AACA,IAAA,OAAO,GAAA;AAAA,EACT,CAAA;AACF","file":"pipe.js","sourcesContent":["/**\n * Variadic point-free composition — left-to-right.\n *\n * ```ts\n * const parseUserName = flow(\n * (raw: string) => parseConfig(raw),\n * map((cfg) => cfg.user),\n * flatMap((u) => u.name ? ok(u.name) : err({ kind: \"missing\" })),\n * );\n *\n * parseUserName(raw); // Result<string, ParseError | { kind: \"missing\" }>\n * ```\n *\n * Use {@link pipe} from `@onrails/result` when you have a starting value;\n * use {@link flow} when you want to define a reusable composed function.\n */\nexport function flow<A extends readonly unknown[], B>(ab: (...a: A) => B): (...a: A) => B;\nexport function flow<A extends readonly unknown[], B, C>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n): (...a: A) => C;\nexport function flow<A extends readonly unknown[], B, C, D>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n): (...a: A) => D;\nexport function flow<A extends readonly unknown[], B, C, D, E>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): (...a: A) => E;\nexport function flow<A extends readonly unknown[], B, C, D, E, F>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n): (...a: A) => F;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n): (...a: A) => G;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n): (...a: A) => H;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n hi: (h: H) => I,\n): (...a: A) => I;\nexport function flow(\n first: (...args: unknown[]) => unknown,\n ...rest: ReadonlyArray<(x: unknown) => unknown>\n): (...args: unknown[]) => unknown {\n return (...args: unknown[]) => {\n let acc = first(...args);\n for (const fn of rest) {\n acc = fn(acc);\n }\n return acc;\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/pipe.ts"],"names":[],"mappings":";AAoEO,SAAS,IAAA,CACd,UACG,IAAA,EAC8B;AACjC,EAAA,OAAO,IAAI,IAAA,KAAoB;AAC7B,IAAA,IAAI,GAAA,GAAM,KAAA,CAAM,GAAG,IAAI,CAAA;AACvB,IAAA,KAAA,MAAW,MAAM,IAAA,EAAM;AACrB,MAAA,GAAA,GAAM,GAAG,GAAG,CAAA;AAAA,IACd;AACA,IAAA,OAAO,GAAA;AAAA,EACT,CAAA;AACF","file":"pipe.js","sourcesContent":["/**\n * Variadic point-free composition — chains up to nine unary fns left-to-right\n * into one reusable function. The first fn may take multiple arguments; the\n * rest are unary. Use {@link pipe} from `@onrails/result` when you already\n * have a starting value; use {@link flow} to define a reusable composed\n * function with no value yet.\n *\n * @example\n * ```ts\n * const parseUserName = flow(\n * (raw: string) => parseConfig(raw),\n * map((cfg) => cfg.user),\n * flatMap((u) => (u.name ? ok(u.name) : err({ kind: \"missing\" as const }))),\n * );\n *\n * parseUserName(raw); // Result<string, ParseError | { kind: \"missing\" }>\n * ```\n */\nexport function flow<A extends readonly unknown[], B>(ab: (...a: A) => B): (...a: A) => B;\nexport function flow<A extends readonly unknown[], B, C>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n): (...a: A) => C;\nexport function flow<A extends readonly unknown[], B, C, D>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n): (...a: A) => D;\nexport function flow<A extends readonly unknown[], B, C, D, E>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): (...a: A) => E;\nexport function flow<A extends readonly unknown[], B, C, D, E, F>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n): (...a: A) => F;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n): (...a: A) => G;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n): (...a: A) => H;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n hi: (h: H) => I,\n): (...a: A) => I;\nexport function flow(\n first: (...args: unknown[]) => unknown,\n ...rest: ReadonlyArray<(x: unknown) => unknown>\n): (...args: unknown[]) => unknown {\n return (...args: unknown[]) => {\n let acc = first(...args);\n for (const fn of rest) {\n acc = fn(acc);\n }\n return acc;\n };\n}\n"]}