wellcrafted 0.34.1 → 0.35.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.
@@ -1,47 +1,8 @@
1
- import { Err } from "../result-xH3TbSDF.js";
1
+ import "../result-BongGO2O.js";
2
+ import { AnyTaggedError, DefineErrorsReturn, ErrorBody, ErrorsConfig, InferError, InferErrors, ValidatedConfig } from "../types-cY80Bw6u.js";
2
3
 
3
- //#region src/error/types.d.ts
4
-
5
- /**
6
- * Base type for any tagged error, used as a minimum constraint.
7
- */
8
- type AnyTaggedError = {
9
- name: string;
10
- message: string;
11
- };
12
- /**
13
- * Constructor return must include `message: string`.
14
- * JSON serializability is a convention, not enforced at the type level
15
- * (optional fields produce `T | undefined` which breaks `JsonObject`).
16
- */
17
- type ErrorBody = {
18
- message: string;
19
- };
20
- /**
21
- * Per-key validation: tells the user exactly what `name` will be stamped as.
22
- * If a user provides `name` in the return object, they see a descriptive error.
23
- */
24
- type ValidateErrorBody<K extends string> = {
25
- message: string;
26
- name?: `The 'name' key is reserved as '${K}'. Remove it.`;
27
- };
28
- /** The config: each key is a variant name, each value is a constructor function. */
29
- type ErrorsConfig = Record<string, (...args: any[]) => ErrorBody>;
30
- /** Validates each config entry, injecting the key-specific `name` reservation message. */
31
- type ValidatedConfig<T extends ErrorsConfig> = { [K in keyof T & string]: T[K] extends ((...args: infer A) => infer R) ? (...args: A) => R & ValidateErrorBody<K> : T[K] };
32
- /** Single factory: takes constructor args, returns Err-wrapped error. */
33
- type ErrorFactory<TName extends string, TFn extends (...args: any[]) => ErrorBody> = { [K in TName]: (...args: Parameters<TFn>) => Err<Readonly<{
34
- name: TName;
35
- } & ReturnType<TFn>>> };
36
- type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
37
- /** Return type of `defineErrors`. Maps each config key to its factory. */
38
- type DefineErrorsReturn<TConfig extends ErrorsConfig> = UnionToIntersection<{ [K in keyof TConfig & string]: ErrorFactory<K, TConfig[K]> }[keyof TConfig & string]>;
39
- /** Extract the error type from a single factory. */
40
- type InferError<T> = T extends ((...args: any[]) => Err<infer R>) ? R : never;
41
- /** Extract union of ALL error types from a defineErrors return. */
42
- type InferErrors<T> = { [K in keyof T]: T[K] extends ((...args: any[]) => Err<infer R>) ? R : never }[keyof T];
43
- //#endregion
44
4
  //#region src/error/defineErrors.d.ts
