functype 1.27.2 → 2.0.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 (181) hide show
  1. package/README.md +63 -88
  2. package/dist/_virtual/_rolldown/runtime.js +1 -0
  3. package/dist/branded/ValidatedBrand.d.ts +122 -0
  4. package/dist/branded/ValidatedBrand.js +1 -0
  5. package/dist/branded/index.d.ts +52 -2
  6. package/dist/cli/data.d.ts +37 -0
  7. package/dist/cli/data.js +1 -0
  8. package/dist/cli/exports.d.ts +5 -46
  9. package/dist/cli/exports.js +1 -1
  10. package/dist/cli/formatters.js +4 -0
  11. package/dist/cli/full-interfaces.d.ts +6 -0
  12. package/dist/cli/full-interfaces.js +1139 -0
  13. package/dist/cli/index.js +3 -6
  14. package/dist/cli/interfaces.generated.js +1 -0
  15. package/dist/collections/index.d.ts +13 -0
  16. package/dist/companion/Companion.d.ts +23 -0
  17. package/dist/companion/Companion.js +1 -0
  18. package/dist/companion/CompanionTypes.d.ts +30 -0
  19. package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
  20. package/dist/companion/index.d.ts +2 -1
  21. package/dist/companion/index.js +1 -1
  22. package/dist/conditional/Cond.d.ts +147 -0
  23. package/dist/conditional/Cond.js +1 -0
  24. package/dist/conditional/Match.d.ts +295 -0
  25. package/dist/conditional/Match.js +1 -0
  26. package/dist/conditional/index.d.ts +3 -2
  27. package/dist/conditional/index.js +1 -1
  28. package/dist/core/base/Base.d.ts +12 -0
  29. package/dist/core/base/Base.js +1 -0
  30. package/dist/core/throwable/Throwable.d.ts +38 -0
  31. package/dist/core/throwable/Throwable.js +1 -0
  32. package/dist/decoder/Decoder.d.ts +15 -0
  33. package/dist/decoder/DecoderCompanion.js +1 -0
  34. package/dist/decoder/DecoderError.d.ts +56 -0
  35. package/dist/decoder/DecoderError.js +2 -0
  36. package/dist/decoder/Encoder.d.ts +15 -0
  37. package/dist/decoder/index.d.ts +71 -2
  38. package/dist/decoder/index.js +1 -1
  39. package/dist/decoder/tagged.js +1 -0
  40. package/dist/do/index.d.ts +246 -2
  41. package/dist/do/index.js +1 -1
  42. package/dist/do/protocol.d.ts +29 -0
  43. package/dist/either/index.d.ts +279 -2
  44. package/dist/either/index.js +1 -1
  45. package/dist/error/ErrorChain.d.ts +60 -0
  46. package/dist/error/ErrorChain.js +4 -0
  47. package/dist/error/ErrorFormatter.d.ts +67 -0
  48. package/dist/error/ErrorFormatter.js +6 -0
  49. package/dist/error/ParseError.d.ts +6 -0
  50. package/dist/error/ParseError.js +1 -0
  51. package/dist/error/typed/TypedError.d.ts +146 -0
  52. package/dist/error/typed/TypedError.js +1 -0
  53. package/dist/error/typed/Validation.d.ts +76 -0
  54. package/dist/error/typed/Validation.js +1 -0
  55. package/dist/extractable/Extractable.d.ts +62 -0
  56. package/dist/extractable/Extractable.js +1 -0
  57. package/dist/fetch/Http.d.ts +32 -0
  58. package/dist/fetch/Http.js +1 -0
  59. package/dist/fetch/HttpClient.d.ts +80 -0
  60. package/dist/fetch/HttpClient.js +1 -0
  61. package/dist/fetch/HttpError.d.ts +57 -0
  62. package/dist/fetch/HttpError.js +1 -0
  63. package/dist/fetch/HttpRequest.d.ts +103 -0
  64. package/dist/fetch/index.d.ts +5 -2
  65. package/dist/fetch/index.js +1 -1
  66. package/dist/foldable/Foldable.d.ts +27 -0
  67. package/dist/foldable/index.d.ts +55 -0
  68. package/dist/foldable/index.js +1 -0
  69. package/dist/functype/Functype.d.ts +76 -0
  70. package/dist/functype/FunctypeSum.d.ts +39 -0
  71. package/dist/functype/index.d.ts +4 -2
  72. package/dist/hkt/index.d.ts +68 -0
  73. package/dist/hkt/index.js +1 -0
  74. package/dist/identity/Identity.d.ts +34 -0
  75. package/dist/identity/Identity.js +1 -0
  76. package/dist/index.d.ts +74 -8
  77. package/dist/index.js +1 -1
  78. package/dist/internal/base64.js +1 -0
  79. package/dist/internal/call-alone.js +1 -0
  80. package/dist/internal/concurrency.d.ts +11 -0
  81. package/dist/internal/concurrency.js +1 -0
  82. package/dist/internal/define.js +1 -0
  83. package/dist/internal/mutation-utils.js +1 -0
  84. package/dist/internal/signal.js +1 -0
  85. package/dist/internal/stringify.js +1 -0
  86. package/dist/invariant/index.d.ts +32 -2
  87. package/dist/io/Context.d.ts +112 -0
  88. package/dist/io/Context.js +1 -0
  89. package/dist/io/Exit.d.ts +249 -0
  90. package/dist/io/Exit.js +1 -0
  91. package/dist/io/IO.d.ts +1243 -0
  92. package/dist/io/IO.js +1 -0
  93. package/dist/io/Layer.d.ts +139 -0
  94. package/dist/io/Layer.js +1 -0
  95. package/dist/io/SpanTracer.d.ts +78 -0
  96. package/dist/io/SpanTracer.js +1 -0
  97. package/dist/io/Tag.d.ts +75 -0
  98. package/dist/io/Tag.js +1 -0
  99. package/dist/io/TestClock.d.ts +133 -0
  100. package/dist/io/TestClock.js +1 -0
  101. package/dist/io/index.d.ts +41 -2
  102. package/dist/io/index.js +1 -1
  103. package/dist/lazy/Lazy.d.ts +312 -0
  104. package/dist/lazy/Lazy.js +1 -0
  105. package/dist/lazy/index.d.ts +2 -2
  106. package/dist/lazy/index.js +1 -1
  107. package/dist/list/LazyList.d.ts +182 -0
  108. package/dist/list/LazyList.js +1 -0
  109. package/dist/list/index.d.ts +137 -2
  110. package/dist/list/index.js +1 -1
  111. package/dist/logger/index.d.ts +24 -2
  112. package/dist/map/index.d.ts +95 -2
  113. package/dist/map/index.js +1 -1
  114. package/dist/map/shim.d.ts +13 -0
  115. package/dist/map/shim.js +1 -0
  116. package/dist/matchable/Matchable.d.ts +38 -0
  117. package/dist/matchable/Matchable.js +1 -0
  118. package/dist/obj/Obj.d.ts +212 -0
  119. package/dist/obj/Obj.js +1 -0
  120. package/dist/obj/index.d.ts +2 -2
  121. package/dist/obj/index.js +1 -1
  122. package/dist/option/index.d.ts +304 -2
  123. package/dist/option/index.js +1 -1
  124. package/dist/package.json.js +1 -0
  125. package/dist/pipe/index.d.ts +14 -0
  126. package/dist/ref/Ref.d.ts +77 -0
  127. package/dist/ref/Ref.js +1 -0
  128. package/dist/reshapeable/Reshapeable.d.ts +90 -0
  129. package/dist/serializable/Serializable.d.ts +39 -0
  130. package/dist/serialization/Serialization.d.ts +147 -0
  131. package/dist/serialization/Serialization.js +1 -0
  132. package/dist/serialization/SerializationCompanion.d.ts +125 -0
  133. package/dist/serialization/SerializationCompanion.js +1 -0
  134. package/dist/serialization/error-envelope.d.ts +44 -0
  135. package/dist/serialization/error-envelope.js +1 -0
  136. package/dist/serialization/index.d.ts +4 -2
  137. package/dist/serialization/index.js +1 -1
  138. package/dist/set/index.d.ts +106 -2
  139. package/dist/set/index.js +1 -1
  140. package/dist/stack/Stack.d.ts +120 -0
  141. package/dist/stack/Stack.js +1 -0
  142. package/dist/traced/TraceEvent.d.ts +27 -0
  143. package/dist/traced/TracedOption.d.ts +46 -0
  144. package/dist/traced/TracedOption.js +1 -0
  145. package/dist/traced/Tracer.d.ts +26 -0
  146. package/dist/traversable/KVTraversable.d.ts +14 -0
  147. package/dist/traversable/Traversable.d.ts +30 -0
  148. package/dist/try/index.d.ts +238 -2
  149. package/dist/try/index.js +1 -1
  150. package/dist/tuple/index.d.ts +92 -2
  151. package/dist/tuple/index.js +1 -1
  152. package/dist/typeable/Typeable.d.ts +40 -0
  153. package/dist/typeable/Typeable.js +1 -0
  154. package/dist/typeclass/ContainerOps.d.ts +131 -0
  155. package/dist/typeclass/Functor.d.ts +41 -0
  156. package/dist/typeclass/Promisable.d.ts +33 -0
  157. package/dist/typeclass/index.d.ts +4 -1
  158. package/dist/typeclass/index.js +1 -1
  159. package/dist/typeclass/variance.d.ts +54 -0
  160. package/dist/typeclass/variance.js +1 -0
  161. package/dist/types/index.d.ts +1 -0
  162. package/dist/util/index.d.ts +1 -3
  163. package/dist/valuable/Valuable.d.ts +28 -0
  164. package/dist/valuable/Valuable.js +1 -0
  165. package/dist/wire/index.d.ts +40 -2
  166. package/package.json +7 -12
  167. package/dist/Brand-bfnGXuum.d.ts +0 -54
  168. package/dist/Companion-DiOMBHDG.js +0 -1
  169. package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
  170. package/dist/Invariant-DEan-SxV.d.ts +0 -35
  171. package/dist/Logger-BmprRS8v.d.ts +0 -27
  172. package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
  173. package/dist/Wire-3hvw0Ogg.d.ts +0 -42
  174. package/dist/core/task/index.d.ts +0 -2
  175. package/dist/core/task/index.js +0 -1
  176. package/dist/full-interfaces-BadxJrCt.js +0 -1202
  177. package/dist/index-CLYh2qZu.d.ts +0 -6649
  178. package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
  179. package/dist/serialization-9_SyrfdG.js +0 -3
  180. package/dist/src-BQPeS6p2.js +0 -10
  181. package/dist/typeclass-C61yDVYd.js +0 -1
