@nicolastoulemont/std 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/dist/adt/index.d.mts +1 -1
  2. package/dist/adt/index.mjs +1 -3
  3. package/dist/adt-DZmVJG4P.mjs +2 -0
  4. package/dist/adt-DZmVJG4P.mjs.map +1 -0
  5. package/dist/{apply-fn.types-0g_9eXRy.d.mts → apply-fn.types-CMgY6WQe.d.mts} +1 -1
  6. package/dist/{apply-fn.types-0g_9eXRy.d.mts.map → apply-fn.types-CMgY6WQe.d.mts.map} +1 -1
  7. package/dist/brand/index.d.mts +1 -1
  8. package/dist/brand/index.mjs +1 -3
  9. package/dist/brand-BUqMmkzC.mjs +2 -0
  10. package/dist/{brand-BqcqFXj5.mjs.map → brand-BUqMmkzC.mjs.map} +1 -1
  11. package/dist/data/index.d.mts +1 -1
  12. package/dist/data/index.mjs +1 -3
  13. package/dist/data-DzqKBCQg.mjs +2 -0
  14. package/dist/data-DzqKBCQg.mjs.map +1 -0
  15. package/dist/{discriminator.types-D-UbMmAD.d.mts → discriminator.types-DkThfvNE.d.mts} +1 -1
  16. package/dist/discriminator.types-DkThfvNE.d.mts.map +1 -0
  17. package/dist/either/index.d.mts +2 -2
  18. package/dist/either/index.mjs +1 -3
  19. package/dist/either-BDY9T5oz.mjs +2 -0
  20. package/dist/either-BDY9T5oz.mjs.map +1 -0
  21. package/dist/equality-D2EJvZm4.mjs +2 -0
  22. package/dist/{equality-C2l3BIi8.mjs.map → equality-D2EJvZm4.mjs.map} +1 -1
  23. package/dist/err/index.d.mts +1 -1
  24. package/dist/err/index.mjs +1 -3
  25. package/dist/err-CYs4b1RV.mjs +2 -0
  26. package/dist/{err-BM-svBaK.mjs.map → err-CYs4b1RV.mjs.map} +1 -1
  27. package/dist/flow/index.d.mts +1 -1
  28. package/dist/flow/index.mjs +1 -3
  29. package/dist/flow-CxKQ5yac.mjs +2 -0
  30. package/dist/{flow-D4cE0EAg.mjs.map → flow-CxKQ5yac.mjs.map} +1 -1
  31. package/dist/fx/index.d.mts +3 -3
  32. package/dist/fx/index.mjs +1 -4
  33. package/dist/fx-C4UuWCqP.mjs +2 -0
  34. package/dist/fx-C4UuWCqP.mjs.map +1 -0
  35. package/dist/fx.types-CXTwEa1G.mjs +2 -0
  36. package/dist/{fx.types-DpIQILok.mjs.map → fx.types-CXTwEa1G.mjs.map} +1 -1
  37. package/dist/{fx.types-aTmhyidu.d.mts → fx.types-DO-8yG4c.d.mts} +1 -1
  38. package/dist/{fx.types-aTmhyidu.d.mts.map → fx.types-DO-8yG4c.d.mts.map} +1 -1
  39. package/dist/{index-USQPafrR.d.mts → index-78LWwTds.d.mts} +1 -1
  40. package/dist/{index-USQPafrR.d.mts.map → index-78LWwTds.d.mts.map} +1 -1
  41. package/dist/{index-BO6bxBeo.d.mts → index-BQ5wVDSP.d.mts} +8 -24
  42. package/dist/index-BQ5wVDSP.d.mts.map +1 -0
  43. package/dist/{index-BOrJQBPO.d.mts → index-BahMvQpA.d.mts} +2 -2
  44. package/dist/{index-BOrJQBPO.d.mts.map → index-BahMvQpA.d.mts.map} +1 -1
  45. package/dist/{index-ClxPiGP9.d.mts → index-Bs5TTFlK.d.mts} +40 -44
  46. package/dist/index-Bs5TTFlK.d.mts.map +1 -0
  47. package/dist/{index-D5tzehjf.d.mts → index-BuLJRX1e.d.mts} +11 -11
  48. package/dist/{index-D5tzehjf.d.mts.map → index-BuLJRX1e.d.mts.map} +1 -1
  49. package/dist/{index-CQxzD1YM.d.mts → index-CDio8mJY.d.mts} +4 -4
  50. package/dist/{index-CQxzD1YM.d.mts.map → index-CDio8mJY.d.mts.map} +1 -1
  51. package/dist/{index-FySViSfh.d.mts → index-DLlx9jiG.d.mts} +5 -105
  52. package/dist/index-DLlx9jiG.d.mts.map +1 -0
  53. package/dist/{index-CLspOlBH.d.mts → index-DQoTXLSm.d.mts} +192 -83
  54. package/dist/index-DQoTXLSm.d.mts.map +1 -0
  55. package/dist/{index-Cydt5ocm.d.mts → index-DjjJIDaA.d.mts} +2 -2
  56. package/dist/{index-Cydt5ocm.d.mts.map → index-DjjJIDaA.d.mts.map} +1 -1
  57. package/dist/{index-EmWRCTY3.d.mts → index-DtAPrec7.d.mts} +2 -2
  58. package/dist/{index-EmWRCTY3.d.mts.map → index-DtAPrec7.d.mts.map} +1 -1
  59. package/dist/{index-CLlcoy8B.d.mts → index-IdejL485.d.mts} +2 -2
  60. package/dist/{index-CLlcoy8B.d.mts.map → index-IdejL485.d.mts.map} +1 -1
  61. package/dist/index.d.mts +16 -40
  62. package/dist/index.mjs +1 -15
  63. package/dist/option/index.d.mts +3 -3
  64. package/dist/option/index.mjs +1 -4
  65. package/dist/option-Qiv7Ls7L.mjs +2 -0
  66. package/dist/option-Qiv7Ls7L.mjs.map +1 -0
  67. package/dist/option.types-By5UOfC2.mjs +2 -0
  68. package/dist/option.types-By5UOfC2.mjs.map +1 -0
  69. package/dist/{option.types-CVvowfmd.d.mts → option.types-Cluybn30.d.mts} +22 -20
  70. package/dist/option.types-Cluybn30.d.mts.map +1 -0
  71. package/dist/pipe/index.d.mts +1 -1
  72. package/dist/pipe/index.mjs +1 -3
  73. package/dist/pipe-BROILDeC.mjs +2 -0
  74. package/dist/{pipe-BF4G4SLo.mjs.map → pipe-BROILDeC.mjs.map} +1 -1
  75. package/dist/{pipeable-Dr0d_q4F.d.mts → pipeable-KHu4D8ol.d.mts} +1 -1
  76. package/dist/{pipeable-Dr0d_q4F.d.mts.map → pipeable-KHu4D8ol.d.mts.map} +1 -1
  77. package/dist/pipeable-rQvolRqh.mjs +2 -0
  78. package/dist/{pipeable-DYNrUps7.mjs.map → pipeable-rQvolRqh.mjs.map} +1 -1
  79. package/dist/predicate/index.d.mts +1 -1
  80. package/dist/predicate/index.mjs +1 -3
  81. package/dist/predicate-DvXnfmeJ.mjs +2 -0
  82. package/dist/{predicate-Dt9Qsbav.mjs.map → predicate-DvXnfmeJ.mjs.map} +1 -1
  83. package/dist/result/index.d.mts +2 -2
  84. package/dist/result/index.mjs +1 -3
  85. package/dist/result-B68pxC7l.mjs +2 -0
  86. package/dist/result-B68pxC7l.mjs.map +1 -0
  87. package/dist/result-uRORQlAQ.mjs +1 -0
  88. package/dist/{result.types-_W95221K.d.mts → result.types-fIbuBwVQ.d.mts} +129 -20
  89. package/dist/result.types-fIbuBwVQ.d.mts.map +1 -0
  90. package/package.json +1 -1
  91. package/dist/adt-DH37Pprw.mjs +0 -318
  92. package/dist/adt-DH37Pprw.mjs.map +0 -1
  93. package/dist/brand-BqcqFXj5.mjs +0 -165
  94. package/dist/chunk-DRYujVrt.mjs +0 -18
  95. package/dist/data-Cg8ySt6-.mjs +0 -244
  96. package/dist/data-Cg8ySt6-.mjs.map +0 -1
  97. package/dist/discriminator.types-D-UbMmAD.d.mts.map +0 -1
  98. package/dist/either-jkBX8xS1.mjs +0 -735
  99. package/dist/either-jkBX8xS1.mjs.map +0 -1
  100. package/dist/equality-C2l3BIi8.mjs +0 -201
  101. package/dist/err-BM-svBaK.mjs +0 -176
  102. package/dist/flow-D4cE0EAg.mjs +0 -28
  103. package/dist/fx-B-0MxGTM.mjs +0 -1306
  104. package/dist/fx-B-0MxGTM.mjs.map +0 -1
  105. package/dist/fx.types-DpIQILok.mjs +0 -13
  106. package/dist/index-BO6bxBeo.d.mts.map +0 -1
  107. package/dist/index-CLspOlBH.d.mts.map +0 -1
  108. package/dist/index-ClxPiGP9.d.mts.map +0 -1
  109. package/dist/index-FySViSfh.d.mts.map +0 -1
  110. package/dist/index.d.mts.map +0 -1
  111. package/dist/option-C2QpGffy.mjs +0 -530
  112. package/dist/option-C2QpGffy.mjs.map +0 -1
  113. package/dist/option.types-BiAiZ8Ks.mjs +0 -33
  114. package/dist/option.types-BiAiZ8Ks.mjs.map +0 -1
  115. package/dist/option.types-CVvowfmd.d.mts.map +0 -1
  116. package/dist/pipe-BF4G4SLo.mjs +0 -10
  117. package/dist/pipeable-DYNrUps7.mjs +0 -92
  118. package/dist/predicate-Dt9Qsbav.mjs +0 -293
  119. package/dist/result-BmqdTN5o.mjs +0 -1
  120. package/dist/result-DhYA-J-M.mjs +0 -542
  121. package/dist/result-DhYA-J-M.mjs.map +0 -1
  122. package/dist/result.types-_W95221K.d.mts.map +0 -1
