functype 1.27.1 → 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.
- package/README.md +63 -88
- package/dist/_virtual/_rolldown/runtime.js +1 -0
- package/dist/branded/ValidatedBrand.d.ts +122 -0
- package/dist/branded/ValidatedBrand.js +1 -0
- package/dist/branded/index.d.ts +52 -2
- package/dist/cli/data.d.ts +37 -0
- package/dist/cli/data.js +1 -0
- package/dist/cli/exports.d.ts +5 -46
- package/dist/cli/exports.js +1 -1
- package/dist/cli/formatters.js +4 -0
- package/dist/cli/full-interfaces.d.ts +6 -0
- package/dist/cli/full-interfaces.js +1139 -0
- package/dist/cli/index.js +3 -6
- package/dist/cli/interfaces.generated.js +1 -0
- package/dist/collections/index.d.ts +13 -0
- package/dist/companion/Companion.d.ts +23 -0
- package/dist/companion/Companion.js +1 -0
- package/dist/companion/CompanionTypes.d.ts +30 -0
- package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
- package/dist/companion/index.d.ts +2 -1
- package/dist/companion/index.js +1 -1
- package/dist/conditional/Cond.d.ts +147 -0
- package/dist/conditional/Cond.js +1 -0
- package/dist/conditional/Match.d.ts +295 -0
- package/dist/conditional/Match.js +1 -0
- package/dist/conditional/index.d.ts +3 -2
- package/dist/conditional/index.js +1 -1
- package/dist/core/base/Base.d.ts +12 -0
- package/dist/core/base/Base.js +1 -0
- package/dist/core/throwable/Throwable.d.ts +38 -0
- package/dist/core/throwable/Throwable.js +1 -0
- package/dist/decoder/Decoder.d.ts +15 -0
- package/dist/decoder/DecoderCompanion.js +1 -0
- package/dist/decoder/DecoderError.d.ts +56 -0
- package/dist/decoder/DecoderError.js +2 -0
- package/dist/decoder/Encoder.d.ts +15 -0
- package/dist/decoder/index.d.ts +71 -2
- package/dist/decoder/index.js +1 -1
- package/dist/decoder/tagged.js +1 -0
- package/dist/do/index.d.ts +246 -2
- package/dist/do/index.js +1 -1
- package/dist/do/protocol.d.ts +29 -0
- package/dist/either/index.d.ts +279 -2
- package/dist/either/index.js +1 -1
- package/dist/error/ErrorChain.d.ts +60 -0
- package/dist/error/ErrorChain.js +4 -0
- package/dist/error/ErrorFormatter.d.ts +67 -0
- package/dist/error/ErrorFormatter.js +6 -0
- package/dist/error/ParseError.d.ts +6 -0
- package/dist/error/ParseError.js +1 -0
- package/dist/error/typed/TypedError.d.ts +146 -0
- package/dist/error/typed/TypedError.js +1 -0
- package/dist/error/typed/Validation.d.ts +76 -0
- package/dist/error/typed/Validation.js +1 -0
- package/dist/extractable/Extractable.d.ts +62 -0
- package/dist/extractable/Extractable.js +1 -0
- package/dist/fetch/Http.d.ts +32 -0
- package/dist/fetch/Http.js +1 -0
- package/dist/fetch/HttpClient.d.ts +80 -0
- package/dist/fetch/HttpClient.js +1 -0
- package/dist/fetch/HttpError.d.ts +57 -0
- package/dist/fetch/HttpError.js +1 -0
- package/dist/fetch/HttpRequest.d.ts +103 -0
- package/dist/fetch/index.d.ts +5 -2
- package/dist/fetch/index.js +1 -1
- package/dist/foldable/Foldable.d.ts +27 -0
- package/dist/foldable/index.d.ts +55 -0
- package/dist/foldable/index.js +1 -0
- package/dist/functype/Functype.d.ts +76 -0
- package/dist/functype/FunctypeSum.d.ts +39 -0
- package/dist/functype/index.d.ts +4 -2
- package/dist/hkt/index.d.ts +68 -0
- package/dist/hkt/index.js +1 -0
- package/dist/identity/Identity.d.ts +34 -0
- package/dist/identity/Identity.js +1 -0
- package/dist/index.d.ts +74 -8
- package/dist/index.js +1 -1
- package/dist/internal/base64.js +1 -0
- package/dist/internal/call-alone.js +1 -0
- package/dist/internal/concurrency.d.ts +11 -0
- package/dist/internal/concurrency.js +1 -0
- package/dist/internal/define.js +1 -0
- package/dist/internal/mutation-utils.js +1 -0
- package/dist/internal/signal.js +1 -0
- package/dist/internal/stringify.js +1 -0
- package/dist/invariant/index.d.ts +32 -2
- package/dist/io/Context.d.ts +112 -0
- package/dist/io/Context.js +1 -0
- package/dist/io/Exit.d.ts +249 -0
- package/dist/io/Exit.js +1 -0
- package/dist/io/IO.d.ts +1243 -0
- package/dist/io/IO.js +1 -0
- package/dist/io/Layer.d.ts +139 -0
- package/dist/io/Layer.js +1 -0
- package/dist/io/SpanTracer.d.ts +78 -0
- package/dist/io/SpanTracer.js +1 -0
- package/dist/io/Tag.d.ts +75 -0
- package/dist/io/Tag.js +1 -0
- package/dist/io/TestClock.d.ts +133 -0
- package/dist/io/TestClock.js +1 -0
- package/dist/io/index.d.ts +41 -2
- package/dist/io/index.js +1 -1
- package/dist/lazy/Lazy.d.ts +312 -0
- package/dist/lazy/Lazy.js +1 -0
- package/dist/lazy/index.d.ts +2 -2
- package/dist/lazy/index.js +1 -1
- package/dist/list/LazyList.d.ts +182 -0
- package/dist/list/LazyList.js +1 -0
- package/dist/list/index.d.ts +137 -2
- package/dist/list/index.js +1 -1
- package/dist/logger/index.d.ts +24 -2
- package/dist/map/index.d.ts +95 -2
- package/dist/map/index.js +1 -1
- package/dist/map/shim.d.ts +13 -0
- package/dist/map/shim.js +1 -0
- package/dist/matchable/Matchable.d.ts +38 -0
- package/dist/matchable/Matchable.js +1 -0
- package/dist/obj/Obj.d.ts +212 -0
- package/dist/obj/Obj.js +1 -0
- package/dist/obj/index.d.ts +2 -2
- package/dist/obj/index.js +1 -1
- package/dist/option/index.d.ts +304 -2
- package/dist/option/index.js +1 -1
- package/dist/package.json.js +1 -0
- package/dist/pipe/index.d.ts +14 -0
- package/dist/ref/Ref.d.ts +77 -0
- package/dist/ref/Ref.js +1 -0
- package/dist/reshapeable/Reshapeable.d.ts +90 -0
- package/dist/serializable/Serializable.d.ts +39 -0
- package/dist/serialization/Serialization.d.ts +147 -0
- package/dist/serialization/Serialization.js +1 -0
- package/dist/serialization/SerializationCompanion.d.ts +125 -0
- package/dist/serialization/SerializationCompanion.js +1 -0
- package/dist/serialization/error-envelope.d.ts +44 -0
- package/dist/serialization/error-envelope.js +1 -0
- package/dist/serialization/index.d.ts +4 -2
- package/dist/serialization/index.js +1 -1
- package/dist/set/index.d.ts +106 -2
- package/dist/set/index.js +1 -1
- package/dist/stack/Stack.d.ts +120 -0
- package/dist/stack/Stack.js +1 -0
- package/dist/traced/TraceEvent.d.ts +27 -0
- package/dist/traced/TracedOption.d.ts +46 -0
- package/dist/traced/TracedOption.js +1 -0
- package/dist/traced/Tracer.d.ts +26 -0
- package/dist/traversable/KVTraversable.d.ts +14 -0
- package/dist/traversable/Traversable.d.ts +30 -0
- package/dist/try/index.d.ts +238 -2
- package/dist/try/index.js +1 -1
- package/dist/tuple/index.d.ts +92 -2
- package/dist/tuple/index.js +1 -1
- package/dist/typeable/Typeable.d.ts +40 -0
- package/dist/typeable/Typeable.js +1 -0
- package/dist/typeclass/ContainerOps.d.ts +131 -0
- package/dist/typeclass/Functor.d.ts +41 -0
- package/dist/typeclass/Promisable.d.ts +33 -0
- package/dist/typeclass/index.d.ts +4 -1
- package/dist/typeclass/index.js +1 -1
- package/dist/typeclass/variance.d.ts +54 -0
- package/dist/typeclass/variance.js +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/util/index.d.ts +1 -3
- package/dist/valuable/Valuable.d.ts +28 -0
- package/dist/valuable/Valuable.js +1 -0
- package/dist/wire/index.d.ts +40 -2
- package/package.json +7 -12
- package/dist/Brand-bfnGXuum.d.ts +0 -54
- package/dist/Companion-DiOMBHDG.js +0 -1
- package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
- package/dist/Invariant-DEan-SxV.d.ts +0 -35
- package/dist/Logger-BmprRS8v.d.ts +0 -27
- package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
- package/dist/Wire-3hvw0Ogg.d.ts +0 -42
- package/dist/core/task/index.d.ts +0 -2
- package/dist/core/task/index.js +0 -1
- package/dist/full-interfaces-0XJEOHi_.js +0 -1202
- package/dist/index-CLYh2qZu.d.ts +0 -6649
- package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
- package/dist/serialization-9_SyrfdG.js +0 -3
- package/dist/src-BTLBc-KK.js +0 -10
- package/dist/typeclass-C61yDVYd.js +0 -1
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { Either } from "../../either/index.js";
|
|
2
|
+
import { TypedError } from "./TypedError.js";
|
|
3
|
+
import { List } from "../../list/index.js";
|
|
4
|
+
import { Type } from "../../types/index.js";
|
|
5
|
+
/**
|
|
6
|
+
* Validation rule types using template literal types
|
|
7
|
+
*/
|
|
8
|
+
export type ValidationRule = `min:${number}` | `max:${number}` | `minLength:${number}` | `maxLength:${number}` | `pattern:${string}` | `email` | `url` | `uuid` | `required` | `numeric` | `alpha` | `alphanumeric` | `date` | `future` | `past` | `in:${string}` | `notIn:${string}`;
|
|
9
|
+
/**
|
|
10
|
+
* Validator function type
|
|
11
|
+
*/
|
|
12
|
+
export type Validator<T> = (value: unknown) => Either<TypedError<"VALIDATION_FAILED">, T>;
|
|
13
|
+
/**
|
|
14
|
+
* Field validation result
|
|
15
|
+
*/
|
|
16
|
+
export type FieldValidation<T> = {
|
|
17
|
+
field: string;
|
|
18
|
+
value: unknown;
|
|
19
|
+
result: Either<TypedError<"VALIDATION_FAILED">, T>;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Form validation result
|
|
23
|
+
*/
|
|
24
|
+
export type FormValidation<T extends Record<string, Type>> = Either<List<TypedError<"VALIDATION_FAILED">>, T>;
|
|
25
|
+
export declare const Validation: (<T extends Type>(rule: ValidationRule) => Validator<T>) & {
|
|
26
|
+
/**
|
|
27
|
+
* Common pre-built validators
|
|
28
|
+
*/
|
|
29
|
+
validators: {
|
|
30
|
+
email: Validator<string>;
|
|
31
|
+
url: Validator<string>;
|
|
32
|
+
uuid: Validator<string>;
|
|
33
|
+
required: Validator<string>;
|
|
34
|
+
numeric: Validator<number>;
|
|
35
|
+
positiveNumber: Validator<number>;
|
|
36
|
+
nonEmptyString: Validator<string>;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Create a validator from a rule string
|
|
40
|
+
* @example
|
|
41
|
+
* const validator = Validation.rule<number>("min:18")
|
|
42
|
+
* const result = validator(25) // Right(25)
|
|
43
|
+
* const error = validator(15) // Left(TypedError)
|
|
44
|
+
*/
|
|
45
|
+
rule: <T extends Type>(rule: ValidationRule) => Validator<T>;
|
|
46
|
+
/**
|
|
47
|
+
* Combine multiple validators
|
|
48
|
+
* @example
|
|
49
|
+
* const validator = Validation.combine(
|
|
50
|
+
* Validation.rule<string>("required"),
|
|
51
|
+
* Validation.rule<string>("email"),
|
|
52
|
+
* Validation.rule<string>("maxLength:100")
|
|
53
|
+
* )
|
|
54
|
+
*/
|
|
55
|
+
combine: <T extends Type>(...validators: Validator<T>[]) => Validator<T>;
|
|
56
|
+
/**
|
|
57
|
+
* Create a custom validator
|
|
58
|
+
* @example
|
|
59
|
+
* const isEven = Validation.custom<number>(
|
|
60
|
+
* (value) => typeof value === "number" && value % 2 === 0,
|
|
61
|
+
* "must be an even number"
|
|
62
|
+
* )
|
|
63
|
+
*/
|
|
64
|
+
custom: <T extends Type>(predicate: (value: unknown) => boolean, errorMessage: string) => Validator<T>;
|
|
65
|
+
/**
|
|
66
|
+
* Validate a form with multiple fields
|
|
67
|
+
* @example
|
|
68
|
+
* const schema = {
|
|
69
|
+
* name: Validation.rule<string>("required"),
|
|
70
|
+
* email: Validation.rule<string>("email"),
|
|
71
|
+
* age: Validation.rule<number>("min:18")
|
|
72
|
+
* }
|
|
73
|
+
* const result = Validation.form(schema, { name: "John", email: "john@example.com", age: 25 })
|
|
74
|
+
*/
|
|
75
|
+
form: <T extends Record<string, Type>>(schema: { [K in keyof T]: Validator<T[K]>; }, data: Record<string, unknown>) => FormValidation<T>;
|
|
76
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Left as e,Right as t}from"../../either/index.js";import{TypedError as n}from"./TypedError.js";import{List as r}from"../../list/index.js";import{mergeObjects as i}from"../../util/index.js";const a={rule:r=>i=>{if(r===`email`)return typeof i!=`string`||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i)?e(n.validation(`value`,i,`must be a valid email`)):t(i);if(r===`url`)try{return new URL(String(i)),t(i)}catch{return e(n.validation(`value`,i,`must be a valid URL`))}if(r===`uuid`)return typeof i!=`string`||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(i)?e(n.validation(`value`,i,`must be a valid UUID`)):t(i);if(r===`required`)return i==null||i===``?e(n.validation(`value`,i,`is required`)):t(i);if(r===`numeric`)return typeof i!=`number`&&!/^\d+$/.test(String(i))?e(n.validation(`value`,i,`must be numeric`)):t(i);if(r===`alpha`)return typeof i!=`string`||!/^[a-zA-Z]+$/.test(i)?e(n.validation(`value`,i,`must contain only letters`)):t(i);if(r===`alphanumeric`)return typeof i!=`string`||!/^[a-zA-Z0-9]+$/.test(i)?e(n.validation(`value`,i,`must be alphanumeric`)):t(i);if(r.startsWith(`min:`)){let a=Number(r.split(`:`)[1]),o=Number(i);return isNaN(o)||o<a?e(n.validation(`value`,i,`must be at least ${a}`)):t(i)}if(r.startsWith(`max:`)){let a=Number(r.split(`:`)[1]),o=Number(i);return isNaN(o)||o>a?e(n.validation(`value`,i,`must be at most ${a}`)):t(i)}if(r.startsWith(`minLength:`)){let a=Number(r.split(`:`)[1]);return String(i).length<a?e(n.validation(`value`,i,`must be at least ${a} characters`)):t(i)}if(r.startsWith(`maxLength:`)){let a=Number(r.split(`:`)[1]);return String(i).length>a?e(n.validation(`value`,i,`must be at most ${a} characters`)):t(i)}if(r.startsWith(`pattern:`)){let a=r.substring(8);return new RegExp(a).test(String(i))?t(i):e(n.validation(`value`,i,`must match pattern ${a}`))}if(r.startsWith(`in:`)){let a=r.substring(3).split(`,`);return a.includes(String(i))?t(i):e(n.validation(`value`,i,`must be one of: ${a.join(`, `)}`))}if(r.startsWith(`notIn:`)){let a=r.substring(6).split(`,`);return a.includes(String(i))?e(n.validation(`value`,i,`must not be one of: ${a.join(`, `)}`)):t(i)}if(r===`date`){let r=new Date(String(i));return isNaN(r.getTime())?e(n.validation(`value`,i,`must be a valid date`)):t(i)}if(r===`future`){let r=new Date(String(i));return isNaN(r.getTime())||r<=/* @__PURE__ */ new Date?e(n.validation(`value`,i,`must be a future date`)):t(i)}if(r===`past`){let r=new Date(String(i));return isNaN(r.getTime())||r>=/* @__PURE__ */ new Date?e(n.validation(`value`,i,`must be a past date`)):t(i)}return t(i)},combine:(...e)=>n=>{for(let t of e){let e=t(n);if(e.isLeft())return e}return t(n)},custom:(r,i)=>a=>r(a)?t(a):e(n.validation(`value`,a,i)),form:(i,a)=>{let o=[],s={};for(let[e,t]of Object.entries(i)){let r=a[e],i=t(r);if(i.isLeft()){let t=i.fold(e=>e,()=>{throw Error(`Should not be left`)}),a=n.validation(e,r,t.context.rule);o.push(a)}else s[e]=i.orThrow()}return o.length>0?e(r(o)):t(s)}},o={...a,validators:{email:a.rule(`email`),url:a.rule(`url`),uuid:a.rule(`uuid`),required:a.rule(`required`),numeric:a.rule(`numeric`),positiveNumber:a.combine(a.rule(`numeric`),a.rule(`min:0`)),nonEmptyString:a.combine(a.rule(`required`),a.custom(e=>typeof e==`string`&&e.trim().length>0,`must not be empty`))}},s=i(a.rule,o);export{s as Validation};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Type } from "../types/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Interface for operations that can fail with exceptions.
|
|
4
|
+
* These methods should be used with care as they can throw at runtime.
|
|
5
|
+
*
|
|
6
|
+
* @interface Unsafe
|
|
7
|
+
* @template T The type of value that can be extracted
|
|
8
|
+
*/
|
|
9
|
+
export interface Unsafe<out T extends Type> {
|
|
10
|
+
/**
|
|
11
|
+
* Extract the value or throw an error
|
|
12
|
+
* @param error Optional custom error to throw. If not provided, uses type-appropriate default error
|
|
13
|
+
* @throws {Error} The specified error, container's error, or a sensible default
|
|
14
|
+
* @returns The contained value
|
|
15
|
+
*/
|
|
16
|
+
orThrow(error?: Error): T;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Extractable type class for data structures that can extract their values
|
|
20
|
+
* with various fallback strategies.
|
|
21
|
+
*
|
|
22
|
+
* Covariance: T is declared `<out T>`. The fallback methods `getOrElse` and `orElse`
|
|
23
|
+
* widen the result via `T2`, matching Scala's `getOrElse[B1 >: B](default: => B1): B1`
|
|
24
|
+
* shape. `getOrElse<T2 = never>(() => T | T2)` types its default against T first, so a
|
|
25
|
+
* default that fits T keeps T exactly (a literal union like `"light" | "dark"` isn't widened
|
|
26
|
+
* to `string`), and only a default of another type widens the result to `T | T2`.
|
|
27
|
+
*
|
|
28
|
+
* Both fallbacks are lazy: they take a function, which runs only when the container
|
|
29
|
+
* has no value. This is Scala's by-name parameter written as a thunk, as Effect and
|
|
30
|
+
* fp-ts do.
|
|
31
|
+
*/
|
|
32
|
+
export interface Extractable<out T extends Type> extends Unsafe<T> {
|
|
33
|
+
/**
|
|
34
|
+
* Returns the contained value, or calls `defaultValue` if there is none. The default is
|
|
35
|
+
* lazy. It is typed against `T` first, so a default that fits `T` keeps `T` and a literal
|
|
36
|
+
* union is not widened to `string`. A default of another type widens the result to `T | T2`.
|
|
37
|
+
* @param defaultValue - A function that returns the value to use if extraction fails
|
|
38
|
+
* @returns The contained value or the default
|
|
39
|
+
*/
|
|
40
|
+
getOrElse<T2 extends Type = never>(defaultValue: () => T | T2): T | T2;
|
|
41
|
+
/**
|
|
42
|
+
* Returns this container if it has a value, otherwise calls `alternative` for another container.
|
|
43
|
+
* The alternative is lazy, and may carry a different type; the result widens to `Extractable<T | T2>`.
|
|
44
|
+
* @param alternative - A function that returns the container to use if this one has no value
|
|
45
|
+
* @returns This container or the alternative
|
|
46
|
+
*/
|
|
47
|
+
orElse<T2 extends Type>(alternative: () => Extractable<T2>): Extractable<T | T2>;
|
|
48
|
+
/**
|
|
49
|
+
* Returns the contained value or null
|
|
50
|
+
* @returns The contained value or null
|
|
51
|
+
*/
|
|
52
|
+
orNull(): T | null;
|
|
53
|
+
/**
|
|
54
|
+
* Returns the contained value or undefined
|
|
55
|
+
* @returns The contained value or undefined
|
|
56
|
+
*/
|
|
57
|
+
orUndefined(): T | undefined;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Type guard to check if a value implements Extractable
|
|
61
|
+
*/
|
|
62
|
+
export declare function isExtractable<T extends Type>(value: unknown): value is Extractable<T>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return typeof e==`object`&&!!e&&`orThrow`in e&&typeof e.orThrow==`function`}function t(t){return e(t)&&`getOrElse`in t&&typeof t.getOrElse==`function`&&`orElse`in t&&typeof t.orElse==`function`&&`orNull`in t&&typeof t.orNull==`function`&&`orUndefined`in t&&typeof t.orUndefined==`function`}export{t as isExtractable,e as isUnsafe};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { IO } from "../io/IO.js";
|
|
2
|
+
import { HttpClientConfig } from "./HttpClient.js";
|
|
3
|
+
import { HttpError } from "./HttpError.js";
|
|
4
|
+
import { HttpMethodOptions, HttpRequestOptions, HttpResponse } from "./HttpRequest.js";
|
|
5
|
+
type HttpMethods = {
|
|
6
|
+
readonly request: <T = unknown, TReq = unknown>(options: HttpRequestOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
7
|
+
readonly get: <T = unknown>(url: string, options?: HttpMethodOptions<T>) => IO<never, HttpError, HttpResponse<T>>;
|
|
8
|
+
readonly post: <T = unknown, TReq = unknown>(url: string, options?: HttpMethodOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
9
|
+
readonly put: <T = unknown, TReq = unknown>(url: string, options?: HttpMethodOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
10
|
+
readonly patch: <T = unknown, TReq = unknown>(url: string, options?: HttpMethodOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
11
|
+
readonly delete: <T = unknown, TReq = unknown>(url: string, options?: HttpMethodOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
12
|
+
readonly head: (url: string, options?: HttpMethodOptions<void>) => IO<never, HttpError, HttpResponse<void>>;
|
|
13
|
+
readonly options: (url: string, options?: HttpMethodOptions<void>) => IO<never, HttpError, HttpResponse<void>>;
|
|
14
|
+
};
|
|
15
|
+
declare const HttpStatics: {
|
|
16
|
+
request: <T = unknown, TReq = unknown>(options: HttpRequestOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
17
|
+
get: <T = unknown>(url: string, options?: HttpMethodOptions<T>) => IO<never, HttpError, HttpResponse<T>>;
|
|
18
|
+
post: <T = unknown, TReq = unknown>(url: string, options?: HttpMethodOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
19
|
+
put: <T = unknown, TReq = unknown>(url: string, options?: HttpMethodOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
20
|
+
patch: <T = unknown, TReq = unknown>(url: string, options?: HttpMethodOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
21
|
+
delete: <T = unknown, TReq = unknown>(url: string, options?: HttpMethodOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
|
|
22
|
+
head: (url: string, options?: HttpMethodOptions<void>) => IO<never, HttpError, HttpResponse<void>>;
|
|
23
|
+
options: (url: string, options?: HttpMethodOptions<void>) => IO<never, HttpError, HttpResponse<void>>;
|
|
24
|
+
client: (config: HttpClientConfig) => HttpMethods;
|
|
25
|
+
};
|
|
26
|
+
export declare const Http: HttpCompanion;
|
|
27
|
+
/** The type of `Http`: its tag and its statics, named so that errors and hovers print `HttpCompanion`. */
|
|
28
|
+
export type HttpCompanion = {
|
|
29
|
+
readonly _tag: "Http";
|
|
30
|
+
} & HttpStaticsType;
|
|
31
|
+
type HttpStaticsType = typeof HttpStatics;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";import{IO as t}from"../io/IO.js";import{defaultHttpClientConfig as n}from"./HttpClient.js";import{HttpError as r}from"./HttpError.js";const i=(e,t)=>!e||t.startsWith(`http://`)||t.startsWith(`https://`)?t:`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`,a=(e,t)=>{let n=new URLSearchParams;for(let e of Object.keys(t)){let r=t[e];if(r!=null){if(Array.isArray(r))for(let t of r)n.append(e,String(t));else n.append(e,String(r))}}let r=n.toString();return r?`${e}${e.includes(`?`)?`&`:`?`}${r}`:e},o=(e,t,n)=>{let r=i(e,t);return n?a(r,n):r},s=(e,t)=>e[Symbol.toStringTag]===t,c=(e,t)=>{if(typeof e!=`object`||!e||e instanceof Date||e instanceof RegExp||typeof Buffer<`u`&&e instanceof Buffer)return e;if(s(e,`Option`)){let n=e;return t===`tagged`?n._tag===`None`?{_tag:`None`,value:null}:{_tag:`Some`,value:c(n.value,t)}:n._tag===`None`?null:c(n.value,t)}if(s(e,`Either`)){let n=e;if(t===`tagged`)return{_tag:n._tag,value:c(n.value,t)};if(n._tag===`Left`)throw Error(`Cannot serialize a Left in a request body — Either's failure path should not cross the wire as data. Resolve the Left before sending, or omit the field. (Left value: ${JSON.stringify(n.value)})`);return c(n.value,t)}if(s(e,`Try`)){let n=e;if(t===`tagged`){if(n._tag===`Failure`){let e=n.error??/* @__PURE__ */ Error(`unknown`);return{_tag:`Failure`,error:e.message,stack:e.stack}}return{_tag:`Success`,value:c(n.value,t)}}if(n._tag===`Failure`)throw n.error??/* @__PURE__ */ Error(`Cannot serialize a Try Failure in a request body`);return c(n.value,t)}if(s(e,`List`)){let n=e.toArray().map(e=>c(e,t));return t===`tagged`?{_tag:`List`,value:n}:n}if(s(e,`FunctypeMap`)){let n=e.toValue().value;if(t===`tagged`)return{_tag:`Map`,value:n.map(([e,n])=>[e,c(n,t)])};let r={};for(let[e,i]of n){if(typeof e!=`string`)throw Error(`Cannot serialize Map with non-string keys to JSON (key: ${String(e)})`);r[e]=c(i,t)}return r}if(Array.isArray(e))return e.map(e=>c(e,t));let n={};for(let r of Object.keys(e))n[r]=c(e[r],t);return n},l=(e,t,n)=>{if(e==null)return{serialized:void 0,contentType:void 0};if(n)return{serialized:JSON.stringify(n(e)),contentType:`application/json`};if(typeof e==`string`)return{serialized:e,contentType:void 0};if(typeof e==`object`||Array.isArray(e)){let n=c(e,t?`primitive`:`tagged`);return{serialized:JSON.stringify(n),contentType:`application/json`}}return{serialized:String(e),contentType:void 0}},u=e=>{let t=e.get(`content-type`)??``;return t.includes(`application/json`)?`json`:t.startsWith(`text/`)?`text`:`raw`},d=async(e,t,n,i,a)=>{let o=t??u(e.headers),s,c={};switch(o){case`json`:{let t=await e.text();c.value=t;try{s=JSON.parse(t)}catch(e){throw r.decodeError(n,i,t,e)}break}case`text`:s=await e.text(),c.value=s;break;case`blob`:s=await e.blob();break;case`arrayBuffer`:s=await e.arrayBuffer();break;case`raw`:s=e}let l;if(a){let e=a(s);if(e.isLeft()){let t=c.value??(typeof s==`string`?s:JSON.stringify(s));throw r.decodeError(n,i,t,e.value)}l=e.value}else l=s;return{data:l,status:e.status,statusText:e.statusText,headers:e.headers}},f=(e,n)=>{let i={url:o(e.baseUrl,n.url,n.params),method:n.method,headers:{...e.defaultHeaders,...n.headers},body:n.body,signal:n.signal,parseAs:n.parseAs,flatten:n.flatten};return(e.beforeRequest?e.beforeRequest(i):t.succeed(i)).flatMap(i=>{let a=i.flatten??!0,o=(()=>{try{return{ok:!0,value:l(i.body,a,n.encode)}}catch(e){return{ok:!1,cause:e}}})();if(!o.ok)return t.fail(r.networkError(i.url,i.method,o.cause));let{serialized:s,contentType:c}=o.value,u={...i.headers,...c?{"Content-Type":c}:{}},f=t.tryAsync(t=>(e.fetch??globalThis.fetch)(i.url,{method:i.method,headers:u,body:s,signal:i.signal??t}).then(async e=>{if(!e.ok){let t=await e.text().catch(()=>``);throw r.httpStatusError(i.url,i.method,e.status,e.statusText,t)}return d(e,i.parseAs,i.url,i.method,n.decode)}),e=>typeof e==`object`&&e&&`_tag`in e?e:r.networkError(i.url,i.method,e));return e.afterResponse?f.flatMap(t=>e.afterResponse(t).map(e=>e)):f})},p=e=>f(n,e),m=e({_tag:`Http`},{request:p,get:(e,t)=>p({...t,url:e,method:`GET`}),post:(e,t)=>p({...t,url:e,method:`POST`}),put:(e,t)=>p({...t,url:e,method:`PUT`}),patch:(e,t)=>p({...t,url:e,method:`PATCH`}),delete:(e,t)=>p({...t,url:e,method:`DELETE`}),head:(e,t)=>p({...t,url:e,method:`HEAD`,parseAs:`raw`}),options:(e,t)=>p({...t,url:e,method:`OPTIONS`,parseAs:`raw`}),client:e=>({request:t=>f(e,t),get:(t,n)=>f(e,{...n,url:t,method:`GET`}),post:(t,n)=>f(e,{...n,url:t,method:`POST`}),put:(t,n)=>f(e,{...n,url:t,method:`PUT`}),patch:(t,n)=>f(e,{...n,url:t,method:`PATCH`}),delete:(t,n)=>f(e,{...n,url:t,method:`DELETE`}),head:(t,n)=>f(e,{...n,url:t,method:`HEAD`,parseAs:`raw`}),options:(t,n)=>f(e,{...n,url:t,method:`OPTIONS`,parseAs:`raw`})})});export{m as Http};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { IO } from "../io/IO.js";
|
|
2
|
+
import { Tag } from "../io/Tag.js";
|
|
3
|
+
import { HttpError } from "./HttpError.js";
|
|
4
|
+
import { HttpRequestView, HttpResponse } from "./HttpRequest.js";
|
|
5
|
+
export interface HttpClientConfig {
|
|
6
|
+
readonly baseUrl?: string;
|
|
7
|
+
readonly defaultHeaders?: Record<string, string>;
|
|
8
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
9
|
+
/**
|
|
10
|
+
* Effectful transformer that runs after `defaultHeaders` and per-call headers
|
|
11
|
+
* are merged, but before the request is sent. Returning a failed IO short-
|
|
12
|
+
* circuits the call with the produced `HttpError`. Compose multiple concerns
|
|
13
|
+
* (request IDs, auth refresh, logging) with standard IO operators — the
|
|
14
|
+
* request side becomes symmetric with the response chain (`.tap`, `.map`,
|
|
15
|
+
* `.flatMap`, `.catchTag`).
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* const addRequestId = (r: HttpRequestView): HttpRequestView => ({
|
|
20
|
+
* ...r,
|
|
21
|
+
* headers: { ...r.headers, "x-request-id": crypto.randomUUID() },
|
|
22
|
+
* })
|
|
23
|
+
*
|
|
24
|
+
* const addBearer = (getToken: () => Promise<string>) =>
|
|
25
|
+
* (r: HttpRequestView): IO<never, HttpError, HttpRequestView> =>
|
|
26
|
+
* IO.tryPromise({
|
|
27
|
+
* try: () => getToken(),
|
|
28
|
+
* catch: (e) => HttpError.networkError(r.url, r.method, e),
|
|
29
|
+
* }).map((token) => ({
|
|
30
|
+
* ...r,
|
|
31
|
+
* headers: { ...r.headers, Authorization: `Bearer ${token}` },
|
|
32
|
+
* }))
|
|
33
|
+
*
|
|
34
|
+
* const api = Http.client({
|
|
35
|
+
* baseUrl: "https://api.example.com",
|
|
36
|
+
* beforeRequest: (r) =>
|
|
37
|
+
* IO.succeed(r)
|
|
38
|
+
* .map(addRequestId)
|
|
39
|
+
* .flatMap(addBearer(getToken))
|
|
40
|
+
* .tap((req) => logger.info(req.method, req.url)),
|
|
41
|
+
* })
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
readonly beforeRequest?: (request: HttpRequestView) => IO<never, HttpError, HttpRequestView>;
|
|
45
|
+
/**
|
|
46
|
+
* Effectful transformer that runs after the response is parsed (and the
|
|
47
|
+
* decoder, if any, succeeds) but before the IO resolves to the caller.
|
|
48
|
+
* Returning a failed IO surfaces the error in place of the response.
|
|
49
|
+
*
|
|
50
|
+
* **Only runs on the success path.** `HttpStatusError` (non-2xx),
|
|
51
|
+
* `DecodeError` (validation failure), and `NetworkError` (fetch / abort)
|
|
52
|
+
* skip this hook and surface directly. For *error*-side observability and
|
|
53
|
+
* recovery (refresh-on-401, error logging), use `.catchTag(...)` /
|
|
54
|
+
* `.tapError(...)` at the call site.
|
|
55
|
+
*
|
|
56
|
+
* The hook receives `HttpResponse<unknown>` — body shape is opaque here
|
|
57
|
+
* because hooks are response-shape-agnostic. The per-call decoder narrows
|
|
58
|
+
* `data` to the typed value before the response reaches the caller, but
|
|
59
|
+
* the hook itself sees `unknown`.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* const api = Http.client({
|
|
64
|
+
* baseUrl: "https://api.example.com",
|
|
65
|
+
* afterResponse: (response) =>
|
|
66
|
+
* IO.succeed(response)
|
|
67
|
+
* .tap((r) => logger.info("response", { status: r.status }))
|
|
68
|
+
* .map((r) => ({ ...r, headers: redactSensitiveHeaders(r.headers) })),
|
|
69
|
+
* })
|
|
70
|
+
*
|
|
71
|
+
* // Refresh-on-401 is a .catchTag pattern, NOT an afterResponse pattern:
|
|
72
|
+
* api.get("/me", { decode })
|
|
73
|
+
* .catchTag("HttpStatusError", (e) =>
|
|
74
|
+
* e.status === 401 ? refreshToken().flatMap(() => api.get("/me", { decode })) : IO.fail(e),
|
|
75
|
+
* )
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
readonly afterResponse?: (response: HttpResponse<unknown>) => IO<never, HttpError, HttpResponse<unknown>>;
|
|
79
|
+
}
|
|
80
|
+
export declare const HttpClient: Tag<HttpClientConfig>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Tag as e}from"../io/Tag.js";const t=e(`HttpClient`),n={};export{t as HttpClient,n as defaultHttpClientConfig};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
|
|
2
|
+
export type NetworkError = {
|
|
3
|
+
readonly _tag: "NetworkError";
|
|
4
|
+
readonly url: string;
|
|
5
|
+
readonly method: HttpMethod;
|
|
6
|
+
readonly cause: unknown;
|
|
7
|
+
};
|
|
8
|
+
export type HttpStatusError = {
|
|
9
|
+
readonly _tag: "HttpStatusError";
|
|
10
|
+
readonly url: string;
|
|
11
|
+
readonly method: HttpMethod;
|
|
12
|
+
readonly status: number;
|
|
13
|
+
readonly statusText: string;
|
|
14
|
+
readonly body: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Raised when a successful HTTP response could not be decoded into the
|
|
18
|
+
* caller's expected shape — JSON parse failure, a `decode: Decoder<T>` that
|
|
19
|
+
* returned `Left(DecoderError)` (including a throw inside `Decoder.fromThrowing`).
|
|
20
|
+
* In practice `cause` is a `DecoderError` (when produced by `decode`) or the
|
|
21
|
+
* `JSON.parse` error (when the body isn't JSON), so the field is typed `unknown`.
|
|
22
|
+
*/
|
|
23
|
+
export type DecodeError = {
|
|
24
|
+
readonly _tag: "DecodeError";
|
|
25
|
+
readonly url: string;
|
|
26
|
+
readonly method: HttpMethod;
|
|
27
|
+
readonly body: string;
|
|
28
|
+
readonly cause: unknown;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* More descriptive alias for `DecodeError` — clarifies that this is the
|
|
32
|
+
* HTTP-level wrapper for response decoding failures, distinct from the
|
|
33
|
+
* structural `DecoderError` tree it usually carries in `cause`. Both names
|
|
34
|
+
* refer to the same `_tag: "DecodeError"` variant.
|
|
35
|
+
*/
|
|
36
|
+
export type ResponseDecodeError = DecodeError;
|
|
37
|
+
export type HttpError = NetworkError | HttpStatusError | DecodeError;
|
|
38
|
+
declare const HttpErrorStatics: {
|
|
39
|
+
networkError: (url: string, method: HttpMethod, cause: unknown) => NetworkError;
|
|
40
|
+
httpStatusError: (url: string, method: HttpMethod, status: number, statusText: string, body: string) => HttpStatusError;
|
|
41
|
+
decodeError: (url: string, method: HttpMethod, body: string, cause: unknown) => DecodeError;
|
|
42
|
+
isNetworkError: (error: HttpError) => error is NetworkError;
|
|
43
|
+
isHttpStatusError: (error: HttpError) => error is HttpStatusError;
|
|
44
|
+
isDecodeError: (error: HttpError) => error is DecodeError;
|
|
45
|
+
match: <T>(error: HttpError, patterns: {
|
|
46
|
+
readonly NetworkError: (e: NetworkError) => T;
|
|
47
|
+
readonly HttpStatusError: (e: HttpStatusError) => T;
|
|
48
|
+
readonly DecodeError: (e: DecodeError) => T;
|
|
49
|
+
}) => T;
|
|
50
|
+
};
|
|
51
|
+
export declare const HttpError: HttpErrorCompanion;
|
|
52
|
+
/** The type of `HttpError`: its tag and its statics, named so that errors and hovers print `HttpErrorCompanion`. */
|
|
53
|
+
export type HttpErrorCompanion = {
|
|
54
|
+
readonly _tag: "HttpError";
|
|
55
|
+
} & HttpErrorStaticsType;
|
|
56
|
+
type HttpErrorStaticsType = typeof HttpErrorStatics;
|
|
57
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";const t=e({_tag:`HttpError`},{networkError:(e,t,n)=>({_tag:`NetworkError`,url:e,method:t,cause:n}),httpStatusError:(e,t,n,r,i)=>({_tag:`HttpStatusError`,url:e,method:t,status:n,statusText:r,body:i}),decodeError:(e,t,n,r)=>({_tag:`DecodeError`,url:e,method:t,body:n,cause:r}),isNetworkError:e=>e._tag===`NetworkError`,isHttpStatusError:e=>e._tag===`HttpStatusError`,isDecodeError:e=>e._tag===`DecodeError`,match:(e,t)=>{switch(e._tag){case`NetworkError`:return t.NetworkError(e);case`HttpStatusError`:return t.HttpStatusError(e);case`DecodeError`:return t.DecodeError(e)}}});export{t as HttpError};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { Decoder } from "../decoder/Decoder.js";
|
|
2
|
+
import { Encoder } from "../decoder/Encoder.js";
|
|
3
|
+
import { HttpMethod } from "./HttpError.js";
|
|
4
|
+
export type ParseMode = "json" | "text" | "blob" | "arrayBuffer" | "raw";
|
|
5
|
+
/**
|
|
6
|
+
* Typed query-parameter record. Scalar values (string | number | boolean) are
|
|
7
|
+
* `String()`-coerced; arrays repeat the key (`{ tag: ["a", "b"] }` → `tag=a&tag=b`);
|
|
8
|
+
* `undefined` and `null` values are dropped (so callers can write
|
|
9
|
+
* `{ foo: maybe.toNullable() }` without conditionals); special characters are
|
|
10
|
+
* percent-encoded via `URLSearchParams`.
|
|
11
|
+
*
|
|
12
|
+
* Nested objects are not supported (the type prevents them at compile time).
|
|
13
|
+
*/
|
|
14
|
+
export type HttpQueryParams = Readonly<Record<string, string | number | boolean | readonly (string | number | boolean)[] | undefined | null>>;
|
|
15
|
+
export interface HttpRequestOptions<T = unknown, TReq = unknown> {
|
|
16
|
+
readonly url: string;
|
|
17
|
+
readonly method: HttpMethod;
|
|
18
|
+
readonly headers?: Record<string, string>;
|
|
19
|
+
readonly body?: unknown;
|
|
20
|
+
readonly signal?: AbortSignal;
|
|
21
|
+
readonly parseAs?: ParseMode;
|
|
22
|
+
/**
|
|
23
|
+
* Query-string parameters appended to the URL. Merges with any query string
|
|
24
|
+
* already present in `url`. See {@link HttpQueryParams} for encoding rules.
|
|
25
|
+
*/
|
|
26
|
+
readonly params?: HttpQueryParams;
|
|
27
|
+
/**
|
|
28
|
+
* Either-returning response decoder. Returns `Left(DecoderError)` on
|
|
29
|
+
* failure; the framework maps that to `HttpError.DecodeError(cause: DecoderError)`.
|
|
30
|
+
* The recursive `DecoderError` tree preserves structural failure info
|
|
31
|
+
* (paths, child errors) for diagnosis and rendering.
|
|
32
|
+
*
|
|
33
|
+
* For a parser that throws (Zod's `.parse`, an inline check), wrap it in
|
|
34
|
+
* `Decoder.fromThrowing(parse)`: a throw becomes a `DecoderError` leaf whose
|
|
35
|
+
* `cause` is the thrown value.
|
|
36
|
+
*/
|
|
37
|
+
readonly decode?: Decoder<T>;
|
|
38
|
+
/**
|
|
39
|
+
* Whether to flatten functype ADTs in the request body to their primitive
|
|
40
|
+
* projections (Option → nullable, Either → right-value-or-throw-on-Left,
|
|
41
|
+
* List → array, Try → success-value-or-throw, Map → record) before serializing.
|
|
42
|
+
* Default `true` — matches the wire shape external JSON APIs expect.
|
|
43
|
+
*
|
|
44
|
+
* Set to `false` to emit each ADT's canonical `{_tag, value}` form via
|
|
45
|
+
* `toValue()` for functype-to-functype services where both ends round-trip
|
|
46
|
+
* the tagged shape via `Decoder.tagged.*`.
|
|
47
|
+
*
|
|
48
|
+
* Ignored when `encode` is set.
|
|
49
|
+
*/
|
|
50
|
+
readonly flatten?: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Request-side encoder. When set, the body goes on the wire as `JSON.stringify(encode(body))`
|
|
53
|
+
* with `Content-Type: application/json`, and `flatten` is ignored. Use it when `flatten` can't
|
|
54
|
+
* express the wire shape: custom date formats, snake_case keys, stripping fields. A throw inside
|
|
55
|
+
* `encode` fails the request with `HttpError.NetworkError`, like any body that can't be serialized.
|
|
56
|
+
*
|
|
57
|
+
* It applies to the body after `beforeRequest` runs, so a hook that swaps the body must keep it
|
|
58
|
+
* a `TReq`.
|
|
59
|
+
*
|
|
60
|
+
* `TReq` is inferred from `encode`. If you pass the response type explicitly
|
|
61
|
+
* (`Http.post<User>(…)`), pass the request type too (`Http.post<User, NewUser>(…)`):
|
|
62
|
+
* TypeScript defaults the rest to `unknown`, and an `Encoder<NewUser>` won't fit `Encoder<unknown>`.
|
|
63
|
+
*/
|
|
64
|
+
readonly encode?: Encoder<TReq>;
|
|
65
|
+
}
|
|
66
|
+
export interface HttpMethodOptions<T = unknown, TReq = unknown> {
|
|
67
|
+
readonly headers?: Record<string, string>;
|
|
68
|
+
readonly body?: unknown;
|
|
69
|
+
readonly signal?: AbortSignal;
|
|
70
|
+
readonly parseAs?: ParseMode;
|
|
71
|
+
/** Either-returning response decoder. See {@link HttpRequestOptions.decode}. */
|
|
72
|
+
readonly decode?: Decoder<T>;
|
|
73
|
+
readonly flatten?: boolean;
|
|
74
|
+
/** Request-side encoder; overrides `flatten`. See {@link HttpRequestOptions.encode}. */
|
|
75
|
+
readonly encode?: Encoder<TReq>;
|
|
76
|
+
/**
|
|
77
|
+
* Query-string parameters appended to the URL. See {@link HttpQueryParams}.
|
|
78
|
+
*/
|
|
79
|
+
readonly params?: HttpQueryParams;
|
|
80
|
+
}
|
|
81
|
+
export interface HttpResponse<T> {
|
|
82
|
+
readonly data: T;
|
|
83
|
+
readonly status: number;
|
|
84
|
+
readonly statusText: string;
|
|
85
|
+
readonly headers: Headers;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The assembled, pre-wire view of a request that `HttpClientConfig.beforeRequest`
|
|
89
|
+
* receives and may return a transformed copy of. URL is resolved against
|
|
90
|
+
* `baseUrl`; headers reflect the `defaultHeaders` + per-call merge. The
|
|
91
|
+
* response decoder (`decode`) is intentionally not exposed here — it isn't
|
|
92
|
+
* part of the wire request and applies to the response. The `flatten` flag IS exposed because it affects how `body`
|
|
93
|
+
* is serialized.
|
|
94
|
+
*/
|
|
95
|
+
export interface HttpRequestView {
|
|
96
|
+
readonly url: string;
|
|
97
|
+
readonly method: HttpMethod;
|
|
98
|
+
readonly headers?: Record<string, string>;
|
|
99
|
+
readonly body?: unknown;
|
|
100
|
+
readonly signal?: AbortSignal;
|
|
101
|
+
readonly parseAs?: ParseMode;
|
|
102
|
+
readonly flatten?: boolean;
|
|
103
|
+
}
|
package/dist/fetch/index.d.ts
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { Http, HttpCompanion } from "./Http.js";
|
|
2
|
+
import { HttpClient, HttpClientConfig } from "./HttpClient.js";
|
|
3
|
+
import { DecodeError, HttpError, HttpErrorCompanion, HttpMethod, HttpStatusError, NetworkError, ResponseDecodeError } from "./HttpError.js";
|
|
4
|
+
import { HttpMethodOptions, HttpQueryParams, HttpRequestOptions, HttpRequestView, HttpResponse, ParseMode } from "./HttpRequest.js";
|
|
5
|
+
export { type DecodeError, Http, HttpClient, type HttpClientConfig, type HttpCompanion, HttpError, type HttpErrorCompanion, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, type NetworkError, type ParseMode, type ResponseDecodeError };
|
package/dist/fetch/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Http as e}from"./Http.js";import{HttpClient as t}from"./HttpClient.js";import{HttpError as n}from"./HttpError.js";export{e as Http,t as HttpClient,n as HttpError,n as HttpErrors};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Foldable type class represents data structures that can be folded to a summary value.
|
|
3
|
+
*
|
|
4
|
+
* This interface provides the universal fold operations (foldLeft, foldRight) that work
|
|
5
|
+
* consistently across all data structures. The `fold` method is intentionally excluded
|
|
6
|
+
* because it has different semantics for sum types vs collections:
|
|
7
|
+
* - Sum types (Option, Either, Try): `fold(onEmpty, onValue)` — pattern match
|
|
8
|
+
* - Collections (List, Set, Map): `fold(initial, fn)` — left-reduce accumulator
|
|
9
|
+
*
|
|
10
|
+
* Each type category defines its own `fold` with the appropriate signature.
|
|
11
|
+
*
|
|
12
|
+
* @typeParam A - The type of elements in the data structure
|
|
13
|
+
*/
|
|
14
|
+
export interface Foldable<out A> {
|
|
15
|
+
/**
|
|
16
|
+
* Left-associative fold using the provided zero value and operation
|
|
17
|
+
* @param z - Zero/identity value
|
|
18
|
+
* @returns A function that takes an operation to apply
|
|
19
|
+
*/
|
|
20
|
+
foldLeft<B>(z: B): (op: (b: B, a: A) => B) => B;
|
|
21
|
+
/**
|
|
22
|
+
* Right-associative fold using the provided zero value and operation
|
|
23
|
+
* @param z - Zero/identity value
|
|
24
|
+
* @returns A function that takes an operation to apply
|
|
25
|
+
*/
|
|
26
|
+
foldRight<B>(z: B): (op: (a: A, b: B) => B) => B;
|
|
27
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { Either } from "../either/index.js";
|
|
2
|
+
import { List } from "../list/index.js";
|
|
3
|
+
import { Option } from "../option/index.js";
|
|
4
|
+
import { Type } from "../types/index.js";
|
|
5
|
+
/**
|
|
6
|
+
* Structural type for sum types that support pattern-match fold (Option, Either, Try, etc.).
|
|
7
|
+
* Uses duck typing so any type with the right fold signature works, without requiring a shared interface.
|
|
8
|
+
*/
|
|
9
|
+
type PatternFoldable<A> = {
|
|
10
|
+
fold<B>(onEmpty: () => B, onValue: (value: A) => B): B;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Utility functions for working with sum-type Foldable data structures.
|
|
14
|
+
* These utilities use pattern-match fold semantics and are designed for
|
|
15
|
+
* sum types (Option, Either, Try) — not collections.
|
|
16
|
+
*/
|
|
17
|
+
export declare const FoldableUtils: {
|
|
18
|
+
/**
|
|
19
|
+
* Converts a sum type to an Option
|
|
20
|
+
*
|
|
21
|
+
* @param foldable - The sum type to convert
|
|
22
|
+
* @returns An Option containing the value, or None if empty
|
|
23
|
+
*/
|
|
24
|
+
toOption: <A extends Type>(foldable: PatternFoldable<A>) => Option<A>;
|
|
25
|
+
/**
|
|
26
|
+
* Converts a sum type to a List
|
|
27
|
+
*
|
|
28
|
+
* @param foldable - The sum type to convert
|
|
29
|
+
* @returns A List containing the value(s), or empty List if empty
|
|
30
|
+
*/
|
|
31
|
+
toList: <A extends Type>(foldable: PatternFoldable<A>) => List<A>;
|
|
32
|
+
/**
|
|
33
|
+
* Converts a sum type to an Either
|
|
34
|
+
*
|
|
35
|
+
* @param foldable - The sum type to convert
|
|
36
|
+
* @param left - The value to use for Left if empty
|
|
37
|
+
* @returns Either.Right with the value if non-empty, or Either.Left with left if empty
|
|
38
|
+
*/
|
|
39
|
+
toEither: <A extends Type, E>(foldable: PatternFoldable<A>, left: E) => Either<E, A>;
|
|
40
|
+
/**
|
|
41
|
+
* Checks if the sum type is empty
|
|
42
|
+
*
|
|
43
|
+
* @param foldable - The sum type to check
|
|
44
|
+
* @returns true if empty, false otherwise
|
|
45
|
+
*/
|
|
46
|
+
isEmpty: <A extends Type>(foldable: PatternFoldable<A>) => boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Calculates the size of the sum type (0 or 1)
|
|
49
|
+
*
|
|
50
|
+
* @param foldable - The sum type to measure
|
|
51
|
+
* @returns The size (0 if empty, 1 if non-empty)
|
|
52
|
+
*/
|
|
53
|
+
size: <A extends Type>(foldable: PatternFoldable<A>) => number;
|
|
54
|
+
};
|
|
55
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Left as e,Right as t}from"../either/index.js";import{List as n}from"../list/index.js";import{None as r,Some as i}from"../option/index.js";const a={toOption:e=>e.fold(()=>r(),e=>i(e)),toList:e=>e.fold(()=>n([]),e=>n([e])),toEither:(n,r)=>n.fold(()=>e(r),e=>t(e)),isEmpty:e=>e.fold(()=>!0,()=>!1),size:e=>e.fold(()=>0,()=>1)};export{a as FoldableUtils};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { Collection } from "../collections/index.js";
|
|
2
|
+
import { Extractable } from "../extractable/Extractable.js";
|
|
3
|
+
import { Foldable } from "../foldable/Foldable.js";
|
|
4
|
+
import { ConcurrencyOptions } from "../internal/concurrency.js";
|
|
5
|
+
import { Matchable } from "../matchable/Matchable.js";
|
|
6
|
+
import { Pipe } from "../pipe/index.js";
|
|
7
|
+
import { Serializable } from "../serializable/Serializable.js";
|
|
8
|
+
import { Reducible, Traversable } from "../traversable/Traversable.js";
|
|
9
|
+
import { Typeable } from "../typeable/Typeable.js";
|
|
10
|
+
import { Applicative, AsyncMonad } from "../typeclass/Functor.js";
|
|
11
|
+
import { CollectionOps, ContainerOps } from "../typeclass/ContainerOps.js";
|
|
12
|
+
import { Type } from "../types/index.js";
|
|
13
|
+
/**
|
|
14
|
+
* Base interface for all functype data structures.
|
|
15
|
+
* This provides a standard contract with core functional programming traits.
|
|
16
|
+
*
|
|
17
|
+
* @typeParam A - The type of value contained in the functor
|
|
18
|
+
* @typeParam Tag - The type tag for pattern matching (e.g., "Some" | "None" for Option)
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```typescript
|
|
22
|
+
* // Implementing FunctypeBase for a custom data structure
|
|
23
|
+
* class MyContainer<T> implements FunctypeBase<T, "Empty" | "Full"> {
|
|
24
|
+
* // Implementation of all required methods...
|
|
25
|
+
* }
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export interface FunctypeBase<A, Tag extends string = string> extends FunctypeCore<A, Tag>, AsyncMonad<A>, Traversable<A> {}
|
|
29
|
+
/**
|
|
30
|
+
* FunctypeBase without the monad's members (`map`, `ap`, `flatMap`, `flatMapAsync`). Types whose
|
|
31
|
+
* `map` or `flatMap` take another shape, such as the collections and Obj, extend this rather than
|
|
32
|
+
* `Omit<FunctypeBase, …>`: a member reached through a mapped type has no declaration, so
|
|
33
|
+
* `@typescript-eslint/unbound-method` can't see a detached call to it.
|
|
34
|
+
*/
|
|
35
|
+
export interface FunctypeCore<A, Tag extends string = string> extends Reducible<A>, Serializable<A>, Foldable<A>, Typeable<Tag>, ContainerOps<A> {
|
|
36
|
+
readonly _tag: Tag;
|
|
37
|
+
readonly [Symbol.toStringTag]: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Interface for single-value containers like Option, Either, Try.
|
|
41
|
+
* Extends FunctypeBase with extraction methods and Pipe.
|
|
42
|
+
*
|
|
43
|
+
* @typeParam A - The type of value contained
|
|
44
|
+
* @typeParam Tag - The type tag for pattern matching
|
|
45
|
+
*/
|
|
46
|
+
export interface Functype<A, Tag extends string = string> extends FunctypeBase<A, Tag>, FunctypeValue<A, Tag> {}
|
|
47
|
+
/**
|
|
48
|
+
* Functype without the monad's members, for a single-value type whose `map` takes another shape,
|
|
49
|
+
* such as Obj. See `FunctypeCore`.
|
|
50
|
+
*/
|
|
51
|
+
export interface FunctypeValue<A, Tag extends string = string> extends FunctypeCore<A, Tag>, Extractable<A>, Pipe<A>, Matchable<A, Tag> {
|
|
52
|
+
toValue(): {
|
|
53
|
+
_tag: Tag;
|
|
54
|
+
value: A;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* A version of Functype for collection types that need iteration support.
|
|
59
|
+
* Extends FunctypeBase with Iterable protocol but without Extractable.
|
|
60
|
+
*
|
|
61
|
+
* @typeParam A - The element type of the collection
|
|
62
|
+
* @typeParam Tag - The type tag for pattern matching
|
|
63
|
+
*/
|
|
64
|
+
export interface FunctypeCollection<A, Tag extends string = string> extends FunctypeCore<A, Tag>, Applicative<A>, Iterable<A>, Pipe<A[]>, Collection<A>, CollectionOps<A, FunctypeCollection<A, Tag>> {
|
|
65
|
+
toValue(): {
|
|
66
|
+
_tag: Tag;
|
|
67
|
+
value: A[];
|
|
68
|
+
};
|
|
69
|
+
flatMap<B extends Type>(f: (value: A) => Iterable<B>): FunctypeCollection<B, Tag>;
|
|
70
|
+
/**
|
|
71
|
+
* Async flatMap. `options.concurrency` caps how many calls of `f` run at once: `1` runs them in order,
|
|
72
|
+
* one after another; `"unbounded"` starts them all together. Results keep input order either way.
|
|
73
|
+
* The default depends on the collection: List starts them all; Set runs them in order.
|
|
74
|
+
*/
|
|
75
|
+
flatMapAsync<B extends Type>(f: (value: A) => PromiseLike<Iterable<B>>, options?: ConcurrencyOptions): PromiseLike<FunctypeCollection<B, Tag>>;
|
|
76
|
+
}
|