5
+
45
6
  /**
46
7
  * Defines a set of typed error factories using Rust-style namespaced variants.
47
8
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/error/types.ts","../../src/error/defineErrors.ts","../../src/error/extractErrorMessage.ts"],"sourcesContent":[],"mappings":";;;;;;AAKA;AAWY,KAXA,cAAA,GAWS;EAMhB,IAAA,EAAA,MAAA;EAOO,OAAA,EAAA,MAAY;CAAA;;;AAAS;AAGjC;;AAAsC,KAhB1B,SAAA,GAgB0B;EAAY,OAErC,EAAA,MAAA;CAAC;;;;;KAZT,iBAamB,CAAA,UAAA,MAAA,CAAA,GAAA;EAAiB,OACrC,EAAA,MAAA;EAAC,IAAC,CAAA,EAAA,kCAZoC,CAYpC,eAAA;AAAC,CAAA;AACL;AAGe,KAXL,YAAA,GAAe,MAWV,CAAA,MAAA,EAAA,CAAA,GAAA,IAAA,EAAA,GAAA,EAAA,EAAA,GAX6C,SAW7C,CAAA;;AAKV,KAbK,eAaL,CAAA,UAb+B,YAa/B,CAAA,GAAA,QACe,MAZT,CAYS,GAAA,MAAA,GAZI,CAYJ,CAZM,CAYN,CAAA,UAAA,CAAA,GAAA,IAAA,EAAA,KAAA,EAAA,EAAA,GAAA,KAAA,EAAA,IAAA,CAAA,GAAA,IAAA,EAXR,CAWQ,EAAA,GAXF,CAWE,GAXE,iBAWF,CAXoB,CAWpB,CAAA,GAVlB,CAUkB,CAVhB,CAUgB,CAAA,EAAG;;KANpB,YAO2C,CAAA,cAAA,MAAA,EAAA,YAAA,CAAA,GAAA,IAAA,EAAA,GAAA,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,iBCNN,YDMM,CAAA,sBCN6B,YDM7B,CAAA,CAAA,MAAA,ECLb,ODKa,GCLH,eDKG,CCLa,ODKb,CAAA,CAAA,ECJnB,kBDImB,CCJA,ODIA,CAAA;;;;;;;AA7DtB;AAWA;AAA4C;AAahC,iBEvBI,mBAAA,CFuBQ,KAAA,EAAA,OAAA,CAAA,EAAA,MAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/error/defineErrors.ts","../../src/error/extractErrorMessage.ts"],"sourcesContent":[],"mappings":";;;;;;;;AA4DA;;;;;;;;AAEqB;;;;ACxDrB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBDsDgB,mCAAmC,sBAC1C,UAAU,gBAAgB,WAChC,mBAAmB;;;;;;;;AAFtB;;AAAmD,iBCtDnC,mBAAA,CDsDmC,KAAA,EAAA,OAAA,CAAA,EAAA,MAAA"}
@@ -1,4 +1,4 @@
1
- import { Err } from "../result-BRfWC87j.js";
1
+ import { Err } from "../result-DzL3K2yA.js";
2
2
 
3
3
  //#region src/error/defineErrors.ts
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { Err, Ok, Result } from "./result-xH3TbSDF.js";
1
+ import { Err, Ok, Result } from "./result-BongGO2O.js";
2
2
 
3
3
  //#region src/result/utils.d.ts
4
4
 
@@ -25,4 +25,4 @@ declare function partitionResults<T, E>(results: Result<T, E>[]): {
25
25
  //# sourceMappingURL=utils.d.ts.map
26
26
  //#endregion
27
27
  export { partitionResults };
28
- //# sourceMappingURL=index-D_iQ3bBj.d.ts.map
28
+ //# sourceMappingURL=index-mb9iYu0a.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index-D_iQ3bBj.d.ts","names":[],"sources":["../src/result/utils.ts"],"sourcesContent":[],"mappings":";;;;;;AAmBA;;;;;;;;;AAK+B;;;;;iBALf,gCAAgC,OAAO,GAAG;OAK7C,GAAG;QAAY,IAAI"}
1
+ {"version":3,"file":"index-mb9iYu0a.d.ts","names":[],"sources":["../src/result/utils.ts"],"sourcesContent":[],"mappings":";;;;;;AAmBA;;;;;;;;;AAK+B;;;;;iBALf,gCAAgC,OAAO,GAAG;OAK7C,GAAG;QAAY,IAAI"}
@@ -0,0 +1,228 @@
1
+ import { Err } from "../result-BongGO2O.js";
2
+ import { AnyTaggedError } from "../types-cY80Bw6u.js";
3
+ import { tapErr } from "../tap-err-Bqs9aQpZ.js";
4
+
5
+ //#region src/logger/types.d.ts
6
+
7
+ /**
8
+ * Five levels, no `fatal`. Matches Rust's `tracing` exactly.
9
+ *
10
+ * Process termination is the application's call, not the library's — so
11
+ * there is no `fatal`. Apps that want to exit on a specific error do so
12
+ * explicitly (`process.exit`, `Bun.exit`) at the call site.
13
+ */
14
+ type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
15
+ /**
16
+ * The normalized event every sink receives.
17
+ *
18
+ * - `ts` is epoch millis (not a `Date`) — cheap to create, easy to serialize,
19
+ * trivially monotonic for ordering. Sinks that want ISO-8601 on the wire
20
+ * convert at serialization time.
21
+ * - `source` is the logger's namespace, stamped once at `createLogger` and
22
+ * carried on every event. Analogous to `tracing`'s `target`.
23
+ * - `message` is human text. For `warn`/`error` it's copied from the
24
+ * typed error's `message` field (so `event.message === event.data.message`
25
+ * on those levels — intentional duplication so sinks have one uniform
26
+ * rendering path regardless of event origin; they never need to know
27
+ * whether `data` is a tagged error or free-form payload). The variant
28
+ * template owns the phrasing; sinks just render.
29
+ * - `data` carries the structured payload. For `warn`/`error` it's the
30
+ * typed error object itself (including `name` + captured fields). For
31
+ * `info`/`debug`/`trace` it's free-form, caller-supplied.
32
+ */
33
+ type LogEvent = {
34
+ ts: number;
35
+ level: LogLevel;
36
+ source: string;
37
+ message: string;
38
+ data?: unknown;
39
+ };
40
+ /**
41
+ * A sink is a callable that accepts events, with optional resource cleanup.
42
+ *
43
+ * The intersection with `Partial<AsyncDisposable>` lets the same type cover
44
+ * both pure functions (no-op dispose) and stateful sinks (file writers,
45
+ * network sockets). Callers who need guaranteed cleanup narrow to a
46
+ * `LogSink & AsyncDisposable` return type or bind with `await using`.
47
+ */
48
+ type LogSink = ((event: LogEvent) => void) & Partial<AsyncDisposable>;
49
+ /**
50
+ * Accepted by `log.warn` / `log.error`. Union of two shapes:
51
+ *
52
+ * - `AnyTaggedError` — the raw tagged error `{ name, message, ...fields }`.
53
+ * Arrives via `result.error` after narrowing a Result.
54
+ * - `Err<AnyTaggedError>` — the `{ error: tagged, data: null }` wrapper
55
+ * that `defineErrors` factories return directly.
56
+ *
57
+ * The logger unwraps via `"name" in err` inside `unwrapLoggable` — a
58
+ * purely structural discriminator:
59
+ *
60
+ * - `AnyTaggedError` always has `name` at the top level (stamped by
61
+ * `defineErrors` from the factory key — a hard invariant of every
62
+ * tagged error).
63
+ * - `Err<AnyTaggedError>` has exactly `{ error, data }` at the top level.
64
+ * The tagged error's `name` lives on `err.error.name`, not `err.name`.
65
+ *
66
+ * Intentionally **not** checking `err.data === null`: that's also true for
67
+ * `Ok(T)` when `T = null` (see wellcrafted's `Ok(null)`/`Err(null)`
68
+ * structural collision edge — discussed in
69
+ * `docs/articles/ok-null-is-fine-err-null-is-a-lie.md`). Always discriminate
70
+ * by an invariant non-null property (`name` here), never by null-presence.
71
+ *
72
+ * Native `Error` instances also satisfy `AnyTaggedError` structurally
73
+ * (`name` and `message` are both present), so `log.warn(new Error("x"))`
74
+ * works out of the box — useful when migrating from `console.warn(err)`
75
+ * call sites that caught a plain `Error`.
76
+ *
77
+ * @example Err-wrapped (direct mint)
78
+ * log.warn(MyError.Thing({ cause }));
79
+ *
80
+ * @example Raw tagged (from result.error, after narrowing)
81
+ * if (isErr(result)) log.warn(result.error);
82
+ *
83
+ * @example Plain Error (migration from console.warn)
84
+ * try { risky(); } catch (e) { log.warn(e as Error); }
85
+ */
86
+ type LoggableError = AnyTaggedError | Err<AnyTaggedError>;
87
+ /**
88
+ * The logger surface.
89
+ *
90
+ * Shape split is intentional:
91
+ * - `warn`/`error` take a typed error **unary** — message and structured
92
+ * data both live on the variant, level is chosen at the call site.
93
+ * - `trace`/`debug`/`info` are free-form — diagnostic events don't need
94
+ * enumeration and often don't have a useful "name" to dedupe on.
95
+ *
96
+ * Mirrors Rust's `tracing::warn!(?err)` vs `tracing::info!("msg", ...)`.
97
+ */
98
+ type Logger = {
99
+ error(err: LoggableError): void;
100
+ warn(err: LoggableError): void;
101
+ info(message: string, data?: unknown): void;
102
+ debug(message: string, data?: unknown): void;
103
+ trace(message: string, data?: unknown): void;
104
+ };
105
+ //# sourceMappingURL=types.d.ts.map
106
+ //#endregion
107
+ //#region src/logger/console-sink.d.ts
108
+ /**
109
+ * Default sink. Writes to `console.*` with a `[source]` prefix.
110
+ *
111
+ * Kept as a singleton value (not a factory) because it takes no config —
112
+ * adding `createConsoleSink({ format })` would be ceremony for a pattern
113
+ * the user can trivially replace by writing their own sink.
114
+ *
115
+ * `console[event.level]` routes directly without a detached lookup table.
116
+ * `LogLevel` is a subset of the Console method keys, so TS errors at this
117
+ * access if a future level drifts (e.g. adding `fatal`). Calling the method
118
+ * through `console[...]` preserves the `this` binding — avoids "Illegal
119
+ * invocation" in runtimes that require it.
120
+ *
121
+ * `satisfies LogSink` (not `: LogSink`) keeps the inferred callable type
122
+ * precise — `LogSink` is an intersection with optional dispose, and the
123
+ * annotation form would widen an unnecessary Partial into the value type.
124
+ *
125
+ * No dispose handler — `console` is not a resource.
126
+ */
127
+ declare const consoleSink: (event: LogEvent) => void;
128
+ //# sourceMappingURL=console-sink.d.ts.map
129
+
130
+ //#endregion
131
+ //#region src/logger/create-logger.d.ts
132
+ /**
133
+ * Create a logger bound to a `source` namespace and a sink.
134
+ *
135
+ * Design choices:
136
+ * - **Positional args, not a bag.** Two arguments, both with obvious meaning;
137
+ * a `{ source, sink }` object would be ceremony.
138
+ * - **`sink` defaults to `consoleSink`.** Most callers during development
139
+ * want console output with zero setup. Production apps swap it out via DI
140
+ * at the attach/wire-up site.
141
+ * - **No global default logger.** There is no `setDefaultLogger()` and no
142
+ * module-level registry. Every consumer takes a `log?: Logger` option
143
+ * and defaults to `createLogger('<source>')` if omitted. Globals make
144
+ * test isolation and sink composition painful.
145
+ * - **Method shorthand in the return object** over higher-order factories.
146
+ * The five methods differ in two simple ways (error-unary vs free-form,
147
+ * plus the level string); spelling them out beats an `emitErr("warn")`
148
+ * riddle.
149
+ *
150
+ * @example Library code (caller wires the sink)
151
+ * function attachThing(ydoc: Doc, opts: { log?: Logger }) {
152
+ * const log = opts.log ?? createLogger('thing');
153
+ * // ...
154
+ * }
155
+ *
156
+ * @example App wiring (share one sink, multiple loggers)
157
+ * const sink = composeSinks(consoleSink, myCustomSink);
158
+ * attachThing(ydoc, { log: createLogger('thing', sink) });
159
+ * attachOther(ydoc, { log: createLogger('other', sink) });
160
+ */
161
+ declare function createLogger(source: string, sink?: LogSink): Logger;
162
+ //# sourceMappingURL=create-logger.d.ts.map
163
+ //#endregion
164
+ //#region src/logger/memory-sink.d.ts
165
+ /**
166
+ * In-memory sink for tests. Returns `{ sink, events }` so callers can
167
+ * both wire the sink and inspect captured events without a module-level
168
+ * spy or `console.*` interception.
169
+ *
170
+ * A factory (not a singleton) so each test gets an isolated array; sharing
171
+ * state across tests would leak events.
172
+ *
173
+ * Returning `{ sink, events }` (rather than an array with a method) keeps
174
+ * the two roles separate — `sink` goes to `createLogger`, `events` goes to
175
+ * assertions.
176
+ *
177
+ * Uses `satisfies LogSink` on the sink expression rather than `: LogSink =`
178
+ * to preserve the precise inferred callable type.
179
+ *
180
+ * @example
181
+ * const { sink, events } = memorySink();
182
+ * const log = createLogger("test", sink);
183
+ * log.warn(MyError.Thing({ cause: new Error("boom") }));
184
+ * expect(events).toHaveLength(1);
185
+ * expect(events[0]).toMatchObject({ level: "warn", source: "test" });
186
+ */
187
+ declare function memorySink(): {
188
+ sink: LogSink;
189
+ events: LogEvent[];
190
+ };
191
+ //# sourceMappingURL=memory-sink.d.ts.map
192
+
193
+ //#endregion
194
+ //#region src/logger/compose-sinks.d.ts
195
+ /**
196
+ * Fan one event out to every sink in order.
197
+ *
198
+ * Disposal: the returned sink has a `[Symbol.asyncDispose]` that forwards
199
+ * to each member via optional chaining. Members without dispose (e.g.
200
+ * `consoleSink`) are silent no-ops; members that own resources (file,
201
+ * network) flush and close. Mix pure and stateful sinks freely — no
202
+ * wrapping required.
203
+ *
204
+ * Fan-out is sequential and unguarded. If a member sink throws on emit,
205
+ * later members do not receive the event — by design, since swallowing
206
+ * sink errors hides real bugs. Wrap individual sinks yourself for
207
+ * best-effort delivery.
208
+ *
209
+ * Dispose is sequential and awaits each member. If one throws, later
210
+ * members don't get their chance; callers who want best-effort cleanup
211
+ * should wrap the composed dispose themselves.
212
+ *
213
+ * Built with `Object.assign` + `satisfies LogSink` rather than mutating a
214
+ * pre-typed `const` — avoids the widening that comes with `: LogSink =` and
215
+ * keeps the inferred type precise (callable + definite dispose, not
216
+ * callable + Partial dispose).
217
+ *
218
+ * @example
219
+ * await using file = jsonlFileSink("/tmp/app.jsonl");
220
+ * const sink = composeSinks(consoleSink, file);
221
+ * const log = createLogger("source", sink);
222
+ */
223
+ declare function composeSinks(...sinks: LogSink[]): LogSink;
224
+ //# sourceMappingURL=compose-sinks.d.ts.map
225
+
226
+ //#endregion
227
+ export { LogEvent, LogLevel, LogSink, LoggableError, Logger, composeSinks, consoleSink, createLogger, memorySink, tapErr };
228
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/logger/types.ts","../../src/logger/console-sink.ts","../../src/logger/create-logger.ts","../../src/logger/memory-sink.ts","../../src/logger/compose-sinks.ts"],"sourcesContent":[],"mappings":";;;;;;;;;AAUA;AAoBA;AAgBA;;AAA+B,KApCnB,QAAA,GAoCmB,OAAA,GAAA,OAAA,GAAA,MAAA,GAAA,MAAA,GAAA,OAAA;;;AAA4B;AAuC3D;;;;;AAAgD;AAahD;;;;AAEwB;;;;AC/ExB;KDSY,QAAA;;SAEJ;EEMQ,MAAA,EAAA,MAAA;EAAY,OAAA,EAAA,MAAA;EAAA,IAErB,CAAA,EAAA,OAAA;CAAqB;AACnB;;;;ACjBT;;;;AAA+D,KHsBnD,OAAA,GGtBmD,CAAA,CAAA,KAAA,EHsBhC,QGtBgC,EAAA,GAAA,IAAA,CAAA,GHsBX,OGtBW,CHsBH,eGtBG,CAAA;;;;ACM/D;;;;AAA0D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KJuD9C,aAAA,GAAgB,iBAAiB,IAAI;;;;;;;;;;;;KAarC,MAAA;aACA;YACD;;;;;;;;;;;;;AA1FX;AAoBA;AAgBA;;;;;AAA2D;AAuC3D;;;;;AAAgD;AAapC,cC7EC,WD6EK,EAAA,CAAA,KAAA,ECtEE,QDsEF,EAAA,GAAA,IAAA;;;;;;;;;AAxFlB;AAoBA;AAgBA;;;;;AAA2D;AAuC3D;;;;;AAAgD;AAahD;;;;AAEwB;;;;AC/ExB;;;iBCiBgB,YAAA,wBAET,UACJ;AAHH;;;;;;;AF5BA;AAoBA;AAgBA;;;;;AAA2D;AAuC3D;;;;;AAAgD;AAahD;;;;AAEwB,iBG5ER,UAAA,CAAA,CH4EQ,EAAA;QG5Ec;UAAiB;;AFHvD;;;;;;;;ADXA;AAoBA;AAgBA;;;;;AAA2D;AAuC3D;;;;;AAAgD;AAahD;;;;AAEwB;;;;AC/ExB;;iBGSgB,YAAA,WAAuB,YAAY"}
@@ -0,0 +1,173 @@
1
+ import "../result-DzL3K2yA.js";
2
+ import { tapErr } from "../tap-err-Bf6rQ4Cw.js";
3
+
4
+ //#region src/logger/console-sink.ts
5
+ /**
6
+ * Default sink. Writes to `console.*` with a `[source]` prefix.
7
+ *
8
+ * Kept as a singleton value (not a factory) because it takes no config —
9
+ * adding `createConsoleSink({ format })` would be ceremony for a pattern
10
+ * the user can trivially replace by writing their own sink.
11
+ *
12
+ * `console[event.level]` routes directly without a detached lookup table.
13
+ * `LogLevel` is a subset of the Console method keys, so TS errors at this
14
+ * access if a future level drifts (e.g. adding `fatal`). Calling the method
15
+ * through `console[...]` preserves the `this` binding — avoids "Illegal
16
+ * invocation" in runtimes that require it.
17
+ *
18
+ * `satisfies LogSink` (not `: LogSink`) keeps the inferred callable type
19
+ * precise — `LogSink` is an intersection with optional dispose, and the
20
+ * annotation form would widen an unnecessary Partial into the value type.
21
+ *
22
+ * No dispose handler — `console` is not a resource.
23
+ */
24
+ const consoleSink = (event) => {
25
+ const prefix = `[${event.source}]`;
26
+ if (event.data === void 0) console[event.level](prefix, event.message);
27
+ else console[event.level](prefix, event.message, event.data);
28
+ };
29
+
30
+ //#endregion
31
+ //#region src/logger/create-logger.ts
32
+ /** Narrow `LoggableError` to the raw tagged object. See `LoggableError` in `types.ts` for the discriminator rationale. */
33
+ function unwrapLoggable(err) {
34
+ return "name" in err ? err : err.error;
35
+ }
36
+ /**
37
+ * Create a logger bound to a `source` namespace and a sink.
38
+ *
39
+ * Design choices:
40
+ * - **Positional args, not a bag.** Two arguments, both with obvious meaning;
41
+ * a `{ source, sink }` object would be ceremony.
42
+ * - **`sink` defaults to `consoleSink`.** Most callers during development
43
+ * want console output with zero setup. Production apps swap it out via DI
44
+ * at the attach/wire-up site.
45
+ * - **No global default logger.** There is no `setDefaultLogger()` and no
46
+ * module-level registry. Every consumer takes a `log?: Logger` option
47
+ * and defaults to `createLogger('<source>')` if omitted. Globals make
48
+ * test isolation and sink composition painful.
49
+ * - **Method shorthand in the return object** over higher-order factories.
50
+ * The five methods differ in two simple ways (error-unary vs free-form,
51
+ * plus the level string); spelling them out beats an `emitErr("warn")`
52
+ * riddle.
53
+ *
54
+ * @example Library code (caller wires the sink)
55
+ * function attachThing(ydoc: Doc, opts: { log?: Logger }) {
56
+ * const log = opts.log ?? createLogger('thing');
57
+ * // ...
58
+ * }
59
+ *
60
+ * @example App wiring (share one sink, multiple loggers)
61
+ * const sink = composeSinks(consoleSink, myCustomSink);
62
+ * attachThing(ydoc, { log: createLogger('thing', sink) });
63
+ * attachOther(ydoc, { log: createLogger('other', sink) });
64
+ */
65
+ function createLogger(source, sink = consoleSink) {
66
+ const emit = (level, message, data) => {
67
+ sink({
68
+ ts: Date.now(),
69
+ level,
70
+ source,
71
+ message,
72
+ data
73
+ });
74
+ };
75
+ return {
76
+ error(err) {
77
+ const tagged = unwrapLoggable(err);
78
+ emit("error", tagged.message, tagged);
79
+ },
80
+ warn(err) {
81
+ const tagged = unwrapLoggable(err);
82
+ emit("warn", tagged.message, tagged);
83
+ },
84
+ info(message, data) {
85
+ emit("info", message, data);
86
+ },
87
+ debug(message, data) {
88
+ emit("debug", message, data);
89
+ },
90
+ trace(message, data) {
91
+ emit("trace", message, data);
92
+ }
93
+ };
94
+ }
95
+
96
+ //#endregion
97
+ //#region src/logger/memory-sink.ts
98
+ /**
99
+ * In-memory sink for tests. Returns `{ sink, events }` so callers can
100
+ * both wire the sink and inspect captured events without a module-level
101
+ * spy or `console.*` interception.
102
+ *
103
+ * A factory (not a singleton) so each test gets an isolated array; sharing
104
+ * state across tests would leak events.
105
+ *
106
+ * Returning `{ sink, events }` (rather than an array with a method) keeps
107
+ * the two roles separate — `sink` goes to `createLogger`, `events` goes to
108
+ * assertions.
109
+ *
110
+ * Uses `satisfies LogSink` on the sink expression rather than `: LogSink =`
111
+ * to preserve the precise inferred callable type.
112
+ *
113
+ * @example
114
+ * const { sink, events } = memorySink();
115
+ * const log = createLogger("test", sink);
116
+ * log.warn(MyError.Thing({ cause: new Error("boom") }));
117
+ * expect(events).toHaveLength(1);
118
+ * expect(events[0]).toMatchObject({ level: "warn", source: "test" });
119
+ */
120
+ function memorySink() {
121
+ const events = [];
122
+ const sink = (event) => {
123
+ events.push(event);
124
+ };
125
+ return {
126
+ sink,
127
+ events
128
+ };
129
+ }
130
+
131
+ //#endregion
132
+ //#region src/logger/compose-sinks.ts
133
+ /**
134
+ * Fan one event out to every sink in order.
135
+ *
136
+ * Disposal: the returned sink has a `[Symbol.asyncDispose]` that forwards
137
+ * to each member via optional chaining. Members without dispose (e.g.
138
+ * `consoleSink`) are silent no-ops; members that own resources (file,
139
+ * network) flush and close. Mix pure and stateful sinks freely — no
140
+ * wrapping required.
141
+ *
142
+ * Fan-out is sequential and unguarded. If a member sink throws on emit,
143
+ * later members do not receive the event — by design, since swallowing
144
+ * sink errors hides real bugs. Wrap individual sinks yourself for
145
+ * best-effort delivery.
146
+ *
147
+ * Dispose is sequential and awaits each member. If one throws, later
148
+ * members don't get their chance; callers who want best-effort cleanup
149
+ * should wrap the composed dispose themselves.
150
+ *
151
+ * Built with `Object.assign` + `satisfies LogSink` rather than mutating a
152
+ * pre-typed `const` — avoids the widening that comes with `: LogSink =` and
153
+ * keeps the inferred type precise (callable + definite dispose, not
154
+ * callable + Partial dispose).
155
+ *
156
+ * @example
157
+ * await using file = jsonlFileSink("/tmp/app.jsonl");
158
+ * const sink = composeSinks(consoleSink, file);
159
+ * const log = createLogger("source", sink);
160
+ */
161
+ function composeSinks(...sinks) {
162
+ const emit = (event) => {
163
+ for (const sink of sinks) sink(event);
164
+ };
165
+ const dispose = async () => {
166
+ for (const sink of sinks) await sink[Symbol.asyncDispose]?.();
167
+ };
168
+ return Object.assign(emit, { [Symbol.asyncDispose]: dispose });
169
+ }
170
+
171
+ //#endregion
172
+ export { composeSinks, consoleSink, createLogger, memorySink, tapErr };
173
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["err: LoggableError","source: string","sink: LogSink","level: LogLevel","message: string","data?: unknown","events: LogEvent[]","event: LogEvent"],"sources":["../../src/logger/console-sink.ts","../../src/logger/create-logger.ts","../../src/logger/memory-sink.ts","../../src/logger/compose-sinks.ts"],"sourcesContent":["import type { LogSink } from \"./types.js\";\n\n/**\n * Default sink. Writes to `console.*` with a `[source]` prefix.\n *\n * Kept as a singleton value (not a factory) because it takes no config —\n * adding `createConsoleSink({ format })` would be ceremony for a pattern\n * the user can trivially replace by writing their own sink.\n *\n * `console[event.level]` routes directly without a detached lookup table.\n * `LogLevel` is a subset of the Console method keys, so TS errors at this\n * access if a future level drifts (e.g. adding `fatal`). Calling the method\n * through `console[...]` preserves the `this` binding — avoids \"Illegal\n * invocation\" in runtimes that require it.\n *\n * `satisfies LogSink` (not `: LogSink`) keeps the inferred callable type\n * precise — `LogSink` is an intersection with optional dispose, and the\n * annotation form would widen an unnecessary Partial into the value type.\n *\n * No dispose handler — `console` is not a resource.\n */\nexport const consoleSink = ((event) => {\n\tconst prefix = `[${event.source}]`;\n\tif (event.data === undefined) {\n\t\tconsole[event.level](prefix, event.message);\n\t} else {\n\t\tconsole[event.level](prefix, event.message, event.data);\n\t}\n}) satisfies LogSink;\n","import type { AnyTaggedError } from \"../error/types.js\";\nimport { consoleSink } from \"./console-sink.js\";\nimport type { LoggableError, LogLevel, Logger, LogSink } from \"./types.js\";\n\n/** Narrow `LoggableError` to the raw tagged object. See `LoggableError` in `types.ts` for the discriminator rationale. */\nfunction unwrapLoggable(err: LoggableError): AnyTaggedError {\n\treturn \"name\" in err ? err : err.error;\n}\n\n/**\n * Create a logger bound to a `source` namespace and a sink.\n *\n * Design choices:\n * - **Positional args, not a bag.** Two arguments, both with obvious meaning;\n * a `{ source, sink }` object would be ceremony.\n * - **`sink` defaults to `consoleSink`.** Most callers during development\n * want console output with zero setup. Production apps swap it out via DI\n * at the attach/wire-up site.\n * - **No global default logger.** There is no `setDefaultLogger()` and no\n * module-level registry. Every consumer takes a `log?: Logger` option\n * and defaults to `createLogger('<source>')` if omitted. Globals make\n * test isolation and sink composition painful.\n * - **Method shorthand in the return object** over higher-order factories.\n * The five methods differ in two simple ways (error-unary vs free-form,\n * plus the level string); spelling them out beats an `emitErr(\"warn\")`\n * riddle.\n *\n * @example Library code (caller wires the sink)\n * function attachThing(ydoc: Doc, opts: { log?: Logger }) {\n * const log = opts.log ?? createLogger('thing');\n * // ...\n * }\n *\n * @example App wiring (share one sink, multiple loggers)\n * const sink = composeSinks(consoleSink, myCustomSink);\n * attachThing(ydoc, { log: createLogger('thing', sink) });\n * attachOther(ydoc, { log: createLogger('other', sink) });\n */\nexport function createLogger(\n\tsource: string,\n\tsink: LogSink = consoleSink,\n): Logger {\n\tconst emit = (level: LogLevel, message: string, data?: unknown): void => {\n\t\tsink({ ts: Date.now(), level, source, message, data });\n\t};\n\treturn {\n\t\terror(err) {\n\t\t\tconst tagged = unwrapLoggable(err);\n\t\t\temit(\"error\", tagged.message, tagged);\n\t\t},\n\t\twarn(err) {\n\t\t\tconst tagged = unwrapLoggable(err);\n\t\t\temit(\"warn\", tagged.message, tagged);\n\t\t},\n\t\tinfo(message, data) {\n\t\t\temit(\"info\", message, data);\n\t\t},\n\t\tdebug(message, data) {\n\t\t\temit(\"debug\", message, data);\n\t\t},\n\t\ttrace(message, data) {\n\t\t\temit(\"trace\", message, data);\n\t\t},\n\t};\n}\n","import type { LogEvent, LogSink } from \"./types.js\";\n\n/**\n * In-memory sink for tests. Returns `{ sink, events }` so callers can\n * both wire the sink and inspect captured events without a module-level\n * spy or `console.*` interception.\n *\n * A factory (not a singleton) so each test gets an isolated array; sharing\n * state across tests would leak events.\n *\n * Returning `{ sink, events }` (rather than an array with a method) keeps\n * the two roles separate — `sink` goes to `createLogger`, `events` goes to\n * assertions.\n *\n * Uses `satisfies LogSink` on the sink expression rather than `: LogSink =`\n * to preserve the precise inferred callable type.\n *\n * @example\n * const { sink, events } = memorySink();\n * const log = createLogger(\"test\", sink);\n * log.warn(MyError.Thing({ cause: new Error(\"boom\") }));\n * expect(events).toHaveLength(1);\n * expect(events[0]).toMatchObject({ level: \"warn\", source: \"test\" });\n */\nexport function memorySink(): { sink: LogSink; events: LogEvent[] } {\n\tconst events: LogEvent[] = [];\n\tconst sink = ((event) => {\n\t\tevents.push(event);\n\t}) satisfies LogSink;\n\treturn { sink, events };\n}\n","import type { LogEvent, LogSink } from \"./types.js\";\n\n/**\n * Fan one event out to every sink in order.\n *\n * Disposal: the returned sink has a `[Symbol.asyncDispose]` that forwards\n * to each member via optional chaining. Members without dispose (e.g.\n * `consoleSink`) are silent no-ops; members that own resources (file,\n * network) flush and close. Mix pure and stateful sinks freely — no\n * wrapping required.\n *\n * Fan-out is sequential and unguarded. If a member sink throws on emit,\n * later members do not receive the event — by design, since swallowing\n * sink errors hides real bugs. Wrap individual sinks yourself for\n * best-effort delivery.\n *\n * Dispose is sequential and awaits each member. If one throws, later\n * members don't get their chance; callers who want best-effort cleanup\n * should wrap the composed dispose themselves.\n *\n * Built with `Object.assign` + `satisfies LogSink` rather than mutating a\n * pre-typed `const` — avoids the widening that comes with `: LogSink =` and\n * keeps the inferred type precise (callable + definite dispose, not\n * callable + Partial dispose).\n *\n * @example\n * await using file = jsonlFileSink(\"/tmp/app.jsonl\");\n * const sink = composeSinks(consoleSink, file);\n * const log = createLogger(\"source\", sink);\n */\nexport function composeSinks(...sinks: LogSink[]): LogSink {\n\tconst emit = (event: LogEvent) => {\n\t\tfor (const sink of sinks) sink(event);\n\t};\n\tconst dispose = async (): Promise<void> => {\n\t\tfor (const sink of sinks) await sink[Symbol.asyncDispose]?.();\n\t};\n\treturn Object.assign(emit, {\n\t\t[Symbol.asyncDispose]: dispose,\n\t}) satisfies LogSink;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,cAAe,CAAC,UAAU;CACtC,MAAM,SAAS,CAAC,CAAC,EAAE,MAAM,OAAO,CAAC,CAAC;AAClC,KAAI,MAAM,gBACT,SAAQ,MAAM,OAAO,QAAQ,MAAM,QAAQ;KAE3C,SAAQ,MAAM,OAAO,QAAQ,MAAM,SAAS,MAAM,KAAK;AAExD;;;;;ACvBD,SAAS,eAAeA,KAAoC;AAC3D,QAAO,UAAU,MAAM,MAAM,IAAI;AACjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BD,SAAgB,aACfC,QACAC,OAAgB,aACP;CACT,MAAM,OAAO,CAACC,OAAiBC,SAAiBC,SAAyB;AACxE,OAAK;GAAE,IAAI,KAAK,KAAK;GAAE;GAAO;GAAQ;GAAS;EAAM,EAAC;CACtD;AACD,QAAO;EACN,MAAM,KAAK;GACV,MAAM,SAAS,eAAe,IAAI;AAClC,QAAK,SAAS,OAAO,SAAS,OAAO;EACrC;EACD,KAAK,KAAK;GACT,MAAM,SAAS,eAAe,IAAI;AAClC,QAAK,QAAQ,OAAO,SAAS,OAAO;EACpC;EACD,KAAK,SAAS,MAAM;AACnB,QAAK,QAAQ,SAAS,KAAK;EAC3B;EACD,MAAM,SAAS,MAAM;AACpB,QAAK,SAAS,SAAS,KAAK;EAC5B;EACD,MAAM,SAAS,MAAM;AACpB,QAAK,SAAS,SAAS,KAAK;EAC5B;CACD;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;ACxCD,SAAgB,aAAoD;CACnE,MAAMC,SAAqB,CAAE;CAC7B,MAAM,OAAQ,CAAC,UAAU;AACxB,SAAO,KAAK,MAAM;CAClB;AACD,QAAO;EAAE;EAAM;CAAQ;AACvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAD,SAAgB,aAAa,GAAG,OAA2B;CAC1D,MAAM,OAAO,CAACC,UAAoB;AACjC,OAAK,MAAM,QAAQ,MAAO,MAAK,MAAM;CACrC;CACD,MAAM,UAAU,YAA2B;AAC1C,OAAK,MAAM,QAAQ,MAAO,OAAM,KAAK,OAAO,iBAAiB;CAC7D;AACD,QAAO,OAAO,OAAO,MAAM,GACzB,OAAO,eAAe,QACvB,EAAC;AACF"}
@@ -1,5 +1,6 @@
1
- import { Result } from "../result-xH3TbSDF.js";
2
- import "../index-D_iQ3bBj.js";
1
+ import { Result } from "../result-BongGO2O.js";
2
+ import "../tap-err-Bqs9aQpZ.js";
3
+ import "../index-mb9iYu0a.js";
3
4
  import { DefaultError, MutationFunction, MutationKey, MutationOptions, QueryClient, QueryFunction, QueryKey, QueryObserverOptions } from "@tanstack/query-core";