package/README.md CHANGED
@@ -36,7 +36,7 @@ npx functype --json # JSON output for programmatic use
36
36
  - **List, Set, Map**: Immutable collection types with functional operators
37
37
  - **Try Type**: Safely execute operations that might throw exceptions
38
38
  - **Do-notation**: Scala-like for-comprehensions with **optimized List performance** (up to 12x faster than traditional flatMap)
39
- - **Task**: Handle synchronous and asynchronous operations with error handling
39
+ - **IO**: Lazy effects with typed errors, dependency injection and cancellation
40
40
  - **Http**: Typed HTTP fetch wrapper returning IO effects with HttpError ADT, auto content-type detection, and configurable clients
41
41
  - **Lazy**: Deferred computation with memoization
42
42
  - **Tuple**: Type-safe fixed-length arrays
@@ -58,6 +58,8 @@ functype deliberately is **not** a framework — no fiber runtime, no structured
58
58
 
59
59
  ## Installation
60
60
 
61
+ Upgrading from 1.x? [functype.org/upgrading-to-2](https://functype.org/upgrading-to-2) lists what to change.
62
+
61
63
  ```bash
62
64
  # NPM
63
65
  npm install functype
@@ -72,20 +74,15 @@ pnpm add functype
72
74
  bun add functype
73
75
  ```
74
76
 
75
- ### Bundle Size Optimization
77
+ ### Bundle Size
76
78
 
77
- Functype is optimized for tree-shaking and offers multiple import strategies to minimize bundle size:
79
+ `dist` has one file per module, so a bundler keeps only what you use. An Option-only program ships 5.7 KB gzipped; one using `IO.gen`, Either, Option and List ships 11.5 KB. Root and subpath imports bundle the same:
78
80
 
79
81
  ```typescript
80
- // Selective module imports (recommended for production)
81
- import { Option } from "functype/option"
82
- import { Either } from "functype/either"
83
-
84
- // Direct constructor imports (smallest bundle)
85
- import { some, none } from "functype/option"
82
+ import { Option } from "functype/option" // bundles the same as importing from "functype"
86
83
  ```
87
84
 
88
- For detailed optimization strategies, see the [Bundle Optimization Guide](docs/BUNDLE_OPTIMIZATION.md).
85
+ For the measured sizes and how they are checked, see the [Bundle Size guide](docs/BUNDLE_OPTIMIZATION.md).
89
86
 
90
87
  ## Usage Examples
91
88
 
@@ -261,83 +258,56 @@ const asyncResult = await DoAsync(async function* () {
261
258
  - Always returns the type of the first yielded monad
262
259
  - Mixed types supported via Reshapeable interface
263
260
 
264
- ### Task
261
+ ### IO
265
262
 
266
- Task v2 provides structured error handling with the **Ok/Err pattern**, returning `TaskOutcome<T>` for all operations:
263
+ `IO<R, E, A>` is a lazy effect: nothing runs until you call a `run` method. `E` is the typed error and `R` the services it needs. functype 2.0 deleted `Task`, and IO replaces it.
267
264
 
268
265
  ```typescript
269
- import { Task, Ok, Err, type TaskOutcome } from "functype"
270
-
271
- // Task v2: All operations return TaskOutcome<T>
272
- const syncResult = Task().Sync(() => "success")
273
- // Returns: TaskSuccess<string> (extends TaskOutcome<string>)
274
-
275
- const asyncResult = await Task().Async(async () => "value")
276
- // Returns: TaskOutcome<string>
277
-
278
- // Explicit Ok/Err returns for precise control
279
- const explicitResult = await Task().Async(async (): Promise<TaskOutcome<string>> => {
280
- if (Math.random() > 0.5) {
281
- return Ok("success") // Explicit success
282
- }
283
- return Err<string>("failed") // Explicit failure
284
- })
285
-
286
- // Auto-wrapping: raw values become Ok, thrown errors become Err
287
- const autoWrapped = await Task().Async(async () => {
288
- if (condition) {
289
- return "raw value" // Auto-wrapped as Ok("raw value")
290
- }
291
- throw new Error("failed") // Auto-wrapped as Err(error)
292
- })
293
-
294
- // Error recovery: error handlers can return Ok
295
- const recovered = await Task().Async(
296
- async () => {
297
- throw new Error("initial error")
298
- },
299
- async (error) => Ok("recovered from error"), // Recovery!
300
- )
266
+ import { IO } from "functype"
301
267
 
302
- // Working with results
303
- if (asyncResult.isSuccess()) {
304
- console.log(asyncResult.value) // Access the success value
305
- } else {
306
- console.error(asyncResult.error) // Access the error (Throwable)
307
- }
268
+ type User = { id: string; name: string }
308
269
 
309
- // Chaining with TaskOutcome
310
- const chainedResult = await Task().Async(async () => {
311
- const firstResult = await Task().Async(async () => "first")
312
- if (firstResult.isFailure()) {
313
- return firstResult // Propagate failure
314
- }
270
+ const loadUser = (id: string) =>
271
+ IO.tryPromise({
272
+ // the run's signal reaches fetch, so cancelling stops the request
273
+ try: (signal) => fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<User>),
274
+ catch: (error) => new Error(`Failed to load ${id}: ${String(error)}`),
275
+ })
315
276
 
316
- const secondResult = await Task().Async(async () => "second")
317
- if (secondResult.isFailure()) {
318
- return secondResult
319
- }
277
+ // Nothing has run yet. run() gives an Either<Error, User>
278
+ const user = await loadUser("42").retry(2).timeout(5000).run()
320
279
 
321
- return Ok(`${firstResult.value} + ${secondResult.value}`)
322
- })
280
+ // Cancel with a handle, or with your own AbortSignal
281
+ const { result, cancel } = loadUser("42").runCancellable()
282
+ const controller = new AbortController()
283
+ const exit = await loadUser("42").runExit({ signal: controller.signal }) // Success | Failure | Die | Interrupted
284
+ ```
323
285
 
324
- // Converting promise-based functions to Task
325
- const fetchUserAPI = (userId: string): Promise<User> => fetch(`/api/users/${userId}`).then((r) => r.json())
286
+ #### Tracing
326
287
 
327
- const fetchUser = Task.fromPromise(fetchUserAPI)
328
- // Returns: (userId: string) => Promise<TaskOutcome<User>>
288
+ `withSpan(name, attributes?)` runs an effect in a span, and a `withSpan` inside it nests under it without being passed a parent. functype ships only the contract, `SpanTracer`: with no tracer provided, `withSpan` does nothing. A tracer has three methods. `start(name, attributes, parent)` opens a span, `run(span, fn)` runs the body with the span active, and `end(span, exit)` closes it once, for every outcome.
329
289
 
330
- const userResult = await fetchUser("user123")
331
- if (userResult.isSuccess()) {
332
- console.log(userResult.value) // User object
290
+ ```typescript
291
+ import { context, type Span, SpanStatusCode, trace } from "@opentelemetry/api" // your dependency, not functype's
292
+ import { SpanTracer } from "functype"
293
+
294
+ const otel = trace.getTracer("my-app")
295
+ const otelTracer: SpanTracer<Span> = {
296
+ start: (name, attributes, parent) =>
297
+ otel.startSpan(name, { attributes }, parent ? trace.setSpan(context.active(), parent) : context.active()),
298
+ run: (span, fn) => context.with(trace.setSpan(context.active(), span), fn), // makes the span active
299
+ end: (span, exit) => {
300
+ if (exit._tag === "Failure" || exit._tag === "Die") span.setStatus({ code: SpanStatusCode.ERROR })
301
+ span.end()
302
+ },
333
303
  }
334
304
 
335
- // Convert TaskOutcome back to Promise (for interop)
336
- const promise = Task.toPromise(asyncResult)
337
- // Success → resolves with value
338
- // Failure → rejects with error
305
+ // Provide the tracer outside the spans
306
+ await loadUser("42").withSpan("loadUser", { "user.id": "42" }).provideService(SpanTracer, otelTracer).run()
339
307
  ```
340
308
 
309
+ This bridge is a sketch, not a package: functype has no OpenTelemetry dependency. Because `run` makes the span active, a log sink inside `withSpan` reads the trace IDs with `trace.getActiveSpan()`. That needs a registered OpenTelemetry context manager, which the Node SDK sets up; without one, `context.with` runs the body with no span active. The [IO docs](https://functype.org/io) cover nesting, cancellation and `runSync`.
310
+
341
311
  ### Branded Types
342
312
 
343
313
  ```typescript
@@ -405,7 +375,7 @@ const tracer: Tracer = { emit: (e) => void events.push(e) }
405
375
 
406
376
  TracedOption(user, tracer, "span-1")
407
377
  .map((u) => u.name.trim(), "trim")
408
- .orElse("anonymous", "fallback")
378
+ .getOrElse(() => "anonymous", "fallback")
409
379
  ```
410
380
 
411
381
  ## Conditional Programming
@@ -696,7 +666,7 @@ list.forEach(console.log) // Logs: 1, 2, 3, 4, 5
696
666
 
697
667
  ## ESLint Plugin
698
668
 
699
- [`eslint-plugin-functype`](https://functype.org/eslint) enforces these patterns. `recommended` fails the build on the rules that are reliably right (loops, `let`, native `Map`/`Set` you only read, `isSome()` branching) and warns on the rest. Declare boundaries with `Wire<T>` and `@interop`, and write bug checks as `invariant(cond, msg)`, instead of `eslint-disable`.
669
+ [`eslint-plugin-functype`](https://functype.org/eslint) enforces these patterns. Its one preset, `recommended`, sets every rule to `error` or `off`, so a finding fails the build rather than sit as a warning. Declare boundaries with `Wire<T>` and `@interop`, and write bug checks as `invariant(cond, msg)`, instead of `eslint-disable`.
700
670
 
701
671
  ## Feature Matrix
702
672
 
@@ -719,20 +689,25 @@ const mappedValue = option.map((x) => x.toString())
719
689
  Functype provides utilities for improved error visualization and logging:
720
690
 
721
691
  ```typescript
722
- import { formatError, createErrorSerializer } from "functype/error"
692
+ import { Throwable, createErrorSerializer, formatError, formatErrorChain } from "functype"
723
693
 
724
- // Create a nested task error
725
- const innerTask = Task({ name: "DbQuery" }).Sync(() => {
726
- throw new Error("Database connection failed")
694
+ // A failure in a named step, wrapping the error below it as its cause
695
+ const dbError = Throwable.apply(new Error("Database connection failed"), undefined, {
696
+ name: "DbQuery",
697
+ description: "Load the user row",
727
698
  })
728
-
729
- const outerTask = Task({ name: "UserFetch" }).Sync(() => {
730
- return innerTask.value
699
+ const error = Throwable.apply(new Error("Failed to fetch user", { cause: dbError }), undefined, {
700
+ name: "UserFetch",
701
+ description: "Fetch user data",
731
702
  })
732
703
 
704
+ formatErrorChain(error, { includeTasks: true })
705
+ // [UserFetch] Failed to fetch user
706
+ // ↳ [DbQuery] Database connection failed
707
+
733
708
  // Format the error for console display
734
709
  console.error(
735
- formatError(outerTask.value as Error, {
710
+ formatError(error, {
736
711
  includeTasks: true,
737
712
  includeStackTrace: true,
738
713
  colors: true,
@@ -750,7 +725,7 @@ const logger = pino({
750
725
  // Log the error with full context
751
726
  logger.error(
752
727
  {
753
- err: outerTask.value,
728
+ err: error,
754
729
  requestId: "req-123",
755
730
  },
756
731
  "Failed to fetch user data",
@@ -857,16 +832,16 @@ For more details, see the [Error Formatting Guide](docs/error-formatting.md).
857
832
  Work that shipped but wasn't captured in the planned roadmap above:
858
833
 
859
834
  - [x] **Scala-aligned covariance for the container family** (0.57.2 → 0.60.0)
860
- - ✓ `<out T>` / `<out K, out V>` across Option, Either, Try, List, Set, Map, Lazy, LazyList, Tuple, Identity, Task/TaskOutcome
835
+ - ✓ `<out T>` / `<out K, out V>` across Option, Either, Try, List, Set, Map, Lazy, LazyList, Tuple, Identity
861
836
  - ✓ `FunctypeSum` hierarchy separating sum types (Either, Try) from iterables
862
837
  - ✓ `Widen<A, B>` conditional-type helper enforcing Scala's `[B >: A]` lower-bound semantics in `reduce` / `reduceRight`
863
- - ✓ Method-level widening patterns (`or`, `orElse`, `recover`, `add`, `concat`, etc.)
838
+ - ✓ Method-level widening patterns (`orElse`, `getOrElse`, `recover`, `add`, `concat`, etc.)
864
839
  - ✓ Contributor guide at [`docs/variance-guide.md`](docs/variance-guide.md)
865
840
  - Deferred: ZIO-style `<in R, out E, out A>` for IO
866
841
  - [x] **Do-notation with generator comprehensions** (`src/do/`)
867
842
  - [x] **HTTP module** — typed fetch wrapper with validator support (`src/fetch/` — Http, HttpClient, HttpError, HttpRequest)
868
843
  - [x] **Throwable** — enhanced error wrapper preserving stack traces and context (`src/core/throwable/`)
869
- - [x] **Task / TaskOutcome** — sync/async with cancellation + progress tracking (`src/core/task/`)
844
+ - [x] **Task / TaskOutcome** — deleted in 2.0; IO's `runCancellable`, `runExit({ signal })` and `interruptOn` replace it
870
845
  - [x] **IO effect system companions** — Context, Tag, Layer, Exit, TestClock (`src/io/`)
871
846
  - [x] **Ref** — mutable reference for controlled mutability (`src/ref/`)
872
847
  - [x] **Identity** — trivial covariant container (`src/identity/`)
@@ -875,7 +850,7 @@ Work that shipped but wasn't captured in the planned roadmap above:
875
850
  - [x] **MCP server for functype documentation** (`mcp-server/`)
876
851
  - [x] **CLI — `npx functype`** (`src/cli/`)
877
852
  - [x] **Claude Code skills** — `functype` (user guide) and `functype-developer` (contributor guide)
878
- - [x] **Serialization infrastructure** — JSON / YAML / binary (`src/serialization/`)
853
+ - [x] **Serialization infrastructure** — JSON / binary (`src/serialization/`)
879
854
 
880
855
  ## Claude Code Skills
881
856
 
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)};export{t as __exportAll};
@@ -0,0 +1,122 @@
1
+ import { Either } from "../either/index.js";
2
+ import { Option } from "../option/index.js";
3
+ import { Brand } from "./index.js";
4
+ export type ValidatedBrand<K extends string, T> = Brand<K, T> & {
5
+ readonly __validated: true;
6
+ };
7
+ export interface ValidatedBrandCompanion<K extends string, T> {
8
+ readonly brand: K;
9
+ readonly validate: (value: T) => boolean;
10
+ readonly of: (value: T) => Option<ValidatedBrand<K, T>>;
11
+ readonly from: (value: T) => Either<string, ValidatedBrand<K, T>>;
12
+ readonly unsafeOf: (value: T) => ValidatedBrand<K, T>;
13
+ readonly is: (value: unknown) => value is ValidatedBrand<K, T>;
14
+ readonly unwrap: (branded: Brand<K, T>) => T;
15
+ readonly refine: <K2 extends string>(brand: K2, validate: (value: Brand<K, T>) => boolean) => ValidatedBrandCompanion<K2, Brand<K, T>>;
16
+ }
17
+ /**
18
+ * Create a validated brand with runtime validation
19
+ * @example
20
+ * const Email = ValidatedBrand("Email", (s: string) => /^[^@]+@[^@]+\.[^@]+$/.test(s))
21
+ * const email = Email.of("user@example.com") // Some(Brand<"Email", string>)
22
+ *
23
+ * @example
24
+ * // With Either for error messages
25
+ * const Port = ValidatedBrand("Port", (n: number) => n >= 1 && n <= 65535)
26
+ * const result = Port.from(8080) // Right(Brand<"Port", number>)
27
+ * const error = Port.from(70000) // Left("Invalid Port: validation failed")
28
+ *
29
+ * @example
30
+ * // Type guard usage
31
+ * const value: unknown = "test@example.com"
32
+ * if (Email.is(value)) {
33
+ * // value is Brand<"Email", string>
34
+ * }
35
+ *
36
+ * @example
37
+ * // Best Practice: Use same brand name for seamless conversion
38
+ * // ValidatedBrand extends Brand, so when using the same brand name,
39
+ * // no casting is needed for conversion
40
+ * const ValidatedUserId = ValidatedBrand("UserId", (s: string) => s.length > 0)
41
+ * type ValidatedUserId = ReturnType<typeof ValidatedUserId.of> extends Option<infer T> ? T : never
42
+ * type UserId = Brand<"UserId", string>
43
+ *
44
+ * const toSimpleUserId = (id: ValidatedUserId): UserId => id // No cast needed!
45
+ *
46
+ * // Avoid different brand names which require casting:
47
+ * // ❌ ValidatedBrand("ValidatedUserId", ...) + Brand<"UserId", string>
48
+ * // ✅ ValidatedBrand("UserId", ...) + Brand<"UserId", string>
49
+ */
50
+ export declare function ValidatedBrand<K extends string, T>(brand: K, validate: (value: T) => boolean): ValidatedBrandCompanion<K, T>;
51
+ /**
52
+ * Positive number brand (> 0)
53
+ * @example
54
+ * const price = PositiveNumber.of(19.99) // Some(Brand<"PositiveNumber", number>)
55
+ * const invalid = PositiveNumber.of(-5) // None
56
+ * const checked = PositiveNumber.from(0) // Left("Invalid PositiveNumber: validation failed")
57
+ */
58
+ export declare const PositiveNumber: ValidatedBrandCompanion<"PositiveNumber", number>;
59
+ export declare const NonNegativeNumber: ValidatedBrandCompanion<"NonNegativeNumber", number>;
60
+ export declare const IntegerNumber: ValidatedBrandCompanion<"IntegerNumber", number>;
61
+ export declare const PositiveInteger: ValidatedBrandCompanion<"PositiveInteger", Brand<"PositiveNumber", number>>;
62
+ /**
63
+ * Non-empty string brand
64
+ * @example
65
+ * const name = NonEmptyString.of("John") // Some(Brand<"NonEmptyString", string>)
66
+ * const empty = NonEmptyString.of("") // None
67
+ */
68
+ export declare const NonEmptyString: ValidatedBrandCompanion<"NonEmptyString", string>;
69
+ /**
70
+ * Email address brand with basic validation
71
+ * @example
72
+ * const email = EmailAddress.of("user@example.com") // Some(Brand<"EmailAddress", string>)
73
+ * const invalid = EmailAddress.of("not-an-email") // None
74
+ *
75
+ * @example
76
+ * // Using with forms
77
+ * const processEmail = (input: string) => {
78
+ * return EmailAddress.from(input)
79
+ * .map(email => sendWelcomeEmail(email))
80
+ * .getOrElse(() => "Invalid email address")
81
+ * }
82
+ */
83
+ export declare const EmailAddress: ValidatedBrandCompanion<"EmailAddress", string>;
84
+ export declare const UrlString: ValidatedBrandCompanion<"UrlString", string>;
85
+ export declare const UUID: ValidatedBrandCompanion<"UUID", string>;
86
+ export declare const ISO8601Date: ValidatedBrandCompanion<"ISO8601Date", string>;
87
+ /**
88
+ * Create a number brand with min/max bounds
89
+ * @example
90
+ * const Percentage = BoundedNumber("Percentage", 0, 100)
91
+ * const valid = Percentage.of(75) // Some(Brand<"Percentage", number>)
92
+ * const invalid = Percentage.of(150) // None
93
+ *
94
+ * @example
95
+ * const Port = BoundedNumber("Port", 1, 65535)
96
+ * const httpPort = Port.unsafeOf(80) // Brand<"Port", number>
97
+ * // Port.unsafeOf(70000) // throws Error
98
+ */
99
+ export declare function BoundedNumber(brand: string, min: number, max: number): ValidatedBrandCompanion<string, number>;
100
+ /**
101
+ * Create a string brand with length constraints
102
+ * @example
103
+ * const Username = BoundedString("Username", 3, 20)
104
+ * const valid = Username.of("johndoe") // Some(Brand<"Username", string>)
105
+ * const tooShort = Username.of("jo") // None
106
+ * const tooLong = Username.of("verylongusernamethatexceedslimit") // None
107
+ */
108
+ export declare function BoundedString(brand: string, minLength: number, maxLength: number): ValidatedBrandCompanion<string, string>;
109
+ /**
110
+ * Create a string brand that matches a regex pattern
111
+ * @example
112
+ * const HexColor = PatternString("HexColor", /^#[0-9a-f]{6}$/i)
113
+ * const red = HexColor.of("#ff0000") // Some(Brand<"HexColor", string>)
114
+ * const invalid = HexColor.of("red") // None
115
+ *
116
+ * @example
117
+ * const PhoneNumber = PatternString("PhoneNumber", /^\+?[1-9]\d{1,14}$/)
118
+ * const phone = PhoneNumber.from("+1234567890")
119
+ * .map(p => formatPhoneNumber(p))
120
+ * .getOrElse(() => "Invalid phone number")
121
+ */
122
+ export declare function PatternString(brand: string, pattern: RegExp): ValidatedBrandCompanion<string, string>;
@@ -0,0 +1 @@
1
+ import{Left as e,Right as t}from"../either/index.js";import{Option as n}from"../option/index.js";import{Brand as r}from"./index.js";function i(a,o){return{brand:a,validate:o,of:e=>o(e)?n(r(a,e)):n.none(),from:n=>o(n)?t(r(a,n)):e(`Invalid ${a}: validation failed`),unsafeOf:e=>{if(!o(e))throw Error(`Invalid ${a}: validation failed`);return r(a,e)},is:e=>{try{return o(e)}catch{return!1}},unwrap:e=>e,refine:(e,t)=>i(e,e=>o(e)&&t(e))}}const a=i(`PositiveNumber`,e=>e>0),o=i(`NonNegativeNumber`,e=>e>=0),s=i(`IntegerNumber`,e=>Number.isInteger(e)),c=a.refine(`PositiveInteger`,e=>Number.isInteger(e)),l=i(`NonEmptyString`,e=>e.length>0),u=i(`EmailAddress`,e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)),d=i(`UrlString`,e=>{try{return new URL(e),!0}catch{return!1}}),f=i(`UUID`,e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)),p=i(`ISO8601Date`,e=>!isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e));function m(e,t,n){return i(e,e=>e>=t&&e<=n)}function h(e,t,n){return i(e,e=>e.length>=t&&e.length<=n)}function g(e,t){return i(e,e=>t.test(e))}export{m as BoundedNumber,h as BoundedString,u as EmailAddress,p as ISO8601Date,s as IntegerNumber,l as NonEmptyString,o as NonNegativeNumber,g as PatternString,c as PositiveInteger,a as PositiveNumber,f as UUID,d as UrlString,i as ValidatedBrand};
@@ -1,2 +1,52 @@
1
- import { a as ExtractBrand, c as hasBrand, i as BrandedString, l as unwrapBrand, n as BrandedBoolean, o as Unwrap, r as BrandedNumber, s as createBrander, t as Brand } from "../Brand-bfnGXuum.js";
2
- export { Brand, BrandedBoolean, BrandedNumber, BrandedString, ExtractBrand, Unwrap, createBrander, hasBrand, unwrapBrand as unwrap, unwrapBrand };
1
+ export type Brand<K extends string, T> = T & {
2
+ readonly __brand: K;
3
+ };
4
+ export type Unwrap<T> = T extends Brand<string, infer U> ? U : T;
5
+ export type ExtractBrand<T> = T extends Brand<infer K, unknown> ? K : never;
6
+ /**
7
+ * Brand is a utility for creating nominal typing in TypeScript.
8
+ * It creates phantom types that exist only at compile time.
9
+ * At runtime, the branded value IS the primitive value.
10
+ *
11
+ * @param _brand
12
+ * @param value - The value to brand
13
+ * @returns The value with phantom type brand
14
+ */
15
+ export declare function Brand<K extends string, T>(_brand: K, value: T): Brand<K, T>;
16
+ /**
17
+ * Helper to unwrap a branded value to its underlying type
18
+ * Works with both Brand and ValidatedBrand
19
+ * @param branded - The branded value (can be null or undefined)
20
+ * @returns The original value without the brand
21
+ *
22
+ * Note: Also exported as 'unwrap' from 'functype/branded' for convenience
23
+ */
24
+ export declare function unwrapBrand<K extends string, T>(branded: Brand<K, T>): T;
25
+ export declare function unwrapBrand<K extends string, T>(branded: Brand<K, T> | null): T | null;
26
+ export declare function unwrapBrand<K extends string, T>(branded: Brand<K, T> | undefined): T | undefined;
27
+ export declare function unwrapBrand<K extends string, T>(branded: Brand<K, T> | null | undefined): T | null | undefined;
28
+ /**
29
+ * Type guard for checking if a value has a specific brand
30
+ * @param value - The value to check
31
+ * @param _brand - The brand to check for (unused at runtime)
32
+ * @returns True if the value has the specified brand
33
+ *
34
+ * Note: Since brands are phantom types that exist only at compile time,
35
+ * this function can only provide a runtime approximation. It always returns true
36
+ * for non-null values, as we have no way to actually check the brand at runtime.
37
+ * This function is primarily for API consistency and documentation purposes.
38
+ */
39
+ export declare function hasBrand<K extends string, T>(value: unknown, _brand: K): value is Brand<K, T>;
40
+ /**
41
+ * Create a branded type constructor for a specific brand
42
+ * @param brand - The brand name
43
+ * @returns A function that brands values with the specified brand
44
+ */
45
+ export declare function createBrander<K extends string, T>(brand: K): (value: T) => Brand<K, T>;
46
+ export type BrandedString<K extends string> = Brand<K, string>;
47
+ export type BrandedNumber<K extends string> = Brand<K, number>;
48
+ export type BrandedBoolean<K extends string> = Brand<K, boolean>;
49
+ export declare const BrandedString: <K extends string>(brand: K) => (value: string) => BrandedString<K>;
50
+ export declare const BrandedNumber: <K extends string>(brand: K) => (value: number) => BrandedNumber<K>;
51
+ export declare const BrandedBoolean: <K extends string>(brand: K) => (value: boolean) => BrandedBoolean<K>;
52
+ export { unwrapBrand as unwrap };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Curated API data for CLI output, optimized for LLM consumption.
3
+ *
4
+ * `interfaces` arrays are composed of (a) the GENERATED_INTERFACES floor
5
+ * derived from each type's `extends` chain in source, plus (b) optional
6
+ * hand-curated additions for capabilities declared inline (e.g. `List.map`
7
+ * lives in the interface body, not via `extends Functor`). The data-sync
8
+ * spec enforces that no source-declared interface is dropped from this list.
9
+ */
10
+ export declare const VERSION: string;
11
+ export interface TypeData {
12
+ description: string;
13
+ interfaces: string[];
14
+ methods: {
15
+ create?: string[];
16
+ transform?: string[];
17
+ extract?: string[];
18
+ check?: string[];
19
+ other?: string[];
20
+ };
21
+ }
22
+ export interface InterfaceData {
23
+ extends?: string;
24
+ description: string;
25
+ methods: string[];
26
+ }
27
+ export declare const TYPES: Record<string, TypeData>;
28
+ export declare const INTERFACES: Record<string, InterfaceData>;
29
+ export declare const CATEGORIES: {
30
+ Core: string[];
31
+ Collection: string[];
32
+ Effect: string[];
33
+ Utility: string[];
34
+ Validation: string[];
35
+ Serialization: string[];
36
+ Service: string[];
37
+ };
@@ -0,0 +1 @@
1
+ import{version as e}from"../package.json.js";import{GENERATED_INTERFACES as t}from"./interfaces.generated.js";const n=e,r=(e,...n)=>Array.from(/* @__PURE__ */ new Set([...t[e],...n])).sort(),i={Option:{description:`Safe nullable handling - Some<T> or None`,interfaces:r(`Option`),methods:{create:[`Option(v)`,`Option.none()`,`Some(v)`,`None()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.ap(ff)`,`.orElse(() => alt)`],extract:[`.fold(n, s)`,`.foldAsync(n, s)`,`.getOrElse(() => d)`,`.orThrow(err | () => Error)`,`.expect(() => never)`,`.orNull()`,`.match({Some, None})`,`.toEither(left | () => left)`,`.toList()`,`.toArray()`],check:[`.isSome()`,`.isNone()`,`.isEmpty`,`.exists(p)`,`.every(p)`],other:[`Option.sequence(arr)`,`Option.traverse(arr, f)`]}},Either:{description:`Error handling with Left (error) or Right (success)`,interfaces:r(`Either`,`Traversable`),methods:{create:[`Right(v)`,`Left(e)`,`Either.right(v)`,`Either.left(e)`,`Either.void()`],transform:[`.map(f)`,`.flatMap(f)`,`.mapLeft(f)`,`.swap()`,`.orElse(() => alt)`],extract:[`.fold(l, r)`,`.foldAsync(l, r)`,`.getOrElse(() => d)`,`.orThrow(err | (left) => Error)`,`.expect((l) => never)`,`.match({Left, Right})`],check:[`.isRight()`,`.isLeft()`,`.exists(p)`,`.every(p)`],other:[`Either.sequence(arr)`,`Either.traverse(arr, f)`,`Either.traverseAsync(items, f, {concurrency?}) // in order by default, stops at first Left`,`Either.fromNullable(v, e)`]}},Try:{description:`Wrap operations that may throw - Success<T> or Failure`,interfaces:r(`Try`,`Matchable`,`Traversable`),methods:{create:[`Try(() => expr)`,`Try.success(v)`,`Try.failure(e)`,`Try.fromPromise(p)`,`Try.async(() => Promise<T>)`],transform:[`.map(f)`,`.flatMap(f)`,`.recover(f)`,`.recoverWith(f)`,`.orElse(() => alt)`],extract:[`.fold(f, s)`,`.foldAsync(f, s)`,`.getOrElse(() => d)`,`.orThrow(err | (error) => Error)`,`.expect((e) => never)`,`.toOption()`,`.toEither(left | (err) => left)`,`.toList()`,`.toArray()`],check:[`.isSuccess()`,`.isFailure()`,`.exists(p)`,`.every(p)`],other:[`Try.sequence(arr)`,`Try.traverse(arr, f)`]}},List:{description:`Immutable array with functional operations`,interfaces:r(`List`,`Functor`,`Monad`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`List([...])`,`List.of(...)`,`List.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.take(n)`,`.takeWhile(p)`,`.takeRight(n)`,`.drop(n)`,`.dropRight(n)`,`.dropWhile(p)`,`.flatten()`,`.concat(list)`,`.reverse()`,`.distinct()`,`.sorted()`,`.sortBy(f)`,`.zip(list)`,`.zipWithIndex()`,`.prepend(v)`,`.slice(s, e)`],extract:[`.fold(z, f)`,`.reduce(f)`,`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.indexOf(v)`,`.toArray()`],check:[`.isEmpty`,`.size`,`.contains(v)`,`.exists(p)`,`.every(p)`],other:[`.groupBy(f)`,`.partition(p)`,`.span(p)`,`.mapAsync(f, {concurrency?}) // in order by default`,`.flatMapAsync(f, {concurrency?})`]}},Set:{description:`Immutable set of unique values`,interfaces:r(`Set`,`Functor`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`Set([...])`,`Set.of(...)`,`Set.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.filterNot(p)`,`.add(v)`,`.remove(v)`,`.union(other)`,`.intersection(other)`,`.difference(other)`,`.symmetricDifference(other)`,`.mapAsync(f, {concurrency?}) // in order by default`],extract:[`.fold(z, f)`,`.toArray()`],check:[`.has(v)`,`.isEmpty`,`.size`,`.exists(p)`,`.every(p)`,`.isSubsetOf(other)`,`.isSupersetOf(other)`,`.isDisjointFrom(other)`],other:[`import { Set } from "functype" // its own name; the built-in is globalThis.Set`]}},Obj:{description:`Immutable object wrapper with fluent operations`,interfaces:r(`Obj`,`KVTraversable`,`Foldable`,`Matchable`,`Extractable`,`Serializable`),methods:{create:[`Obj({...})`,`Obj.of({...})`,`Obj.empty()`],transform:[`.set(k, v)`,`.assign(partial)`,`.merge(obj)`,`.when(cond, partial)`,`.omit(...keys)`,`.pick(...keys)`,`.map(f)`,`.flatMap(f)`],extract:[`.get(k)`,`.value()`,`.keys()`,`.values()`,`.entries()`,`.fold(n, s)`,`.match({Obj})`],check:[`.has(k)`,`.isEmpty`,`.size`]}},Map:{description:`Immutable key-value store`,interfaces:r(`Map`),methods:{create:[`Map([[k, v], ...])`,`Map.of([k, v], ...)`,`Map.empty()`,`Map.fromJSON(json)`,`Map.fromBinary(b)`],transform:[`.add(Tuple([k, v]))`,`.remove(k)`,`.map(f)`,`.flatMap(f)`,`.ap(ff)`,`.flatMapAsync(f)`],extract:[`.get(k) // Option<V>`,`.keys() // List<K>`,`.values() // List<V>`,`.getOrElse(k, () => d)`,`.orElse(k, () => Option<V>)`,`.fold(z, f)`,`.foldLeft(z)(f)`,`.foldRight(z)(f)`,`.match({Empty, NonEmpty})`,`.toList()`,`.toSet()`,`[...map] // iterate [k, v] pairs`],check:[`.has(k) // key only`,`.contains(Tuple([k, v])) // === on the value`,`.isEmpty`,`.size`],other:[`import { Map } from "functype" // its own name; the built-in is globalThis.Map`]}},Lazy:{description:"Deferred computation with memoization. Note: `serialize()` and `toValue()` FORCE the thunk (visible side effect) since a closure cannot be JSON-serialized — there is no representable 'unevaluated post-serialize' state. Thunk failures are captured via SerializedError and rethrown on access after fromJSON.",interfaces:r(`Lazy`),methods:{create:[`Lazy(() => expr)`,`Lazy.fromValue(value) — wrap a non-deferred value`,`Lazy.evaluated(value) — reads as 'already-forced'; used by fromJSON`,`Lazy.fail(error) — Lazy that throws on access`],transform:[`.map(f)`,`.flatMap(f)`],extract:[`.fold(f)`,`.foldWith(onFailure, onSuccess)`,`.getOrElse(() => d)`,`.orNull()`,`.orThrow()`,`.toJSON()`,`Lazy.fromJSON(json)`],check:[`.isEvaluated`]}},LazyList:{description:`Lazy sequences for large/infinite data`,interfaces:r(`LazyList`,`Functor`,`Monad`,`Iterable`),methods:{create:[`LazyList(iterable)`,`LazyList.from(a, b, ...)`,`LazyList.of(a, b, ...)`,`LazyList.range(start, end)`,`LazyList.iterate(seed, f)`,`LazyList.generate(f)`,`LazyList.fromJSON(json)`],transform:[`.map(f)`,`.filter(p)`,`.take(n)`,`.takeRight(n)`,`.drop(n)`,`.takeWhile(p)`,`.dropWhile(p)`,`.concat(ll)`,`.reverse()`,`.distinct()`,`.zip(ll)`,`.zipWithIndex()`],extract:[`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.find(p)`,`.toArray()`,`.toJSON()`],check:[`.some(p)`,`.every(p)`,`.count()`]}},Exit:{description:`Outcome of running an IO effect — Success | Failure | Die | Interrupted, returned by .runExit(). Die carries a defect: a value that is not an E. Either has no branch for one, so .run() rejects on it.`,interfaces:[],methods:{create:[`Exit.succeed(v)`,`Exit.fail(e)`,`Exit.die(defect)`,`Exit.interrupt(fiberId)`,`Exit.interrupted()`],transform:[`.map(f)`,`.mapError(f)`,`.mapBoth(onErr, onOk)`,`.flatMap(f)`],extract:[`.fold(onFailure, onSuccess, onInterrupted?, onDie?)`,`.match({Success, Failure, Interrupted, Die?})`,`.orThrow()`,`.getOrElse(() => v)`,`.toOption()`,`.toEither()`,`.toValue()`],check:[`.isSuccess()`,`.isFailure()`,`.isDie()`,`.isInterrupted()`],other:[`Exit.zip(a, b)`,`Exit.all(exits)`,`Exit.fromEither(e)`,`Exit.fromOption(o, onNone)`,`// after a guard: .value / .error / .defect / .fiberId`,`// onDie / Die are optional and fall back to the failure handler`,`// defects stay recoverable: .recover/.recoverWith/.fold/.mapError treat Die as Failure`]}},IO:{description:`Lazy effect type with typed errors and dependency injection`,interfaces:[`Functor`,`Monad`,`Foldable`,`Matchable`],methods:{create:[`IO(() => v)`,`IO.succeed(v)`,`IO.fail(e)`,`IO.sync(f)`,`IO.async(f)`,`IO.tryPromise({try, catch})`,`IO.fromEither(e)`,`IO.fromPromiseEither(f, onReject?)`,`IO.fromOption(o)`,`IO.fromTry(t)`,`IO.die(defect)`],transform:[`.map(f)`,`.flatMap(f)`,`.tap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.run() // Either<E,A> — Left holds only E; a defect or interruption rejects`,`.runOrThrow()`,`.runSync() // Either<E,A>; throws a defect or interruption`,`.runSyncOrThrow()`,`.runExit() // Exit<E,A> — the only terminal that distinguishes Failure/Die/Interrupted`,`.runCancellable() // { result, cancel }`,`.runExit({ signal }) // Interrupted on abort, E unchanged`,`.runOption()`,`.runTry()`,`.fold(onErr, onOk)`,`.match({failure, success})`],check:[],other:[`.catchTag(tag, f)`,`.catchAll(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.repeatUntil(done, { max, delayMs? })`,`.repeatWhile(cont, { max, delayMs? })`,`.timeout(ms) // interrupts the effect at the deadline`,`.interruptOn(signal) // stops at the next step once the AbortSignal fires; E gains InterruptedError`,`.withSpan(name, attributes?) // runs in a span via the provided SpanTracer; an inner withSpan nests under it`,`IO.async((signal?) => fetch(url, { signal })) // thunk gets the run's AbortSignal inside a region`,`.delay(ms)`,`.zip(io)`,`.pipe(f)`,`IO.all([...], { concurrency? }) // all at once by default; first failure interrupts the rest`,`IO.forEach(items, f, { concurrency? })`,`IO.race([...]) // first to settle wins; the rest are interrupted`,`IO.firstSuccessOf([...]) // tries each in order; the first success wins`,`IO.iterate(seed, step, done, { max? })`,`IO.bracket(acquire, use, release)`,`IO.gen(function*() {...})`,`IO.Do.bind().map()`,`IO.service(Tag)`,`.provideService(Tag, impl)`,`.provideLayer(layer)`]}},Cond:{description:`Conditional expression builder - replace if-else chains`,interfaces:[],methods:{create:[`Cond<T>()`],other:[`.case(pred, result)`,`.otherwise(result)`,`.eval()`]}},Match:{description:`Pattern matching - replace switch statements`,interfaces:[],methods:{create:[`Match(value)`],other:[`.case(pattern, result)`,`.when(pred, result)`,`.default(result)`,`.done()`]}},Brand:{description:`Nominal typing without runtime overhead`,interfaces:[],methods:{create:[`Brand<K, T>(value)`],extract:[`.unwrap()`,`.toString()`]}},Wire:{description:`Serialization-boundary marker for a row, collection or nullable field at DB / HTTP / JSONB boundaries. Zero runtime, assignable both ways with T. prefer-list and prefer-option skip everything inside it. A collection is Wire<ReadonlyArray<Row>>.`,interfaces:[],methods:{create:[`type UserRow = Wire<{ email: string | null }>`,`type Rows = Wire<ReadonlyArray<Row>>`,`email: Wire<string | null>`],other:[`List(rows).filter(...) // convert to List for transformation`,`Option(row.email) // convert to Option`]}},ValidatedBrand:{description:`Branded types with runtime validation`,interfaces:[],methods:{create:[`ValidatedBrand(validator)`,`.of(v)`,`.from(v)`,`.unsafeOf(v)`],check:[`.is(v)`],other:[`.refine(validator)`]}},Tuple:{description:`Fixed-size typed array`,interfaces:r(`Tuple`,`Typeable`,`Valuable`,`Iterable`),methods:{create:[`Tuple([a, b, ...])`,`Tuple.of(a, b, ...)`,`Tuple.fromJSON(json)`],extract:[`.get(i)`,`.length`,`.toArray()`,`.toJSON()`],transform:[`.map(f)`]}},Identity:{description:`The identity monad: wraps a value with no extra effect. Useful as a neutral container in generic code.`,interfaces:[],methods:{create:[`Identity(value)`,`Identity.of(value)`,`Identity.pure(value)`],extract:[`.id`],other:[`.isSame(other)`]}},Ref:{description:`Mutable reference cell for controlled, local mutability. Invariant in A by design (a mutable cell can't be widened).`,interfaces:[],methods:{create:[`Ref(initial)`,`Ref.of(initial)`],extract:[`.get()`],transform:[`.set(a)`,`.update(f)`,`.modify(f) // returns B, stores A`],other:[`.getAndSet(a)`,`.updateAndGet(f)`,`.getAndUpdate(f)`,`.compareAndSet(expected, next)`]}},Do:{description:`Generator do-notation across Option, Either, List and Try (DoAsync for promises). Short-circuits on None/Left/Failure/empty List.`,interfaces:[],methods:{create:[`Do(function* () { const a = yield* $(opt); return a })`,`DoAsync(async function* () { … })`],other:[`$(monad) // unwrap inside Do`,`isDoCapable(value)`,`unwrap(monad)`]}},invariant:{description:`One-line bug check: invariant(cond, msg) throws a tagged InvariantViolation when cond is falsy and narrows cond after it. For programmer errors only; expected failures return Either.`,interfaces:[],methods:{create:[`invariant(row, "upsert returned no row")`,"invariant(n >= 0, () => `bad step ${n}`) // lazy message"],other:[`InvariantViolation(msg) // throw directly for an unreachable branch`]}},TracedOption:{description:`Opt-in Option wrapper that emits one TraceEvent per combinator to an injected Tracer, then delegates. For code-path introspection.`,interfaces:[],methods:{create:[`TracedOption(option, tracer, spanId, seq?)`],transform:[`.map(f, label?)`,`.flatMap(f, label?)`,`.filter(p, label?)`],extract:[`.fold(onNone, onSome, label?)`,`.getOrElse(() => default, label?)`,`.unwrap() // back to Option`]}},Tracer:{description:`One-method trace sink consumed by TracedOption. Type-only, like Logger; declare your own Tag for injection.`,interfaces:[],methods:{create:[`const tracer: Tracer = { emit: (e: TraceEvent) => … }`],other:[`TraceEvent: { spanId, seq, op, tag, inTag, outTag?, label?, meta? }`]}},SpanTracer:{description:`Span contract and Tag for IO.withSpan: start, run (body with the span active), end. None provided: withSpan is a no-op.`,interfaces:[],methods:{create:[`const tracer: SpanTracer<MySpan> = { start, run, end }`,`io.withSpan("name", { key: "value" }).provideService(SpanTracer, tracer) // provide outside the spans`],other:[`OpenTelemetry: run = (span, fn) => context.with(trace.setSpan(context.active(), span), fn)`,`parent is the enclosing span in this run, or undefined; fall back to the ambient context then`]}},Stack:{description:`Immutable LIFO stack`,interfaces:[`Foldable`,`Collection`,`Serializable`,`Traversable`],methods:{create:[`Stack()`,`Stack.of(...)`],transform:[`.push(v)`,`.pop()`],extract:[`.peek()`,`.toArray()`],check:[`.isEmpty`,`.size`]}},Http:{description:"HTTP fetch wrapper returning IO<never, HttpError, HttpResponse<T>>. Pass `decode: Decoder<T>` (Either-returning) for typed responses; wrap a throwing parser such as Zod's .parse in `Decoder.fromThrowing(parse)`. 2.0 removed the `validate` field. Request bodies auto-flatten functype ADTs to primitives; `flatten: false` preserves tagged emission for functype-to-functype services. Per-call `params` (HttpQueryParams) appends query strings with proper encoding. Http.client accepts `beforeRequest` and `afterResponse` (both effectful IO transformers). `afterResponse` runs on the success path only — error handling belongs in .catchTag. Composes via .tap/.map/.flatMap/.catchTag/.retry/.retryWhile/.retryWithBackoff/.timeout.",interfaces:[],methods:{create:[`Http.get(url, { decode, params }?)`,`Http.post(url, { body, decode, params }?)`,`Http.put(url, { body, decode, params }?)`,`Http.patch(url, { body, decode, params }?)`,`Http.delete(url, { decode, params }?)`,`Http.request({ url, decode, params })`,`Http.client({ baseUrl, defaultHeaders, fetch, beforeRequest, afterResponse })`],transform:[`.tap(f)`,`.map(f)`,`.flatMap(f)`,`.mapError(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.timeout(ms)`],extract:[`.run()`,`.runOrThrow()`,`.runOption()`,`.runTry()`,`.runExit()`,`.runCancellable()`],check:[],other:[`.catchTag(tag, handler)`,`.catchAll(handler)`,`.recover(fallback)`,`decode: Decoder<T> (Either-returning, structural failures preserved)`,`decode: Decoder.fromThrowing(parse) (a throwing parser such as Zod .parse; a throw becomes a DecoderError leaf)`,`flatten: boolean (default true; false preserves tagged emission)`,`encode: Encoder<TReq> = (value) => JSONValue (custom wire shape; overrides flatten)`,`params: HttpQueryParams (scalar | array; undefined/null dropped; percent-encoded)`,`beforeRequest: (req) => IO<never, HttpError, HttpRequestView>`,`afterResponse: (HttpResponse<unknown>) => IO<never, HttpError, HttpResponse<unknown>> — success path only; refresh-on-401 uses .catchTag`]}},HttpError:{description:`Three-variant ADT for HTTP failures: NetworkError | HttpStatusError | DecodeError (also exported as ResponseDecodeError alias)`,interfaces:[],methods:{create:[`HttpError.networkError(url, method, cause)`,`HttpError.httpStatusError(url, method, status, statusText, body)`,`HttpError.decodeError(url, method, body, cause)`],check:[`HttpError.isNetworkError(e)`,`HttpError.isHttpStatusError(e)`,`HttpError.isDecodeError(e)`],other:[`HttpError.match(error, { NetworkError, HttpStatusError, DecodeError })`]}},Decoder:{description:"Either-returning decoder contract: `Decoder<A> = (raw: unknown) => Either<DecoderError, A>`. Bundled combinators for primitives + functype ADTs (Option/Either/List/Map, null-bias). `Decoder.tagged.*` round-trips the `{_tag, value}` shape for functype-to-functype services.",interfaces:[],methods:{create:[`Decoder.string / .number / .boolean / .unknown / .nullable(inner)`,`Decoder.fromThrowing(parse) // adapt a throwing parser such as Zod's schema.parse`,`Decoder.option(inner)`,`Decoder.either.envelope({ok, err})`,`Decoder.either.discriminated({tag, leftTag, rightTag}, l, r)`,`Decoder.list(inner) / .array(inner) / .map(inner)`,`Decoder.object({k: Decoder<V>, ...}) — accumulates field failures into Composite`,`Decoder.tagged.option/either/try/list/map/obj(inner?) — round-trips {_tag, value}`],other:[`Pluggable by construction: any (raw) => Either<DecoderError, T> IS a Decoder<T>`,`Composes across sources: Decoder.object({a: Decoder.fromZod(s), b: Decoder.option(myAjv)})`]}},DecoderError:{description:"Recursive ADT for decoder failures: Leaf | Composite. Children mirror the input tree so multi-field failures preserve structural paths. Distinct from `HttpError.DecodeError` — this is the inner structural cause that the HTTP wrapper carries.",interfaces:[],methods:{create:[`DecoderError.leaf(path, message, cause?)`,`DecoderError.composite(path, children: List<DecoderError>)`],check:[`DecoderError.isLeaf(e)`,`DecoderError.isComposite(e)`],other:[`DecoderError.match(e, { Leaf, Composite })`,`DecoderError.prepend(segment, e) — used by combinators to attribute child failures`,`DecoderError.flatten(e): List<{path, message}> — collect leaves`,`DecoderError.format(e): string — render tree as multi-line`]}},Serialization:{description:"Universal `@functype`-marked JSON serialization. `deserialize` walks parsed JSON and reconstructs any functype value found — no type argument needed. Lenient: plain JSON passes through. Strict on unknown markers (defends against Effect/fp-ts `_tag` collision). 1.2.1 adds `toEnvelope`/`fromEnvelope` for nesting inside structured serializers (SuperJSON, DBOS), and `deserializeStrict` for boundaries that require functype on the wire.",interfaces:[],methods:{create:[],transform:[`Serialization.serialize(value: unknown): string — lenient JSON codec`,`Serialization.deserialize(json: string): Try<unknown> — lenient; pass-through for unmarked JSON`,`Serialization.deserializeStrict(json: string): Try<unknown> — Failure if no @functype marker at top level`,`Serialization.toEnvelope(value: unknown): JSONValue — parsed JSON shape (1.2.2 tightened from unknown)`,`Serialization.fromEnvelope(envelope: unknown): Try<unknown> — inverse of toEnvelope; input stays permissive (Postel's law)`,`Serialization.JSONValue — exported recursive type for the envelope shape`],check:[`Serialization.isFunctypeValue(v): v is Serializable<unknown>`],other:[`Plain JSON passthrough: non-functype data walks through unchanged (use deserializeStrict to reject)`,`Strict policy on unknown markers: unknown @functype marker → Try.Failure`,`Dispatch table covers all 11 Serializable types (Option, Either, Try, List, Set, Map, Obj, Stack, Tuple, LazyList, Lazy)`,`Algebraic square: serialize ≡ JSON.stringify ∘ toEnvelope; deserialize ≡ fromEnvelope ∘ JSON.parse`,`No DBOS / SuperJSON facade — consumers wire host serializer in ~8 lines via toEnvelope/fromEnvelope`]}},SerializedError:{description:"Canonical Error projection used by Try.Failure and Lazy-with-thrown-thunk. Round-trips name + message + stack + cause chain. `e.name === 'TypeError'` survives; `instanceof TypeError` does NOT.",interfaces:[],methods:{create:[`serializeError(err: unknown): SerializedError`,`deserializeError(s: SerializedError | string): Error`],other:[`Shape: { name: string; message: string; stack?: string; cause?: SerializedError | string }`,`Non-Error throwables (strings, plain objects) projected under name: 'NonErrorThrowable'`,`Cause chain is recursive — arbitrary nesting depth survives`]}},Logger:{description:`Minimal 4-method logging interface every functype-* package targets. Type-only, no runtime. Impls live in consumers: consoleBootLogger (functype-os/config), DirectLogger (functype-log/direct). Tracer is type-only on the same terms; Clock/Random are not added.`,interfaces:[],methods:{create:[`interface Logger { debug, info, warn, error: (msg, meta?) => void }`,`import type { Logger } from "functype"`],check:[],other:[`All 4 methods MANDATORY (no defensive logger.debug?.() at call sites)`,`Signature: (message: string, metadata?: Record<string, unknown>) => void`,`DirectLogger from functype-log/direct structurally satisfies Logger (superset shape)`,`IO-shaped Logger from functype-log does NOT satisfy core Logger (methods return IO<>, not void) — bridge via toDirectLogger(ioLogger)`,`Used by: bootDiagnostics({ logger? }) in functype-os/config`]}},TypedError:{description:`Code-tagged structured error ADT (extends Throwable); TypedError.validation(...) feeds accumulating validation.`,interfaces:[],methods:{create:[`TypedError.validation(field, value, rule) → TypedError<"VALIDATION_FAILED">`,`TypedError.badRequest(reason, expected?)`,`TypedError.notFound(resource, id)`,`TypedError.auth(resource, requiredRole?)`,`TypedError.permission(action, resource, userId?)`,`TypedError.conflict(resource, value) / .rateLimit(limit, window, retryAfter?)`,`TypedError.timeout(ms, operation) / .network(url, method, status?) / .internal(errorId)`],check:[`TypedError.isTypedError(v)`,`TypedError.hasCode(e, code)`],other:[`Fields: .code, .message, .status (HTTP), .context, .timestamp, .traceId?`,`VALIDATION_FAILED context shape: { field, value, rule }`,`getErrorChain(error) → Error[] and formatErrorChain(error, { includeTasks? }) walk any error's cause chain`]}},Validation:{description:`Error-accumulating validation (functype's Validated role) — FormValidation<T> collects all field errors, not fail-fast.`,interfaces:[],methods:{create:[`Validation.rule<T>('min:18' | 'email' | 'required' | 'in:a,b' | ...)`,`Validation.combine(...validators) / Validation.custom(predicate, message)`,`Validation.validators.email / .url / .uuid / .required / .numeric / .positiveNumber / .nonEmptyString`],transform:[`Validation.form(schema, data) → FormValidation<T> (accumulates all field errors)`,`Validator<T> = (value: unknown) => Either<TypedError<'VALIDATION_FAILED'>, T>`],other:[`FormValidation<T> = Either<List<TypedError<"VALIDATION_FAILED">>, T> — functype's "Validated" accumulating result type`,`form() is flat/per-field: for cross-field (lo < hi) or dynamic-key (weights.*) checks, hand-accumulate into a List<TypedError> and return the FormValidation shape`]}}},a={Functor:{description:`Transform contained values`,methods:[`.map<B>(f: A => B): Functor<B>`]},Applicative:{extends:`Functor`,description:`Apply wrapped functions`,methods:[`.ap<B>(ff: Applicative<A => B>): Applicative<B>`]},Monad:{extends:`Applicative`,description:`Chain operations returning wrapped values`,methods:[`.flatMap<B>(f: A => Monad<B>): Monad<B>`]},Foldable:{description:`Extract via pattern matching`,methods:[`.fold<B>(empty: () => B, f: A => B): B`,`.foldLeft<B>(z: B, op: (B, A) => B): B`,`.foldRight<B>(z: B, op: (A, B) => B): B`]},Extractable:{description:`Get contained value with fallback`,methods:[`.getOrElse(d: () => T): T`,`.orThrow(e?: Error): T`,`.expect(handler: (e?) => never): T`,`.orNull(): T | null`,`.orUndefined(): T | undefined`]},Matchable:{description:`Pattern match on type variants`,methods:[`.match<R>(patterns: Record<Tag, Handler>): R`]},Traversable:{description:`Iterate and check contents`,methods:[`.size: number`,`.isEmpty: boolean`,`.contains(v: A): boolean`,`.reduce<B>(f, init): B`]},Collection:{description:`Collection operations`,methods:[`.toArray(): A[]`,`.forEach(f: A => void): void`]},Serializable:{description:`Convert to string formats`,methods:[`.serialize().toJSON(): string`,`.serialize().toBinary(): string`]}},o={Core:[`Option`,`Either`,`Try`,`Obj`,`Identity`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Exit`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Do`,`Ref`,`Brand`,`ValidatedBrand`,`Wire`,`invariant`,`TracedOption`],Validation:[`TypedError`,`Validation`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`,`Tracer`,`SpanTracer`]};export{o as CATEGORIES,a as INTERFACES,i as TYPES,n as VERSION};
@@ -1,48 +1,7 @@
1
- //#region src/cli/data.d.ts
2
1
  /**
3
- * Curated API data for CLI output, optimized for LLM consumption.
4
- *
5
- * `interfaces` arrays are composed of (a) the GENERATED_INTERFACES floor
6
- * derived from each type's `extends` chain in source, plus (b) optional
7
- * hand-curated additions for capabilities declared inline (e.g. `List.map`
8
- * lives in the interface body, not via `extends Functor`). The data-sync
9
- * spec enforces that no source-declared interface is dropped from this list.
2
+ * Public API for functype CLI data.
3
+ * Re-exports curated type/interface metadata for use by tooling (MCP servers, editors, etc.)
10
4
  */
11
- export declare const VERSION: string;
12
- interface TypeData {
13
- description: string;
14
- interfaces: string[];
15
- methods: {
16
- create?: string[];
17
- transform?: string[];
18
- extract?: string[];
19
- check?: string[];
20
- other?: string[];
21
- };
22
- }
23
- interface InterfaceData {
24
- extends?: string;
25
- description: string;
26
- methods: string[];
27
- }
28
- export declare const TYPES: Record<string, TypeData>;
29
- export declare const INTERFACES: Record<string, InterfaceData>;
30
- export declare const CATEGORIES: {
31
- Core: string[];
32
- Collection: string[];
33
- Effect: string[];
34
- Utility: string[];
35
- Validation: string[];
36
- Serialization: string[];
37
- Service: string[];
38
- };
39
- //#endregion
40
- //#region src/cli/full-interfaces.d.ts
41
- /**
42
- * Auto-generated full interface definitions.
43
- * Generated by scripts/extract-interfaces.ts
44
- * DO NOT EDIT MANUALLY
45
- */
46
- export declare const FULL_INTERFACES: Record<string, string>;
47
- //#endregion
48
- export type { InterfaceData, TypeData };
5
+ import { CATEGORIES, INTERFACES, InterfaceData, TYPES, TypeData, VERSION } from "./data.js";
6
+ import { FULL_INTERFACES } from "./full-interfaces.js";
7
+ export { CATEGORIES, FULL_INTERFACES, INTERFACES, type InterfaceData, TYPES, type TypeData, VERSION };
@@ -1 +1 @@
1
- import{a as e,i as t,n,r,t as i}from"../full-interfaces-BadxJrCt.js";export{n as CATEGORIES,i as FULL_INTERFACES,r as INTERFACES,t as TYPES,e as VERSION};
1
+ import{CATEGORIES as e,INTERFACES as t,TYPES as n,VERSION as r}from"./data.js";import{FULL_INTERFACES as i}from"./full-interfaces.js";export{e as CATEGORIES,i as FULL_INTERFACES,t as INTERFACES,n as TYPES,r as VERSION};
@@ -0,0 +1,4 @@
1
+ import{List as e}from"../list/index.js";import{Option as t}from"../option/index.js";import{CATEGORIES as n,INTERFACES as r,TYPES as i,VERSION as a}from"./data.js";const o=()=>{let r=e([`functype ${a} - Scala-inspired FP for TypeScript`,``]);return e(Object.entries(n)).foldLeft(r)((n,[r,a])=>{let o=n.add(r.toUpperCase());return e(a).foldLeft(o)((e,n)=>t(i[n]).fold(()=>e,t=>{let r=t.interfaces.length>0?` [${t.interfaces.join(`, `)}]`:``;return e.add(` ${n}${r}`).add(` ${t.description}`)})).add(``)}).concat(e([`Use: npx functype <Type> for details`,`Use: npx functype interfaces for interface reference`])).toArray().join(`
2
+ `)},s=(n,r)=>{let i=r.interfaces.length>0?` [${r.interfaces.join(`, `)}]`:``,a=e([`create`,`transform`,`extract`,`check`,`other`]),o=e([`${n}<T>${i}`,``,r.description,``]);return a.foldLeft(o)((n,i)=>t(r.methods[i]).filter(e=>e.length>0).fold(()=>n,t=>{let r=n.add(i.toUpperCase());return e(t).foldLeft(r)((e,t)=>e.add(` ${t}`)).add(``)})).toArray().join(`
3
+ `).trimEnd()},c=()=>{let t=e([`INTERFACES`,``]);return e(Object.entries(r)).foldLeft(t)((t,[n,r])=>{let i=r.extends?` extends ${r.extends}`:``,a=t.add(`${n}<A>${i}`).add(` ${r.description}`);return e(r.methods).foldLeft(a)((e,t)=>e.add(` ${t}`)).add(``)}).toArray().join(`
4
+ `).trimEnd()},l=e=>JSON.stringify(e,null,2),u=()=>({version:a,categories:n,types:i}),d=n=>t(i[n]).map(e=>({name:n,data:e})).orElse(()=>e(Object.entries(i)).find(([e])=>e.toLowerCase()===n.toLowerCase()).map(([e,t])=>({name:e,data:t}))).orUndefined(),f=()=>Object.keys(i),p=()=>r;export{c as formatInterfaces,l as formatJson,o as formatOverview,s as formatType,f as getAllTypeNames,p as getInterfacesData,u as getOverviewData,d as getType};
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Auto-generated full interface definitions.
3
+ * Generated by scripts/extract-interfaces.ts
4
+ * DO NOT EDIT MANUALLY
5
+ */
6
+ export declare const FULL_INTERFACES: Record<string, string>;