@nicolastoulemont/std 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +232 -33
- package/dist/adt/index.d.mts +2 -2
- package/dist/adt/index.mjs +1 -1
- package/dist/adt-DajUZvJe.mjs +2 -0
- package/dist/adt-DajUZvJe.mjs.map +1 -0
- package/dist/brand/index.d.mts +2 -2
- package/dist/brand/index.mjs +1 -1
- package/dist/brand-Bia3Vj6l.mjs +2 -0
- package/dist/brand-Bia3Vj6l.mjs.map +1 -0
- package/dist/context/index.d.mts +2 -0
- package/dist/context/index.mjs +1 -0
- package/dist/context-CCHj1nab.mjs +2 -0
- package/dist/context-CCHj1nab.mjs.map +1 -0
- package/dist/context-r8ESJiFn.d.mts +176 -0
- package/dist/context-r8ESJiFn.d.mts.map +1 -0
- package/dist/data/index.d.mts +2 -2
- package/dist/data/index.mjs +1 -1
- package/dist/data-BLXO4XwS.mjs +2 -0
- package/dist/data-BLXO4XwS.mjs.map +1 -0
- package/dist/data.tagged-error.types-CGiKD-ES.d.mts +29 -0
- package/dist/data.tagged-error.types-CGiKD-ES.d.mts.map +1 -0
- package/dist/{discriminator.types-9PxvrZki.d.mts → discriminator.types-CTURejXz.d.mts} +1 -1
- package/dist/discriminator.types-CTURejXz.d.mts.map +1 -0
- package/dist/dual-CZhzZslG.mjs +2 -0
- package/dist/dual-CZhzZslG.mjs.map +1 -0
- package/dist/either/index.d.mts +2 -2
- package/dist/either/index.mjs +1 -1
- package/dist/either-BMLPfvMl.mjs +2 -0
- package/dist/either-BMLPfvMl.mjs.map +1 -0
- package/dist/{equality-CD4_A1Op.mjs → equality-CoyUHWh9.mjs} +1 -1
- package/dist/{equality-CD4_A1Op.mjs.map → equality-CoyUHWh9.mjs.map} +1 -1
- package/dist/{flow-CYjiodlC.mjs → flow-D8_tllWl.mjs} +1 -1
- package/dist/flow-D8_tllWl.mjs.map +1 -0
- package/dist/functions/index.d.mts +2 -0
- package/dist/functions/index.mjs +1 -0
- package/dist/functions-BkevX2Dw.mjs +2 -0
- package/dist/functions-BkevX2Dw.mjs.map +1 -0
- package/dist/fx/index.d.mts +2 -3
- package/dist/fx/index.mjs +1 -1
- package/dist/fx-K-a9Smhn.mjs +2 -0
- package/dist/fx-K-a9Smhn.mjs.map +1 -0
- package/dist/fx.runtime-DclEDyjY.mjs +2 -0
- package/dist/fx.runtime-DclEDyjY.mjs.map +1 -0
- package/dist/{fx.types-CDVjDn_3.mjs → fx.types-Bg-Mmdm5.mjs} +1 -1
- package/dist/fx.types-Bg-Mmdm5.mjs.map +1 -0
- package/dist/{fx.types-B34asVRX.d.mts → fx.types-DeEWEltG.d.mts} +2 -2
- package/dist/{fx.types-B34asVRX.d.mts.map → fx.types-DeEWEltG.d.mts.map} +1 -1
- package/dist/index-7Lv982Om.d.mts +217 -0
- package/dist/index-7Lv982Om.d.mts.map +1 -0
- package/dist/{index-CklRfom5.d.mts → index-B1-tBzc0.d.mts} +263 -368
- package/dist/index-B1-tBzc0.d.mts.map +1 -0
- package/dist/index-BNQ9xSAz.d.mts +464 -0
- package/dist/index-BNQ9xSAz.d.mts.map +1 -0
- package/dist/index-B_iY5tq0.d.mts +241 -0
- package/dist/index-B_iY5tq0.d.mts.map +1 -0
- package/dist/index-B_wWGszy.d.mts +129 -0
- package/dist/index-B_wWGszy.d.mts.map +1 -0
- package/dist/index-BiiE8NS7.d.mts +108 -0
- package/dist/index-BiiE8NS7.d.mts.map +1 -0
- package/dist/index-By6dNRc4.d.mts +277 -0
- package/dist/index-By6dNRc4.d.mts.map +1 -0
- package/dist/{index-BzYtgdX0.d.mts → index-CGiLfREk.d.mts} +123 -16
- package/dist/index-CGiLfREk.d.mts.map +1 -0
- package/dist/index-CUZn-ohG.d.mts +490 -0
- package/dist/index-CUZn-ohG.d.mts.map +1 -0
- package/dist/index-Cq2IFito.d.mts +121 -0
- package/dist/index-Cq2IFito.d.mts.map +1 -0
- package/dist/{index-B2l8_CiD.d.mts → index-DEAWPlcI.d.mts} +155 -216
- package/dist/index-DEAWPlcI.d.mts.map +1 -0
- package/dist/{index-C4v_3f3-.d.mts → index-DKS1g1oC.d.mts} +95 -42
- package/dist/index-DKS1g1oC.d.mts.map +1 -0
- package/dist/{index-jeC5jyRh.d.mts → index-DXbYlSnB.d.mts} +64 -101
- package/dist/index-DXbYlSnB.d.mts.map +1 -0
- package/dist/{index-CjZ95Dsv.d.mts → index-UzMbg1dh.d.mts} +188 -202
- package/dist/index-UzMbg1dh.d.mts.map +1 -0
- package/dist/index.d.mts +23 -16
- package/dist/index.mjs +1 -1
- package/dist/layer/index.d.mts +2 -0
- package/dist/layer/index.mjs +1 -0
- package/dist/layer-BttmtDrs.mjs +2 -0
- package/dist/layer-BttmtDrs.mjs.map +1 -0
- package/dist/layer.types-DgpCIsk_.d.mts +100 -0
- package/dist/layer.types-DgpCIsk_.d.mts.map +1 -0
- package/dist/multithread/index.d.mts +2 -0
- package/dist/multithread/index.mjs +1 -0
- package/dist/multithread-xUUh4eLn.mjs +19 -0
- package/dist/multithread-xUUh4eLn.mjs.map +1 -0
- package/dist/option/index.d.mts +2 -3
- package/dist/option/index.mjs +1 -1
- package/dist/option-Tfbo4wty.mjs +2 -0
- package/dist/option-Tfbo4wty.mjs.map +1 -0
- package/dist/option.types-D1mm0zUb.mjs +2 -0
- package/dist/option.types-D1mm0zUb.mjs.map +1 -0
- package/dist/{option.types-ClJiBTdg.d.mts → option.types-qPevEZQd.d.mts} +7 -12
- package/dist/option.types-qPevEZQd.d.mts.map +1 -0
- package/dist/order/index.d.mts +2 -0
- package/dist/order/index.mjs +1 -0
- package/dist/order-D5c4QChk.mjs +2 -0
- package/dist/order-D5c4QChk.mjs.map +1 -0
- package/dist/pipeable-COGyGMUV.mjs +2 -0
- package/dist/pipeable-COGyGMUV.mjs.map +1 -0
- package/dist/{pipeable-B4YJA56p.d.mts → pipeable-rfqacPxZ.d.mts} +2 -9
- package/dist/{pipeable-B4YJA56p.d.mts.map → pipeable-rfqacPxZ.d.mts.map} +1 -1
- package/dist/predicate/index.d.mts +2 -2
- package/dist/predicate/index.mjs +1 -1
- package/dist/predicate-DUhhQqWY.mjs +2 -0
- package/dist/predicate-DUhhQqWY.mjs.map +1 -0
- package/dist/provide/index.d.mts +2 -0
- package/dist/provide/index.mjs +1 -0
- package/dist/provide-C2cWOx2B.mjs +2 -0
- package/dist/provide-C2cWOx2B.mjs.map +1 -0
- package/dist/queue/index.d.mts +2 -0
- package/dist/queue/index.mjs +1 -0
- package/dist/queue-Sg6KJerl.mjs +2 -0
- package/dist/queue-Sg6KJerl.mjs.map +1 -0
- package/dist/queue.types-CD2LOu37.d.mts +36 -0
- package/dist/queue.types-CD2LOu37.d.mts.map +1 -0
- package/dist/result/index.d.mts +2 -3
- package/dist/result/index.mjs +1 -1
- package/dist/result-BEzV0DYC.mjs +2 -0
- package/dist/result-BEzV0DYC.mjs.map +1 -0
- package/dist/{result.types-HHDzgSTV.d.mts → result.types-_xDAei3-.d.mts} +5 -97
- package/dist/result.types-_xDAei3-.d.mts.map +1 -0
- package/dist/schedule/index.d.mts +2 -0
- package/dist/schedule/index.mjs +1 -0
- package/dist/schedule-C6tjcJ1O.mjs +2 -0
- package/dist/schedule-C6tjcJ1O.mjs.map +1 -0
- package/dist/schedule-DlX2Dg69.d.mts +144 -0
- package/dist/schedule-DlX2Dg69.d.mts.map +1 -0
- package/dist/scope/index.d.mts +2 -0
- package/dist/scope/index.mjs +1 -0
- package/dist/scope-CZdp4wKX.d.mts +79 -0
- package/dist/scope-CZdp4wKX.d.mts.map +1 -0
- package/dist/scope-D_kzd1nT.mjs +2 -0
- package/dist/scope-D_kzd1nT.mjs.map +1 -0
- package/dist/service/index.d.mts +2 -0
- package/dist/service/index.mjs +1 -0
- package/dist/service-3PYQTUdH.mjs +2 -0
- package/dist/service-3PYQTUdH.mjs.map +1 -0
- package/dist/service-DrXU7KJG.d.mts +69 -0
- package/dist/service-DrXU7KJG.d.mts.map +1 -0
- package/dist/service-resolution-C19smeaO.mjs +2 -0
- package/dist/service-resolution-C19smeaO.mjs.map +1 -0
- package/package.json +50 -12
- package/dist/adt-CkRcY_GA.mjs +0 -2
- package/dist/adt-CkRcY_GA.mjs.map +0 -1
- package/dist/apply-fn.types-0g_9eXRy.d.mts +0 -8
- package/dist/apply-fn.types-0g_9eXRy.d.mts.map +0 -1
- package/dist/brand-Gy0kW6-n.mjs +0 -2
- package/dist/brand-Gy0kW6-n.mjs.map +0 -1
- package/dist/data-C0_3MGwm.mjs +0 -2
- package/dist/data-C0_3MGwm.mjs.map +0 -1
- package/dist/discriminator.types-9PxvrZki.d.mts.map +0 -1
- package/dist/either-CPzK-s8W.mjs +0 -2
- package/dist/either-CPzK-s8W.mjs.map +0 -1
- package/dist/err/index.d.mts +0 -2
- package/dist/err/index.mjs +0 -1
- package/dist/err-3KpQ4pj9.mjs +0 -2
- package/dist/err-3KpQ4pj9.mjs.map +0 -1
- package/dist/flow/index.d.mts +0 -2
- package/dist/flow/index.mjs +0 -1
- package/dist/flow-CYjiodlC.mjs.map +0 -1
- package/dist/fx-vqywVJhV.mjs +0 -2
- package/dist/fx-vqywVJhV.mjs.map +0 -1
- package/dist/fx.types-CDVjDn_3.mjs.map +0 -1
- package/dist/index-8Ne4GdOG.d.mts +0 -288
- package/dist/index-8Ne4GdOG.d.mts.map +0 -1
- package/dist/index-B2l8_CiD.d.mts.map +0 -1
- package/dist/index-BOrJQBPO.d.mts +0 -80
- package/dist/index-BOrJQBPO.d.mts.map +0 -1
- package/dist/index-BsXtpnw-.d.mts +0 -225
- package/dist/index-BsXtpnw-.d.mts.map +0 -1
- package/dist/index-BzYtgdX0.d.mts.map +0 -1
- package/dist/index-C4v_3f3-.d.mts.map +0 -1
- package/dist/index-CjZ95Dsv.d.mts.map +0 -1
- package/dist/index-CklRfom5.d.mts.map +0 -1
- package/dist/index-DZdmFtjA.d.mts +0 -79
- package/dist/index-DZdmFtjA.d.mts.map +0 -1
- package/dist/index-a4MEBZZ1.d.mts +0 -850
- package/dist/index-a4MEBZZ1.d.mts.map +0 -1
- package/dist/index-jeC5jyRh.d.mts.map +0 -1
- package/dist/option-DawZC1cE.mjs +0 -2
- package/dist/option-DawZC1cE.mjs.map +0 -1
- package/dist/option.types-ClJiBTdg.d.mts.map +0 -1
- package/dist/pipe/index.d.mts +0 -2
- package/dist/pipe/index.mjs +0 -1
- package/dist/pipe-BPpJyZf7.mjs +0 -2
- package/dist/pipe-BPpJyZf7.mjs.map +0 -1
- package/dist/pipeable-BA0mXhs4.mjs +0 -2
- package/dist/pipeable-BA0mXhs4.mjs.map +0 -1
- package/dist/predicate-Cy_oHA1Q.mjs +0 -2
- package/dist/predicate-Cy_oHA1Q.mjs.map +0 -1
- package/dist/result-CgGYLp0L.mjs +0 -2
- package/dist/result-CgGYLp0L.mjs.map +0 -1
- package/dist/result.types-HHDzgSTV.d.mts.map +0 -1
- /package/dist/{chunk-DAexk1S7.mjs → chunk-C934ptG5.mjs} +0 -0
- /package/dist/{option-Bb-taghv.mjs → option-CBCwzF0L.mjs} +0 -0
- /package/dist/{result-fiJhwVGz.mjs → result-B5WbPg8C.mjs} +0 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
declare namespace schedule_d_exports {
|
|
2
|
+
export { AsyncRetrySchedule, RetrySchedule, SyncRetrySchedule, exponential, fixed, recurs };
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Retry schedule constructors used by `Fx.retry`.
|
|
6
|
+
*
|
|
7
|
+
* **Mental model**
|
|
8
|
+
* - A schedule defines retry count and per-attempt delay.
|
|
9
|
+
* - Sync schedules have no async delay requirements.
|
|
10
|
+
*
|
|
11
|
+
* **Common tasks**
|
|
12
|
+
* - Use `Schedule.recurs` for immediate retries.
|
|
13
|
+
* - Use `Schedule.fixed` for constant-delay retries.
|
|
14
|
+
* - Use `Schedule.exponential` for backoff.
|
|
15
|
+
*
|
|
16
|
+
* **Gotchas**
|
|
17
|
+
* - `times` is the number of retries after the first attempt.
|
|
18
|
+
* - Delay values must be finite and non-negative.
|
|
19
|
+
*
|
|
20
|
+
* **Quickstart**
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* import { Schedule } from "@nicolastoulemont/std"
|
|
25
|
+
*
|
|
26
|
+
* const schedule = Schedule.recurs(2)
|
|
27
|
+
* const delay = schedule.delayForAttempt(1)
|
|
28
|
+
* // => 0
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @module
|
|
32
|
+
*/
|
|
33
|
+
/**
|
|
34
|
+
* Retry schedule used by Fx.retry.
|
|
35
|
+
*
|
|
36
|
+
* A schedule defines:
|
|
37
|
+
* - how many retries are allowed after the first attempt
|
|
38
|
+
* - how long to wait before each retry attempt
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* import { Schedule } from "@nicolastoulemont/std"
|
|
43
|
+
*
|
|
44
|
+
* type Example = typeof Schedule
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* @category Models
|
|
48
|
+
*/
|
|
49
|
+
type RetrySchedule = SyncRetrySchedule | AsyncRetrySchedule;
|
|
50
|
+
/**
|
|
51
|
+
* Schedule that never introduces async delays.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```ts
|
|
55
|
+
* import { Schedule } from "@nicolastoulemont/std"
|
|
56
|
+
*
|
|
57
|
+
* type Example = typeof Schedule
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
* @category Models
|
|
61
|
+
*/
|
|
62
|
+
type SyncRetrySchedule = {
|
|
63
|
+
readonly _tag: "RetrySchedule";
|
|
64
|
+
readonly _sync: true;
|
|
65
|
+
readonly maxRetries: number;
|
|
66
|
+
readonly delayForAttempt: (retryAttempt: number) => number;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Schedule that may delay retries, requiring async execution.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```ts
|
|
73
|
+
* import { Schedule } from "@nicolastoulemont/std"
|
|
74
|
+
*
|
|
75
|
+
* type Example = typeof Schedule
|
|
76
|
+
* ```
|
|
77
|
+
*
|
|
78
|
+
* @category Models
|
|
79
|
+
*/
|
|
80
|
+
type AsyncRetrySchedule = {
|
|
81
|
+
readonly _tag: "RetrySchedule";
|
|
82
|
+
readonly _sync: false;
|
|
83
|
+
readonly maxRetries: number;
|
|
84
|
+
readonly delayForAttempt: (retryAttempt: number) => number;
|
|
85
|
+
};
|
|
86
|
+
type FixedScheduleOptions = {
|
|
87
|
+
readonly times: number;
|
|
88
|
+
readonly delayMs: number;
|
|
89
|
+
};
|
|
90
|
+
type ExponentialScheduleOptions = {
|
|
91
|
+
readonly times: number;
|
|
92
|
+
readonly baseDelayMs: number;
|
|
93
|
+
readonly factor?: number | undefined;
|
|
94
|
+
readonly maxDelayMs?: number | undefined;
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* Retry immediately up to `times` times.
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* ```ts
|
|
101
|
+
* import { Schedule } from "@nicolastoulemont/std"
|
|
102
|
+
*
|
|
103
|
+
* const schedule = Schedule.recurs(2)
|
|
104
|
+
* const delay = schedule.delayForAttempt(1)
|
|
105
|
+
* // => 0
|
|
106
|
+
* ```
|
|
107
|
+
*
|
|
108
|
+
* @category Constructors
|
|
109
|
+
*/
|
|
110
|
+
declare const recurs: (times: number) => SyncRetrySchedule;
|
|
111
|
+
/**
|
|
112
|
+
* Retry with a fixed delay between attempts.
|
|
113
|
+
*
|
|
114
|
+
* @example
|
|
115
|
+
* ```ts
|
|
116
|
+
* import { Schedule } from "@nicolastoulemont/std"
|
|
117
|
+
*
|
|
118
|
+
* const schedule = Schedule.fixed({ times: 2, delayMs: 100 })
|
|
119
|
+
* const delay = schedule.delayForAttempt(2)
|
|
120
|
+
* // => 100
|
|
121
|
+
* ```
|
|
122
|
+
*
|
|
123
|
+
* @category Constructors
|
|
124
|
+
*/
|
|
125
|
+
declare const fixed: (options: FixedScheduleOptions) => AsyncRetrySchedule;
|
|
126
|
+
/**
|
|
127
|
+
* Retry with exponential backoff:
|
|
128
|
+
* `baseDelayMs * factor^(retryAttempt - 1)`, optionally capped by `maxDelayMs`.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* ```ts
|
|
132
|
+
* import { Schedule } from "@nicolastoulemont/std"
|
|
133
|
+
*
|
|
134
|
+
* const schedule = Schedule.exponential({ times: 3, baseDelayMs: 100 })
|
|
135
|
+
* const delay = schedule.delayForAttempt(3)
|
|
136
|
+
* // => 400
|
|
137
|
+
* ```
|
|
138
|
+
*
|
|
139
|
+
* @category Constructors
|
|
140
|
+
*/
|
|
141
|
+
declare const exponential: (options: ExponentialScheduleOptions) => AsyncRetrySchedule;
|
|
142
|
+
//#endregion
|
|
143
|
+
export { SyncRetrySchedule as n, schedule_d_exports as r, RetrySchedule as t };
|
|
144
|
+
//# sourceMappingURL=schedule-DlX2Dg69.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schedule-DlX2Dg69.d.mts","names":[],"sources":["../src/schedule/schedule.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;AA6CA;AAcA;AAmBA;AAKC;AAEwB;AAgEzB;AAmBA;AAsBA;;;;;;;;;;;;;;;;;;;;;;;;;;;KAjJY,aAAA,GAAgB,oBAAoB;;;;;;;;;;;;;KAcpC,iBAAA;;;;;;;;;;;;;;;;;;KAmBA,kBAAA;;;;;;KAOP,oBAAA;;;;KAKA,0BAAA;;;;;;;;;;;;;;;;;;;;cA2DQ,2BAA0B;;;;;;;;;;;;;;;cAmB1B,iBAAkB,yBAAuB;;;;;;;;;;;;;;;;cAsBzC,uBAAwB,+BAA6B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"../scope-D_kzd1nT.mjs";export{e as Scope};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { m as SyncFx, t as AsyncFx } from "./fx.types-DeEWEltG.mjs";
|
|
2
|
+
import { t as Result } from "./result.types-_xDAei3-.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/scope/scope.d.ts
|
|
5
|
+
declare namespace scope_d_exports {
|
|
6
|
+
export { ExcludeScope, ScopeService, make };
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Scope manages resource lifecycles with finalizers.
|
|
10
|
+
* Finalizers run in LIFO (Last In, First Out) order when the scope closes.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { Scope } from "@nicolastoulemont/std"
|
|
15
|
+
*
|
|
16
|
+
* type Example = typeof Scope
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* @category Type-level
|
|
20
|
+
*/
|
|
21
|
+
type ScopeService = {
|
|
22
|
+
/**
|
|
23
|
+
* Add a finalizer to be run when the scope closes.
|
|
24
|
+
* Finalizers are run in LIFO order.
|
|
25
|
+
*
|
|
26
|
+
* @param finalizer - A function that returns an Fx to run on cleanup
|
|
27
|
+
* @returns An Fx that completes when the finalizer is registered
|
|
28
|
+
*/
|
|
29
|
+
addFinalizer(finalizer: () => SyncFx<void> | AsyncFx<void>): SyncFx<void>;
|
|
30
|
+
/**
|
|
31
|
+
* Close the scope, running all finalizers in LIFO order.
|
|
32
|
+
*
|
|
33
|
+
* @param exit - The exit status of the computation
|
|
34
|
+
* @returns An Fx that completes when all finalizers have run
|
|
35
|
+
*/
|
|
36
|
+
close(exit: Result<unknown, unknown>): SyncFx<void> | AsyncFx<void>;
|
|
37
|
+
/**
|
|
38
|
+
* Fork a child scope.
|
|
39
|
+
* The child scope will be closed when the parent scope closes.
|
|
40
|
+
*
|
|
41
|
+
* @returns A new child scope
|
|
42
|
+
*/
|
|
43
|
+
fork(): ScopeService;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Create a new Scope instance.
|
|
47
|
+
* This is the concrete implementation of the ScopeService interface.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```ts
|
|
51
|
+
* import { Scope } from "@nicolastoulemont/std"
|
|
52
|
+
*
|
|
53
|
+
* import { Result } from "@nicolastoulemont/std"
|
|
54
|
+
*
|
|
55
|
+
* const scope = Scope.make()
|
|
56
|
+
* const closeFx = scope.close(Result.ok(undefined))
|
|
57
|
+
* // => SyncFx<void> | AsyncFx<void>
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
* @category Constructors
|
|
61
|
+
*/
|
|
62
|
+
declare function make(): ScopeService;
|
|
63
|
+
/**
|
|
64
|
+
* Type utility to exclude Scope from requirements.
|
|
65
|
+
* Used by Layer.scoped to auto-provide Scope.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* import { Scope } from "@nicolastoulemont/std"
|
|
70
|
+
*
|
|
71
|
+
* type Example = typeof Scope
|
|
72
|
+
* ```
|
|
73
|
+
*
|
|
74
|
+
* @category Type-level
|
|
75
|
+
*/
|
|
76
|
+
type ExcludeScope<R> = Exclude<R, ScopeService>;
|
|
77
|
+
//#endregion
|
|
78
|
+
export { ScopeService as n, scope_d_exports as r, ExcludeScope as t };
|
|
79
|
+
//# sourceMappingURL=scope-CZdp4wKX.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope-CZdp4wKX.d.mts","names":[],"sources":["../src/scope/scope.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;AAuDA;;;;;AAgByC,KAhB7B,YAAA,GAgB6B;EAAe;;;AA4BxD;AA8HA;;;EAA8B,YAAA,CAAA,SAAA,EAAA,GAAA,GAlKE,MAkKF,CAAA,IAAA,CAAA,GAlKiB,OAkKjB,CAAA,IAAA,CAAA,CAAA,EAlKiC,MAkKjC,CAAA,IAAA,CAAA;EAAO;;;;;;cA1JvB,2BAA2B,eAAe;;;;;;;UAQ9C;;;;;;;;;;;;;;;;;;;iBAoBM,IAAA,CAAA,GAAQ;;;;;;;;;;;;;;KA8HZ,kBAAkB,QAAQ,GAAG"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C934ptG5.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";import{n,t as r}from"./fx.runtime-DclEDyjY.mjs";var i=e({make:()=>a});function a(){let e=[],i=!1,o=[];return{addFinalizer(n){return{_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){i||e.push(n)}}},close(a){return e.some(e=>e()._tag===`AsyncFx`)?{_tag:`AsyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){if(i)return;i=!0;for(let e of[...o].toReversed()){let t=e.close(a);t._tag===`AsyncFx`?await r(t):n(t)}let t=[...e].toReversed();for(let e of t){let t=e();t._tag===`AsyncFx`?await r(t):n(t)}}}:{_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){if(i)return;i=!0;for(let e of[...o].toReversed())n(e.close(a));let t=[...e].toReversed();for(let e of t)n(e())}}},fork(){let e=a();return o.push(e),e}}}export{i as n,a as t};
|
|
2
|
+
//# sourceMappingURL=scope-D_kzd1nT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope-D_kzd1nT.mjs","names":[],"sources":["../src/scope/scope.ts"],"sourcesContent":["/**\n * Scope lifecycle management for registering and running finalizers.\n *\n * **Mental model**\n * - A scope tracks cleanup actions and executes them in LIFO order.\n * - `Layer.scoped` and `Provide.layer` rely on scope semantics.\n *\n * **Common tasks**\n * - Create scopes with `Scope.make`.\n * - Register cleanup with `scope.addFinalizer`.\n * - Close scopes with `scope.close`.\n *\n * **Gotchas**\n * - Child scopes close before parent finalizers.\n * - Async finalizers force async scope close.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Scope } from \"@nicolastoulemont/std\"\n *\n * import { Result } from \"@nicolastoulemont/std\"\n *\n * const scope = Scope.make()\n * const closeFx = scope.close(Result.ok(undefined))\n * // => SyncFx<void> | AsyncFx<void>\n * ```\n *\n * @module\n */\nimport { runSync, runAsync } from \"../fx/fx.runtime\"\nimport { FxTypeId } from \"../fx/fx.types\"\nimport type { SyncFx, AsyncFx, FxYield } from \"../fx/fx.types\"\nimport type { Result } from \"../result/result.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Scope encodes Fx phantom type slots and sync/async branch narrowing via assertions. */\n\n// ============================================================================\n// Scope Service\n// ============================================================================\n\n/**\n * Scope manages resource lifecycles with finalizers.\n * Finalizers run in LIFO (Last In, First Out) order when the scope closes.\n *\n * @example\n * ```ts\n * import { Scope } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Scope\n * ```\n *\n * @category Type-level\n */\nexport type ScopeService = {\n /**\n * Add a finalizer to be run when the scope closes.\n * Finalizers are run in LIFO order.\n *\n * @param finalizer - A function that returns an Fx to run on cleanup\n * @returns An Fx that completes when the finalizer is registered\n */\n addFinalizer(finalizer: () => SyncFx<void> | AsyncFx<void>): SyncFx<void>\n\n /**\n * Close the scope, running all finalizers in LIFO order.\n *\n * @param exit - The exit status of the computation\n * @returns An Fx that completes when all finalizers have run\n */\n close(exit: Result<unknown, unknown>): SyncFx<void> | AsyncFx<void>\n\n /**\n * Fork a child scope.\n * The child scope will be closed when the parent scope closes.\n *\n * @returns A new child scope\n */\n fork(): ScopeService\n}\n\n/**\n * Create a new Scope instance.\n * This is the concrete implementation of the ScopeService interface.\n *\n * @example\n * ```ts\n * import { Scope } from \"@nicolastoulemont/std\"\n *\n * import { Result } from \"@nicolastoulemont/std\"\n *\n * const scope = Scope.make()\n * const closeFx = scope.close(Result.ok(undefined))\n * // => SyncFx<void> | AsyncFx<void>\n * ```\n *\n * @category Constructors\n */\nexport function make(): ScopeService {\n type Finalizer = () => SyncFx<void> | AsyncFx<void>\n const finalizers: Finalizer[] = []\n let closed = false\n const children: ScopeService[] = []\n\n const scope: ScopeService = {\n addFinalizer(finalizer: Finalizer): SyncFx<void> {\n return {\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as void,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<FxYield<never, never>, void, unknown> {\n if (!closed) {\n finalizers.push(finalizer)\n }\n },\n } as SyncFx<void>\n },\n\n close(exit: Result<unknown, unknown>): SyncFx<void> | AsyncFx<void> {\n // Check if any finalizer is async\n const hasAsyncFinalizer = finalizers.some((f) => {\n const fx = f()\n return fx._tag === \"AsyncFx\"\n })\n\n if (hasAsyncFinalizer) {\n return {\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined as void,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n // oxlint-disable-next-line require-yield\n async *[Symbol.asyncIterator](): AsyncGenerator<FxYield<never, never>, void, unknown> {\n if (closed) return\n closed = true\n\n // Close children first\n for (const child of [...children].toReversed()) {\n const childClose = child.close(exit)\n if (childClose._tag === \"AsyncFx\") {\n // oxlint-disable-next-line no-await-in-loop\n await runAsync(childClose)\n } else {\n runSync(childClose)\n }\n }\n\n // Run finalizers in LIFO order\n const reversed = [...finalizers].toReversed()\n for (const finalizer of reversed) {\n const fx = finalizer()\n if (fx._tag === \"AsyncFx\") {\n // oxlint-disable-next-line no-await-in-loop\n await runAsync(fx)\n } else {\n runSync(fx)\n }\n }\n },\n } as AsyncFx<void>\n }\n\n // Sync version\n return {\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as void,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<FxYield<never, never>, void, unknown> {\n if (closed) return\n closed = true\n\n // Close children first\n for (const child of [...children].toReversed()) {\n const childClose = child.close(exit)\n runSync(childClose as SyncFx<void>)\n }\n\n // Run finalizers in LIFO order\n const reversed = [...finalizers].toReversed()\n for (const finalizer of reversed) {\n const fx = finalizer()\n runSync(fx as SyncFx<void>)\n }\n },\n } as SyncFx<void>\n },\n\n fork(): ScopeService {\n const child = make()\n children.push(child)\n return child\n },\n }\n\n return scope\n}\n\n// ============================================================================\n// Helper Types\n// ============================================================================\n\n/**\n * Type utility to exclude Scope from requirements.\n * Used by Layer.scoped to auto-provide Scope.\n *\n * @example\n * ```ts\n * import { Scope } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Scope\n * ```\n *\n * @category Type-level\n */\nexport type ExcludeScope<R> = Exclude<R, ScopeService>\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"sJAmGA,SAAgB,GAAqB,CAEnC,IAAM,EAA0B,EAAE,CAC9B,EAAS,GACP,EAA2B,EAAE,CAsGnC,MApG4B,CAC1B,aAAa,EAAoC,CAC/C,MAAO,CACL,KAAM,UACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CAED,EAAE,OAAO,WAA6D,CAC/D,GACH,EAAW,KAAK,EAAU,EAG/B,EAGH,MAAM,EAA8D,CA+ClE,OA7C0B,EAAW,KAAM,GAC9B,GAAG,CACJ,OAAS,UACnB,CAGO,CACL,KAAM,WACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CAED,OAAQ,OAAO,gBAAuE,CACpF,GAAI,EAAQ,OACZ,EAAS,GAGT,IAAK,IAAM,IAAS,CAAC,GAAG,EAAS,CAAC,YAAY,CAAE,CAC9C,IAAM,EAAa,EAAM,MAAM,EAAK,CAChC,EAAW,OAAS,UAEtB,MAAM,EAAS,EAAW,CAE1B,EAAQ,EAAW,CAKvB,IAAM,EAAW,CAAC,GAAG,EAAW,CAAC,YAAY,CAC7C,IAAK,IAAM,KAAa,EAAU,CAChC,IAAM,EAAK,GAAW,CAClB,EAAG,OAAS,UAEd,MAAM,EAAS,EAAG,CAElB,EAAQ,EAAG,GAIlB,CAII,CACL,KAAM,UACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CAED,EAAE,OAAO,WAA6D,CACpE,GAAI,EAAQ,OACZ,EAAS,GAGT,IAAK,IAAM,IAAS,CAAC,GAAG,EAAS,CAAC,YAAY,CAE5C,EADmB,EAAM,MAAM,EAAK,CACD,CAIrC,IAAM,EAAW,CAAC,GAAG,EAAW,CAAC,YAAY,CAC7C,IAAK,IAAM,KAAa,EAEtB,EADW,GAAW,CACK,EAGhC,EAGH,MAAqB,CACnB,IAAM,EAAQ,GAAM,CAEpB,OADA,EAAS,KAAK,EAAM,CACb,GAEV"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"../service-3PYQTUdH.mjs";export{e as Service};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C934ptG5.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";var n=e({Service:()=>r,tag:()=>i});function r(){return e=>{let n=class{static _tag=`Service`;static key=e;static _Self=void 0;static[t]={_A:()=>void 0,_E:()=>void 0,_R:()=>void 0};static*[Symbol.iterator](){return yield n}};return n}}function i(e){let n={_tag:`Service`,key:e,_Self:void 0,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){return yield n}};return n}export{n as t};
|
|
2
|
+
//# sourceMappingURL=service-3PYQTUdH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-3PYQTUdH.mjs","names":["tag"],"sources":["../src/service/service.ts"],"sourcesContent":["/**\n * Service tag constructors for `Fx` dependency injection.\n *\n * **Mental model**\n * - A service tag is both a runtime lookup key and a typed requirement marker.\n * - `Service()` and `tag()` create values that can be yielded in `Fx.gen`.\n *\n * **Common tasks**\n * - Define class-based services with `Service`.\n * - Define interface-only tags with `tag`.\n *\n * **Gotchas**\n * - Service keys must be globally unique in a context.\n * - Yielding a service tag requires the service to be provided.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Service } from \"@nicolastoulemont/std\"\n *\n * const Logger = Service.Service<{ log: (message: string) => void }>()(\"Logger\")\n * // => service class with key \"Logger\"\n * ```\n *\n * @module\n */\nimport { FxTypeId } from \"../fx/fx.types\"\nimport type { Fx } from \"../fx/fx.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Service tags carry phantom generic metadata at runtime and require explicit type assertions. */\n\n// ============================================================================\n// Service Class Types\n// ============================================================================\n\n/**\n * The interface returned by Service()().\n * Acts as both a type tag and a runtime lookup key.\n * Implements Fx protocol with E = never (no errors) and R = Self (requires itself).\n * When yielded, yields itself (as Fx) for proper type inference.\n *\n * @example\n * ```ts\n * import { Service } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Service\n * ```\n *\n * @category Models\n */\nexport type ServiceClass<Self, Key extends string = string> = Fx<Self, never, Self> & {\n readonly _tag: \"Service\"\n readonly key: Key\n // Phantom type\n readonly _Self: Self\n\n /**\n * Yielding the service class in a gen computation\n * returns the service instance from context.\n * Yields the ServiceClass itself (which implements Fx) for type inference.\n */\n [Symbol.iterator](): Generator<ServiceClass<Self, Key>, Self, unknown>\n}\n\n// ============================================================================\n// Service Factory\n// ============================================================================\n\n/**\n * Define a service with a unique key.\n * The returned class acts as both a type and a runtime tag for lookup.\n *\n * Usage follows a double-invocation pattern:\n * - First call provides the Self type parameter\n * - Second call provides the unique key\n *\n * @example\n * ```ts\n * import { Service } from \"@nicolastoulemont/std\"\n *\n * const Logger = Service.Service<string>()(\"Logger\")\n * // => service class with key \"Logger\"\n * ```\n *\n * @category Utilities\n */\nexport function Service<Self>(): <Key extends string>(key: Key) => ServiceClass<Self, Key> & (new () => Self) {\n return <Key extends string>(key: Key): ServiceClass<Self, Key> & (new () => Self) => {\n // Create the base class with proper prototype\n // oxlint-disable-next-line typescript/no-extraneous-class\n const ServiceBase = class {\n static readonly _tag = \"Service\" as const\n static readonly key: Key = key\n static readonly _Self: Self = undefined as unknown as Self\n\n static readonly [FxTypeId] = {\n _A: () => undefined as unknown as Self,\n _E: () => undefined as never,\n _R: () => undefined as unknown as Self,\n };\n\n /**\n * Yielding the class returns the class itself (for type inference).\n * The runtime intercepts this and provides the actual service instance.\n */\n static *[Symbol.iterator](): Generator<typeof ServiceBase, Self, Self> {\n // Yield the class itself - it implements Fx<Self, never, Self>\n // The runtime will recognize ServiceClass and inject the service\n const serviceInstance = yield ServiceBase\n return serviceInstance\n }\n }\n\n // Return with correct typing\n return ServiceBase as unknown as ServiceClass<Self, Key> & (new () => Self)\n }\n}\n\n/**\n * Create a service tag without class syntax.\n * Useful for simple services that don't need class inheritance.\n *\n * @example\n * ```ts\n * import { Service } from \"@nicolastoulemont/std\"\n *\n * const Logger = Service.tag<string>(\"Logger\")\n * // => plain service tag with key \"Logger\"\n * ```\n *\n * @category Utilities\n */\nexport function tag<S>(key: string): ServiceClass<S> {\n const tag: ServiceClass<S> = {\n _tag: \"Service\",\n key,\n _Self: undefined as unknown as S,\n [FxTypeId]: {\n _A: () => undefined as unknown as S,\n _E: () => undefined as never,\n _R: () => undefined as unknown as S,\n },\n *[Symbol.iterator](): Generator<ServiceClass<S>, S, S> {\n // Yield the tag itself - it implements Fx<S, never, S>\n // The runtime will recognize ServiceClass and inject the service\n const serviceInstance = yield tag\n return serviceInstance\n },\n }\n return tag\n}\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"mHAuFA,SAAgB,GAA8F,CAC5G,MAA4B,IAAyD,CAGnF,IAAM,EAAc,KAAM,CACxB,OAAgB,KAAO,UACvB,OAAgB,IAAW,EAC3B,OAAgB,MAAc,IAAA,GAE9B,OAAiB,GAAY,CAC3B,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CAMD,QAAS,OAAO,WAAuD,CAIrE,OADwB,MAAM,IAMlC,OAAO,GAkBX,SAAgB,EAAO,EAA8B,CACnD,IAAMA,EAAuB,CAC3B,KAAM,UACN,MACA,MAAO,IAAA,IACN,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,EAAE,OAAO,WAA8C,CAIrD,OADwB,MAAMA,GAGjC,CACD,OAAOA"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { i as Fx } from "./fx.types-DeEWEltG.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/service/service.d.ts
|
|
4
|
+
declare namespace service_d_exports {
|
|
5
|
+
export { Service, ServiceClass, tag };
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The interface returned by Service()().
|
|
9
|
+
* Acts as both a type tag and a runtime lookup key.
|
|
10
|
+
* Implements Fx protocol with E = never (no errors) and R = Self (requires itself).
|
|
11
|
+
* When yielded, yields itself (as Fx) for proper type inference.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { Service } from "@nicolastoulemont/std"
|
|
16
|
+
*
|
|
17
|
+
* type Example = typeof Service
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @category Models
|
|
21
|
+
*/
|
|
22
|
+
type ServiceClass<Self, Key extends string = string> = Fx<Self, never, Self> & {
|
|
23
|
+
readonly _tag: "Service";
|
|
24
|
+
readonly key: Key;
|
|
25
|
+
readonly _Self: Self;
|
|
26
|
+
/**
|
|
27
|
+
* Yielding the service class in a gen computation
|
|
28
|
+
* returns the service instance from context.
|
|
29
|
+
* Yields the ServiceClass itself (which implements Fx) for type inference.
|
|
30
|
+
*/
|
|
31
|
+
[Symbol.iterator](): Generator<ServiceClass<Self, Key>, Self, unknown>;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Define a service with a unique key.
|
|
35
|
+
* The returned class acts as both a type and a runtime tag for lookup.
|
|
36
|
+
*
|
|
37
|
+
* Usage follows a double-invocation pattern:
|
|
38
|
+
* - First call provides the Self type parameter
|
|
39
|
+
* - Second call provides the unique key
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* import { Service } from "@nicolastoulemont/std"
|
|
44
|
+
*
|
|
45
|
+
* const Logger = Service.Service<string>()("Logger")
|
|
46
|
+
* // => service class with key "Logger"
|
|
47
|
+
* ```
|
|
48
|
+
*
|
|
49
|
+
* @category Utilities
|
|
50
|
+
*/
|
|
51
|
+
declare function Service<Self>(): <Key extends string>(key: Key) => ServiceClass<Self, Key> & (new () => Self);
|
|
52
|
+
/**
|
|
53
|
+
* Create a service tag without class syntax.
|
|
54
|
+
* Useful for simple services that don't need class inheritance.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* import { Service } from "@nicolastoulemont/std"
|
|
59
|
+
*
|
|
60
|
+
* const Logger = Service.tag<string>("Logger")
|
|
61
|
+
* // => plain service tag with key "Logger"
|
|
62
|
+
* ```
|
|
63
|
+
*
|
|
64
|
+
* @category Utilities
|
|
65
|
+
*/
|
|
66
|
+
declare function tag<S>(key: string): ServiceClass<S>;
|
|
67
|
+
//#endregion
|
|
68
|
+
export { service_d_exports as n, ServiceClass as t };
|
|
69
|
+
//# sourceMappingURL=service-DrXU7KJG.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-DrXU7KJG.d.mts","names":[],"sources":["../src/service/service.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;AAmDA;;;;;;;AAWoD,KAXxC,YAWwC,CAAA,IAAA,EAAA,YAAA,MAAA,GAAA,MAAA,CAAA,GAXU,EAWV,CAXa,IAWb,EAAA,KAAA,EAX0B,IAW1B,CAAA,GAAA;EAAnB,SAAA,IAAA,EAAA,SAAA;EAAyB,SAAA,GAAA,EAT1C,GAS0C;EAAnC,SAAA,KAAA,EAPL,IAOK;EAAS;AAyBhC;;;;EAAmE,CAAA,MAAA,CAAA,QAAA,GAAA,EAzB5C,SAyB4C,CAzBlC,YAyBkC,CAzBrB,IAyBqB,EAzBf,GAyBe,CAAA,EAzBT,IAyBS,EAAA,OAAA,CAAA;CAAqC;;AA8CxG;;;;;;;;;;;;;;;;;iBA9CgB,2CAA2C,QAAQ,aAAa,MAAM,kBAAkB;;;;;;;;;;;;;;;iBA8CxF,qBAAqB,aAAa"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`Service`&&`key`in e&&typeof e.key==`string`}function t(t){return e(t)?t:void 0}function n(e,n){let r=t(n);if(r!==void 0)return e._services.get(r.key)}export{n,t};
|
|
2
|
+
//# sourceMappingURL=service-resolution-C19smeaO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-resolution-C19smeaO.mjs","names":[],"sources":["../src/service/service-resolution.ts"],"sourcesContent":["import type { Context } from \"../context/context\"\n\ntype ServiceRequest = {\n _tag: \"Service\"\n key: string\n}\n\n/**\n * Narrow an unknown yielded value to a service request.\n */\nfunction isServiceRequest(value: unknown): value is ServiceRequest {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"_tag\" in value &&\n value._tag === \"Service\" &&\n \"key\" in value &&\n typeof value.key === \"string\"\n )\n}\n\nexport function asServiceRequest(value: unknown) {\n return isServiceRequest(value) ? value : undefined\n}\n\n/**\n * Resolve a yielded service request from a context.\n */\nexport function resolveService<R>(ctx: Context<R>, value: unknown) {\n const request = asServiceRequest(value)\n if (request === undefined) return undefined\n return ctx._services.get(request.key)\n}\n"],"mappings":"AAUA,SAAS,EAAiB,EAAyC,CACjE,OACE,OAAO,GAAU,YACjB,GACA,SAAU,GACV,EAAM,OAAS,WACf,QAAS,GACT,OAAO,EAAM,KAAQ,SAIzB,SAAgB,EAAiB,EAAgB,CAC/C,OAAO,EAAiB,EAAM,CAAG,EAAQ,IAAA,GAM3C,SAAgB,EAAkB,EAAiB,EAAgB,CACjE,IAAM,EAAU,EAAiB,EAAM,CACnC,OAAY,IAAA,GAChB,OAAO,EAAI,UAAU,IAAI,EAAQ,IAAI"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nicolastoulemont/std",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Collection of
|
|
3
|
+
"version": "0.7.1",
|
|
4
|
+
"description": "Collection of utility functions",
|
|
5
|
+
"homepage": "https://github.com/nicolastoulemont/toolbelt/tree/main/packages/std",
|
|
5
6
|
"license": "ISC",
|
|
6
7
|
"files": [
|
|
7
8
|
"dist"
|
|
@@ -23,6 +24,10 @@
|
|
|
23
24
|
"types": "./dist/brand/index.d.mts",
|
|
24
25
|
"default": "./dist/brand/index.mjs"
|
|
25
26
|
},
|
|
27
|
+
"./context": {
|
|
28
|
+
"types": "./dist/context/index.d.mts",
|
|
29
|
+
"default": "./dist/context/index.mjs"
|
|
30
|
+
},
|
|
26
31
|
"./data": {
|
|
27
32
|
"types": "./dist/data/index.d.mts",
|
|
28
33
|
"default": "./dist/data/index.mjs"
|
|
@@ -31,33 +36,57 @@
|
|
|
31
36
|
"types": "./dist/either/index.d.mts",
|
|
32
37
|
"default": "./dist/either/index.mjs"
|
|
33
38
|
},
|
|
34
|
-
"./
|
|
35
|
-
"types": "./dist/
|
|
36
|
-
"default": "./dist/
|
|
37
|
-
},
|
|
38
|
-
"./flow": {
|
|
39
|
-
"types": "./dist/flow/index.d.mts",
|
|
40
|
-
"default": "./dist/flow/index.mjs"
|
|
39
|
+
"./functions": {
|
|
40
|
+
"types": "./dist/functions/index.d.mts",
|
|
41
|
+
"default": "./dist/functions/index.mjs"
|
|
41
42
|
},
|
|
42
43
|
"./fx": {
|
|
43
44
|
"types": "./dist/fx/index.d.mts",
|
|
44
45
|
"default": "./dist/fx/index.mjs"
|
|
45
46
|
},
|
|
47
|
+
"./layer": {
|
|
48
|
+
"types": "./dist/layer/index.d.mts",
|
|
49
|
+
"default": "./dist/layer/index.mjs"
|
|
50
|
+
},
|
|
51
|
+
"./multithread": {
|
|
52
|
+
"types": "./dist/multithread/index.d.mts",
|
|
53
|
+
"default": "./dist/multithread/index.mjs"
|
|
54
|
+
},
|
|
46
55
|
"./option": {
|
|
47
56
|
"types": "./dist/option/index.d.mts",
|
|
48
57
|
"default": "./dist/option/index.mjs"
|
|
49
58
|
},
|
|
50
|
-
"./
|
|
51
|
-
"types": "./dist/
|
|
52
|
-
"default": "./dist/
|
|
59
|
+
"./order": {
|
|
60
|
+
"types": "./dist/order/index.d.mts",
|
|
61
|
+
"default": "./dist/order/index.mjs"
|
|
53
62
|
},
|
|
54
63
|
"./predicate": {
|
|
55
64
|
"types": "./dist/predicate/index.d.mts",
|
|
56
65
|
"default": "./dist/predicate/index.mjs"
|
|
57
66
|
},
|
|
67
|
+
"./provide": {
|
|
68
|
+
"types": "./dist/provide/index.d.mts",
|
|
69
|
+
"default": "./dist/provide/index.mjs"
|
|
70
|
+
},
|
|
71
|
+
"./queue": {
|
|
72
|
+
"types": "./dist/queue/index.d.mts",
|
|
73
|
+
"default": "./dist/queue/index.mjs"
|
|
74
|
+
},
|
|
58
75
|
"./result": {
|
|
59
76
|
"types": "./dist/result/index.d.mts",
|
|
60
77
|
"default": "./dist/result/index.mjs"
|
|
78
|
+
},
|
|
79
|
+
"./schedule": {
|
|
80
|
+
"types": "./dist/schedule/index.d.mts",
|
|
81
|
+
"default": "./dist/schedule/index.mjs"
|
|
82
|
+
},
|
|
83
|
+
"./scope": {
|
|
84
|
+
"types": "./dist/scope/index.d.mts",
|
|
85
|
+
"default": "./dist/scope/index.mjs"
|
|
86
|
+
},
|
|
87
|
+
"./service": {
|
|
88
|
+
"types": "./dist/service/index.d.mts",
|
|
89
|
+
"default": "./dist/service/index.mjs"
|
|
61
90
|
}
|
|
62
91
|
},
|
|
63
92
|
"publishConfig": {
|
|
@@ -67,6 +96,7 @@
|
|
|
67
96
|
"@standard-schema/spec": "^1.0.0",
|
|
68
97
|
"@types/node": "^24.1.0",
|
|
69
98
|
"knip": "^5.77.4",
|
|
99
|
+
"multithreading": "^0.3.50",
|
|
70
100
|
"oxlint": "^1.42.0",
|
|
71
101
|
"oxlint-tsgolint": "latest",
|
|
72
102
|
"tsdown": "^0.19.0",
|
|
@@ -74,6 +104,14 @@
|
|
|
74
104
|
"vitest": "^4.0.16",
|
|
75
105
|
"@repo/configs": "1.0.0"
|
|
76
106
|
},
|
|
107
|
+
"peerDependencies": {
|
|
108
|
+
"multithreading": "^0.3.50"
|
|
109
|
+
},
|
|
110
|
+
"peerDependenciesMeta": {
|
|
111
|
+
"multithreading": {
|
|
112
|
+
"optional": true
|
|
113
|
+
}
|
|
114
|
+
},
|
|
77
115
|
"scripts": {
|
|
78
116
|
"build": "tsdown",
|
|
79
117
|
"dev": "tsdown --watch",
|
package/dist/adt-CkRcY_GA.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{i as e,n as t,r as n,t as r}from"./equality-CD4_A1Op.mjs";import{n as i}from"./flow-CYjiodlC.mjs";import{f as a,r as o}from"./result-CgGYLp0L.mjs";function s(e,t){let n=t[e._tag];return n(e)}function c(e){return typeof e!=`object`||!e?!1:Object.getPrototypeOf(e)===null||Object.getPrototypeOf(e)===Object.prototype}function l(e){return typeof e==`function`&&`_variant`in e&&e._variant===!0}function u(e){return e.issues?o({issues:e.issues.map(e=>({message:e.message,path:e.path?.map(e=>typeof e==`object`&&`key`in e?e.key:e)}))}):a(e.value)}function d(e,t,n){let r=e[`~standard`].validate(t);if(i(r))throw Error(`Async validation not supported. Schema for "${n}" returned a Promise. Use a synchronous schema or handle async validation separately.`);return u(r)}function f(e){return t=>c(t)&&`_tag`in t&&t._tag===e}function p(e){let t=new Set(e);return e=>c(e)&&`_tag`in e&&typeof e._tag==`string`&&t.has(e._tag)}function m(e,t,n,r){return n!==void 0&&r!==void 0?{kind:e,message:t,cause:n,validationIssues:r}:n===void 0?r===void 0?{kind:e,message:t}:{kind:e,message:t,validationIssues:r}:{kind:e,message:t,cause:n}}function h(e){return{to:e=>JSON.stringify(e),from:e=>{try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`_tag`in t){let{_tag:e,...n}=t;return n}return t}catch{return null}}}}function g(e,t,n){let r=h(e),i={json:n=>{let i=d(t,{...n,_tag:e},e);if(i._tag===`Err`)return o(m(`ValidationError`,`Cannot encode invalid data: ${i.error.issues.map(e=>e.message).join(`, `)}`,void 0,i.error.issues));try{return a(r.to(i.value))}catch(e){return o(m(`EncodingError`,`JSON encoding failed: ${e instanceof Error?e.message:String(e)}`,e))}}};if(n)for(let[r,s]of Object.entries(n))i[r]=n=>{let i=d(t,{...n,_tag:e},e);if(i._tag===`Err`)return o(m(`ValidationError`,`Cannot encode invalid data: ${i.error.issues.map(e=>e.message).join(`, `)}`,void 0,i.error.issues));try{return a(s.to(i.value))}catch(e){return o(m(`EncodingError`,`Encoding with codec '${r}' failed: ${e instanceof Error?e.message:String(e)}`,e))}};return i}function _(e,t,n){let r=h(e),i={json:n=>{let i=r.from(n);if(i===null)return o(m(`DecodingError`,`Invalid JSON format`));let s=d(t,{...i,_tag:e},e);return s._tag===`Err`?o(m(`ValidationError`,`Decoded data failed schema validation`,void 0,s.error.issues)):a({...s.value,_tag:e})}};if(n)for(let[r,s]of Object.entries(n))i[r]=n=>{let i;try{i=s.from(n)}catch(e){return o(m(`DecodingError`,`Decoding with codec '${r}' threw an error`,e))}if(i===null)return o(m(`DecodingError`,`Codec '${r}' failed to decode input`));let c=d(t,{...i,_tag:e},e);return c._tag===`Err`?o(m(`ValidationError`,`Decoded data failed schema validation`,void 0,c.error.issues)):a({...c.value,_tag:e})};return i}function v(t,r,i){let s=f(t),c=g(t,r,i),l=_(t,r,i),u=n(t),p=e(t),m=e=>{let n=d(r,{...e,_tag:t},t);return n._tag===`Err`?o(n.error):a({...n.value,_tag:t})};return m._variant=!0,m._tag=t,m.schema=r,i&&(m.codecs=i),m.is=s,m.to=c,m.from=l,m.equals=u,m.hash=p,m}function y(e,n){let i=Object.keys(n),a={};for(let[e,t]of Object.entries(n))l(t)?t._tag===e?a[e]=t:t.codecs?a[e]=v(e,t.schema,t.codecs):a[e]=v(e,t.schema):a[e]=v(e,t);return{_name:e,is:p(i),equals:r(i),hash:t(i),...a}}const b={union:y,variant:v,match:s};export{m as n,b as t};
|
|
2
|
-
//# sourceMappingURL=adt-CkRcY_GA.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"adt-CkRcY_GA.mjs","names":[],"sources":["../src/adt/adt.match.ts","../src/shared/is-plain-object.ts","../src/adt/adt.utils.ts","../src/adt/adt.codec.ts","../src/adt/adt.variant.ts","../src/adt/adt.union.ts","../src/adt/adt.ts"],"sourcesContent":["/**\n * Handler functions for each variant in a discriminated union.\n * Each key maps to a function that receives the variant value and returns TResult.\n *\n * @template T - The discriminated union type (must have readonly _tag)\n * @template TResult - The return type of all handlers\n */\nexport type AdtMatchHandlers<T extends { readonly _tag: string }, TResult> = {\n [K in T[\"_tag\"]]: (value: Extract<T, { readonly _tag: K }>) => TResult\n}\n\n/**\n * Exhaustive pattern matching for discriminated unions.\n *\n * TypeScript will error if any variant is missing from handlers,\n * ensuring exhaustive handling of all cases.\n *\n * @template T - The discriminated union type (must have readonly _tag)\n * @template TResult - The return type of all handlers\n * @template Handlers - The handler object type (inferred)\n * @param value - A discriminated union value with _tag\n * @param handlers - An object with a handler function for each variant\n * @returns The result of calling the matching handler\n *\n * @see {@link union} for creating discriminated unions\n * @see {@link variant} for creating individual variant types\n *\n * @example\n * ```ts\n * const Shape = union('Shape', { Circle, Square })\n * type Shape = AdtInfer<typeof Shape>\n *\n * function describeShape(shape: Shape): string {\n * return match(shape, {\n * Circle: (c) => `Circle with radius ${c.radius}`,\n * Square: (s) => `Square with size ${s.size}`,\n * })\n * }\n * ```\n */\nexport function match<\n T extends { readonly _tag: string },\n TResult,\n Handlers extends AdtMatchHandlers<T, TResult> = AdtMatchHandlers<T, TResult>,\n>(value: T, handlers: Handlers): TResult {\n const tag = value._tag as keyof Handlers\n const handler = handlers[tag]\n // oxlint-disable-next-line no-explicit-any, no-unsafe-argument, no-unsafe-type-assertion -- Required for variant dispatch\n return handler(value as any)\n}\n","/**\n * Check if a value is a plain object.\n * A plain object is an object created with `{}`, `Object.create(null)`, or `new Object()`.\n * Arrays, functions, dates, maps, etc. are not considered plain objects.\n */\nexport function isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n\n return Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype\n}\n","import { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport { isPlainObject } from \"../shared/is-plain-object\"\nimport { isPromise } from \"../shared/is-promise\"\nimport type { AdtVariant, AdtValidationError } from \"./adt.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Check if a value is an AdtVariant created by variant().\n * AdtVariants are callable functions with static properties.\n */\nexport function isVariant(value: unknown): value is AdtVariant {\n return typeof value === \"function\" && \"_variant\" in value && value[\"_variant\"] === true\n}\n\n/**\n * Wrap Standard Schema validation result into our Result type.\n */\nfunction wrapValidationResult<T>(result: StandardSchemaV1.Result<T>): Result<T, AdtValidationError> {\n if (result.issues) {\n return err({\n issues: result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((segment) => (typeof segment === \"object\" && \"key\" in segment ? segment.key : segment)),\n })),\n })\n }\n return ok(result.value)\n}\n\n/**\n * Validate data using a Standard Schema, enforcing sync-only validation.\n * Throws if the schema returns a Promise.\n */\nexport function validateSync<T>(\n schema: StandardSchemaV1<unknown, T>,\n data: unknown,\n _tag: string,\n): Result<T, AdtValidationError> {\n const result = schema[\"~standard\"].validate(data)\n\n if (isPromise(result)) {\n throw new Error(\n `Async validation not supported. Schema for \"${_tag}\" returned a Promise. ` +\n `Use a synchronous schema or handle async validation separately.`,\n )\n }\n\n return wrapValidationResult(result)\n}\n\n/**\n * Create a type guard function for a specific _tag.\n */\nexport function createIsGuard<Tag extends string, T>(\n _tag: Tag,\n): (value: unknown) => value is T & { readonly _tag: Tag } {\n return (value: unknown): value is T & { readonly _tag: Tag } => {\n return isPlainObject(value) && \"_tag\" in value && value[\"_tag\"] === _tag\n }\n}\n\n/**\n * Create a type guard function for multiple _tags (AdtUnion root guard).\n */\nexport function createIsAnyGuard<T>(_tags: readonly string[]): (value: unknown) => value is T {\n const _tagSet = new Set(_tags)\n return (value: unknown): value is T => {\n return isPlainObject(value) && \"_tag\" in value && typeof value[\"_tag\"] === \"string\" && _tagSet.has(value[\"_tag\"])\n }\n}\n","import { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport type {\n AdtCodecConstraint,\n AdtCodecDef,\n AdtCodecError,\n AdtInferInput,\n AdtInferOutput,\n AdtValidationError,\n ToMethods,\n FromMethods,\n} from \"./adt.types\"\nimport { validateSync } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a AdtCodecError with consistent structure.\n */\nexport function createCodecError(\n kind: AdtCodecError[\"kind\"],\n message: string,\n cause?: unknown,\n validationIssues?: AdtValidationError[\"issues\"],\n): AdtCodecError {\n if (cause !== undefined && validationIssues !== undefined) {\n return { kind, message, cause, validationIssues }\n }\n if (cause !== undefined) {\n return { kind, message, cause }\n }\n if (validationIssues !== undefined) {\n return { kind, message, validationIssues }\n }\n return { kind, message }\n}\n\n/**\n * Built-in JSON codec that works with any schema.\n * Encodes to JSON string and decodes with JSON.parse.\n */\nfunction createJsonCodec<Tag extends string, S extends StandardSchemaV1>(\n _tag: Tag,\n): AdtCodecDef<AdtInferOutput<S> & Discriminator<Tag>, string, AdtInferInput<S>> {\n return {\n to: (value) => {\n // JSON.stringify can throw for circular references, BigInt, etc.\n // We let it throw and catch it in the wrapper\n return JSON.stringify(value)\n },\n /* oxlint-disable no-unsafe-assignment, no-unsafe-type-assertion, no-unsafe-return -- Required for JSON parsing which returns unknown types */\n from: (input: string) => {\n try {\n const parsed = JSON.parse(input)\n // Return parsed object without _tag - it will be added during validation\n if (typeof parsed === \"object\" && parsed !== null && \"_tag\" in parsed) {\n const { _tag: _, ...rest } = parsed\n return rest as AdtInferInput<S>\n }\n return parsed\n } catch {\n return null\n }\n },\n /* oxlint-enable no-unsafe-assignment, no-unsafe-type-assertion, no-unsafe-return */\n }\n}\n\n/**\n * Create the \"to\" methods object with JSON codec and custom codecs.\n * All methods return Result<T, AdtCodecError> for consistent error handling.\n */\nexport function createToMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): ToMethods<S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const jsonCodec = createJsonCodec<Tag, S>(_tag)\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const to: Record<string, (value: AdtInferInput<S>) => Result<any, AdtCodecError>> = {\n json: (value: AdtInferInput<S>): Result<string, AdtCodecError> => {\n // First, create a validated variant to ensure the encoded payload is well-typed.\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input into object\n const taggedInput = { ...(value as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(\", \")}`,\n undefined,\n result.error.issues,\n ),\n )\n }\n\n try {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for validated value cast\n return ok(jsonCodec.to(result.value as Output))\n } catch (e) {\n return err(\n createCodecError(\"EncodingError\", `JSON encoding failed: ${e instanceof Error ? e.message : String(e)}`, e),\n )\n }\n },\n }\n\n // Add custom codecs\n if (customCodecs) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const [name, codec] of Object.entries(customCodecs) as Array<[string, AdtCodecDef<Output, any, any>]>) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n to[name] = (value: AdtInferInput<S>): Result<any, AdtCodecError> => {\n // Validate input first\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input\n const taggedInput = { ...(value as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(\", \")}`,\n undefined,\n result.error.issues,\n ),\n )\n }\n\n try {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for validated value cast\n return ok(codec.to(result.value as Output))\n } catch (e) {\n return err(\n createCodecError(\n \"EncodingError\",\n `Encoding with codec '${name}' failed: ${e instanceof Error ? e.message : String(e)}`,\n e,\n ),\n )\n }\n }\n }\n }\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic return type\n return to as ToMethods<S, Codecs>\n}\n\n/**\n * Create the \"from\" methods object with JSON codec and custom codecs.\n * All methods return Result<T, AdtCodecError> for consistent error handling.\n */\nexport function createFromMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): FromMethods<Tag, S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const jsonCodec = createJsonCodec<Tag, S>(_tag)\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const from: Record<string, (input: any) => Result<Output, AdtCodecError>> = {\n json: (input: string): Result<Output, AdtCodecError> => {\n // Decode\n const decoded = jsonCodec.from(input)\n if (decoded === null) {\n return err(createCodecError(\"DecodingError\", \"Invalid JSON format\"))\n }\n\n // Validate through schema\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading decoded value\n const taggedInput = { ...(decoded as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\"ValidationError\", \"Decoded data failed schema validation\", undefined, result.error.issues),\n )\n }\n\n // Ensure _tag in output\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n },\n }\n\n // Add custom codecs\n if (customCodecs) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const [name, codec] of Object.entries(customCodecs) as Array<[string, AdtCodecDef<Output, any, any>]>) {\n from[name] = (input: unknown): Result<Output, AdtCodecError> => {\n // Decode\n let decoded: unknown\n try {\n decoded = codec.from(input)\n } catch (e) {\n return err(createCodecError(\"DecodingError\", `Decoding with codec '${name}' threw an error`, e))\n }\n\n if (decoded === null) {\n return err(createCodecError(\"DecodingError\", `Codec '${name}' failed to decode input`))\n }\n\n // Validate through schema\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading decoded value\n const taggedInput = { ...(decoded as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n \"Decoded data failed schema validation\",\n undefined,\n result.error.issues,\n ),\n )\n }\n\n // Ensure _tag in output\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n }\n }\n }\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic return type\n return from as FromMethods<Tag, S, Codecs>\n}\n","import { createEqualsMethod, createHashMethod } from \"../equality/equality\"\nimport { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport { createToMethods, createFromMethods } from \"./adt.codec\"\nimport type { AdtCodecConstraint, AdtInferInput, AdtInferOutput, AdtVariant, AdtValidationError } from \"./adt.types\"\nimport { createIsGuard, validateSync } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a standalone tagged variant from a Standard Schema with optional codecs.\n *\n * Variants can be used independently or composed into an AdtUnion via union().\n * All defaults should be defined at the schema level (e.g., Zod's .default()).\n *\n * @template Tag - The string literal type for the _tag discriminator\n * @template S - The Standard Schema type for validation\n * @template Codecs - Optional codec definitions for custom serialization formats\n * @param _tag - The _tag discriminator value\n * @param schema - A Standard Schema compliant validator\n * @param codecs - Optional codec definitions for custom serialization formats\n * @returns A callable AdtVariant with is(), to, and from methods\n *\n * @see {@link union} for composing variants into discriminated unions\n * @see {@link tagged} for unvalidated tagged value constructors\n *\n * @example\n * ```ts\n * const CircleSchema = z.object({\n * radius: z.number().positive(),\n * color: z.string().default('blue')\n * })\n *\n * // Basic variant with JSON codec (always included)\n * const Circle = variant('Circle', CircleSchema)\n *\n * const result = Circle({ radius: 10 })\n * // { _tag: \"Ok\", value: { _tag: \"Circle\", radius: 10, color: \"blue\" } }\n *\n * Circle.is(someValue) // type guard\n *\n * const json = Circle.to.json({ radius: 10 }) // JSON string\n * const result2 = Circle.from.json(json) // Result<Circle, AdtCodecError>\n *\n * // Variant with custom codec\n * const Circle2 = variant('Circle', CircleSchema, {\n * graphic: {\n * to: (circle) => `(${circle.radius})`,\n * from: (input: string) => {\n * const match = input.match(/^\\((\\d+)\\)$/)\n * return match ? { radius: parseInt(match[1]!) } : null\n * }\n * }\n * })\n *\n * const graphic = Circle2.to.graphic({ radius: 10 }) // \"(10)\"\n * const result3 = Circle2.from.graphic(\"(10)\") // Result<Circle, AdtCodecError>\n * ```\n */\n// Overload: with codecs\nexport function variant<Tag extends string, S extends StandardSchemaV1, Codecs extends AdtCodecConstraint<Tag, S>>(\n _tag: Tag,\n schema: S,\n codecs: Codecs,\n): AdtVariant<Tag, S, Codecs>\n\n// Overload: without codecs\nexport function variant<Tag extends string, S extends StandardSchemaV1>(_tag: Tag, schema: S): AdtVariant<Tag, S>\n\n// Implementation\nexport function variant<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined,\n>(_tag: Tag, schema: S, codecs?: Codecs): AdtVariant<Tag, S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const isGuard = createIsGuard<Tag, Output>(_tag)\n const to = createToMethods(_tag, schema, codecs)\n const from = createFromMethods(_tag, schema, codecs)\n const equals = createEqualsMethod<Tag, AdtInferOutput<S>>(_tag)\n const hash = createHashMethod<Tag, AdtInferOutput<S>>(_tag)\n\n // Constructor function\n const constructor = (input: AdtInferInput<S>): Result<Output, AdtValidationError> => {\n // Add _tag to the input before validation\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input\n const taggedInput = { ...(input as object), _tag }\n\n // Validate using the schema\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(result.error)\n }\n\n // Ensure _tag is in the output (schema might strip unknown keys)\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n }\n\n // Attach static properties to constructor function\n constructor._variant = true as const\n constructor._tag = _tag\n constructor.schema = schema\n if (codecs) {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Conditional assignment of codecs\n ;(constructor as { codecs?: Codecs }).codecs = codecs\n }\n constructor.is = isGuard\n constructor.to = to\n constructor.from = from\n constructor.equals = equals\n constructor.hash = hash\n\n return constructor as AdtVariant<Tag, S, Codecs>\n}\n","import { createADTEqualsMethod, createADTHashMethod } from \"../equality/equality\"\nimport { variant } from \"./adt.variant\"\nimport type { AdtUnion, AdtVariantDef, AdtVariant } from \"./adt.types\"\nimport { createIsAnyGuard, isVariant } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Compose records or schemas into a discriminated union (AdtUnion).\n *\n * Accepts either:\n * - Pre-built AdtVariants from variant() (codecs are preserved)\n * - Raw Standard Schema validators (will be wrapped internally)\n *\n * When using pre-built records, the object key overrides the original _tag.\n *\n * @template R - Record of variant names to AdtVariants or StandardSchema validators\n * @param name - The name of this AdtUnion (for identification)\n * @param records - An object mapping _tag names to AdtVariants or schemas\n * @returns An AdtUnion object with accessors for each variant\n *\n * @see {@link variant} for creating individual variant types\n * @see {@link match} for exhaustive pattern matching on AdtUnion values\n *\n * @example\n * ```ts\n * // From pre-built variants\n * const Circle = variant('Circle', CircleSchema)\n * const Square = variant('Square', SquareSchema)\n * const Shape = union('Shape', { Circle, Square })\n *\n * // From raw schemas (JSON codec is automatically included)\n * const Shape = union('Shape', {\n * Circle: CircleSchema,\n * Square: SquareSchema\n * })\n *\n * // JSON codec works on all variants\n * Shape.Circle.to.json({ radius: 10 })\n * Shape.Circle.from.json(jsonString)\n *\n * // Mixed\n * const Shape = union('Shape', {\n * Circle, // Pre-built variant\n * Square: SquareSchema // Raw schema\n * })\n *\n * // Usage\n * Shape.Circle({ radius: 10 })\n * Shape.is(someValue) // type guard for any variant\n * Shape.Circle.is(someValue) // type guard for Circle\n * ```\n */\nexport function union<R extends Record<string, AdtVariantDef>>(name: string, records: R): AdtUnion<R> {\n const tags = Object.keys(records)\n const variants: Record<string, AdtVariant> = {}\n\n for (const [_tag, def] of Object.entries(records)) {\n if (isVariant(def)) {\n // Pre-built AdtVariant - key overrides original _tag\n if (def._tag === _tag) {\n // _tag matches key, use as-is (preserves codecs)\n variants[_tag] = def\n // oxlint-disable-next-line strict-boolean-expressions -- codecs can be undefined\n } else if (def.codecs) {\n // _tag differs from key - create new variant with key as _tag\n // Preserve codecs\n variants[_tag] = variant(_tag, def.schema, def.codecs)\n } else {\n // _tag differs from key and no codecs\n variants[_tag] = variant(_tag, def.schema)\n }\n } else {\n // Raw schema - wrap in variant\n // Note: Even without custom codecs, this still gets JSON codec!\n // oxlint-disable-next-line no-unsafe-type-assertion -- def is a StandardSchemaV1 in this branch\n variants[_tag] = variant(_tag, def as StandardSchemaV1)\n }\n }\n\n // Create the root type guard for any variant\n const isAnyVariant = createIsAnyGuard(tags)\n const equals = createADTEqualsMethod(tags)\n const hash = createADTHashMethod(tags)\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic AdtUnion return type\n return {\n _name: name,\n is: isAnyVariant,\n equals,\n hash,\n ...variants,\n } as AdtUnion<R>\n}\n","import { match } from \"./adt.match\"\nimport { union } from \"./adt.union\"\nimport { variant } from \"./adt.variant\"\n\nexport const Adt = {\n union,\n variant,\n match,\n} as const\n"],"mappings":"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"}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
//#region src/shared/lambda.types.d.ts
|
|
2
|
-
type λ<TA extends any[] = any[], TR = any> = (...args: TA) => TR;
|
|
3
|
-
//#endregion
|
|
4
|
-
//#region src/shared/apply-fn.types.d.ts
|
|
5
|
-
type ApplyFn<F extends λ, Arg> = F extends ((arg: Arg) => infer R) ? R : F extends ((arg: any) => infer R) ? R : never;
|
|
6
|
-
//#endregion
|
|
7
|
-
export { λ as n, ApplyFn as t };
|
|
8
|
-
//# sourceMappingURL=apply-fn.types-0g_9eXRy.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"apply-fn.types-0g_9eXRy.d.mts","names":[],"sources":["../src/shared/lambda.types.ts","../src/shared/apply-fn.types.ts"],"sourcesContent":[],"mappings":";KACY,kDAAkD,OAAO;;;ACMzD,KAAA,OAAO,CAAA,UAAW,CAAX,EAAA,GAAA,CAAA,GAAqB,CAArB,UAAA,CAAA,GAAA,EAAqC,GAArC,EAAA,GAAA,KAAA,EAAA,IAAA,CAAA,GAEf,CAFe,UAAA,CAAA,GAAA,EAAA,GAAA,EAAA,GAAA,KAAA,EAAA,IAAA,CAAA,GAAA,KAAA"}
|
package/dist/brand-Gy0kW6-n.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./result-CgGYLp0L.mjs";const t=e=>e,n=e=>e,r=e=>t=>e(t),i=(t,n)=>r=>{if(!t(r)){let t=typeof n==`function`?n(r):n??`Brand validation failed`;return e.err({_tag:`BrandError`,value:r,message:t})}return e.ok(r)},a={make:t,unsafeMake:n,is:r,refine:i};export{n as a,i,r as n,t as r,a as t};
|
|
2
|
-
//# sourceMappingURL=brand-Gy0kW6-n.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"brand-Gy0kW6-n.mjs","names":[],"sources":["../src/brand/brand.ts"],"sourcesContent":["import { Result } from \"../result\"\nimport type { Result as ResultType } from \"../result/result.types\"\nimport type { BrandError, Branded, Unbrand, Validator } from \"./brand.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Branding is a deliberate nominal cast at the type level and requires explicit assertions. */\n\n/**\n * Create a branded value without validation.\n * This is a type-level cast with zero runtime cost.\n *\n * Use this when you trust the value source (e.g., from a database)\n * or when validation happens elsewhere.\n *\n * @template B - The branded type\n * @param value - The value to brand\n * @returns The value as a branded type\n *\n * @example\n * ```ts\n * type UserId = Branded<string, \"UserId\">\n *\n * // Trust the value from database\n * const userId = Brand.make<UserId>(row.id)\n *\n * // Or use in a validated factory\n * function createUserId(input: string): UserId {\n * if (!input.startsWith(\"user_\")) throw new Error(\"Invalid\")\n * return Brand.make<UserId>(input)\n * }\n * ```\n */\nexport const make = <B extends Branded<unknown, string>>(value: Unbrand<B>): B => {\n return value as B\n}\n\n/**\n * Alias for make() - explicitly indicates no validation occurs.\n * Prefer this when readability about the lack of validation is important.\n *\n * @template B - The branded type\n * @param value - The value to brand (unchecked)\n * @returns The value as a branded type\n *\n * @example\n * ```ts\n * type PositiveNumber = Branded<number, \"PositiveNumber\">\n *\n * // Explicitly unsafe - reader knows no validation\n * const n = Brand.unsafeMake<PositiveNumber>(-5) // No error, but logically wrong\n * ```\n */\nexport const unsafeMake = <B extends Branded<unknown, string>>(value: Unbrand<B>): B => {\n return value as B\n}\n\n/**\n * Create a type guard with validation for a branded type.\n * Returns a refinement predicate that narrows to the branded type.\n *\n * @template T - The base type\n * @template K - The brand key (string literal)\n * @param validator - A function that validates the base value\n * @returns A type guard that returns true if validation passes\n *\n * @example\n * ```ts\n * type PositiveNumber = Branded<number, \"PositiveNumber\">\n *\n * const isPositive = Brand.is<number, \"PositiveNumber\">(n => n > 0)\n *\n * const value: number = 42\n * if (isPositive(value)) {\n * // value is now PositiveNumber\n * acceptPositive(value) // OK\n * }\n * ```\n */\nexport const is = <T, K extends string>(validator: Validator<T>): ((value: T) => value is Branded<T, K>) => {\n return (value: T): value is Branded<T, K> => validator(value)\n}\n\n/**\n * Create a validated branded value wrapped in a Result.\n * Returns `Result.ok(brandedValue)` on success, `Result.err(BrandError)` on failure.\n *\n * The returned Result is yieldable in Fx.gen computations via `yield*`.\n *\n * @template B - The branded type\n * @param validator - A function that validates the base value\n * @param errorMessage - Optional custom error message (or function)\n * @returns A function that takes a value and returns a Result\n *\n * @example\n * ```ts\n * type Email = Branded<string, \"Email\">\n *\n * const parseEmail = Brand.refine<Email>(\n * s => s.includes(\"@\"),\n * (v) => `Invalid email: ${v}`\n * )\n *\n * // Basic usage\n * const result = parseEmail(\"user@example.com\")\n * // { _tag: \"Ok\", value: \"user@example.com\" }\n *\n * const bad = parseEmail(\"not-an-email\")\n * // { _tag: \"Err\", error: { _tag: \"BrandError\", value: \"not-an-email\", message: \"...\" } }\n *\n * // With Fx.gen computation\n * const computation = Fx.gen(function* () {\n * const email = yield* parseEmail(input)\n * return email\n * })\n *\n * // With pipe\n * pipe(\n * userInput,\n * parseEmail,\n * Result.map(email => sendTo(email)),\n * Result.unwrapOr(defaultEmail)\n * )\n * ```\n */\nexport const refine = <B extends Branded<unknown, string>>(\n validator: Validator<Unbrand<B>>,\n errorMessage?: string | ((value: Unbrand<B>) => string),\n): ((value: Unbrand<B>) => ResultType<B, BrandError<Unbrand<B>>>) => {\n return (value: Unbrand<B>) => {\n if (!validator(value)) {\n const msg = typeof errorMessage === \"function\" ? errorMessage(value) : (errorMessage ?? \"Brand validation failed\")\n return Result.err({ _tag: \"BrandError\" as const, value, message: msg })\n }\n return Result.ok(value as B)\n }\n}\n\n/**\n * Brand namespace containing utilities for nominal typing in TypeScript.\n *\n * Brand types add type-level distinctiveness to primitive types without\n * any runtime overhead. This prevents accidental mixing of semantically\n * different values that share the same structural type.\n *\n * @example\n * ```ts\n * import { Brand } from \"@nicolastoulemont/std\"\n * import type { Branded } from \"@nicolastoulemont/std\"\n *\n * // Define branded types\n * type UserId = Branded<string, \"UserId\">\n * type Email = Branded<string, \"Email\">\n *\n * // Create values\n * const userId = Brand.make<UserId>(\"user-123\")\n * const isValidEmail = Brand.is<Email>(s => s.includes(\"@\"))\n *\n * // Type safety\n * function sendEmail(email: Email) { ... }\n * sendEmail(userId) // Type error! UserId is not Email\n * ```\n */\nexport const Brand = {\n make,\n unsafeMake,\n is,\n refine,\n} as const\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"0CA+BA,MAAa,EAA4C,GAChD,EAmBI,EAAkD,GACtD,EAyBI,EAA2B,GAC9B,GAAqC,EAAU,EAAM,CA6ClD,GACX,EACA,IAEQ,GAAsB,CAC5B,GAAI,CAAC,EAAU,EAAM,CAAE,CACrB,IAAM,EAAM,OAAO,GAAiB,WAAa,EAAa,EAAM,CAAI,GAAgB,0BACxF,OAAO,EAAO,IAAI,CAAE,KAAM,aAAuB,QAAO,QAAS,EAAK,CAAC,CAEzE,OAAO,EAAO,GAAG,EAAW,EA6BnB,EAAQ,CACnB,OACA,aACA,KACA,SACD"}
|
package/dist/data-C0_3MGwm.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{a as e,i as t,o as n,r}from"./equality-CD4_A1Op.mjs";function i(t){let r=[...t];Object.defineProperty(r,`equals`,{value:t=>e(r,t),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(r,`hash`,{value:()=>n(r),enumerable:!1,writable:!1,configurable:!1});let a=r.map.bind(r);Object.defineProperty(r,`map`,{value:e=>i(a(e)),enumerable:!1,writable:!1,configurable:!1});let o=r.filter.bind(r);Object.defineProperty(r,`filter`,{value:e=>i(o(e)),enumerable:!1,writable:!1,configurable:!1});let s=r.slice.bind(r);Object.defineProperty(r,`slice`,{value:(e,t)=>i(s(e,t)),enumerable:!1,writable:!1,configurable:!1});let c=r.concat.bind(r);return Object.defineProperty(r,`concat`,{value:(...e)=>i(c(...e)),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(r)}function a(t){let r={...t};return Object.defineProperty(r,`equals`,{value:t=>e(r,t),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(r,`hash`,{value:()=>n(r),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(r)}function o(e){let n=t=>Object.freeze({...t,_tag:e});return n.is=t=>typeof t==`object`&&!!t&&`_tag`in t&&t._tag===e,n.equals=r(e),n.hash=t(e),n._tag=e,n}function s(...t){let r=[...t];return Object.defineProperty(r,`equals`,{value:t=>e(r,t),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(r,`hash`,{value:()=>n(r),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(r)}const c={tagged:o,struct:a,tuple:s,array:i};export{c as t};
|
|
2
|
-
//# sourceMappingURL=data-C0_3MGwm.mjs.map
|