4
5
 
5
6
  //#region src/query/utils.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/query/utils.ts"],"s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,CA9HvB,MA8HuB,CA9HhB,KA8HgB,EA9HT,MA8HS,CAAA,CAAA,CAAA,GAAA;EAAS,OAApE,EA7HM,eA6HN,CA7HsB,KA6HtB,EA7H6B,MA6H7B,EA7HqC,UA6HrC,EA7HiD,QA6HjD,CAAA;EAAiB,OA8LU,EAAA,CAAA,SAAA,EA1TT,UA0TS,EAAA,GA1TM,OA0TN,CA1Tc,MA0Td,CA1TqB,KA0TrB,EA1T4B,MA0T5B,CAAA,CAAA;CAAK;;;;;;;;;AACZ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA9QR,oBAAA,cAAkC;iDAmE1C,eACD,2BACK,gCACQ,wCAET,iBACR,cACA,QACA,OACA,YACA,eAEC,kBAAkB,cAAc,QAAQ,OAAO,YAAY;kFA8LpD,oBAAoB,OAAO,QAAQ,YAAY,cACtD,qBAAqB,OAAO,QAAQ,YAAY"}
@@ -1,5 +1,6 @@
1
- import { Err, Ok, resolve } from "../result-BRfWC87j.js";
2
- import "../result-Cd0chHlN.js";
1
+ import { Err, Ok, resolve } from "../result-DzL3K2yA.js";
2
+ import "../tap-err-Bf6rQ4Cw.js";
3
+ import "../result-corfYKOe.js";
3
4
 
4
5
  //#region src/query/utils.ts