@@ -1,318 +0,0 @@
1
- import { i as createHashMethod, n as createADTHashMethod, r as createEqualsMethod, t as createADTEqualsMethod } from "./equality-C2l3BIi8.mjs";
2
- import { n as isPromise } from "./flow-D4cE0EAg.mjs";
3
- import { f as ok, r as err } from "./result-DhYA-J-M.mjs";
4
-
5
- //#region src/shared/is-plain-object.ts
6
- /**
7
- * Check if a value is a plain object.
8
- * A plain object is an object created with `{}`, `Object.create(null)`, or `new Object()`.
9
- * Arrays, functions, dates, maps, etc. are not considered plain objects.
10
- */
11
- function isPlainObject(value) {
12
- if (value === null || typeof value !== "object") return false;
13
- const proto = Object.getPrototypeOf(value);
14
- return proto === null || proto === Object.prototype;
15
- }
16
-
17
- //#endregion
18
- //#region src/adt/adt.utils.ts
19
- /**
20
- * Check if a value is a RecordObject created by record().
21
- * RecordObjects are callable functions with static properties.
22
- */
23
- function isRecord(value) {
24
- return typeof value === "function" && "_record" in value && value["_record"] === true;
25
- }
26
- /**
27
- * Wrap Standard Schema validation result into our Result type.
28
- */
29
- function wrapValidationResult(result) {
30
- if (result.issues) return err({ issues: result.issues.map((issue) => ({
31
- message: issue.message,
32
- path: issue.path?.map((segment) => typeof segment === "object" && "key" in segment ? segment.key : segment)
33
- })) });
34
- return ok(result.value);
35
- }
36
- /**
37
- * Validate data using a Standard Schema, enforcing sync-only validation.
38
- * Throws if the schema returns a Promise.
39
- */
40
- function validateSync(schema, data$1, _tag) {
41
- const result = schema["~standard"].validate(data$1);
42
- if (isPromise(result)) throw new Error(`Async validation not supported. Schema for "${_tag}" returned a Promise. Use a synchronous schema or handle async validation separately.`);
43
- return wrapValidationResult(result);
44
- }
45
- /**
46
- * Create a type guard function for a specific _tag.
47
- */
48
- function createIsGuard(_tag) {
49
- return (value) => {
50
- return isPlainObject(value) && "_tag" in value && value["_tag"] === _tag;
51
- };
52
- }
53
- /**
54
- * Create a type guard function for multiple _tags (ADT root guard).
55
- */
56
- function createIsAnyGuard(_tags) {
57
- const _tagSet = new Set(_tags);
58
- return (value) => {
59
- return isPlainObject(value) && "_tag" in value && typeof value["_tag"] === "string" && _tagSet.has(value["_tag"]);
60
- };
61
- }
62
-
63
- //#endregion
64
- //#region src/adt/adt.codec.ts
65
- /**
66
- * Create a CodecError with consistent structure.
67
- */
68
- function createCodecError(kind, message, cause, validationIssues) {
69
- if (cause !== void 0 && validationIssues !== void 0) return {
70
- kind,
71
- message,
72
- cause,
73
- validationIssues
74
- };
75
- if (cause !== void 0) return {
76
- kind,
77
- message,
78
- cause
79
- };
80
- if (validationIssues !== void 0) return {
81
- kind,
82
- message,
83
- validationIssues
84
- };
85
- return {
86
- kind,
87
- message
88
- };
89
- }
90
- /**
91
- * Built-in JSON codec that works with any schema.
92
- * Encodes to JSON string and decodes with JSON.parse.
93
- */
94
- function createJsonCodec(_tag) {
95
- return {
96
- to: (value) => {
97
- return JSON.stringify(value);
98
- },
99
- from: (input) => {
100
- try {
101
- const parsed = JSON.parse(input);
102
- if (typeof parsed === "object" && parsed !== null && "_tag" in parsed) {
103
- const { _tag: _, ...rest } = parsed;
104
- return rest;
105
- }
106
- return parsed;
107
- } catch {
108
- return null;
109
- }
110
- }
111
- };
112
- }
113
- /**
114
- * Create the "to" methods object with JSON codec and custom codecs.
115
- * All methods return Result<T, CodecError> for consistent error handling.
116
- */
117
- function createToMethods(_tag, schema, customCodecs) {
118
- const jsonCodec = createJsonCodec(_tag);
119
- const to = { json: (value) => {
120
- const result = validateSync(schema, {
121
- ...value,
122
- _tag
123
- }, _tag);
124
- if (!result.ok) return err(createCodecError("ValidationError", `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(", ")}`, void 0, result.error.issues));
125
- try {
126
- return ok(jsonCodec.to(result.value));
127
- } catch (e) {
128
- return err(createCodecError("EncodingError", `JSON encoding failed: ${e instanceof Error ? e.message : String(e)}`, e));
129
- }
130
- } };
131
- if (customCodecs) for (const [name, codec] of Object.entries(customCodecs)) to[name] = (value) => {
132
- const result = validateSync(schema, {
133
- ...value,
134
- _tag
135
- }, _tag);
136
- if (!result.ok) return err(createCodecError("ValidationError", `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(", ")}`, void 0, result.error.issues));
137
- try {
138
- return ok(codec.to(result.value));
139
- } catch (e) {
140
- return err(createCodecError("EncodingError", `Encoding with codec '${name}' failed: ${e instanceof Error ? e.message : String(e)}`, e));
141
- }
142
- };
143
- return to;
144
- }
145
- /**
146
- * Create the "from" methods object with JSON codec and custom codecs.
147
- * All methods return Result<T, CodecError> for consistent error handling.
148
- */
149
- function createFromMethods(_tag, schema, customCodecs) {
150
- const jsonCodec = createJsonCodec(_tag);
151
- const from = { json: (input) => {
152
- const decoded = jsonCodec.from(input);
153
- if (decoded === null) return err(createCodecError("DecodingError", "Invalid JSON format"));
154
- const result = validateSync(schema, {
155
- ...decoded,
156
- _tag
157
- }, _tag);
158
- if (!result.ok) return err(createCodecError("ValidationError", "Decoded data failed schema validation", void 0, result.error.issues));
159
- return ok({
160
- ...result.value,
161
- _tag
162
- });
163
- } };
164
- if (customCodecs) for (const [name, codec] of Object.entries(customCodecs)) from[name] = (input) => {
165
- let decoded;
166
- try {
167
- decoded = codec.from(input);
168
- } catch (e) {
169
- return err(createCodecError("DecodingError", `Decoding with codec '${name}' threw an error`, e));
170
- }
171
- if (decoded === null) return err(createCodecError("DecodingError", `Codec '${name}' failed to decode input`));
172
- const result = validateSync(schema, {
173
- ...decoded,
174
- _tag
175
- }, _tag);
176
- if (!result.ok) return err(createCodecError("ValidationError", "Decoded data failed schema validation", void 0, result.error.issues));
177
- return ok({
178
- ...result.value,
179
- _tag
180
- });
181
- };
182
- return from;
183
- }
184
-
185
- //#endregion
186
- //#region src/adt/adt.record.ts
187
- function record(_tag, schema, codecs) {
188
- const isGuard = createIsGuard(_tag);
189
- const to = createToMethods(_tag, schema, codecs);
190
- const from = createFromMethods(_tag, schema, codecs);
191
- const equals = createEqualsMethod(_tag);
192
- const hash = createHashMethod(_tag);
193
- const constructor = (input) => {
194
- const result = validateSync(schema, {
195
- ...input,
196
- _tag
197
- }, _tag);
198
- if (!result.ok) return err(result.error);
199
- return ok({
200
- ...result.value,
201
- _tag
202
- });
203
- };
204
- constructor._record = true;
205
- constructor._tag = _tag;
206
- constructor.schema = schema;
207
- if (codecs) constructor.codecs = codecs;
208
- constructor.is = isGuard;
209
- constructor.to = to;
210
- constructor.from = from;
211
- constructor.equals = equals;
212
- constructor.hash = hash;
213
- return constructor;
214
- }
215
-
216
- //#endregion
217
- //#region src/adt/adt.data.ts
218
- /**
219
- * Compose records or schemas into a discriminated union (ADT).
220
- *
221
- * Accepts either:
222
- * - Pre-built RecordObjects from record() (codecs are preserved)
223
- * - Raw Standard Schema validators (will be wrapped internally)
224
- *
225
- * When using pre-built records, the object key overrides the original _tag.
226
- *
227
- * @template R - Record of variant names to RecordObjects or StandardSchema validators
228
- * @param name - The name of this ADT (for identification)
229
- * @param records - An object mapping _tag names to RecordObjects or schemas
230
- * @returns An ADT object with accessors for each variant
231
- *
232
- * @see {@link record} for creating individual record types
233
- * @see {@link match} for exhaustive pattern matching on ADT values
234
- *
235
- * @example
236
- * ```ts
237
- * // From pre-built records
238
- * const Circle = record('Circle', CircleSchema)
239
- * const Square = record('Square', SquareSchema)
240
- * const Shape = data('Shape', { Circle, Square })
241
- *
242
- * // From raw schemas (JSON codec is automatically included)
243
- * const Shape = data('Shape', {
244
- * Circle: CircleSchema,
245
- * Square: SquareSchema
246
- * })
247
- *
248
- * // JSON codec works on all variants
249
- * Shape.Circle.to.json({ radius: 10 })
250
- * Shape.Circle.from.json(jsonString)
251
- *
252
- * // Mixed
253
- * const Shape = data('Shape', {
254
- * Circle, // Pre-built record
255
- * Square: SquareSchema // Raw schema
256
- * })
257
- *
258
- * // Usage
259
- * Shape.Circle({ radius: 10 })
260
- * Shape.is(someValue) // type guard for any variant
261
- * Shape.Circle.is(someValue) // type guard for Circle
262
- * ```
263
- */
264
- function data(name, records) {
265
- const tags = Object.keys(records);
266
- const variants = {};
267
- for (const [_tag, def] of Object.entries(records)) if (isRecord(def)) if (def._tag === _tag) variants[_tag] = def;
268
- else if (def.codecs) variants[_tag] = record(_tag, def.schema, def.codecs);
269
- else variants[_tag] = record(_tag, def.schema);
270
- else variants[_tag] = record(_tag, def);
271
- return {
272
- _name: name,
273
- is: createIsAnyGuard(tags),
274
- equals: createADTEqualsMethod(tags),
275
- hash: createADTHashMethod(tags),
276
- ...variants
277
- };
278
- }
279
-
280
- //#endregion
281
- //#region src/adt/adt.match.ts
282
- /**
283
- * Exhaustive pattern matching for discriminated unions.
284
- *
285
- * TypeScript will error if any variant is missing from handlers,
286
- * ensuring exhaustive handling of all cases.
287
- *
288
- * @template T - The discriminated union type (must have readonly _tag)
289
- * @template TResult - The return type of all handlers
290
- * @template Handlers - The handler object type (inferred)
291
- * @param value - A discriminated union value with _tag
292
- * @param handlers - An object with a handler function for each variant
293
- * @returns The result of calling the matching handler
294
- *
295
- * @see {@link data} for creating discriminated unions
296
- * @see {@link record} for creating individual record types
297
- *
298
- * @example
299
- * ```ts
300
- * const Shape = data('Shape', { Circle, Square })
301
- * type Shape = Infer<typeof Shape>
302
- *
303
- * function describeShape(shape: Shape): string {
304
- * return match(shape, {
305
- * Circle: (c) => `Circle with radius ${c.radius}`,
306
- * Square: (s) => `Square with size ${s.size}`,
307
- * })
308
- * }
309
- * ```
310
- */
311
- function match(value, handlers) {
312
- const handler = handlers[value._tag];
313
- return handler(value);
314
- }
315
-
316
- //#endregion
317
- export { createCodecError as i, data as n, record as r, match as t };
318
- //# sourceMappingURL=adt-DH37Pprw.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"adt-DH37Pprw.mjs","names":["data"],"sources":["../src/shared/is-plain-object.ts","../src/adt/adt.utils.ts","../src/adt/adt.codec.ts","../src/adt/adt.record.ts","../src/adt/adt.data.ts","../src/adt/adt.match.ts"],"sourcesContent":["/**\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 const proto = Object.getPrototypeOf(value)\n return proto === null || proto === 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 { RecordObject, ValidationError } from \"./adt.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Check if a value is a RecordObject created by record().\n * RecordObjects are callable functions with static properties.\n */\nexport function isRecord(value: unknown): value is RecordObject {\n return typeof value === \"function\" && \"_record\" in value && value[\"_record\"] === true\n}\n\n/**\n * Wrap Standard Schema validation result into our Result type.\n */\nfunction wrapValidationResult<T>(result: StandardSchemaV1.Result<T>): Result<T, ValidationError> {\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, ValidationError> {\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 (ADT 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 CodecConstraint,\n CodecDef,\n CodecError,\n InferInput,\n InferOutput,\n ValidationError,\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 CodecError with consistent structure.\n */\nexport function createCodecError(\n kind: CodecError[\"kind\"],\n message: string,\n cause?: unknown,\n validationIssues?: ValidationError[\"issues\"],\n): CodecError {\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): CodecDef<InferOutput<S> & Discriminator<Tag>, string, InferInput<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 InferInput<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, CodecError> for consistent error handling.\n */\nexport function createToMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends CodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): ToMethods<S, Codecs> {\n type Output = InferOutput<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: InferInput<S>) => Result<any, CodecError>> = {\n json: (value: InferInput<S>): Result<string, CodecError> => {\n // First, create a validated record to ensure we're encoding valid data\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.ok) {\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, CodecDef<Output, any, any>]>) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n to[name] = (value: InferInput<S>): Result<any, CodecError> => {\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.ok) {\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, CodecError> for consistent error handling.\n */\nexport function createFromMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends CodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): FromMethods<Tag, S, Codecs> {\n type Output = InferOutput<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, CodecError>> = {\n json: (input: string): Result<Output, CodecError> => {\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.ok) {\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, CodecDef<Output, any, any>]>) {\n from[name] = (input: unknown): Result<Output, CodecError> => {\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.ok) {\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 { CodecConstraint, InferInput, InferOutput, RecordObject, ValidationError } from \"./adt.types\"\nimport { createIsGuard, validateSync } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a standalone tagged record from a Standard Schema with optional codecs.\n *\n * Records can be used independently or composed into an ADT via data().\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 RecordObject with is(), to, and from methods\n *\n * @see {@link data} for composing records 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 record with JSON codec (always included)\n * const Circle = record('Circle', CircleSchema)\n *\n * const result = Circle({ radius: 10 })\n * // { ok: true, 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, CodecError>\n *\n * // Record with custom codec\n * const Circle2 = record('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, CodecError>\n * ```\n */\n// Overload: with codecs\nexport function record<Tag extends string, S extends StandardSchemaV1, Codecs extends CodecConstraint<Tag, S>>(\n _tag: Tag,\n schema: S,\n codecs: Codecs,\n): RecordObject<Tag, S, Codecs>\n\n// Overload: without codecs\nexport function record<Tag extends string, S extends StandardSchemaV1>(_tag: Tag, schema: S): RecordObject<Tag, S>\n\n// Implementation\nexport function record<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends CodecConstraint<Tag, S> | undefined,\n>(_tag: Tag, schema: S, codecs?: Codecs): RecordObject<Tag, S, Codecs> {\n type Output = InferOutput<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, InferOutput<S>>(_tag)\n const hash = createHashMethod<Tag, InferOutput<S>>(_tag)\n\n // Constructor function\n const constructor = (input: InferInput<S>): Result<Output, ValidationError> => {\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.ok) {\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._record = 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 RecordObject<Tag, S, Codecs>\n}\n","import { createADTEqualsMethod, createADTHashMethod } from \"../equality/equality\"\nimport { record } from \"./adt.record\"\nimport type { ADT, RecordDef, RecordObject } from \"./adt.types\"\nimport { createIsAnyGuard, isRecord } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Compose records or schemas into a discriminated union (ADT).\n *\n * Accepts either:\n * - Pre-built RecordObjects from record() (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 RecordObjects or StandardSchema validators\n * @param name - The name of this ADT (for identification)\n * @param records - An object mapping _tag names to RecordObjects or schemas\n * @returns An ADT object with accessors for each variant\n *\n * @see {@link record} for creating individual record types\n * @see {@link match} for exhaustive pattern matching on ADT values\n *\n * @example\n * ```ts\n * // From pre-built records\n * const Circle = record('Circle', CircleSchema)\n * const Square = record('Square', SquareSchema)\n * const Shape = data('Shape', { Circle, Square })\n *\n * // From raw schemas (JSON codec is automatically included)\n * const Shape = data('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 = data('Shape', {\n * Circle, // Pre-built record\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 data<R extends Record<string, RecordDef>>(name: string, records: R): ADT<R> {\n const tags = Object.keys(records)\n const variants: Record<string, RecordObject> = {}\n\n for (const [_tag, def] of Object.entries(records)) {\n if (isRecord(def)) {\n // Pre-built RecordObject - 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 record with key as _tag\n // Preserve codecs\n variants[_tag] = record(_tag, def.schema, def.codecs)\n } else {\n // _tag differs from key and no codecs\n variants[_tag] = record(_tag, def.schema)\n }\n } else {\n // Raw schema - wrap in record\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] = record(_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 ADT return type\n return {\n _name: name,\n is: isAnyVariant,\n equals,\n hash,\n ...variants,\n } as ADT<R>\n}\n","/**\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 MatchHandlers<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 data} for creating discriminated unions\n * @see {@link record} for creating individual record types\n *\n * @example\n * ```ts\n * const Shape = data('Shape', { Circle, Square })\n * type Shape = Infer<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 MatchHandlers<T, TResult> = MatchHandlers<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"],"mappings":";;;;;;;;;;AAKA,SAAgB,cAAc,OAAuD;AACnF,KAAI,UAAU,QAAQ,OAAO,UAAU,SACrC,QAAO;CAGT,MAAM,QAAQ,OAAO,eAAe,MAAM;AAC1C,QAAO,UAAU,QAAQ,UAAU,OAAO;;;;;;;;;ACA5C,SAAgB,SAAS,OAAuC;AAC9D,QAAO,OAAO,UAAU,cAAc,aAAa,SAAS,MAAM,eAAe;;;;;AAMnF,SAAS,qBAAwB,QAAgE;AAC/F,KAAI,OAAO,OACT,QAAO,IAAI,EACT,QAAQ,OAAO,OAAO,KAAK,WAAW;EACpC,SAAS,MAAM;EACf,MAAM,MAAM,MAAM,KAAK,YAAa,OAAO,YAAY,YAAY,SAAS,UAAU,QAAQ,MAAM,QAAS;EAC9G,EAAE,EACJ,CAAC;AAEJ,QAAO,GAAG,OAAO,MAAM;;;;;;AAOzB,SAAgB,aACd,QACA,QACA,MAC4B;CAC5B,MAAM,SAAS,OAAO,aAAa,SAASA,OAAK;A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oB;CAC1F,MAAM,OAAO,OAAO,KAAK,QAAQ;CACjC,MAAM,WAAyC,EAAE;AAEjD,MAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,QAAQ,CAC/C,KAAI,SAAS,IAAI,CAEf,KAAI,IAAI,SAAS,KAEf,UAAS,QAAQ;UAER,IAAI,OAGb,UAAS,QAAQ,OAAO,MAAM,IAAI,QAAQ,IAAI,OAAO;KAGrD,UAAS,QAAQ,OAAO,MAAM,IAAI,OAAO;KAM3C,UAAS,QAAQ,OAAO,MAAM,IAAwB;AAU1D,QAAO;EACL,OAAO;EACP,IAPmB,iBAAiB,KAAK;EAQzC,QAPa,sBAAsB,KAAK;EAQxC,MAPW,oBAAoB,KAAK;EAQpC,GAAG;EACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACnDH,SAAgB,MAId,OAAU,UAA6B;CAEvC,MAAM,UAAU,SADJ,MAAM;AAGlB,QAAO,QAAQ,MAAa"}
@@ -1,165 +0,0 @@
1
- import { t as Result } from "./result-DhYA-J-M.mjs";
2
-
3
- //#region src/brand/brand.ts
4
- /**
5
- * Create a branded value without validation.
6
- * This is a type-level cast with zero runtime cost.
7
- *
8
- * Use this when you trust the value source (e.g., from a database)
9
- * or when validation happens elsewhere.
10
- *
11
- * @template B - The branded type
12
- * @param value - The value to brand
13
- * @returns The value as a branded type
14
- *
15
- * @example
16
- * ```ts
17
- * type UserId = Branded<string, "UserId">
18
- *
19
- * // Trust the value from database
20
- * const userId = Brand.make<UserId>(row.id)
21
- *
22
- * // Or use in a validated factory
23
- * function createUserId(input: string): UserId {
24
- * if (!input.startsWith("user_")) throw new Error("Invalid")
25
- * return Brand.make<UserId>(input)
26
- * }
27
- * ```
28
- */
29
- const make = (value) => {
30
- return value;
31
- };
32
- /**
33
- * Alias for make() - explicitly indicates no validation occurs.
34
- * Prefer this when readability about the lack of validation is important.
35
- *
36
- * @template B - The branded type
37
- * @param value - The value to brand (unchecked)
38
- * @returns The value as a branded type
39
- *
40
- * @example
41
- * ```ts
42
- * type PositiveNumber = Branded<number, "PositiveNumber">
43
- *
44
- * // Explicitly unsafe - reader knows no validation
45
- * const n = Brand.unsafeMake<PositiveNumber>(-5) // No error, but logically wrong
46
- * ```
47
- */
48
- const unsafeMake = (value) => {
49
- return value;
50
- };
51
- /**
52
- * Create a type guard with validation for a branded type.
53
- * Returns a refinement predicate that narrows to the branded type.
54
- *
55
- * @template T - The base type
56
- * @template K - The brand key (string literal)
57
- * @param validator - A function that validates the base value
58
- * @returns A type guard that returns true if validation passes
59
- *
60
- * @example
61
- * ```ts
62
- * type PositiveNumber = Branded<number, "PositiveNumber">
63
- *
64
- * const isPositive = Brand.is<number, "PositiveNumber">(n => n > 0)
65
- *
66
- * const value: number = 42
67
- * if (isPositive(value)) {
68
- * // value is now PositiveNumber
69
- * acceptPositive(value) // OK
70
- * }
71
- * ```
72
- */
73
- const is = (validator) => {
74
- return (value) => validator(value);
75
- };
76
- /**
77
- * Create a validated branded value wrapped in a Result.
78
- * Returns `Result.ok(brandedValue)` on success, `Result.err(BrandError)` on failure.
79
- *
80
- * The returned Result is yieldable in Do computations via `yield*`.
81
- *
82
- * @template B - The branded type
83
- * @param validator - A function that validates the base value
84
- * @param errorMessage - Optional custom error message (or function)
85
- * @returns A function that takes a value and returns a Result
86
- *
87
- * @example
88
- * ```ts
89
- * type Email = Branded<string, "Email">
90
- *
91
- * const parseEmail = Brand.refine<Email>(
92
- * s => s.includes("@"),
93
- * (v) => `Invalid email: ${v}`
94
- * )
95
- *
96
- * // Basic usage
97
- * const result = parseEmail("user@example.com")
98
- * // { ok: true, value: "user@example.com" }
99
- *
100
- * const bad = parseEmail("not-an-email")
101
- * // { ok: false, error: { _tag: "BrandError", value: "not-an-email", message: "..." } }
102
- *
103
- * // With Do computation
104
- * const computation = Fx.gen(function* () {
105
- * const email = yield* parseEmail(input)
106
- * return email
107
- * })
108
- *
109
- * // With pipe
110
- * pipe(
111
- * userInput,
112
- * parseEmail,
113
- * Result.map(email => sendTo(email)),
114
- * Result.unwrapOr(defaultEmail)
115
- * )
116
- * ```
117
- */
118
- const refine = (validator, errorMessage) => {
119
- return (value) => {
120
- if (!validator(value)) {
121
- const msg = typeof errorMessage === "function" ? errorMessage(value) : errorMessage ?? "Brand validation failed";
122
- return Result.err({
123
- _tag: "BrandError",
124
- value,
125
- message: msg
126
- });
127
- }
128
- return Result.ok(value);
129
- };
130
- };
131
- /**
132
- * Brand namespace containing utilities for nominal typing in TypeScript.
133
- *
134
- * Brand types add type-level distinctiveness to primitive types without
135
- * any runtime overhead. This prevents accidental mixing of semantically
136
- * different values that share the same structural type.
137
- *
138
- * @example
139
- * ```ts
140
- * import { Brand } from "@repo/std"
141
- * import type { Branded } from "@repo/std"
142
- *
143
- * // Define branded types
144
- * type UserId = Branded<string, "UserId">
145
- * type Email = Branded<string, "Email">
146
- *
147
- * // Create values
148
- * const userId = Brand.make<UserId>("user-123")
149
- * const isValidEmail = Brand.is<Email>(s => s.includes("@"))
150
- *
151
- * // Type safety
152
- * function sendEmail(email: Email) { ... }
153
- * sendEmail(userId) // Type error! UserId is not Email
154
- * ```
155
- */
156
- const Brand = {
157
- make,
158
- unsafeMake,
159
- is,
160
- refine
161
- };
162
-
163
- //#endregion
164
- export { unsafeMake as a, refine as i, is as n, make as r, Brand as t };
165
- //# sourceMappingURL=brand-BqcqFXj5.mjs.map
@@ -1,18 +0,0 @@
1
- //#region rolldown:runtime
2
- var __defProp = Object.defineProperty;
3
- var __exportAll = (all, symbols) => {
4
- let target = {};
5
- for (var name in all) {
6
- __defProp(target, name, {
7
- get: all[name],
8
- enumerable: true
9
- });
10
- }
11
- if (symbols) {
12
- __defProp(target, Symbol.toStringTag, { value: "Module" });
13
- }
14
- return target;
15
- };
16
-
17
- //#endregion
18
- export { __exportAll as t };