5
6
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["queryClient: QueryClient","options: DefineQueryInput<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>","options: DefineMutationInput<TData, TError, TVariables, TContext>","variables: TVariables","options: MutationOptions<TData, TError, TVariables, TContext>"],"sources":["../../src/query/utils.ts"],"sourcesContent":["import type {\n\tDefaultError,\n\tMutationFunction,\n\tMutationKey,\n\tMutationOptions,\n\tQueryClient,\n\tQueryFunction,\n\tQueryKey,\n\tQueryObserverOptions,\n} from \"@tanstack/query-core\";\nimport { Err, Ok, type Result, resolve } from \"../result/index.js\";\n\n/**\n * Input options for defining a query.\n *\n * Extends TanStack Query's QueryObserverOptions but expects queryFn to return a Result type.\n * This type represents the configuration for creating a query definition with both\n * reactive and imperative interfaces for data fetching.\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n */\ntype DefineQueryInput<\n\tTQueryFnData = unknown,\n\tTError = DefaultError,\n\tTData = TQueryFnData,\n\tTQueryData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = Omit<\n\tQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>,\n\t\"queryFn\"\n> & {\n\tqueryKey: TQueryKey;\n\tqueryFn: QueryFunction<Result<TQueryFnData, TError>, TQueryKey>;\n};\n\n/**\n * Output of defineQuery function.\n *\n * The query definition is directly callable and defaults to `ensure()` behavior,\n * which is recommended for most imperative use cases like preloaders.\n *\n * Provides both reactive and imperative interfaces for data fetching:\n * - `()` (callable): Same as `ensure()` - returns cached data if available, fetches if not\n * - `options`: Returns config for use with useQuery() or createQuery()\n * - `fetch()`: Always attempts to fetch data (from cache if fresh, network if stale)\n * - `ensure()`: Guarantees data availability, preferring cached data (recommended for preloaders)\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n *\n * @example\n * ```typescript\n * const userQuery = defineQuery({...});\n *\n * // Directly callable (same as .ensure())\n * const { data, error } = await userQuery();\n *\n * // Or use explicit methods\n * const { data, error } = await userQuery.ensure();\n * const { data, error } = await userQuery.fetch();\n *\n * // For reactive usage (Svelte 5 requires accessor wrapper)\n * const query = createQuery(() => userQuery.options); // Svelte 5\n * const query = useQuery(userQuery.options); // React\n * ```\n */\ntype DefineQueryOutput<\n\tTQueryFnData = unknown,\n\tTError = DefaultError,\n\tTData = TQueryFnData,\n\tTQueryData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = (() => Promise<Result<TQueryData, TError>>) & {\n\toptions: QueryObserverOptions<\n\t\tTQueryFnData,\n\t\tTError,\n\t\tTData,\n\t\tTQueryData,\n\t\tTQueryKey\n\t>;\n\tfetch: () => Promise<Result<TQueryData, TError>>;\n\tensure: () => Promise<Result<TQueryData, TError>>;\n};\n\n/**\n * Input options for defining a mutation.\n *\n * Extends TanStack Query's MutationOptions but expects mutationFn to return a Result type.\n * This type represents the configuration for creating a mutation definition with both\n * reactive and imperative interfaces for data mutations.\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n */\ntype DefineMutationInput<\n\tTData,\n\tTError,\n\tTVariables = void,\n\tTContext = unknown,\n> = Omit<MutationOptions<TData, TError, TVariables, TContext>, \"mutationFn\"> & {\n\tmutationKey: MutationKey;\n\tmutationFn: MutationFunction<Result<TData, TError>, TVariables>;\n};\n\n/**\n * Output of defineMutation function.\n *\n * The mutation definition is directly callable, which executes the mutation\n * and returns a Result. This is equivalent to calling `.execute()`.\n *\n * Provides both reactive and imperative interfaces for data mutations:\n * - `(variables)` (callable): Same as `execute()` - directly executes the mutation\n * - `options`: Returns config for use with useMutation() or createMutation()\n * - `execute(variables)`: Directly executes the mutation and returns a Result\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n *\n * @example\n * ```typescript\n * const createUser = defineMutation({...});\n *\n * // Directly callable (same as .execute())\n * const { data, error } = await createUser({ name: 'John' });\n *\n * // Or use explicit method\n * const { data, error } = await createUser.execute({ name: 'John' });\n *\n * // For reactive usage (Svelte 5 requires accessor wrapper)\n * const mutation = createMutation(() => createUser.options); // Svelte 5\n * const mutation = useMutation(createUser.options); // React\n * ```\n */\ntype DefineMutationOutput<\n\tTData,\n\tTError,\n\tTVariables = void,\n\tTContext = unknown,\n> = ((variables: TVariables) => Promise<Result<TData, TError>>) & {\n\toptions: MutationOptions<TData, TError, TVariables, TContext>;\n\texecute: (variables: TVariables) => Promise<Result<TData, TError>>;\n};\n\n/**\n * Creates factory functions for defining queries and mutations bound to a specific QueryClient.\n *\n * This factory pattern allows you to create isolated query/mutation definitions that are\n * bound to a specific QueryClient instance, enabling:\n * - Multiple query clients in the same application\n * - Testing with isolated query clients\n * - Framework-agnostic query definitions\n * - Proper separation of concerns between query logic and client instances\n *\n * The returned functions handle Result types automatically, unwrapping them for TanStack Query\n * while maintaining type safety throughout your application.\n *\n * @param queryClient - The QueryClient instance to bind the factories to\n * @returns An object containing defineQuery and defineMutation functions bound to the provided client\n *\n * @example\n * ```typescript\n * // Create your query client\n * const queryClient = new QueryClient({\n * defaultOptions: {\n * queries: { staleTime: 5 * 60 * 1000 }\n * }\n * });\n *\n * // Create the factory functions\n * const { defineQuery, defineMutation } = createQueryFactories(queryClient);\n *\n * // Now use defineQuery and defineMutation as before\n * const userQuery = defineQuery({\n * queryKey: ['user', userId],\n * queryFn: () => services.getUser(userId)\n * });\n *\n * // Use in components (Svelte 5 requires accessor wrapper)\n * const query = createQuery(() => userQuery.options); // Svelte 5\n * const query = useQuery(userQuery.options); // React\n *\n * // Or imperatively\n * const { data, error } = await userQuery.fetch();\n * ```\n */\nexport function createQueryFactories(queryClient: QueryClient) {\n\t/**\n\t * Creates a query definition that bridges the gap between pure service functions and reactive UI components.\n\t *\n\t * This factory function is the cornerstone of our data fetching architecture. It wraps service calls\n\t * with TanStack Query superpowers while maintaining type safety through Result types.\n\t *\n\t * The returned query definition is **directly callable** and defaults to `ensure()` behavior,\n\t * which is recommended for most imperative use cases like preloaders.\n\t *\n\t * ## Why use defineQuery?\n\t *\n\t * 1. **Callable**: Call directly like `userQuery()` for imperative data fetching\n\t * 2. **Dual Interface**: Also provides reactive (`.options`) and explicit imperative (`.fetch()`, `.ensure()`) APIs\n\t * 3. **Automatic Error Handling**: Service functions return `Result<T, E>` types which are automatically\n\t * unwrapped by TanStack Query, giving you proper error states in your components\n\t * 4. **Type Safety**: Full TypeScript support with proper inference for data and error types\n\t * 5. **Consistency**: Every query in the app follows the same pattern, making it easy to understand\n\t *\n\t * @template TQueryFnData - The type of data returned by the query function\n\t * @template TError - The type of error that can be thrown\n\t * @template TData - The type of data returned by the query (after select transform)\n\t * @template TQueryKey - The type of the query key\n\t *\n\t * @param options - Query configuration object\n\t * @param options.queryKey - Unique key for this query (used for caching and refetching)\n\t * @param options.queryFn - Function that fetches data and returns a Result type\n\t * @param options.* - Any other TanStack Query options (staleTime, refetchInterval, etc.)\n\t *\n\t * @returns Callable query definition with:\n\t * - `()` (callable): Same as `ensure()` - returns cached data if available, fetches if not\n\t * - `.options`: Config for use with useQuery() or createQuery()\n\t * - `.fetch()`: Always attempts to fetch (from cache if fresh, network if stale)\n\t * - `.ensure()`: Guarantees data availability, preferring cached data (recommended for preloaders)\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your query in the query layer\n\t * const userQuery = defineQuery({\n\t * queryKey: ['users', userId],\n\t * queryFn: () => services.getUser(userId), // Returns Result<User, ApiError>\n\t * staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte 5 component (accessor wrapper required)\n\t * const query = createQuery(() => userQuery.options);\n\t * // query.data is User | undefined\n\t * // query.error is ApiError | null\n\t *\n\t * // Step 2b: Call directly in preloaders (recommended)\n\t * export const load = async () => {\n\t * const { data, error } = await userQuery(); // Same as userQuery.ensure()\n\t * if (error) throw error;\n\t * return { user: data };\n\t * };\n\t *\n\t * // Step 2c: Use explicit methods when needed\n\t * async function refreshUser() {\n\t * const { data, error } = await userQuery.fetch(); // Force fresh fetch\n\t * if (error) {\n\t * console.error('Failed to fetch user:', error);\n\t * }\n\t * }\n\t * ```\n\t */\n\tconst defineQuery = <\n\t\tTQueryFnData = unknown,\n\t\tTError = DefaultError,\n\t\tTData = TQueryFnData,\n\t\tTQueryData = TQueryFnData,\n\t\tTQueryKey extends QueryKey = QueryKey,\n\t>(\n\t\toptions: DefineQueryInput<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>,\n\t): DefineQueryOutput<TQueryFnData, TError, TData, TQueryData, TQueryKey> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tqueryFn: async (context) => {\n\t\t\t\tlet result = options.queryFn(context);\n\t\t\t\tif (result instanceof Promise) result = await result;\n\t\t\t\treturn resolve(result);\n\t\t\t},\n\t\t} satisfies QueryObserverOptions<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>;\n\n\t\t/**\n\t\t * Fetches data for this query using queryClient.fetchQuery().\n\t\t *\n\t\t * This method ALWAYS evaluates freshness and will refetch if data is stale.\n\t\t * It wraps TanStack Query's fetchQuery method, which returns cached data if fresh\n\t\t * or makes a network request if the data is stale or missing.\n\t\t *\n\t\t * **When to use fetch():**\n\t\t * - When you explicitly want to check data freshness\n\t\t * - For user-triggered refresh actions\n\t\t * - When you need the most up-to-date data\n\t\t *\n\t\t * **For preloaders, use ensure() instead** - it's more efficient for initial data loading.\n\t\t *\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // Good for user-triggered refresh\n\t\t * const { data, error } = await userQuery.fetch();\n\t\t * if (error) {\n\t\t * console.error('Failed to load user:', error);\n\t\t * }\n\t\t */\n\t\tasync function fetch(): Promise<Result<TQueryData, TError>> {\n\t\t\ttry {\n\t\t\t\treturn Ok(\n\t\t\t\t\tawait queryClient.fetchQuery<\n\t\t\t\t\t\tTQueryFnData,\n\t\t\t\t\t\tTError,\n\t\t\t\t\t\tTQueryData,\n\t\t\t\t\t\tTQueryKey\n\t\t\t\t\t>({\n\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Ensures data is available for this query using queryClient.ensureQueryData().\n\t\t *\n\t\t * This method PRIORITIZES cached data and only calls fetchQuery internally if no cached\n\t\t * data exists. It wraps TanStack Query's ensureQueryData method, which is perfect for\n\t\t * guaranteeing data availability with minimal network requests.\n\t\t *\n\t\t * **This is the RECOMMENDED method for preloaders** because:\n\t\t * - It returns cached data immediately if available\n\t\t * - It updates the query client cache properly\n\t\t * - It minimizes network requests during navigation\n\t\t * - It ensures components have data ready when they mount\n\t\t *\n\t\t * **When to use ensure():**\n\t\t * - Route preloaders and data loading functions\n\t\t * - Initial component data requirements\n\t\t * - When cached data is acceptable for immediate display\n\t\t *\n\t\t * This is also the default behavior when calling the query directly.\n\t\t *\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // Perfect for preloaders\n\t\t * export const load = async () => {\n\t\t * const { data, error } = await userQuery.ensure();\n\t\t * // Or simply: await userQuery();\n\t\t * if (error) {\n\t\t * throw error;\n\t\t * }\n\t\t * return { user: data };\n\t\t * };\n\t\t */\n\t\tasync function ensure(): Promise<Result<TQueryData, TError>> {\n\t\t\ttry {\n\t\t\t\treturn Ok(\n\t\t\t\t\tawait queryClient.ensureQueryData<\n\t\t\t\t\t\tTQueryFnData,\n\t\t\t\t\t\tTError,\n\t\t\t\t\t\tTQueryData,\n\t\t\t\t\t\tTQueryKey\n\t\t\t\t\t>({\n\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t// Create a callable function that defaults to ensure() behavior\n\t\t// and attach options, fetch, and ensure as properties\n\t\treturn Object.assign(ensure, {\n\t\t\toptions: newOptions,\n\t\t\tfetch,\n\t\t\tensure,\n\t\t});\n\t};\n\n\t/**\n\t * Creates a mutation definition for operations that modify data (create, update, delete).\n\t *\n\t * This factory function is the mutation counterpart to defineQuery. It provides a clean way to\n\t * wrap service functions that perform side effects, while maintaining the same dual interface\n\t * pattern for maximum flexibility.\n\t *\n\t * The returned mutation definition is **directly callable**, which executes the mutation\n\t * and returns a Result. This is equivalent to calling `.execute()`.\n\t *\n\t * ## Why use defineMutation?\n\t *\n\t * 1. **Callable**: Call directly like `createUser({ name: 'John' })` for imperative execution\n\t * 2. **Dual Interface**: Also provides reactive (`.options`) and explicit imperative (`.execute()`) APIs\n\t * 3. **Consistent Error Handling**: Service functions return `Result<T, E>` types, ensuring\n\t * errors are handled consistently throughout the app\n\t * 4. **Cache Management**: Mutations often update the cache after success (see examples)\n\t *\n\t * @template TData - The type of data returned by the mutation\n\t * @template TError - The type of error that can be thrown\n\t * @template TVariables - The type of variables passed to the mutation\n\t * @template TContext - The type of context data for optimistic updates\n\t *\n\t * @param options - Mutation configuration object\n\t * @param options.mutationKey - Unique key for this mutation (used for tracking in-flight state)\n\t * @param options.mutationFn - Function that performs the mutation and returns a Result type\n\t * @param options.* - Any other TanStack Mutation options (onSuccess, onError, etc.)\n\t *\n\t * @returns Callable mutation definition with:\n\t * - `(variables)` (callable): Same as `execute()` - directly executes the mutation\n\t * - `.options`: Config for use with useMutation() or createMutation()\n\t * - `.execute(variables)`: Directly executes the mutation and returns a Result\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your mutation with cache updates\n\t * const createRecording = defineMutation({\n\t * mutationKey: ['recordings', 'create'],\n\t * mutationFn: async (recording: Recording) => {\n\t * // Call the service\n\t * const result = await services.db.createRecording(recording);\n\t * if (result.error) return Err(result.error);\n\t *\n\t * // Update cache on success\n\t * queryClient.setQueryData(['recordings'], (old) =>\n\t * [...(old || []), recording]\n\t * );\n\t *\n\t * return Ok(result.data);\n\t * }\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte 5 component (accessor wrapper required)\n\t * const mutation = createMutation(() => createRecording.options);\n\t * // Call with: mutation.mutate(recordingData)\n\t *\n\t * // Step 2b: Call directly in an action (recommended)\n\t * async function saveRecording(data: Recording) {\n\t * const { error } = await createRecording(data); // Same as createRecording.execute(data)\n\t * if (error) {\n\t * notify.error({ title: 'Failed to save', description: error.message });\n\t * } else {\n\t * notify.success({ title: 'Recording saved!' });\n\t * }\n\t * }\n\t * ```\n\t *\n\t * @tip Calling directly is especially useful for:\n\t * - Event handlers that need to await the result\n\t * - Sequential operations that depend on each other\n\t * - Non-component code that needs to trigger mutations\n\t */\n\tconst defineMutation = <TData, TError, TVariables = void, TContext = unknown>(\n\t\toptions: DefineMutationInput<TData, TError, TVariables, TContext>,\n\t): DefineMutationOutput<TData, TError, TVariables, TContext> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tmutationFn: async (variables: TVariables) => {\n\t\t\t\treturn resolve(await options.mutationFn(variables));\n\t\t\t},\n\t\t} satisfies MutationOptions<TData, TError, TVariables, TContext>;\n\n\t\t/**\n\t\t * Executes the mutation imperatively and returns a Result.\n\t\t *\n\t\t * This is the recommended way to trigger mutations from:\n\t\t * - Button click handlers\n\t\t * - Form submissions\n\t\t * - Keyboard shortcuts\n\t\t * - Any non-component code\n\t\t *\n\t\t * The method automatically wraps the result in a Result type, so you always\n\t\t * get back `{ data, error }` for consistent error handling.\n\t\t *\n\t\t * This is also the default behavior when calling the mutation directly.\n\t\t *\n\t\t * @param variables - The variables to pass to the mutation function\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // In an event handler\n\t\t * async function handleSubmit(formData: FormData) {\n\t\t * const { data, error } = await createUser.execute(formData);\n\t\t * // Or simply: await createUser(formData);\n\t\t * if (error) {\n\t\t * notify.error({ title: 'Failed to create user', description: error.message });\n\t\t * return;\n\t\t * }\n\t\t * goto(`/users/${data.id}`);\n\t\t * }\n\t\t */\n\t\tasync function execute(variables: TVariables) {\n\t\t\ttry {\n\t\t\t\treturn Ok(await runMutation(queryClient, newOptions, variables));\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t// Create a callable function that executes the mutation\n\t\t// and attach options and execute as properties\n\t\treturn Object.assign(execute, {\n\t\t\toptions: newOptions,\n\t\t\texecute,\n\t\t});\n\t};\n\n\treturn {\n\t\tdefineQuery,\n\t\tdefineMutation,\n\t};\n}\n\n/**\n * Internal helper that executes a mutation directly using the query client's mutation cache.\n *\n * This is what powers the callable behavior and `.execute()` method on mutations.\n * It bypasses the reactive mutation hooks and runs the mutation imperatively,\n * which is perfect for event handlers and other imperative code.\n *\n * @internal\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data\n * @param queryClient - The query client instance to use\n * @param options - The mutation options including mutationFn and mutationKey\n * @param variables - The variables to pass to the mutation function\n * @returns Promise that resolves with the mutation result\n */\nfunction runMutation<TData, TError, TVariables, TContext>(\n\tqueryClient: QueryClient,\n\toptions: MutationOptions<TData, TError, TVariables, TContext>,\n\tvariables: TVariables,\n) {\n\tconst mutation = queryClient.getMutationCache().build(queryClient, options);\n\treturn mutation.execute(variables);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkMA,SAAgB,qBAAqBA,aAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiE9D,MAAM,cAAc,CAOnBC,YAO2E;EAC3E,MAAM,aAAa;GAClB,GAAG;GACH,SAAS,OAAO,YAAY;IAC3B,IAAI,SAAS,QAAQ,QAAQ,QAAQ;AACrC,QAAI,kBAAkB,QAAS,UAAS,MAAM;AAC9C,WAAO,QAAQ,OAAO;GACtB;EACD;;;;;;;;;;;;;;;;;;;;;;;;EA+BD,eAAe,QAA6C;AAC3D,OAAI;AACH,WAAO,GACN,MAAM,YAAY,WAKhB;KACD,UAAU,WAAW;KACrB,SAAS,WAAW;IACpB,EAAC,CACF;GACD,SAAQ,OAAO;AACf,WAAO,IAAI,MAAgB;GAC3B;EACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmCD,eAAe,SAA8C;AAC5D,OAAI;AACH,WAAO,GACN,MAAM,YAAY,gBAKhB;KACD,UAAU,WAAW;KACrB,SAAS,WAAW;IACpB,EAAC,CACF;GACD,SAAQ,OAAO;AACf,WAAO,IAAI,MAAgB;GAC3B;EACD;AAID,SAAO,OAAO,OAAO,QAAQ;GAC5B,SAAS;GACT;GACA;EACA,EAAC;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0ED,MAAM,iBAAiB,CACtBC,YAC+D;EAC/D,MAAM,aAAa;GAClB,GAAG;GACH,YAAY,OAAOC,cAA0B;AAC5C,WAAO,QAAQ,MAAM,QAAQ,WAAW,UAAU,CAAC;GACnD;EACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BD,eAAe,QAAQA,WAAuB;AAC7C,OAAI;AACH,WAAO,GAAG,MAAM,YAAY,aAAa,YAAY,UAAU,CAAC;GAChE,SAAQ,OAAO;AACf,WAAO,IAAI,MAAgB;GAC3B;EACD;AAID,SAAO,OAAO,OAAO,SAAS;GAC7B,SAAS;GACT;EACA,EAAC;CACF;AAED,QAAO;EACN;EACA;CACA;AACD;;;;;;;;;;;;;;;;;;AAmBD,SAAS,YACRH,aACAI,SACAD,WACC;CACD,MAAM,WAAW,YAAY,kBAAkB,CAAC,MAAM,aAAa,QAAQ;AAC3E,QAAO,SAAS,QAAQ,UAAU;AAClC"}
1
+ {"version":3,"file":"index.js","names":["queryClient: QueryClient","options: DefineQueryInput<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>","options: DefineMutationInput<TData, TError, TVariables, TContext>","variables: TVariables","options: MutationOptions<TData, TError, TVariables, TContext>"],"sources":["../../src/query/utils.ts"],"sourcesContent":["import type {\n\tDefaultError,\n\tMutationFunction,\n\tMutationKey,\n\tMutationOptions,\n\tQueryClient,\n\tQueryFunction,\n\tQueryKey,\n\tQueryObserverOptions,\n} from \"@tanstack/query-core\";\nimport { Err, Ok, type Result, resolve } from \"../result/index.js\";\n\n/**\n * Input options for defining a query.\n *\n * Extends TanStack Query's QueryObserverOptions but expects queryFn to return a Result type.\n * This type represents the configuration for creating a query definition with both\n * reactive and imperative interfaces for data fetching.\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n */\ntype DefineQueryInput<\n\tTQueryFnData = unknown,\n\tTError = DefaultError,\n\tTData = TQueryFnData,\n\tTQueryData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = Omit<\n\tQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>,\n\t\"queryFn\"\n> & {\n\tqueryKey: TQueryKey;\n\tqueryFn: QueryFunction<Result<TQueryFnData, TError>, TQueryKey>;\n};\n\n/**\n * Output of defineQuery function.\n *\n * The query definition is directly callable and defaults to `ensure()` behavior,\n * which is recommended for most imperative use cases like preloaders.\n *\n * Provides both reactive and imperative interfaces for data fetching:\n * - `()` (callable): Same as `ensure()` - returns cached data if available, fetches if not\n * - `options`: Returns config for use with useQuery() or createQuery()\n * - `fetch()`: Always attempts to fetch data (from cache if fresh, network if stale)\n * - `ensure()`: Guarantees data availability, preferring cached data (recommended for preloaders)\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n *\n * @example\n * ```typescript\n * const userQuery = defineQuery({...});\n *\n * // Directly callable (same as .ensure())\n * const { data, error } = await userQuery();\n *\n * // Or use explicit methods\n * const { data, error } = await userQuery.ensure();\n * const { data, error } = await userQuery.fetch();\n *\n * // For reactive usage (Svelte 5 requires accessor wrapper)\n * const query = createQuery(() => userQuery.options); // Svelte 5\n * const query = useQuery(userQuery.options); // React\n * ```\n */\ntype DefineQueryOutput<\n\tTQueryFnData = unknown,\n\tTError = DefaultError,\n\tTData = TQueryFnData,\n\tTQueryData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = (() => Promise<Result<TQueryData, TError>>) & {\n\toptions: QueryObserverOptions<\n\t\tTQueryFnData,\n\t\tTError,\n\t\tTData,\n\t\tTQueryData,\n\t\tTQueryKey\n\t>;\n\tfetch: () => Promise<Result<TQueryData, TError>>;\n\tensure: () => Promise<Result<TQueryData, TError>>;\n};\n\n/**\n * Input options for defining a mutation.\n *\n * Extends TanStack Query's MutationOptions but expects mutationFn to return a Result type.\n * This type represents the configuration for creating a mutation definition with both\n * reactive and imperative interfaces for data mutations.\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n */\ntype DefineMutationInput<\n\tTData,\n\tTError,\n\tTVariables = void,\n\tTContext = unknown,\n> = Omit<MutationOptions<TData, TError, TVariables, TContext>, \"mutationFn\"> & {\n\tmutationKey: MutationKey;\n\tmutationFn: MutationFunction<Result<TData, TError>, TVariables>;\n};\n\n/**\n * Output of defineMutation function.\n *\n * The mutation definition is directly callable, which executes the mutation\n * and returns a Result. This is equivalent to calling `.execute()`.\n *\n * Provides both reactive and imperative interfaces for data mutations:\n * - `(variables)` (callable): Same as `execute()` - directly executes the mutation\n * - `options`: Returns config for use with useMutation() or createMutation()\n * - `execute(variables)`: Directly executes the mutation and returns a Result\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n *\n * @example\n * ```typescript\n * const createUser = defineMutation({...});\n *\n * // Directly callable (same as .execute())\n * const { data, error } = await createUser({ name: 'John' });\n *\n * // Or use explicit method\n * const { data, error } = await createUser.execute({ name: 'John' });\n *\n * // For reactive usage (Svelte 5 requires accessor wrapper)\n * const mutation = createMutation(() => createUser.options); // Svelte 5\n * const mutation = useMutation(createUser.options); // React\n * ```\n */\ntype DefineMutationOutput<\n\tTData,\n\tTError,\n\tTVariables = void,\n\tTContext = unknown,\n> = ((variables: TVariables) => Promise<Result<TData, TError>>) & {\n\toptions: MutationOptions<TData, TError, TVariables, TContext>;\n\texecute: (variables: TVariables) => Promise<Result<TData, TError>>;\n};\n\n/**\n * Creates factory functions for defining queries and mutations bound to a specific QueryClient.\n *\n * This factory pattern allows you to create isolated query/mutation definitions that are\n * bound to a specific QueryClient instance, enabling:\n * - Multiple query clients in the same application\n * - Testing with isolated query clients\n * - Framework-agnostic query definitions\n * - Proper separation of concerns between query logic and client instances\n *\n * The returned functions handle Result types automatically, unwrapping them for TanStack Query\n * while maintaining type safety throughout your application.\n *\n * @param queryClient - The QueryClient instance to bind the factories to\n * @returns An object containing defineQuery and defineMutation functions bound to the provided client\n *\n * @example\n * ```typescript\n * // Create your query client\n * const queryClient = new QueryClient({\n * defaultOptions: {\n * queries: { staleTime: 5 * 60 * 1000 }\n * }\n * });\n *\n * // Create the factory functions\n * const { defineQuery, defineMutation } = createQueryFactories(queryClient);\n *\n * // Now use defineQuery and defineMutation as before\n * const userQuery = defineQuery({\n * queryKey: ['user', userId],\n * queryFn: () => services.getUser(userId)\n * });\n *\n * // Use in components (Svelte 5 requires accessor wrapper)\n * const query = createQuery(() => userQuery.options); // Svelte 5\n * const query = useQuery(userQuery.options); // React\n *\n * // Or imperatively\n * const { data, error } = await userQuery.fetch();\n * ```\n */\nexport function createQueryFactories(queryClient: QueryClient) {\n\t/**\n\t * Creates a query definition that bridges the gap between pure service functions and reactive UI components.\n\t *\n\t * This factory function is the cornerstone of our data fetching architecture. It wraps service calls\n\t * with TanStack Query superpowers while maintaining type safety through Result types.\n\t *\n\t * The returned query definition is **directly callable** and defaults to `ensure()` behavior,\n\t * which is recommended for most imperative use cases like preloaders.\n\t *\n\t * ## Why use defineQuery?\n\t *\n\t * 1. **Callable**: Call directly like `userQuery()` for imperative data fetching\n\t * 2. **Dual Interface**: Also provides reactive (`.options`) and explicit imperative (`.fetch()`, `.ensure()`) APIs\n\t * 3. **Automatic Error Handling**: Service functions return `Result<T, E>` types which are automatically\n\t * unwrapped by TanStack Query, giving you proper error states in your components\n\t * 4. **Type Safety**: Full TypeScript support with proper inference for data and error types\n\t * 5. **Consistency**: Every query in the app follows the same pattern, making it easy to understand\n\t *\n\t * @template TQueryFnData - The type of data returned by the query function\n\t * @template TError - The type of error that can be thrown\n\t * @template TData - The type of data returned by the query (after select transform)\n\t * @template TQueryKey - The type of the query key\n\t *\n\t * @param options - Query configuration object\n\t * @param options.queryKey - Unique key for this query (used for caching and refetching)\n\t * @param options.queryFn - Function that fetches data and returns a Result type\n\t * @param options.* - Any other TanStack Query options (staleTime, refetchInterval, etc.)\n\t *\n\t * @returns Callable query definition with:\n\t * - `()` (callable): Same as `ensure()` - returns cached data if available, fetches if not\n\t * - `.options`: Config for use with useQuery() or createQuery()\n\t * - `.fetch()`: Always attempts to fetch (from cache if fresh, network if stale)\n\t * - `.ensure()`: Guarantees data availability, preferring cached data (recommended for preloaders)\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your query in the query layer\n\t * const userQuery = defineQuery({\n\t * queryKey: ['users', userId],\n\t * queryFn: () => services.getUser(userId), // Returns Result<User, ApiError>\n\t * staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte 5 component (accessor wrapper required)\n\t * const query = createQuery(() => userQuery.options);\n\t * // query.data is User | undefined\n\t * // query.error is ApiError | null\n\t *\n\t * // Step 2b: Call directly in preloaders (recommended)\n\t * export const load = async () => {\n\t * const { data, error } = await userQuery(); // Same as userQuery.ensure()\n\t * if (error) throw error;\n\t * return { user: data };\n\t * };\n\t *\n\t * // Step 2c: Use explicit methods when needed\n\t * async function refreshUser() {\n\t * const { data, error } = await userQuery.fetch(); // Force fresh fetch\n\t * if (error) {\n\t * console.error('Failed to fetch user:', error);\n\t * }\n\t * }\n\t * ```\n\t */\n\tconst defineQuery = <\n\t\tTQueryFnData = unknown,\n\t\tTError = DefaultError,\n\t\tTData = TQueryFnData,\n\t\tTQueryData = TQueryFnData,\n\t\tTQueryKey extends QueryKey = QueryKey,\n\t>(\n\t\toptions: DefineQueryInput<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>,\n\t): DefineQueryOutput<TQueryFnData, TError, TData, TQueryData, TQueryKey> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tqueryFn: async (context) => {\n\t\t\t\tlet result = options.queryFn(context);\n\t\t\t\tif (result instanceof Promise) result = await result;\n\t\t\t\treturn resolve(result);\n\t\t\t},\n\t\t} satisfies QueryObserverOptions<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>;\n\n\t\t/**\n\t\t * Fetches data for this query using queryClient.fetchQuery().\n\t\t *\n\t\t * This method ALWAYS evaluates freshness and will refetch if data is stale.\n\t\t * It wraps TanStack Query's fetchQuery method, which returns cached data if fresh\n\t\t * or makes a network request if the data is stale or missing.\n\t\t *\n\t\t * **When to use fetch():**\n\t\t * - When you explicitly want to check data freshness\n\t\t * - For user-triggered refresh actions\n\t\t * - When you need the most up-to-date data\n\t\t *\n\t\t * **For preloaders, use ensure() instead** - it's more efficient for initial data loading.\n\t\t *\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // Good for user-triggered refresh\n\t\t * const { data, error } = await userQuery.fetch();\n\t\t * if (error) {\n\t\t * console.error('Failed to load user:', error);\n\t\t * }\n\t\t */\n\t\tasync function fetch(): Promise<Result<TQueryData, TError>> {\n\t\t\ttry {\n\t\t\t\treturn Ok(\n\t\t\t\t\tawait queryClient.fetchQuery<\n\t\t\t\t\t\tTQueryFnData,\n\t\t\t\t\t\tTError,\n\t\t\t\t\t\tTQueryData,\n\t\t\t\t\t\tTQueryKey\n\t\t\t\t\t>({\n\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Ensures data is available for this query using queryClient.ensureQueryData().\n\t\t *\n\t\t * This method PRIORITIZES cached data and only calls fetchQuery internally if no cached\n\t\t * data exists. It wraps TanStack Query's ensureQueryData method, which is perfect for\n\t\t * guaranteeing data availability with minimal network requests.\n\t\t *\n\t\t * **This is the RECOMMENDED method for preloaders** because:\n\t\t * - It returns cached data immediately if available\n\t\t * - It updates the query client cache properly\n\t\t * - It minimizes network requests during navigation\n\t\t * - It ensures components have data ready when they mount\n\t\t *\n\t\t * **When to use ensure():**\n\t\t * - Route preloaders and data loading functions\n\t\t * - Initial component data requirements\n\t\t * - When cached data is acceptable for immediate display\n\t\t *\n\t\t * This is also the default behavior when calling the query directly.\n\t\t *\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // Perfect for preloaders\n\t\t * export const load = async () => {\n\t\t * const { data, error } = await userQuery.ensure();\n\t\t * // Or simply: await userQuery();\n\t\t * if (error) {\n\t\t * throw error;\n\t\t * }\n\t\t * return { user: data };\n\t\t * };\n\t\t */\n\t\tasync function ensure(): Promise<Result<TQueryData, TError>> {\n\t\t\ttry {\n\t\t\t\treturn Ok(\n\t\t\t\t\tawait queryClient.ensureQueryData<\n\t\t\t\t\t\tTQueryFnData,\n\t\t\t\t\t\tTError,\n\t\t\t\t\t\tTQueryData,\n\t\t\t\t\t\tTQueryKey\n\t\t\t\t\t>({\n\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t// Create a callable function that defaults to ensure() behavior\n\t\t// and attach options, fetch, and ensure as properties\n\t\treturn Object.assign(ensure, {\n\t\t\toptions: newOptions,\n\t\t\tfetch,\n\t\t\tensure,\n\t\t});\n\t};\n\n\t/**\n\t * Creates a mutation definition for operations that modify data (create, update, delete).\n\t *\n\t * This factory function is the mutation counterpart to defineQuery. It provides a clean way to\n\t * wrap service functions that perform side effects, while maintaining the same dual interface\n\t * pattern for maximum flexibility.\n\t *\n\t * The returned mutation definition is **directly callable**, which executes the mutation\n\t * and returns a Result. This is equivalent to calling `.execute()`.\n\t *\n\t * ## Why use defineMutation?\n\t *\n\t * 1. **Callable**: Call directly like `createUser({ name: 'John' })` for imperative execution\n\t * 2. **Dual Interface**: Also provides reactive (`.options`) and explicit imperative (`.execute()`) APIs\n\t * 3. **Consistent Error Handling**: Service functions return `Result<T, E>` types, ensuring\n\t * errors are handled consistently throughout the app\n\t * 4. **Cache Management**: Mutations often update the cache after success (see examples)\n\t *\n\t * @template TData - The type of data returned by the mutation\n\t * @template TError - The type of error that can be thrown\n\t * @template TVariables - The type of variables passed to the mutation\n\t * @template TContext - The type of context data for optimistic updates\n\t *\n\t * @param options - Mutation configuration object\n\t * @param options.mutationKey - Unique key for this mutation (used for tracking in-flight state)\n\t * @param options.mutationFn - Function that performs the mutation and returns a Result type\n\t * @param options.* - Any other TanStack Mutation options (onSuccess, onError, etc.)\n\t *\n\t * @returns Callable mutation definition with:\n\t * - `(variables)` (callable): Same as `execute()` - directly executes the mutation\n\t * - `.options`: Config for use with useMutation() or createMutation()\n\t * - `.execute(variables)`: Directly executes the mutation and returns a Result\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your mutation with cache updates\n\t * const createRecording = defineMutation({\n\t * mutationKey: ['recordings', 'create'],\n\t * mutationFn: async (recording: Recording) => {\n\t * // Call the service\n\t * const result = await services.db.createRecording(recording);\n\t * if (result.error) return Err(result.error);\n\t *\n\t * // Update cache on success\n\t * queryClient.setQueryData(['recordings'], (old) =>\n\t * [...(old || []), recording]\n\t * );\n\t *\n\t * return Ok(result.data);\n\t * }\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte 5 component (accessor wrapper required)\n\t * const mutation = createMutation(() => createRecording.options);\n\t * // Call with: mutation.mutate(recordingData)\n\t *\n\t * // Step 2b: Call directly in an action (recommended)\n\t * async function saveRecording(data: Recording) {\n\t * const { error } = await createRecording(data); // Same as createRecording.execute(data)\n\t * if (error) {\n\t * notify.error({ title: 'Failed to save', description: error.message });\n\t * } else {\n\t * notify.success({ title: 'Recording saved!' });\n\t * }\n\t * }\n\t * ```\n\t *\n\t * @tip Calling directly is especially useful for:\n\t * - Event handlers that need to await the result\n\t * - Sequential operations that depend on each other\n\t * - Non-component code that needs to trigger mutations\n\t */\n\tconst defineMutation = <TData, TError, TVariables = void, TContext = unknown>(\n\t\toptions: DefineMutationInput<TData, TError, TVariables, TContext>,\n\t): DefineMutationOutput<TData, TError, TVariables, TContext> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tmutationFn: async (variables: TVariables) => {\n\t\t\t\treturn resolve(await options.mutationFn(variables));\n\t\t\t},\n\t\t} satisfies MutationOptions<TData, TError, TVariables, TContext>;\n\n\t\t/**\n\t\t * Executes the mutation imperatively and returns a Result.\n\t\t *\n\t\t * This is the recommended way to trigger mutations from:\n\t\t * - Button click handlers\n\t\t * - Form submissions\n\t\t * - Keyboard shortcuts\n\t\t * - Any non-component code\n\t\t *\n\t\t * The method automatically wraps the result in a Result type, so you always\n\t\t * get back `{ data, error }` for consistent error handling.\n\t\t *\n\t\t * This is also the default behavior when calling the mutation directly.\n\t\t *\n\t\t * @param variables - The variables to pass to the mutation function\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // In an event handler\n\t\t * async function handleSubmit(formData: FormData) {\n\t\t * const { data, error } = await createUser.execute(formData);\n\t\t * // Or simply: await createUser(formData);\n\t\t * if (error) {\n\t\t * notify.error({ title: 'Failed to create user', description: error.message });\n\t\t * return;\n\t\t * }\n\t\t * goto(`/users/${data.id}`);\n\t\t * }\n\t\t */\n\t\tasync function execute(variables: TVariables) {\n\t\t\ttry {\n\t\t\t\treturn Ok(await runMutation(queryClient, newOptions, variables));\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t// Create a callable function that executes the mutation\n\t\t// and attach options and execute as properties\n\t\treturn Object.assign(execute, {\n\t\t\toptions: newOptions,\n\t\t\texecute,\n\t\t});\n\t};\n\n\treturn {\n\t\tdefineQuery,\n\t\tdefineMutation,\n\t};\n}\n\n/**\n * Internal helper that executes a mutation directly using the query client's mutation cache.\n *\n * This is what powers the callable behavior and `.execute()` method on mutations.\n * It bypasses the reactive mutation hooks and runs the mutation imperatively,\n * which is perfect for event handlers and other imperative code.\n *\n * @internal\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data\n * @param queryClient - The query client instance to use\n * @param options - The mutation options including mutationFn and mutationKey\n * @param variables - The variables to pass to the mutation function\n * @returns Promise that resolves with the mutation result\n */\nfunction runMutation<TData, TError, TVariables, TContext>(\n\tqueryClient: QueryClient,\n\toptions: MutationOptions<TData, TError, TVariables, TContext>,\n\tvariables: TVariables,\n) {\n\tconst mutation = queryClient.getMutationCache().build(queryClient, options);\n\treturn mutation.execute(variables);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkMA,SAAgB,qBAAqBA,aAA0B;;;;;;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GACT;EACA,EAAC;CACF;AAED,QAAO;EACN;EACA;CACA;AACD;;;;;;;;;;;;;;;;;;AAmBD,SAAS,YACRH,aACAI,SACAD,WACC;CACD,MAAM,WAAW,YAAY,kBAAkB,CAAC,MAAM,aAAa,QAAQ;AAC3E,QAAO,SAAS,QAAQ,UAAU;AAClC"}
@@ -1,3 +1,4 @@
1
- import { Err, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-xH3TbSDF.js";
2
- import { partitionResults } from "../index-D_iQ3bBj.js";
3
- export { Err, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };
1
+ import { Err, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-BongGO2O.js";
2
+ import { tapErr } from "../tap-err-Bqs9aQpZ.js";
3
+ import { partitionResults } from "../index-mb9iYu0a.js";
4
+ export { Err, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, partitionResults, resolve, tapErr, tryAsync, trySync, unwrap };
@@ -1,4 +1,5 @@
1
- import { Err, Ok, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-BRfWC87j.js";
2
- import { partitionResults } from "../result-Cd0chHlN.js";
1
+ import { Err, Ok, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-DzL3K2yA.js";
2
+ import { tapErr } from "../tap-err-Bf6rQ4Cw.js";
3
+ import { partitionResults } from "../result-corfYKOe.js";
3
4
 
4
- export { Err, Ok, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };
5
+ export { Err, Ok, isErr, isOk, isResult, partitionResults, resolve, tapErr, tryAsync, trySync, unwrap };
@@ -84,11 +84,27 @@ declare const Ok: <T>(data: T) => Ok<T>;
84
84
  /**
85
85
  * Constructs an `Err<E>` variant, representing a failure outcome.
86
86
  *
87
- * This factory function creates the error variant of a `Result`.
88
- * It wraps the provided `error` (the error value) and ensures the `data` property is `null`.
87
+ * Wraps the provided `error` (the failure value) and sets `data` to `null`.
88
+ *
89
+ * **Don't call `Err(null)`.** It produces `{ data: null, error: null }` —
90
+ * structurally identical to `Ok(null)`. The built-in `isErr` check
91
+ * (`result.error !== null`) reads it as Ok, silently misclassifying your
92
+ * failure as success. `Err(undefined)` is also discouraged: the discriminator
93
+ * technically works (`undefined !== null`), but `undefined` is falsy, so
94
+ * downstream `if (error)` checks trip and the error carries no information
95
+ * anyway. Pass a meaningful error value (a string, a tagged error from
96
+ * `defineErrors`, an `Error` instance), or use `Ok(null)`/`Ok(undefined)` if
97
+ * what you meant was success-with-no-payload.
98
+ *
99
+ * At `catch (error: unknown)` boundaries, wrap the caught value in a tagged
100
+ * error rather than passing it through — `TaggedError.X({ cause: error })`
101
+ * is always non-null by construction, so the discriminator works regardless
102
+ * of what was thrown.
103
+ *
104
+ * See `docs/philosophy/err-null-is-ok-null.md` for the full rationale.
89
105
  *
90
106
  * @template E - The type of the error value.
91
- * @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.
107
+ * @param error - The error value to wrap. Don't pass `null` or `undefined`.
92
108
  * @returns An `Err<E>` object with the provided error and `data` set to `null`.
93
109
  * @example
94
110
  * ```ts
@@ -416,4 +432,4 @@ declare function resolve<T, E>(value: T | Result<T, E>): T;
416
432
  //# sourceMappingURL=result.d.ts.map
417
433
  //#endregion
418
434
  export { Err, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap };
419
- //# sourceMappingURL=result-xH3TbSDF.d.ts.map
435
+ //# sourceMappingURL=result-BongGO2O.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-BongGO2O.d.ts","names":[],"sources":["../src/result/result.ts"],"sourcesContent":[],"mappings":";;AAWA;AAaA;AAqCA;;;;;;AAAsC;AAiBtC;AAAgE,KAnEpD,EAmEoD,CAAA,CAAA,CAAA,GAAA;EAAA,I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B,QAAQ,GAAG,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuGJ,qBAAqB,OAAO,GAAG,KAAK;iBAOpC,qBAAqB,IAAI,OAAO,GAAG,KAAK"}
@@ -21,11 +21,27 @@ const Ok = (data) => ({
21
21
  /**
22
22
  * Constructs an `Err<E>` variant, representing a failure outcome.
23
23
  *
24
- * This factory function creates the error variant of a `Result`.
25
- * It wraps the provided `error` (the error value) and ensures the `data` property is `null`.
24
+ * Wraps the provided `error` (the failure value) and sets `data` to `null`.
25
+ *
26
+ * **Don't call `Err(null)`.** It produces `{ data: null, error: null }` —
27
+ * structurally identical to `Ok(null)`. The built-in `isErr` check
28
+ * (`result.error !== null`) reads it as Ok, silently misclassifying your
29
+ * failure as success. `Err(undefined)` is also discouraged: the discriminator
30
+ * technically works (`undefined !== null`), but `undefined` is falsy, so
31
+ * downstream `if (error)` checks trip and the error carries no information
32
+ * anyway. Pass a meaningful error value (a string, a tagged error from
33
+ * `defineErrors`, an `Error` instance), or use `Ok(null)`/`Ok(undefined)` if
34
+ * what you meant was success-with-no-payload.
35
+ *
36
+ * At `catch (error: unknown)` boundaries, wrap the caught value in a tagged
37
+ * error rather than passing it through — `TaggedError.X({ cause: error })`
38
+ * is always non-null by construction, so the discriminator works regardless
39
+ * of what was thrown.
40
+ *
41
+ * See `docs/philosophy/err-null-is-ok-null.md` for the full rationale.
26
42
  *
27
43
  * @template E - The type of the error value.
28
- * @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.
44
+ * @param error - The error value to wrap. Don't pass `null` or `undefined`.
29
45
  * @returns An `Err<E>` object with the provided error and `data` set to `null`.
30
46
  * @example
31
47
  * ```ts
@@ -340,4 +356,4 @@ function resolve(value) {
340
356
 
341
357
  //#endregion
342
358
  export { Err, Ok, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap };
343
- //# sourceMappingURL=result-BRfWC87j.js.map
359
+ //# sourceMappingURL=result-DzL3K2yA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-DzL3K2yA.js","names":["data: T","error: E","value: unknown","result: Result<T, E>","value: T | Result<T, E>"],"sources":["../src/result/result.ts"],"sourcesContent":["/**\n * Represents the successful outcome of an operation, encapsulating the success value.\n *\n * This is the 'Ok' variant of the `Result` type. It holds a `data` property\n * of type `T` (the success value) and an `error` property explicitly set to `null`,\n * signifying no error occurred.\n *\n * Use this type in conjunction with `Err<E>` and `Result<T, E>`.\n *\n * @template T - The type of the success value contained within.\n */\nexport type Ok<T> = { data: T; error: null };\n\n/**\n * Represents the failure outcome of an operation, encapsulating the error value.\n *\n * This is the 'Err' variant of the `Result` type. It holds an `error` property\n * of type `E` (the error value) and a `data` property explicitly set to `null`,\n * signifying that no success value is present due to the failure.\n *\n * Use this type in conjunction with `Ok<T>` and `Result<T, E>`.\n *\n * @template E - The type of the error value contained within.\n */\nexport type Err<E> = { error: E; data: null };\n\n/**\n * A type that represents the outcome of an operation that can either succeed or fail.\n *\n * `Result<T, E>` is a discriminated union type with two possible variants:\n * - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.\n * In this case, the `error` field is `null`.\n * - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.\n * In this case, the `data` field is `null`.\n *\n * This type promotes explicit error handling by requiring developers to check\n * the variant of the `Result` before accessing its potential value or error.\n * It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).\n *\n * @template T - The type of the success value if the operation is successful (held in `Ok<T>`).\n * @template E - The type of the error value if the operation fails (held in `Err<E>`).\n * @example\n * ```ts\n * function divide(numerator: number, denominator: number): Result<number, string> {\n * if (denominator === 0) {\n * return Err(\"Cannot divide by zero\");\n * }\n * return Ok(numerator / denominator);\n * }\n *\n * const result1 = divide(10, 2);\n * if (isOk(result1)) {\n * console.log(\"Success:\", result1.data); // Output: Success: 5\n * }\n *\n * const result2 = divide(10, 0);\n * if (isErr(result2)) {\n * console.error(\"Failure:\", result2.error); // Output: Failure: Cannot divide by zero\n * }\n * ```\n */\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/**\n * Constructs an `Ok<T>` variant, representing a successful outcome.\n *\n * This factory function creates the success variant of a `Result`.\n * It wraps the provided `data` (the success value) and ensures the `error` property is `null`.\n *\n * @template T - The type of the success value.\n * @param data - The success value to be wrapped in the `Ok` variant.\n * @returns An `Ok<T>` object with the provided data and `error` set to `null`.\n * @example\n * ```ts\n * const successfulResult = Ok(\"Operation completed successfully\");\n * // successfulResult is { data: \"Operation completed successfully\", error: null }\n * ```\n */\nexport const Ok = <T>(data: T): Ok<T> => ({ data, error: null });\n\n/**\n * Constructs an `Err<E>` variant, representing a failure outcome.\n *\n * Wraps the provided `error` (the failure value) and sets `data` to `null`.\n *\n * **Don't call `Err(null)`.** It produces `{ data: null, error: null }` —\n * structurally identical to `Ok(null)`. The built-in `isErr` check\n * (`result.error !== null`) reads it as Ok, silently misclassifying your\n * failure as success. `Err(undefined)` is also discouraged: the discriminator\n * technically works (`undefined !== null`), but `undefined` is falsy, so\n * downstream `if (error)` checks trip and the error carries no information\n * anyway. Pass a meaningful error value (a string, a tagged error from\n * `defineErrors`, an `Error` instance), or use `Ok(null)`/`Ok(undefined)` if\n * what you meant was success-with-no-payload.\n *\n * At `catch (error: unknown)` boundaries, wrap the caught value in a tagged\n * error rather than passing it through — `TaggedError.X({ cause: error })`\n * is always non-null by construction, so the discriminator works regardless\n * of what was thrown.\n *\n * See `docs/philosophy/err-null-is-ok-null.md` for the full rationale.\n *\n * @template E - The type of the error value.\n * @param error - The error value to wrap. Don't pass `null` or `undefined`.\n * @returns An `Err<E>` object with the provided error and `data` set to `null`.\n * @example\n * ```ts\n * const failedResult = Err(new TypeError(\"Invalid input\"));\n * // failedResult is { error: TypeError(\"Invalid input\"), data: null }\n * ```\n */\nexport const Err = <E>(error: E): Err<E> => ({ error, data: null });\n\n/**\n * Utility type to extract the success value's type `T` from a `Result<T, E>` type.\n *\n * If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),\n * this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `data` field when you know you have a success.\n *\n * @template R - The `Result<T, E>` type from which to extract the success value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number\n *\n * type MyErrorResult = Err<string>;\n * type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never\n * ```\n */\nexport type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U>\n\t? U\n\t: never;\n\n/**\n * Utility type to extract the error value's type `E` from a `Result<T, E>` type.\n *\n * If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),\n * this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `error` field when you know you have a failure.\n *\n * @template R - The `Result<T, E>` type from which to extract the error value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string\n *\n * type MySuccessResult = Ok<number>;\n * type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never\n * ```\n */\nexport type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<\n\tinfer E\n>\n\t? E\n\t: never;\n\n/**\n * Type guard to runtime check if an unknown value is a valid `Result<T, E>`.\n *\n * A value is considered a valid `Result` if:\n * 1. It is a non-null object.\n * 2. It has both `data` and `error` properties.\n * 3. At least one of the `data` or `error` channels is `null`. Both being `null` represents `Ok(null)`.\n *\n * This function does not validate the types of `data` or `error` beyond `null` checks.\n *\n * @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).\n * @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).\n * @param value - The value to check.\n * @returns `true` if the value conforms to the `Result` structure, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.\n * @example\n * ```ts\n * declare const someValue: unknown;\n *\n * if (isResult<string, Error>(someValue)) {\n * // someValue is now typed as Result<string, Error>\n * if (isOk(someValue)) {\n * console.log(someValue.data); // string\n * } else {\n * console.error(someValue.error); // Error\n * }\n * }\n * ```\n */\nexport function isResult<T = unknown, E = unknown>(\n\tvalue: unknown,\n): value is Result<T, E> {\n\tconst isNonNullObject = typeof value === \"object\" && value !== null;\n\tif (!isNonNullObject) return false;\n\n\tconst hasDataProperty = \"data\" in value;\n\tconst hasErrorProperty = \"error\" in value;\n\tif (!hasDataProperty || !hasErrorProperty) return false;\n\n\treturn true;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.\n *\n * This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.\n * An `Ok<T>` variant is identified by its `error` property being `null`.\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isOk(myResult)) {\n * // myResult is now typed as Ok<number>\n * console.log(\"Success value:\", myResult.data); // myResult.data is number\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T> {\n\treturn result.error === null;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.\n *\n * This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.\n * An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Err<E>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isErr(myResult)) {\n * // myResult is now typed as Err<string>\n * console.error(\"Error value:\", myResult.error); // myResult.error is string\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E> {\n\treturn result.error !== null; // Equivalent to result.data === null\n}\n\n/**\n * Executes a synchronous operation and wraps its outcome in a Result type.\n *\n * This function attempts to execute the `try` operation:\n * - If the `try` operation completes successfully, its return value is wrapped in an `Ok<T>` variant.\n * - If the `try` operation throws an exception, the caught exception (of type `unknown`) is passed to\n * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).\n *\n * The return type is automatically determined by what your catch function returns:\n * - If catch always returns `Ok<T>`, the return type collapses to `Ok<T>` (guaranteed success)\n * - If catch always returns `Err<E>`, the return type is `Ok<T> | Err<E>` (may succeed or fail)\n * - If catch returns a union like `Err<A> | Err<B>`, the return type is `Ok<T> | Err<A> | Err<B>` (union propagation)\n * - If catch can return either `Ok<T>` or `Err<E>`, the return type is `Ok<T> | Err<E>` (conditional recovery)\n *\n * @template T - The success value type\n * @template R - The return type of the catch handler (`Ok<T>` for recovery, `Err<E>` for propagation, or a union)\n * @param options - Configuration object\n * @param options.try - The operation to execute\n * @param options.catch - Error handler that transforms caught exceptions into either `Ok<T>` (recovery) or `Err<E>` (propagation)\n * @returns `Ok<T> | R` — the union of the success path and whatever the catch handler returns\n *\n * @example\n * ```ts\n * // Returns Ok<string> - guaranteed success since catch always returns Ok\n * const alwaysOk = trySync({\n * try: () => JSON.parse(input),\n * catch: () => Ok(\"fallback\") // Always Ok<T>\n * });\n *\n * // Returns Result<object, string> - may fail since catch always returns Err\n * const mayFail = trySync({\n * try: () => JSON.parse(input),\n * catch: (err) => Err(\"Parse failed\") // Returns Err<E>\n * });\n *\n * // Returns Result<void, MyError> - conditional recovery based on error type\n * const conditional = trySync({\n * try: () => riskyOperation(),\n * catch: (err) => {\n * if (isRecoverable(err)) return Ok(undefined);\n * return MyErr({ message: \"Unrecoverable\" });\n * }\n * });\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: required for union type inference in catch handlers\nexport function trySync<T, R extends Ok<T> | Err<any>>({\n\ttry: operation,\n\tcatch: catchFn,\n}: {\n\ttry: () => T;\n\tcatch: (error: unknown) => R;\n}): Ok<T> | R {\n\ttry {\n\t\tconst data = operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn catchFn(error);\n\t}\n}\n\n/**\n * Executes an asynchronous operation and wraps its outcome in a Promise<Result>.\n *\n * This function attempts to execute the `try` operation:\n * - If the `try` operation resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.\n * - If the `try` operation rejects or throws an exception, the caught error (of type `unknown`) is passed to\n * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).\n *\n * The return type is automatically determined by what your catch function returns:\n * - If catch always returns `Ok<T>`, the return type collapses to `Promise<Ok<T>>` (guaranteed success)\n * - If catch always returns `Err<E>`, the return type is `Promise<Ok<T> | Err<E>>` (may succeed or fail)\n * - If catch returns a union like `Err<A> | Err<B>`, the return type is `Promise<Ok<T> | Err<A> | Err<B>>` (union propagation)\n * - If catch can return either `Ok<T>` or `Err<E>`, the return type is `Promise<Ok<T> | Err<E>>` (conditional recovery)\n *\n * @template T - The success value type\n * @template R - The return type of the catch handler (`Ok<T>` for recovery, `Err<E>` for propagation, or a union)\n * @param options - Configuration object\n * @param options.try - The async operation to execute\n * @param options.catch - Error handler that transforms caught exceptions/rejections into either `Ok<T>` (recovery) or `Err<E>` (propagation)\n * @returns `Promise<Ok<T> | R>` — the union of the success path and whatever the catch handler returns\n *\n * @example\n * ```ts\n * // Returns Promise<Ok<Response>> - guaranteed success since catch always returns Ok\n * const alwaysOk = tryAsync({\n * try: async () => fetch(url),\n * catch: () => Ok(new Response()) // Always Ok<T>\n * });\n *\n * // Returns Promise<Result<Response, Error>> - may fail since catch always returns Err\n * const mayFail = tryAsync({\n * try: async () => fetch(url),\n * catch: (err) => Err(new Error(\"Fetch failed\")) // Returns Err<E>\n * });\n *\n * // Returns Promise<Result<void, BlobError>> - conditional recovery based on error type\n * const conditional = await tryAsync({\n * try: async () => {\n * await deleteFile(filename);\n * },\n * catch: (err) => {\n * if ((err as { name?: string }).name === 'NotFoundError') {\n * return Ok(undefined); // Already deleted, that's fine\n * }\n * return BlobErr({ message: \"Delete failed\" });\n * }\n * });\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: required for union type inference in catch handlers\nexport async function tryAsync<T, R extends Ok<T> | Err<any>>({\n\ttry: operation,\n\tcatch: catchFn,\n}: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => R;\n}): Promise<Ok<T> | R> {\n\ttry {\n\t\tconst data = await operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn catchFn(error);\n\t}\n}\n\n/**\n * Resolves a value that may or may not be wrapped in a `Result`, returning the final value.\n *\n * This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:\n * - If `value` is an `Ok<T>` variant, returns the contained success value.\n * - If `value` is an `Err<E>` variant, throws the contained error value.\n * - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),\n * returns it as-is.\n *\n * This is useful when working with APIs that might return either direct values or Results,\n * allowing you to normalize them to the actual value or propagate errors via throwing.\n *\n * Use `resolve` when the input might or might not be a Result.\n * Use `unwrap` when you know the input is definitely a Result.\n *\n * @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.\n * @template E - The type of the error value (if `value` is `Err<E>`).\n * @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.\n * @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.\n * @throws The error value `E` if `value` is an `Err<E>` variant.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const resolved = resolve(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"failure\"));\n * try {\n * resolve(errResult);\n * } catch (e) {\n * console.error(e.message); // \"failure\"\n * }\n *\n * // Example with a plain value\n * const plainValue = \"plain data\";\n * const resolved = resolve(plainValue); // \"plain data\"\n *\n * // Example with a function that might return Result or plain value\n * declare function mightReturnResult(): string | Result<string, Error>;\n * const outcome = mightReturnResult();\n * try {\n * const finalValue = resolve(outcome); // handles both cases\n * console.log(\"Final value:\", finalValue);\n * } catch (e) {\n * console.error(\"Operation failed:\", e);\n * }\n * ```\n */\n/**\n * Unwraps a `Result<T, E>`, returning the success value or throwing the error.\n *\n * This function extracts the data from a `Result`:\n * - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.\n * - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.\n *\n * Unlike `resolve`, this function expects the input to always be a `Result` type,\n * making it more direct for cases where you know you're working with a `Result`.\n *\n * @template T - The type of the success value contained in the `Ok<T>` variant.\n * @template E - The type of the error value contained in the `Err<E>` variant.\n * @param result - The `Result<T, E>` to unwrap.\n * @returns The success value of type `T` if the `Result` is `Ok<T>`.\n * @throws The error value of type `E` if the `Result` is `Err<E>`.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const value = unwrap(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"something went wrong\"));\n * try {\n * unwrap(errResult);\n * } catch (error) {\n * console.error(error.message); // \"something went wrong\"\n * }\n *\n * // Usage in a function that returns Result\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return Err(\"Division by zero\");\n * return Ok(a / b);\n * }\n *\n * try {\n * const result = unwrap(divide(10, 2)); // 5\n * console.log(\"Result:\", result);\n * } catch (error) {\n * console.error(\"Division failed:\", error);\n * }\n * ```\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n\tif (isOk(result)) {\n\t\treturn result.data;\n\t}\n\tthrow result.error;\n}\n\nexport function resolve<T, E>(value: T | Result<T, E>): T {\n\tif (isResult<T, E>(value)) {\n\t\tif (isOk(value)) {\n\t\t\treturn value.data;\n\t\t}\n\t\t// If it's a Result and not Ok, it must be Err.\n\t\t// The type guard isResult<T,E>(value) and isOk(value) already refine the type.\n\t\t// So, 'value' here is known to be Err<E>.\n\t\tthrow value.error;\n\t}\n\n\t// If it's not a Result type, return the value as-is.\n\t// 'value' here is known to be of type T.\n\treturn value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8EA,MAAa,KAAK,CAAIA,UAAoB;CAAE;CAAM,OAAO;AAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiC/D,MAAa,MAAM,CAAIC,WAAsB;CAAE;CAAO,MAAM;AAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ElE,SAAgB,SACfC,OACwB;CACxB,MAAM,yBAAyB,UAAU,YAAY,UAAU;AAC/D,MAAK,gBAAiB,QAAO;CAE7B,MAAM,kBAAkB,UAAU;CAClC,MAAM,mBAAmB,WAAW;AACpC,MAAK,oBAAoB,iBAAkB,QAAO;AAElD,QAAO;AACP;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,KAAWC,QAAuC;AACjE,QAAO,OAAO,UAAU;AACxB;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,MAAYA,QAAwC;AACnE,QAAO,OAAO,UAAU;AACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDD,SAAgB,QAAuC,EACtD,KAAK,WACL,OAAO,SAIP,EAAa;AACb,KAAI;EACH,MAAM,OAAO,WAAW;AACxB,SAAO,GAAG,KAAK;CACf,SAAQ,OAAO;AACf,SAAO,QAAQ,MAAM;CACrB;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDD,eAAsB,SAAwC,EAC7D,KAAK,WACL,OAAO,SAIP,EAAsB;AACtB,KAAI;EACH,MAAM,OAAO,MAAM,WAAW;AAC9B,SAAO,GAAG,KAAK;CACf,SAAQ,OAAO;AACf,SAAO,QAAQ,MAAM;CACrB;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGD,SAAgB,OAAaA,QAAyB;AACrD,KAAI,KAAK,OAAO,CACf,QAAO,OAAO;AAEf,OAAM,OAAO;AACb;AAED,SAAgB,QAAcC,OAA4B;AACzD,KAAI,SAAe,MAAM,EAAE;AAC1B,MAAI,KAAK,MAAM,CACd,QAAO,MAAM;AAKd,QAAM,MAAM;CACZ;AAID,QAAO;AACP"}
@@ -1,4 +1,4 @@
1
- import { isOk } from "./result-BRfWC87j.js";
1
+ import { isOk } from "./result-DzL3K2yA.js";
2
2
 
3
3
  //#region src/result/utils.ts
4
4
  /**
@@ -27,4 +27,4 @@ function partitionResults(results) {
27
27
 
28
28
  //#endregion
29
29
  export { partitionResults };
30
- //# sourceMappingURL=result-Cd0chHlN.js.map
30
+ //# sourceMappingURL=result-corfYKOe.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"result-Cd0chHlN.js","names":["results: Result<T, E>[]"],"sources":["../src/result/utils.ts"],"sourcesContent":["import type { Err, Ok, Result } from \"./result.js\";\nimport { isOk } from \"./result.js\";\n\n/**\n * Partitions an array of Result objects into two separate arrays based on their status.\n *\n * @template T - The success type\n * @template E - The error type\n * @param results - An array of Result objects to partition\n * @returns An object containing two arrays:\n * - `oks`: Array of successful Result objects (Ok<T>[])\n * - `errs`: Array of error Result objects (Err<E>[])\n *\n * @example\n * const results = [Ok(1), Err(\"error\"), Ok(2)];\n * const { oks, errs } = partitionResults(results);\n * // oks = [Ok(1), Ok(2)]\n * // errs = [Err(\"error\")]\n */\nexport function partitionResults<T, E>(results: Result<T, E>[]) {\n\treturn {\n\t\toks: [],\n\t\terrs: [],\n\t\t...Object.groupBy(results, (result) => (isOk(result) ? \"oks\" : \"errs\")),\n\t} as { oks: Ok<T>[]; errs: Err<E>[] };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,iBAAuBA,SAAyB;AAC/D,QAAO;EACN,KAAK,CAAE;EACP,MAAM,CAAE;EACR,GAAG,OAAO,QAAQ,SAAS,CAAC,WAAY,KAAK,OAAO,GAAG,QAAQ,OAAQ;CACvE;AACD"}
1
+ {"version":3,"file":"result-corfYKOe.js","names":["results: Result<T, E>[]"],"sources":["../src/result/utils.ts"],"sourcesContent":["import type { Err, Ok, Result } from \"./result.js\";\nimport { isOk } from \"./result.js\";\n\n/**\n * Partitions an array of Result objects into two separate arrays based on their status.\n *\n * @template T - The success type\n * @template E - The error type\n * @param results - An array of Result objects to partition\n * @returns An object containing two arrays:\n * - `oks`: Array of successful Result objects (Ok<T>[])\n * - `errs`: Array of error Result objects (Err<E>[])\n *\n * @example\n * const results = [Ok(1), Err(\"error\"), Ok(2)];\n * const { oks, errs } = partitionResults(results);\n * // oks = [Ok(1), Ok(2)]\n * // errs = [Err(\"error\")]\n */\nexport function partitionResults<T, E>(results: Result<T, E>[]) {\n\treturn {\n\t\toks: [],\n\t\terrs: [],\n\t\t...Object.groupBy(results, (result) => (isOk(result) ? \"oks\" : \"errs\")),\n\t} as { oks: Ok<T>[]; errs: Err<E>[] };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,iBAAuBA,SAAyB;AAC/D,QAAO;EACN,KAAK,CAAE;EACP,MAAM,CAAE;EACR,GAAG,OAAO,QAAQ,SAAS,CAAC,WAAY,KAAK,OAAO,GAAG,QAAQ,OAAQ;CACvE;AACD"}
@@ -0,0 +1,37 @@
1
+ import { isErr } from "./result-DzL3K2yA.js";
2
+
3
+ //#region src/result/tap-err.ts
4
+ /**
5
+ * Result-flow combinator. Logs on the `Err` branch and returns the `Result`
6
+ * unchanged. Mirrors Rust's `Result::inspect_err` and Effect's
7
+ * `tapErrorCause`.
8
+ *
9
+ * Takes a log **method**, not a whole logger. The caller picks the level at
10
+ * the pipeline site — the same typed error can be logged as `warn` inside a
11
+ * retry loop and as `error` on the last attempt, without the variant itself
12
+ * carrying level. This is the `tracing::warn!(?err)` vs
13
+ * `tracing::error!(?err)` idiom translated to Result-flow.
14
+ *
15
+ * No message argument. The typed error owns its message; a message
16
+ * parameter here would drift away from the variant's template over time.
17
+ *
18
+ * @example
19
+ * const result = await tryAsync({
20
+ * try: () => writeTable(path),
21
+ * catch: (cause) => MarkdownError.TableWrite({ path, cause }),
22
+ * }).then(tapErr(log.warn));
23
+ *
24
+ * @example Level chosen at call site
25
+ * await tryAttempt().then(tapErr(log.warn)); // inside retry
26
+ * await tryFinal().then(tapErr(log.error)); // last try, giving up
27
+ */
28
+ function tapErr(logFn) {
29
+ return (result) => {
30
+ if (isErr(result)) logFn(result.error);
31
+ return result;
32
+ };
33
+ }
34
+
35
+ //#endregion
36
+ export { tapErr };
37
+ //# sourceMappingURL=tap-err-Bf6rQ4Cw.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tap-err-Bf6rQ4Cw.js","names":["logFn: (err: E) => void"],"sources":["../src/result/tap-err.ts"],"sourcesContent":["import { isErr } from \"./result.js\";\nimport type { Result } from \"./result.js\";\n\n/**\n * Result-flow combinator. Logs on the `Err` branch and returns the `Result`\n * unchanged. Mirrors Rust's `Result::inspect_err` and Effect's\n * `tapErrorCause`.\n *\n * Takes a log **method**, not a whole logger. The caller picks the level at\n * the pipeline site — the same typed error can be logged as `warn` inside a\n * retry loop and as `error` on the last attempt, without the variant itself\n * carrying level. This is the `tracing::warn!(?err)` vs\n * `tracing::error!(?err)` idiom translated to Result-flow.\n *\n * No message argument. The typed error owns its message; a message\n * parameter here would drift away from the variant's template over time.\n *\n * @example\n * const result = await tryAsync({\n * try: () => writeTable(path),\n * catch: (cause) => MarkdownError.TableWrite({ path, cause }),\n * }).then(tapErr(log.warn));\n *\n * @example Level chosen at call site\n * await tryAttempt().then(tapErr(log.warn)); // inside retry\n * await tryFinal().then(tapErr(log.error)); // last try, giving up\n */\nexport function tapErr<T, E>(\n\tlogFn: (err: E) => void,\n): (result: Result<T, E>) => Result<T, E> {\n\treturn (result) => {\n\t\tif (isErr(result)) logFn(result.error);\n\t\treturn result;\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,OACfA,OACyC;AACzC,QAAO,CAAC,WAAW;AAClB,MAAI,MAAM,OAAO,CAAE,OAAM,OAAO,MAAM;AACtC,SAAO;CACP;AACD"}
@@ -0,0 +1,33 @@
1
+ import { Result } from "./result-BongGO2O.js";
2
+
3
+ //#region src/result/tap-err.d.ts
4
+
5
+ /**
6
+ * Result-flow combinator. Logs on the `Err` branch and returns the `Result`
7
+ * unchanged. Mirrors Rust's `Result::inspect_err` and Effect's
8
+ * `tapErrorCause`.
9
+ *
10
+ * Takes a log **method**, not a whole logger. The caller picks the level at
11
+ * the pipeline site — the same typed error can be logged as `warn` inside a
12
+ * retry loop and as `error` on the last attempt, without the variant itself
13
+ * carrying level. This is the `tracing::warn!(?err)` vs
14
+ * `tracing::error!(?err)` idiom translated to Result-flow.
15
+ *
16
+ * No message argument. The typed error owns its message; a message
17
+ * parameter here would drift away from the variant's template over time.
18
+ *
19
+ * @example
20
+ * const result = await tryAsync({
21
+ * try: () => writeTable(path),
22
+ * catch: (cause) => MarkdownError.TableWrite({ path, cause }),
23
+ * }).then(tapErr(log.warn));
24
+ *
25
+ * @example Level chosen at call site
26
+ * await tryAttempt().then(tapErr(log.warn)); // inside retry
27
+ * await tryFinal().then(tapErr(log.error)); // last try, giving up
28
+ */
29
+ declare function tapErr<T, E>(logFn: (err: E) => void): (result: Result<T, E>) => Result<T, E>;
30
+ //# sourceMappingURL=tap-err.d.ts.map
31
+ //#endregion
32
+ export { tapErr };
33
+ //# sourceMappingURL=tap-err-Bqs9aQpZ.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tap-err-Bqs9aQpZ.d.ts","names":[],"sources":["../src/result/tap-err.ts"],"sourcesContent":[],"mappings":";;;;;;AA2BA;;;;;;;;;AAEmC;;;;;;;;;;;;;iBAFnB,0BACF,sBACF,OAAO,GAAG,OAAO,OAAO,GAAG"}
@@ -0,0 +1,47 @@
1
+ import { Err } from "./result-BongGO2O.js";
2
+
3
+ //#region src/error/types.d.ts
4
+
5
+ /**
6
+ * Base type for any tagged error, used as a minimum constraint.
7
+ */
8
+ type AnyTaggedError = {
9
+ name: string;
10
+ message: string;
11
+ };
12
+ /**
13
+ * Constructor return must include `message: string`.
14
+ * JSON serializability is a convention, not enforced at the type level
15
+ * (optional fields produce `T | undefined` which breaks `JsonObject`).
16
+ */
17
+ type ErrorBody = {
18
+ message: string;
19
+ };
20
+ /**
21
+ * Per-key validation: tells the user exactly what `name` will be stamped as.
22
+ *
23
+ * `name` is stamped by the factory itself (`{ name: K } & ReturnType<fn>`);
24
+ * a user-provided `name` would be silently overwritten, so we error loudly.
25
+ */
26
+ type ValidateErrorBody<K extends string> = {
27
+ message: string;
28
+ name?: `The 'name' key is reserved as '${K}'. Remove it.`;
29
+ };
30
+ /** The config: each key is a variant name, each value is a constructor function. */
31
+ type ErrorsConfig = Record<string, (...args: any[]) => ErrorBody>;
32
+ /** Validates each config entry, injecting the key-specific `name` reservation message. */
33
+ type ValidatedConfig<T extends ErrorsConfig> = { [K in keyof T & string]: T[K] extends ((...args: infer A) => infer R) ? (...args: A) => R & ValidateErrorBody<K> : T[K] };
34
+ /** Single factory: takes constructor args, returns Err-wrapped error. */
35
+ type ErrorFactory<TName extends string, TFn extends (...args: any[]) => ErrorBody> = { [K in TName]: (...args: Parameters<TFn>) => Err<Readonly<{
36
+ name: TName;
37
+ } & ReturnType<TFn>>> };
38
+ type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
39
+ /** Return type of `defineErrors`. Maps each config key to its factory. */
40
+ type DefineErrorsReturn<TConfig extends ErrorsConfig> = UnionToIntersection<{ [K in keyof TConfig & string]: ErrorFactory<K, TConfig[K]> }[keyof TConfig & string]>;
41
+ /** Extract the error type from a single factory. */
42
+ type InferError<T> = T extends ((...args: any[]) => Err<infer R>) ? R : never;
43
+ /** Extract union of ALL error types from a defineErrors return. */
44
+ type InferErrors<T> = { [K in keyof T]: T[K] extends ((...args: any[]) => Err<infer R>) ? R : never }[keyof T];
45
+ //#endregion
46
+ export { AnyTaggedError, DefineErrorsReturn, ErrorBody, ErrorsConfig, InferError, InferErrors, ValidatedConfig };
47
+ //# sourceMappingURL=types-cY80Bw6u.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-cY80Bw6u.d.ts","names":[],"sources":["../src/error/types.ts"],"sourcesContent":[],"mappings":";;;;;;AAKA;AAWY,KAXA,cAAA,GAWS;EAQhB,IAAA,EAAA,MAAA;EAOO,OAAA,EAAA,MAAY;CAAA;;;AAAS;AAGjC;;AAAsC,KAlB1B,SAAA,GAkB0B;EAAY,OAErC,EAAA,MAAA;CAAC;;;;;;;KAZT,iBAcC,CAAA,UAAA,MAAA,CAAA,GAAA;EAAC,OAAA,EAAA,MAAA;EAIF,IAAA,CAAA,EAAA,kCAhBqC,CAgBzB,eAAA;CAAA;;AAKV,KAhBK,YAAA,GAAe,MAgBpB,CAAA,MAAA,EAAA,CAAA,GAAA,IAAA,EAAA,GAAA,EAAA,EAAA,GAhBuD,SAgBvD,CAAA;;AACI,KAdC,eAcD,CAAA,UAd2B,YAc3B,CAAA,GAAA,QACgB,MAbd,CAac,GAAA,MAAA,GAbD,CAaC,CAbC,CAaD,CAAA,UAAA,CAAA,GAAA,IAAA,EAAA,KAAA,EAAA,EAAA,GAAA,KAAA,EAAA,IAAA,CAAA,GAAA,IAAA,EAZb,CAYa,EAAA,GAZP,CAYO,GAZH,iBAYG,CAZe,CAYf,CAAA,GAXvB,CAWuB,CAXrB,CAWqB,CAAA,EAAK;;KAP3B,YAOK,CAAA,cAAA,MAAA,EAAA,YAAA,CAAA,GAAA,IAAA,EAAA,GAAA,EAAA,EAAA,GAJuB,SAIvB,CAAA,GAAA,QAFH,KAED,GAAA,CAAA,GAAA,IAAA,EADK,UACL,CADgB,GAChB,CAAA,EAAA,GAAA,GAAA,CAAI,QAAJ,CAAA;EAAG,IAAA,EAAkB,KAAlB;AAIJ,CAAA,GAJgC,UAIhC,CAJ2C,GAI3C,CAAA,CAAA,CAAA,EAAmB;KAAnB,mBAA0B,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,SAAA,GAAA,GAAA,CAAA,CAAA,EAAoB,CAApB,EAAA,GAAA,IAAA,GAAA,KAAA,CAAA,UAAA,CAAA,CAAA,EAAA,KAAA,EAAA,EAAA,GAAA,IAAA,IAG5B,CAH4B,GAAA,KAAA;;AAG5B,KAIS,kBAJT,CAAA,gBAI4C,YAJ5C,CAAA,GAKF,mBALE,CAAA,QAAC,MAOW,OAPX,GAAA,MAAA,GAO8B,YAP9B,CAO2C,CAP3C,EAO8C,OAP9C,CAOsD,CAPtD,CAAA,CAAA,EAIJ,CAAA,MAIU,OAJE,GAAA,MAAA,CAAkB,CAAA;;AAAiB,KAQnC,UARmC,CAAA,CAAA,CAAA,GAU9C,CAV8C,UAAA,CAAA,GAAA,IAAA,EAAA,GAAA,EAAA,EAAA,GAUhB,GAVgB,CAAA,KAAA,EAAA,CAAA,IAUD,CAVC,GAAA,KAAA;;AAGA,KAUnC,WAVmC,CAAA,CAAA,CAAA,GAAA,QAAG,MAYrC,CAZqC,GAYjC,CAZiC,CAY/B,CAZ+B,CAAA,UAAA,CAAA,GAAA,IAAA,EAAA,GAAA,EAAA,EAAA,GAYA,GAZA,CAAA,KAAA,EAAA,CAAA,IAYe,CAZf,GAAA,KAAA,EAAO,CAAA,MAajD,CAbkD,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wellcrafted",
3
- "version": "0.34.1",
3
+ "version": "0.35.0",
4
4
  "description": "Delightful TypeScript patterns for elegant, type-safe applications",
5
5
  "type": "module",
6
6
  "files": [
@@ -17,6 +17,10 @@
17
17
  "types": "./dist/error/index.d.ts",
18
18
  "import": "./dist/error/index.js"
19
19
  },
20
+ "./logger": {
21
+ "types": "./dist/logger/index.d.ts",
22
+ "import": "./dist/logger/index.js"
23
+ },
20
24
  "./json": {
21
25
  "types": "./dist/json.d.ts",
22
26
  "import": "./dist/json.js"
@@ -1 +0,0 @@
1
- {"version":3,"file":"result-BRfWC87j.js","names":["data: T","error: E","value: unknown","result: Result<T, E>","value: T | Result<T, E>"],"sources":["../src/result/result.ts"],"sourcesContent":["/**\n * Represents the successful outcome of an operation, encapsulating the success value.\n *\n * This is the 'Ok' variant of the `Result` type. It holds a `data` property\n * of type `T` (the success value) and an `error` property explicitly set to `null`,\n * signifying no error occurred.\n *\n * Use this type in conjunction with `Err<E>` and `Result<T, E>`.\n *\n * @template T - The type of the success value contained within.\n */\nexport type Ok<T> = { data: T; error: null };\n\n/**\n * Represents the failure outcome of an operation, encapsulating the error value.\n *\n * This is the 'Err' variant of the `Result` type. It holds an `error` property\n * of type `E` (the error value) and a `data` property explicitly set to `null`,\n * signifying that no success value is present due to the failure.\n *\n * Use this type in conjunction with `Ok<T>` and `Result<T, E>`.\n *\n * @template E - The type of the error value contained within.\n */\nexport type Err<E> = { error: E; data: null };\n\n/**\n * A type that represents the outcome of an operation that can either succeed or fail.\n *\n * `Result<T, E>` is a discriminated union type with two possible variants:\n * - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.\n * In this case, the `error` field is `null`.\n * - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.\n * In this case, the `data` field is `null`.\n *\n * This type promotes explicit error handling by requiring developers to check\n * the variant of the `Result` before accessing its potential value or error.\n * It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).\n *\n * @template T - The type of the success value if the operation is successful (held in `Ok<T>`).\n * @template E - The type of the error value if the operation fails (held in `Err<E>`).\n * @example\n * ```ts\n * function divide(numerator: number, denominator: number): Result<number, string> {\n * if (denominator === 0) {\n * return Err(\"Cannot divide by zero\");\n * }\n * return Ok(numerator / denominator);\n * }\n *\n * const result1 = divide(10, 2);\n * if (isOk(result1)) {\n * console.log(\"Success:\", result1.data); // Output: Success: 5\n * }\n *\n * const result2 = divide(10, 0);\n * if (isErr(result2)) {\n * console.error(\"Failure:\", result2.error); // Output: Failure: Cannot divide by zero\n * }\n * ```\n */\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/**\n * Constructs an `Ok<T>` variant, representing a successful outcome.\n *\n * This factory function creates the success variant of a `Result`.\n * It wraps the provided `data` (the success value) and ensures the `error` property is `null`.\n *\n * @template T - The type of the success value.\n * @param data - The success value to be wrapped in the `Ok` variant.\n * @returns An `Ok<T>` object with the provided data and `error` set to `null`.\n * @example\n * ```ts\n * const successfulResult = Ok(\"Operation completed successfully\");\n * // successfulResult is { data: \"Operation completed successfully\", error: null }\n * ```\n */\nexport const Ok = <T>(data: T): Ok<T> => ({ data, error: null });\n\n/**\n * Constructs an `Err<E>` variant, representing a failure outcome.\n *\n * This factory function creates the error variant of a `Result`.\n * It wraps the provided `error` (the error value) and ensures the `data` property is `null`.\n *\n * @template E - The type of the error value.\n * @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.\n * @returns An `Err<E>` object with the provided error and `data` set to `null`.\n * @example\n * ```ts\n * const failedResult = Err(new TypeError(\"Invalid input\"));\n * // failedResult is { error: TypeError(\"Invalid input\"), data: null }\n * ```\n */\nexport const Err = <E>(error: E): Err<E> => ({ error, data: null });\n\n/**\n * Utility type to extract the success value's type `T` from a `Result<T, E>` type.\n *\n * If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),\n * this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `data` field when you know you have a success.\n *\n * @template R - The `Result<T, E>` type from which to extract the success value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number\n *\n * type MyErrorResult = Err<string>;\n * type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never\n * ```\n */\nexport type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U>\n\t? U\n\t: never;\n\n/**\n * Utility type to extract the error value's type `E` from a `Result<T, E>` type.\n *\n * If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),\n * this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `error` field when you know you have a failure.\n *\n * @template R - The `Result<T, E>` type from which to extract the error value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string\n *\n * type MySuccessResult = Ok<number>;\n * type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never\n * ```\n */\nexport type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<\n\tinfer E\n>\n\t? E\n\t: never;\n\n/**\n * Type guard to runtime check if an unknown value is a valid `Result<T, E>`.\n *\n * A value is considered a valid `Result` if:\n * 1. It is a non-null object.\n * 2. It has both `data` and `error` properties.\n * 3. At least one of the `data` or `error` channels is `null`. Both being `null` represents `Ok(null)`.\n *\n * This function does not validate the types of `data` or `error` beyond `null` checks.\n *\n * @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).\n * @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).\n * @param value - The value to check.\n * @returns `true` if the value conforms to the `Result` structure, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.\n * @example\n * ```ts\n * declare const someValue: unknown;\n *\n * if (isResult<string, Error>(someValue)) {\n * // someValue is now typed as Result<string, Error>\n * if (isOk(someValue)) {\n * console.log(someValue.data); // string\n * } else {\n * console.error(someValue.error); // Error\n * }\n * }\n * ```\n */\nexport function isResult<T = unknown, E = unknown>(\n\tvalue: unknown,\n): value is Result<T, E> {\n\tconst isNonNullObject = typeof value === \"object\" && value !== null;\n\tif (!isNonNullObject) return false;\n\n\tconst hasDataProperty = \"data\" in value;\n\tconst hasErrorProperty = \"error\" in value;\n\tif (!hasDataProperty || !hasErrorProperty) return false;\n\n\treturn true;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.\n *\n * This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.\n * An `Ok<T>` variant is identified by its `error` property being `null`.\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isOk(myResult)) {\n * // myResult is now typed as Ok<number>\n * console.log(\"Success value:\", myResult.data); // myResult.data is number\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T> {\n\treturn result.error === null;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.\n *\n * This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.\n * An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Err<E>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isErr(myResult)) {\n * // myResult is now typed as Err<string>\n * console.error(\"Error value:\", myResult.error); // myResult.error is string\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E> {\n\treturn result.error !== null; // Equivalent to result.data === null\n}\n\n/**\n * Executes a synchronous operation and wraps its outcome in a Result type.\n *\n * This function attempts to execute the `try` operation:\n * - If the `try` operation completes successfully, its return value is wrapped in an `Ok<T>` variant.\n * - If the `try` operation throws an exception, the caught exception (of type `unknown`) is passed to\n * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).\n *\n * The return type is automatically determined by what your catch function returns:\n * - If catch always returns `Ok<T>`, the return type collapses to `Ok<T>` (guaranteed success)\n * - If catch always returns `Err<E>`, the return type is `Ok<T> | Err<E>` (may succeed or fail)\n * - If catch returns a union like `Err<A> | Err<B>`, the return type is `Ok<T> | Err<A> | Err<B>` (union propagation)\n * - If catch can return either `Ok<T>` or `Err<E>`, the return type is `Ok<T> | Err<E>` (conditional recovery)\n *\n * @template T - The success value type\n * @template R - The return type of the catch handler (`Ok<T>` for recovery, `Err<E>` for propagation, or a union)\n * @param options - Configuration object\n * @param options.try - The operation to execute\n * @param options.catch - Error handler that transforms caught exceptions into either `Ok<T>` (recovery) or `Err<E>` (propagation)\n * @returns `Ok<T> | R` — the union of the success path and whatever the catch handler returns\n *\n * @example\n * ```ts\n * // Returns Ok<string> - guaranteed success since catch always returns Ok\n * const alwaysOk = trySync({\n * try: () => JSON.parse(input),\n * catch: () => Ok(\"fallback\") // Always Ok<T>\n * });\n *\n * // Returns Result<object, string> - may fail since catch always returns Err\n * const mayFail = trySync({\n * try: () => JSON.parse(input),\n * catch: (err) => Err(\"Parse failed\") // Returns Err<E>\n * });\n *\n * // Returns Result<void, MyError> - conditional recovery based on error type\n * const conditional = trySync({\n * try: () => riskyOperation(),\n * catch: (err) => {\n * if (isRecoverable(err)) return Ok(undefined);\n * return MyErr({ message: \"Unrecoverable\" });\n * }\n * });\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: required for union type inference in catch handlers\nexport function trySync<T, R extends Ok<T> | Err<any>>({\n\ttry: operation,\n\tcatch: catchFn,\n}: {\n\ttry: () => T;\n\tcatch: (error: unknown) => R;\n}): Ok<T> | R {\n\ttry {\n\t\tconst data = operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn catchFn(error);\n\t}\n}\n\n/**\n * Executes an asynchronous operation and wraps its outcome in a Promise<Result>.\n *\n * This function attempts to execute the `try` operation:\n * - If the `try` operation resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.\n * - If the `try` operation rejects or throws an exception, the caught error (of type `unknown`) is passed to\n * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).\n *\n * The return type is automatically determined by what your catch function returns:\n * - If catch always returns `Ok<T>`, the return type collapses to `Promise<Ok<T>>` (guaranteed success)\n * - If catch always returns `Err<E>`, the return type is `Promise<Ok<T> | Err<E>>` (may succeed or fail)\n * - If catch returns a union like `Err<A> | Err<B>`, the return type is `Promise<Ok<T> | Err<A> | Err<B>>` (union propagation)\n * - If catch can return either `Ok<T>` or `Err<E>`, the return type is `Promise<Ok<T> | Err<E>>` (conditional recovery)\n *\n * @template T - The success value type\n * @template R - The return type of the catch handler (`Ok<T>` for recovery, `Err<E>` for propagation, or a union)\n * @param options - Configuration object\n * @param options.try - The async operation to execute\n * @param options.catch - Error handler that transforms caught exceptions/rejections into either `Ok<T>` (recovery) or `Err<E>` (propagation)\n * @returns `Promise<Ok<T> | R>` — the union of the success path and whatever the catch handler returns\n *\n * @example\n * ```ts\n * // Returns Promise<Ok<Response>> - guaranteed success since catch always returns Ok\n * const alwaysOk = tryAsync({\n * try: async () => fetch(url),\n * catch: () => Ok(new Response()) // Always Ok<T>\n * });\n *\n * // Returns Promise<Result<Response, Error>> - may fail since catch always returns Err\n * const mayFail = tryAsync({\n * try: async () => fetch(url),\n * catch: (err) => Err(new Error(\"Fetch failed\")) // Returns Err<E>\n * });\n *\n * // Returns Promise<Result<void, BlobError>> - conditional recovery based on error type\n * const conditional = await tryAsync({\n * try: async () => {\n * await deleteFile(filename);\n * },\n * catch: (err) => {\n * if ((err as { name?: string }).name === 'NotFoundError') {\n * return Ok(undefined); // Already deleted, that's fine\n * }\n * return BlobErr({ message: \"Delete failed\" });\n * }\n * });\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: required for union type inference in catch handlers\nexport async function tryAsync<T, R extends Ok<T> | Err<any>>({\n\ttry: operation,\n\tcatch: catchFn,\n}: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => R;\n}): Promise<Ok<T> | R> {\n\ttry {\n\t\tconst data = await operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn catchFn(error);\n\t}\n}\n\n/**\n * Resolves a value that may or may not be wrapped in a `Result`, returning the final value.\n *\n * This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:\n * - If `value` is an `Ok<T>` variant, returns the contained success value.\n * - If `value` is an `Err<E>` variant, throws the contained error value.\n * - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),\n * returns it as-is.\n *\n * This is useful when working with APIs that might return either direct values or Results,\n * allowing you to normalize them to the actual value or propagate errors via throwing.\n *\n * Use `resolve` when the input might or might not be a Result.\n * Use `unwrap` when you know the input is definitely a Result.\n *\n * @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.\n * @template E - The type of the error value (if `value` is `Err<E>`).\n * @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.\n * @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.\n * @throws The error value `E` if `value` is an `Err<E>` variant.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const resolved = resolve(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"failure\"));\n * try {\n * resolve(errResult);\n * } catch (e) {\n * console.error(e.message); // \"failure\"\n * }\n *\n * // Example with a plain value\n * const plainValue = \"plain data\";\n * const resolved = resolve(plainValue); // \"plain data\"\n *\n * // Example with a function that might return Result or plain value\n * declare function mightReturnResult(): string | Result<string, Error>;\n * const outcome = mightReturnResult();\n * try {\n * const finalValue = resolve(outcome); // handles both cases\n * console.log(\"Final value:\", finalValue);\n * } catch (e) {\n * console.error(\"Operation failed:\", e);\n * }\n * ```\n */\n/**\n * Unwraps a `Result<T, E>`, returning the success value or throwing the error.\n *\n * This function extracts the data from a `Result`:\n * - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.\n * - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.\n *\n * Unlike `resolve`, this function expects the input to always be a `Result` type,\n * making it more direct for cases where you know you're working with a `Result`.\n *\n * @template T - The type of the success value contained in the `Ok<T>` variant.\n * @template E - The type of the error value contained in the `Err<E>` variant.\n * @param result - The `Result<T, E>` to unwrap.\n * @returns The success value of type `T` if the `Result` is `Ok<T>`.\n * @throws The error value of type `E` if the `Result` is `Err<E>`.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const value = unwrap(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"something went wrong\"));\n * try {\n * unwrap(errResult);\n * } catch (error) {\n * console.error(error.message); // \"something went wrong\"\n * }\n *\n * // Usage in a function that returns Result\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return Err(\"Division by zero\");\n * return Ok(a / b);\n * }\n *\n * try {\n * const result = unwrap(divide(10, 2)); // 5\n * console.log(\"Result:\", result);\n * } catch (error) {\n * console.error(\"Division failed:\", error);\n * }\n * ```\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n\tif (isOk(result)) {\n\t\treturn result.data;\n\t}\n\tthrow result.error;\n}\n\nexport function resolve<T, E>(value: T | Result<T, E>): T {\n\tif (isResult<T, E>(value)) {\n\t\tif (isOk(value)) {\n\t\t\treturn value.data;\n\t\t}\n\t\t// If it's a Result and not Ok, it must be Err.\n\t\t// The type guard isResult<T,E>(value) and isOk(value) already refine the type.\n\t\t// So, 'value' here is known to be Err<E>.\n\t\tthrow value.error;\n\t}\n\n\t// If it's not a Result type, return the value as-is.\n\t// 'value' here is known to be of type T.\n\treturn value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8EA,MAAa,KAAK,CAAIA,UAAoB;CAAE;CAAM,OAAO;AAAM;;;;;;;;;;;;;;;;AAiB/D,MAAa,MAAM,CAAIC,WAAsB;CAAE;CAAO,MAAM;AAAM;;;;;;;;;;;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