functype 1.27.2 → 2.1.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 +70 -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 +1150 -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 +290 -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 +1263 -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 +8 -13
- 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-BadxJrCt.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-BQPeS6p2.js +0 -10
- package/dist/typeclass-C61yDVYd.js +0 -1
package/dist/io/IO.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";import{Left as t,Right as n}from"../either/index.js";import{workerCount as r}from"../internal/concurrency.js";import{define as i}from"../internal/define.js";import{anySignal as a}from"../internal/signal.js";import{safeStringify as o}from"../internal/stringify.js";import{None as s,Option as c,Some as l}from"../option/index.js";import{Try as u}from"../try/index.js";import{Context as d}from"./Context.js";import{Exit as f}from"./Exit.js";import{SpanTracer as p}from"./SpanTracer.js";const m=e=>e,h=e=>e(),g=(e,t)=>e(t),_=(e,t,n)=>e(t,n);var v=class extends Error{constructor(e,t){super(t??`Effect timed out after ${e}ms`),this.duration=e,this._tag=`TimeoutError`,this.name=`TimeoutError`}},y=class extends Error{constructor(e){super(e??`Effect was interrupted`),this._tag=`InterruptedError`,this.name=`InterruptedError`}static is(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`InterruptedError`}},b=class extends Error{constructor(e){super(`Cannot run ${e} effect synchronously — use run()/runExit() instead`),this.operation=e,this._tag=`UnsupportedSyncOperationError`,this.name=`UnsupportedSyncOperationError`}},x=class extends Error{constructor(e,t,n){super(n??`Repeat exhausted after ${e} iterations`),this.max=e,this.lastValue=t,this._tag=`RepeatExhausted`,this.name=`RepeatExhausted`}static is(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`RepeatExhausted`}};const S=`effect`,C=e=>e[S],w=e=>{let t=!1;return{next:n=>t?{done:!0,value:n}:(t=!0,{done:!1,value:e})}},T=e=>m(e),E=i()(`IO`,{[Symbol.toStringTag]:`IO`,map(e){return D(m({_tag:`Map`,effect:this,f:e}))},flatMap(e){return D(m({_tag:`FlatMap`,effect:this,f:e}))},mapTry(e,t){return this.flatMap(n=>Q.tryCatch(()=>e(n),t))},tap(e){return this.map(t=>(e(t),t))},tapEffect(e){return this.flatMap(t=>e(t).map(()=>t))},mapError(e){return D(m({_tag:`MapError`,effect:this,f:e}))},tapError(e){return this.mapError(t=>(e(t),t))},recover(e){return D(m({_tag:`Recover`,effect:this,fallback:e}))},recoverWith(e){return D(m({_tag:`RecoverWith`,effect:this,f:e}))},fold(e,t){return D(m({_tag:`Fold`,effect:this,onFailure:e,onSuccess:t}))},match(e){return this.fold(e.failure,e.success)},catchTag(e,t){return D(m({_tag:`RecoverWith`,effect:this,f:n=>typeof n==`object`&&n&&`_tag`in n&&n._tag===e?m(t(m(n))):m(Q.fail(n))}))},catchAll(e){return this.recoverWith(e)},retry(e){return e<=0?this:this.recoverWith(()=>this.retry(e-1))},retryWithDelay(e,t){return e<=0?this:this.recoverWith(()=>Q.sleep(t).flatMap(()=>this.retryWithDelay(e-1,t)))},retryWhile(e){let t=(n,r)=>this.recoverWith(i=>{if(n<=0||!e.while(i,r))return m(Q.fail(i));let a=t(n-1,r+1);return e.delayMs===void 0?a:m(Q.sleep(e.delayMs).flatMap(()=>a))});return t(e.n,1)},retryWithBackoff(e){let t=e.factor??2,n=e.maxMs??3e4,r=e.jitter??!0,i=e.while??(()=>!0),a=(o,s)=>this.recoverWith(c=>{if(o<=0||!i(c,s))return m(Q.fail(c));let l=Math.min(n,e.baseMs*t**(s-1)),u=r?l*(.5+Math.random()*.5):l,d=a(o-1,s+1);return m(Q.sleep(u).flatMap(()=>d))});return a(e.n,1)},repeatUntil(e,t){if(t.max<=0)return m(Q.fail(new x(t.max)));let n=r=>this.flatMap(i=>{if(e(i))return m(Q.succeed(i));if(r<=1)return m(Q.fail(new x(t.max,i)));let a=n(r-1);return t.delayMs===void 0?a:m(Q.sleep(t.delayMs).flatMap(()=>a))});return n(t.max)},repeatWhile(e,t){return this.repeatUntil(t=>!e(t),t)},zipRight(e){return this.flatMap(()=>e)},zipLeft(e){return this.flatMap(t=>e.map(()=>t))},zip(e){return this.flatMap(t=>e.map(e=>[t,e]))},flatten(){return this.flatMap(e=>e)},provideContext(e){return D(m({_tag:`ProvideContext`,effect:this,context:e}))},provideService(e,t){let n=d.make(e,t);return D(m({_tag:`ProvideContext`,effect:this,context:n}))},provideLayer(e){let t=m(Q.async(async()=>{let t=d.empty();return await e.build(m(t))}));return m(t.flatMap(e=>D(m({_tag:`ProvideContext`,effect:this,context:e}))))},async run(){return F(await q(C(T(this)),A,void 0,void 0))},async runOrThrow(){return I(await q(C(T(this)),A,void 0,void 0))},runSync(){return F(B(C(T(this)),A,void 0))},runSyncOrThrow(){return I(B(C(T(this)),A,void 0))},async runExit(e){let t=e?.signal;if(!t)return q(C(T(this)),A,void 0,void 0);let n=await q(C(T(this)),A,t,void 0);return t.aborted&&n.isFailure()?f.interrupted():n},async runOption(){let e=await q(C(T(this)),A,void 0,void 0);return e.isSuccess()?l(e.value):s()},async runTry(){let e=await q(C(T(this)),A,void 0,void 0);if(e.isSuccess())return m(u(()=>e.value));let t=O(e),n=t?t.value:/* @__PURE__ */ Error(`Effect was interrupted`);return m(u(()=>{throw n}))},runCancellable(){let e=new AbortController;return{result:T(this).interruptOn(e.signal).run(),cancel:()=>e.abort()}},pipe(e){return e(this)},delay(e){return Q.sleep(e).flatMap(()=>this)},timeout(e){return D(m({_tag:`Timeout`,effect:this,duration:e}))},timeoutTo(e,t){return m(this.timeout(e).recover(m(t)))},interruptOn(e){return D(m({_tag:`InterruptWhen`,effect:this,signal:e}))},withSpan(e,t=j){return D(m({_tag:`WithSpan`,effect:this,name:e,attributes:t}))},toString(){return`IO(${o(this[S]._tag)})`},toJSON(){return{_tag:`IO`,effect:this[S]._tag}},[Symbol.iterator](){return w(this)}}),D=e=>{let t=Object.create(E);return t[S]=e,t},O=e=>{if(e._tag===`Failure`)return{value:e.error};if(e._tag===`Die`)return{value:e.defect}},k=e=>e._tag===`Die`&&e.defect instanceof b?void 0:O(e),A=d.empty(),j=Object.freeze({}),M=e=>{let t=e.get(p);return t.isNone()?void 0:t.orThrow()},N=()=>/* @__PURE__ */ Error(`Cannot run async effect synchronously`),P=e=>/* @__PURE__ */ Error(`Service not found: ${e.id}`),F=e=>{if(e._tag===`Success`)return n(e.value);if(e._tag===`Failure`)return t(e.error);throw e._tag===`Die`?e.defect:new y},I=e=>{if(e._tag===`Success`)return e.value;throw e._tag===`Failure`?e.error:e._tag===`Die`?e.defect:new y},L=e=>{try{return e()}catch(e){return f.die(e)}},R=e=>{let t=typeof e==`object`&&e?e[S]:void 0;if(typeof t==`object`&&t&&typeof t._tag==`string`)return m(t);throw TypeError("IO.gen was yielded a value that isn't an IO. Use `yield*` on an IO; convert an Option, Either or Try first with IO.fromOption, IO.fromEither or IO.fromTry, and wrap a plain value with IO.succeed.")},z=()=>f.die(/* @__PURE__ */ TypeError(`A step produced no outcome: a SpanTracer's run must return what its fn returns`)),B=(e,t,n)=>{let r=[],i=m(e),a=m(t),o;for(;;){if(o===void 0)try{switch(i._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:r.push(i,a),i=C(i.effect);continue;case`ProvideContext`:a=a.merge(i.context),i=C(i.effect);continue;case`Gen`:{let e=h(i.start),t=e.next(void 0);if(t.done===!0){o=f.succeed(t.value);continue}r.push({_tag:`GenNext`,iterator:e},a),i=R(t.value);continue}default:o=V(i,a,n)??z();continue}}catch(e){o=f.die(e);continue}if(r.length===0)return m(o);let e=r.pop(),t=r.pop();try{switch(t._tag){case`Map`:o._tag===`Success`&&(o=f.succeed(g(t.f,o.value)));break;case`FlatMap`:o._tag===`Success`&&(i=C(g(t.f,o.value)),a=e,o=void 0);break;case`MapError`:{let e=k(o);e&&(o=f.fail(g(t.f,e.value)));break}case`Recover`:k(o)&&(o=f.succeed(t.fallback));break;case`RecoverWith`:{let n=k(o);n&&(i=C(g(t.f,n.value)),a=e,o=void 0);break}case`Fold`:{let e=k(o);e?o=f.succeed(g(t.onFailure,e.value)):o._tag===`Success`&&(o=f.succeed(g(t.onSuccess,o.value)));break}case`GenNext`:if(o._tag===`Success`){let n=t.iterator.next(o.value);n.done===!0?o=f.succeed(n.value):(r.push(t,e),i=R(n.value),a=e,o=void 0)}}}catch(e){o=f.die(e)}}},V=(e,t,n)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return f.die(N());case`Auto`:return H(e.thunk);case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Bracket`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(g(e.release,i)),t,n);return o.isSuccess()?a:o}case`BracketExit`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(_(e.release,i,a)),t,n);return o.isSuccess()?a:o}case`All`:return W(e.effects,t,n);case`Race`:return f.die(new b(`race`));case`Timeout`:return f.die(new b(`timeout`));case`Sleep`:return f.die(new b(`sleep`));case`WithSpan`:return U(e,t,n);case`InterruptWhen`:{if(e.signal.aborted)return f.fail(new y);let r=B(C(e.effect),t,n);return r.isInterrupted()?f.fail(new y):r}default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},H=e=>{try{let t=e();return t instanceof Promise?f.die(N()):f.succeed(t)}catch(e){return f.fail(e)}},U=(e,t,n)=>{let r=M(t);if(!r)return B(C(e.effect),t,n);let i=r.start(e.name,e.attributes,n),a=L(()=>r.run(i,()=>B(C(e.effect),t,i)));return r.end(i,a),a},W=(e,t,n)=>{let r=[];for(let i of e){let e=B(C(i),t,n);if(!e.isSuccess())return m(e);r.push(e.value)}return f.succeed(r)},G=(e,t)=>{if(t)return e.isDie()?m(e):f.interrupted()},K=(e,t,n)=>e.isSuccess()||e.isDie()?e:n?f.interrupted():e.isInterrupted()||t.aborted?f.fail(new y):e,q=async(e,t,n,r)=>{let i=[],a=m(e),o=m(t),s,c=()=>n?.aborted??!1;for(;;){if(s===void 0){if(c()){s=f.interrupted();continue}try{switch(a._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:i.push(a,o),a=C(a.effect);continue;case`ProvideContext`:o=o.merge(a.context),a=C(a.effect);continue;case`Gen`:{let e=h(a.start),t=e.next(void 0);if(t.done===!0){s=c()?f.interrupted():f.succeed(t.value);continue}i.push({_tag:`GenNext`,iterator:e},o),a=R(t.value);continue}default:{let e=X(a,o,n,r);s=(e instanceof Promise?await e:e)??z();continue}}}catch(e){s=f.die(e);continue}}if(i.length===0)return m(s);let e=i.pop(),t=i.pop();try{switch(t._tag){case`Map`:s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.f,s.value)));break;case`FlatMap`:s._tag===`Success`&&(c()?s=f.interrupted():(a=C(g(t.f,s.value)),o=e,s=void 0));break;case`MapError`:{let e=O(s);e&&(s=G(s,c())??f.fail(g(t.f,e.value)));break}case`Recover`:O(s)&&(s=G(s,c())??f.succeed(t.fallback));break;case`RecoverWith`:{let n=O(s);if(n){let r=G(s,c());r?s=r:(a=C(g(t.f,n.value)),o=e,s=void 0)}break}case`Fold`:{let e=O(s);e?s=G(s,c())??f.succeed(g(t.onFailure,e.value)):s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.onSuccess,s.value)));break}case`GenNext`:if(s._tag===`Success`){if(c())s=f.interrupted();else{let n=t.iterator.next(s.value);n.done===!0?s=c()?f.interrupted():f.succeed(n.value):(i.push(t,e),a=R(n.value),o=e,s=void 0)}}}}catch(e){s=f.die(e)}}},J=e=>e.catch(e=>f.die(e)),Y=(e,t)=>J(Promise.resolve().then(()=>t?.aborted?f.interrupted():e())),X=(e,t,n,r)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return ee(e.thunk,n);case`Auto`:try{let t=h(e.thunk);return t instanceof Promise?t.then(e=>f.succeed(e),e=>f.fail(e)):f.succeed(t)}catch(e){return f.fail(e)}case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Sleep`:return se(e.duration,n);case`Bracket`:return Y(()=>te(e,t,n,r),n);case`BracketExit`:return Y(()=>ne(e,t,n,r),n);case`Race`:return e.effects.length===0?f.die(/* @__PURE__ */ Error(`No effects to race`)):Y(()=>ce(e.effects,t,n,r),n);case`Timeout`:return Y(()=>le(e.effect,e.duration,t,n,r),n);case`InterruptWhen`:return Y(()=>re(e,t,n,r),n);case`WithSpan`:return Y(()=>ie(e,t,n,r),n);case`All`:return Y(()=>ue(e.effects,e.concurrency,t,n,r),n);default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},ee=async(e,t)=>{try{return f.succeed(await e(t))}catch(e){return f.fail(e)}},Z=async(e,t,n,r)=>{if(n?.aborted)return f.interrupted();try{return await q(C(e()),t,n,r)}catch(e){return f.die(e)}},te=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(g(e.release,a)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},ne=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(_(e.release,a,o)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},re=async(e,t,n,r)=>{let{signal:i}=e,o=a([n,i]);try{let a=await q(C(e.effect),t,o.signal,r);return K(a,i,n?.aborted??!1)}catch(e){return f.die(e)}finally{o.dispose()}},ie=async(e,t,n,r)=>{let i=M(t);if(!i)return q(C(e.effect),t,n,r);let a=i.start(e.name,e.attributes,r),o=await ae(()=>i.run(a,()=>q(C(e.effect),t,n,a)));return i.end(a,oe(o,n)),o},ae=async e=>{try{return await e()}catch(e){return f.die(e)}},oe=(e,t)=>e.isFailure()&&t?.aborted===!0?f.interrupted():e,se=(e,t)=>new Promise(n=>{let r=e===1/0?void 0:setTimeout(()=>{t?.removeEventListener(`abort`,i),n(f.succeed(void 0))},e);function i(){clearTimeout(r),n(f.interrupted())}t?.addEventListener(`abort`,i,{once:!0})}),ce=(e,t,n,r)=>{let i=e.map(()=>{let e=new AbortController;return{own:e,scope:a([n,e.signal])}}),o={settled:!1};return new Promise(n=>{e.forEach((e,a)=>{q(C(e),t,i[a].scope.signal,r).then(e=>{o.settled||(o.settled=!0,i.forEach(({own:e,scope:t},n)=>{n!==a&&e.abort(),t.dispose()}),n(e))})})})},le=(e,t,n,r,i)=>{let o=new AbortController,s=a([r,o.signal]);return new Promise(r=>{let a=setTimeout(()=>{o.abort(),s.dispose(),r(f.fail(new v(t)))},t);q(C(e),n,s.signal,i).then(e=>{clearTimeout(a),s.dispose(),r(e)})})},ue=(e,t,n,i,o)=>{if(e.length===0)return Promise.resolve(f.succeed([]));let s=new AbortController,c=a([i,s.signal]),l=Array(e.length),u={next:0,succeeded:0,settled:!1};return new Promise(i=>{let a=e=>{u.settled=!0,e.isSuccess()||s.abort(),c.dispose(),i(e)},d=()=>{if(u.settled||u.next>=e.length)return;let t=u.next;u.next=t+1,q(C(e[t]),n,c.signal,o).then(n=>{u.settled||(n.isSuccess()?(l[t]=n.value,u.succeeded+=1,u.succeeded===e.length?a(f.succeed(l)):d()):a(m(n)))})};Array.from({length:r(t,e.length)}).forEach(d)})},Q={sync:e=>D({_tag:`Sync`,thunk:e}),succeed:e=>D({_tag:`Succeed`,value:e}),fail:e=>D({_tag:`Fail`,error:e}),die:e=>D({_tag:`Die`,defect:e}),async:e=>D(m({_tag:`Async`,thunk:e})),tryPromise:e=>D({_tag:`Async`,thunk:e.try}).mapError(e.catch),tryCatch:(e,r)=>Q.sync(()=>{try{return n(e())}catch(e){return t(r(e))}}).flatMap(e=>Q.fromEither(e)),liftSync:e=>(...t)=>Q.sync(()=>e(...t)),liftPromise:e=>(...t)=>Q.async(()=>e(...t)),fromEither:e=>m(e.isRight()?Q.succeed(e.value):Q.fail(e.value)),fromPromiseEither:(e,t)=>{let n=Q.async(async()=>e());return(t?n.mapError(t):n.recoverWith(e=>Q.die(e))).flatMap(e=>Q.fromEither(e))},fromOption:e=>m(e.isSome()?Q.succeed(e.value):Q.fail(void 0)),fromOptionOrFail:(e,t)=>m(e.isSome()?Q.succeed(e.value):Q.fail(t())),fromTry:e=>m(e.isSuccess()?Q.succeed(e.orThrow()):Q.fail(e.error)),fromResult:e=>m(e.error?Q.fail(e.error):Q.succeed(c(e.data))),tryAsync:(e,t,n)=>n?.aborted?m(Q.fail(t(n.reason??new DOMException(`Aborted`,`AbortError`)))):Q.async(t=>{if(!n)return e(t);if(!t)return e(n);let r=a([n,t]);try{return e(r.signal).finally(r.dispose)}catch(e){throw r.dispose(),e}}).mapError(t),asyncResult:(e,t,n)=>{let r=n?.dataKey??`data`,i=n?.errorKey??`error`;return Q.tryAsync(t=>e(t),t,n?.signal).flatMap(e=>Q.fromResult({data:e[r],error:e[i]}))},service:e=>D({_tag:`Service`,tag:e}),serviceWith:(e,t)=>Q.service(e).map(t),serviceWithIO:(e,t)=>Q.service(e).flatMap(t),withServices:(e,t)=>{let n=Object.entries(e);if(n.length===0)return m(D({_tag:`Auto`,thunk:()=>t({})}));let r=m(Q.succeed({})),i=n.reduce((e,[t,n])=>m(e.flatMap(e=>Q.service(n).map(n=>({...e,[t]:n})))),r);return m(i.flatMap(e=>D({_tag:`Auto`,thunk:()=>t(e)})))},all:(e,t)=>{let n=t?.concurrency??`unbounded`;if(r(n,1),n!==1&&e.length>1)return D(m({_tag:`All`,effects:e,concurrency:n}));if(e.length===0)return m(Q.succeed([]));let i=m(Q.succeed([]));return m(e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),i))},firstSuccessOf:e=>e.length===0?m(Q.die(/* @__PURE__ */ Error(`No effects provided`))):e.reduce((e,t)=>e.recoverWith(()=>t)),sleep:e=>D(m({_tag:`Sleep`,duration:e})),iterate:(e,t,n,r)=>{let i=r?.max??1e4,a=(e,r)=>n(e)?m(Q.succeed(e)):r<=0?m(Q.fail(new x(i,e))):t(e).flatMap(e=>a(e,r-1));return a(e,i)},never:()=>D(m({_tag:`Sleep`,duration:1/0})),get unit(){return m(D({_tag:`Succeed`,value:void 0}))},fromNullable:e=>m(e==null?Q.fail(void 0):Q.succeed(e)),interrupt:()=>D({_tag:`Interrupt`}),bracket:(e,t,n)=>D({_tag:`Bracket`,acquire:e,use:t,release:n}),acquireRelease:(e,t,n)=>Q.bracket(e,t,n),bracketExit:(e,t,n)=>D({_tag:`BracketExit`,acquire:e,use:t,release:n}),race:e=>D({_tag:`Race`,effects:e}),forEach:(e,t,n)=>{let i=n?.concurrency??1;if(r(i,1),i!==1)return Q.unit.flatMap(()=>Q.all(e.map(t),{concurrency:i}));if(e.length===0)return m(Q.succeed([]));let a=m(Q.succeed([]));return m(e.reduce((e,n)=>e.flatMap(e=>t(n).map(t=>[...e,t])),a))},timeout:(e,t)=>D(m({_tag:`Timeout`,effect:e,duration:t})),gen:e=>D(m({_tag:`Gen`,start:e})),get Do(){return $(Q.succeed({}))}},$=e=>({effect:e,bind(t,n){let r=e.flatMap(e=>n(e).map(n=>({...e,[t]:n})));return $(r)},let(t,n){let r=e.map(e=>({...e,[t]:n(e)}));return $(r)},map(t){return e.map(t)},flatMap(t){return e.flatMap(t)},tap(t){return $(e.tap(t))},tapEffect(t){return $(e.tapEffect(t))},done(){return e}}),de=e(e=>D(m({_tag:`Auto`,thunk:e})),Q);export{de as IO,S as IOEffectKey,y as InterruptedError,x as RepeatExhausted,v as TimeoutError,b as UnsupportedSyncOperationError};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { Type } from "../types/index.js";
|
|
2
|
+
import { Context } from "./Context.js";
|
|
3
|
+
import { Tag } from "./Tag.js";
|
|
4
|
+
/**
|
|
5
|
+
* Layer module - service construction recipes.
|
|
6
|
+
* @module Layer
|
|
7
|
+
* @category IO
|
|
8
|
+
*
|
|
9
|
+
* Layers describe how to construct services, including their dependencies.
|
|
10
|
+
* They can be composed to build complex service graphs.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* A Layer describes how to build a service or set of services.
|
|
14
|
+
*
|
|
15
|
+
* @typeParam RIn - Required services (dependencies)
|
|
16
|
+
* @typeParam E - Possible errors during construction
|
|
17
|
+
* @typeParam ROut - Services provided by this layer
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```typescript
|
|
21
|
+
* // A layer that provides a Logger service
|
|
22
|
+
* const LoggerLive = Layer.succeed(Logger, consoleLogger)
|
|
23
|
+
*
|
|
24
|
+
* // A layer that requires Config and provides Database
|
|
25
|
+
* const DatabaseLive = Layer.fromFunction(Database, (config: Config) =>
|
|
26
|
+
* createDatabase(config.connectionString)
|
|
27
|
+
* )
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export interface Layer<RIn extends Type, E extends Type, ROut extends Type> {
|
|
31
|
+
/**
|
|
32
|
+
* Type brand
|
|
33
|
+
* @internal
|
|
34
|
+
*/
|
|
35
|
+
readonly _tag: "Layer";
|
|
36
|
+
/**
|
|
37
|
+
* Phantom types
|
|
38
|
+
* @internal
|
|
39
|
+
*/
|
|
40
|
+
readonly _RIn?: RIn;
|
|
41
|
+
readonly _E?: E;
|
|
42
|
+
readonly _ROut?: ROut;
|
|
43
|
+
/**
|
|
44
|
+
* Builds the services, given the ones this layer needs.
|
|
45
|
+
* @internal
|
|
46
|
+
*/
|
|
47
|
+
build(input: Context<RIn>): Promise<Context<ROut>>;
|
|
48
|
+
/**
|
|
49
|
+
* Composes this layer with another, running them in sequence.
|
|
50
|
+
* The output of this layer becomes available to the next layer.
|
|
51
|
+
* @param that - Layer to compose with
|
|
52
|
+
*/
|
|
53
|
+
provideToAndMerge<RIn2 extends Type, E2 extends Type, ROut2 extends Type>(that: Layer<RIn2 | ROut, E2, ROut2>): Layer<RIn | Exclude<RIn2, ROut>, E | E2, ROut | ROut2>;
|
|
54
|
+
/**
|
|
55
|
+
* Merges two independent layers.
|
|
56
|
+
* @param that - Layer to merge with
|
|
57
|
+
*/
|
|
58
|
+
merge<RIn2 extends Type, E2 extends Type, ROut2 extends Type>(that: Layer<RIn2, E2, ROut2>): Layer<RIn | RIn2, E | E2, ROut | ROut2>;
|
|
59
|
+
/**
|
|
60
|
+
* Maps the output of this layer.
|
|
61
|
+
* @param f - Function to transform the output
|
|
62
|
+
*/
|
|
63
|
+
map<ROut2 extends Type>(f: (ctx: Context<ROut>) => Context<ROut2>): Layer<RIn, E, ROut2>;
|
|
64
|
+
/**
|
|
65
|
+
* String representation
|
|
66
|
+
*/
|
|
67
|
+
toString(): string;
|
|
68
|
+
/**
|
|
69
|
+
* The layer's kind, for logs: `{ _tag: "Layer", recipe: "Succeed" }`. It leaves out the
|
|
70
|
+
* services, as an IO's `toJSON` leaves out its values, so a logged layer can't print a secret.
|
|
71
|
+
*/
|
|
72
|
+
toJSON(): {
|
|
73
|
+
readonly _tag: "Layer";
|
|
74
|
+
readonly recipe: string;
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Layer companion object with construction methods
|
|
79
|
+
*/
|
|
80
|
+
export declare const Layer: {
|
|
81
|
+
/**
|
|
82
|
+
* Creates a layer that provides a service with a constant value.
|
|
83
|
+
* @param tag - The service tag
|
|
84
|
+
* @param service - The service implementation
|
|
85
|
+
*/
|
|
86
|
+
succeed: <S extends Type>(tag: Tag<S>, service: S) => Layer<never, never, S>;
|
|
87
|
+
/**
|
|
88
|
+
* Creates a layer from an async function.
|
|
89
|
+
* @param tag - The service tag
|
|
90
|
+
* @param f - Async function to create the service
|
|
91
|
+
*/
|
|
92
|
+
effect: <S extends Type, E extends Type>(tag: Tag<S>, f: () => Promise<S>) => Layer<never, E, S>;
|
|
93
|
+
/**
|
|
94
|
+
* Creates a layer from a sync function.
|
|
95
|
+
* @param tag - The service tag
|
|
96
|
+
* @param f - Function to create the service
|
|
97
|
+
*/
|
|
98
|
+
sync: <S extends Type>(tag: Tag<S>, f: () => S) => Layer<never, never, S>;
|
|
99
|
+
/**
|
|
100
|
+
* Creates a layer that depends on another service.
|
|
101
|
+
* @param tag - The service tag to provide
|
|
102
|
+
* @param depTag - The dependency tag
|
|
103
|
+
* @param f - Function to create the service from the dependency
|
|
104
|
+
*/
|
|
105
|
+
fromService: <Dep extends Type, S extends Type>(tag: Tag<S>, depTag: Tag<Dep>, f: (dep: Dep) => S) => Layer<Dep, never, S>;
|
|
106
|
+
/**
|
|
107
|
+
* Creates a layer that depends on another service (async).
|
|
108
|
+
* @param tag - The service tag to provide
|
|
109
|
+
* @param depTag - The dependency tag
|
|
110
|
+
* @param f - Async function to create the service from the dependency
|
|
111
|
+
*/
|
|
112
|
+
fromServiceEffect: <Dep extends Type, E extends Type, S extends Type>(tag: Tag<S>, depTag: Tag<Dep>, f: (dep: Dep) => Promise<S>) => Layer<Dep, E, S>;
|
|
113
|
+
/**
|
|
114
|
+
* Creates a layer from a context.
|
|
115
|
+
* @param context - The context to use
|
|
116
|
+
*/
|
|
117
|
+
fromContext: <R extends Type>(context: Context<R>) => Layer<never, never, R>;
|
|
118
|
+
/**
|
|
119
|
+
* Creates an empty layer that provides nothing.
|
|
120
|
+
*/
|
|
121
|
+
empty: () => Layer<never, never, never>;
|
|
122
|
+
/**
|
|
123
|
+
* Merges multiple layers into one.
|
|
124
|
+
* @param layers - Layers to merge
|
|
125
|
+
*/
|
|
126
|
+
mergeAll: <Layers extends Layer<Type, Type, Type>[]>(...layers: Layers) => Layer<Layers[number] extends Layer<infer RIn, Type, Type> ? RIn : never, Layers[number] extends Layer<Type, infer E, Type> ? E : never, Layers[number] extends Layer<Type, Type, infer ROut> ? ROut : never>;
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Type helper to extract input requirements from a Layer
|
|
130
|
+
*/
|
|
131
|
+
export type LayerInput<L> = L extends Layer<infer RIn, Type, Type> ? RIn : never;
|
|
132
|
+
/**
|
|
133
|
+
* Type helper to extract error type from a Layer
|
|
134
|
+
*/
|
|
135
|
+
export type LayerError<L> = L extends Layer<Type, infer E, Type> ? E : never;
|
|
136
|
+
/**
|
|
137
|
+
* Type helper to extract output services from a Layer
|
|
138
|
+
*/
|
|
139
|
+
export type LayerOutput<L> = L extends Layer<Type, Type, infer ROut> ? ROut : never;
|
package/dist/io/Layer.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{callAlone0 as e,callAlone1 as t}from"../internal/call-alone.js";import{define as n}from"../internal/define.js";import{Context as r}from"./Context.js";const i=async(n,i)=>{switch(n._tag){case`Succeed`:return r.make(n.tag,n.service);case`Sync`:return r.make(n.tag,e(n.make));case`Effect`:return r.make(n.tag,await e(n.make));case`FromService`:return r.make(n.tag,t(n.make,i.unsafeGet(n.dep)));case`FromServiceEffect`:return r.make(n.tag,await t(n.make,i.unsafeGet(n.dep)));case`FromContext`:return n.context;case`Empty`:return r.empty();case`Merge`:return(await Promise.all(n.layers.map(e=>e.build(i)))).reduce((e,t)=>e.merge(t),r.empty());case`ProvideToAndMerge`:{let e=await n.first.build(i),t=await n.second.build(i.merge(e));return e.merge(t)}case`Map`:return t(n.f,await n.layer.build(i))}},a=e=>{switch(e._tag){case`Succeed`:case`Sync`:case`Effect`:case`FromService`:case`FromServiceEffect`:return e.tag.id;case`Empty`:return`empty`;default:return`anonymous`}},o=n()(`Layer`,{build(e){return s(i(this.recipe,s(e)))},provideToAndMerge(e){return c({_tag:`ProvideToAndMerge`,first:s(this),second:s(e)})},merge(e){return c({_tag:`Merge`,layers:[s(this),s(e)]})},map(e){return c({_tag:`Map`,layer:s(this),f:s(e)})},toString(){return`Layer(${a(this.recipe)})`},toJSON(){return{_tag:`Layer`,recipe:this.recipe._tag}}}),s=e=>e,c=e=>{let t=Object.create(o);return t._tag=`Layer`,t.recipe=e,Object.freeze(t)},l={succeed:(e,t)=>c({_tag:`Succeed`,tag:s(e),service:t}),effect:(e,t)=>c({_tag:`Effect`,tag:s(e),make:t}),sync:(e,t)=>c({_tag:`Sync`,tag:s(e),make:t}),fromService:(e,t,n)=>c({_tag:`FromService`,tag:s(e),dep:s(t),make:s(n)}),fromServiceEffect:(e,t,n)=>c({_tag:`FromServiceEffect`,tag:s(e),dep:s(t),make:s(n)}),fromContext:e=>c({_tag:`FromContext`,context:s(e)}),empty:()=>c({_tag:`Empty`}),mergeAll:(...e)=>c({_tag:`Merge`,layers:e})};export{l as Layer};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { Exit } from "./Exit.js";
|
|
2
|
+
import { Tag } from "./Tag.js";
|
|
3
|
+
/**
|
|
4
|
+
* SpanTracer module - the contract `IO.withSpan` opens spans through.
|
|
5
|
+
* @module SpanTracer
|
|
6
|
+
* @category IO
|
|
7
|
+
*
|
|
8
|
+
* Core defines only the contract. An OpenTelemetry bridge, or any other tracer, lives in the
|
|
9
|
+
* consuming code, so functype stays free of runtime dependencies.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* The attributes given to {@link IO.withSpan}. Each value matches OpenTelemetry's
|
|
13
|
+
* `AttributeValue`, so a bridge passes them through unchanged. The arrays are mutable for that
|
|
14
|
+
* reason: a readonly array doesn't fit OpenTelemetry's `Array`.
|
|
15
|
+
*/
|
|
16
|
+
export type SpanAttributes = Readonly<Record<string, string | number | boolean | Array<string | null | undefined> | Array<number | null | undefined> | Array<boolean | null | undefined>>>;
|
|
17
|
+
/**
|
|
18
|
+
* What `IO.withSpan` needs from a tracer. Provide one with `io.provideService(SpanTracer, tracer)`
|
|
19
|
+
* or `io.provideLayer(Layer.succeed(SpanTracer, tracer))`, outside the spans. With no tracer
|
|
20
|
+
* provided, `withSpan` does nothing.
|
|
21
|
+
*
|
|
22
|
+
* This is not the `Tracer` that `TracedOption` writes to. That one records steps through
|
|
23
|
+
* `emit(event)` and has no spans.
|
|
24
|
+
*
|
|
25
|
+
* For each `withSpan`, the interpreter calls `start`, then `run`, then `end` exactly once.
|
|
26
|
+
*
|
|
27
|
+
* @typeParam S - The tracer's own span type. Core never looks inside it.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* // A sketch of an OpenTelemetry bridge. functype ships no such package.
|
|
32
|
+
* import { context, type Span, SpanStatusCode, trace } from "@opentelemetry/api"
|
|
33
|
+
*
|
|
34
|
+
* const otel = trace.getTracer("my-app")
|
|
35
|
+
* const tracer: SpanTracer<Span> = {
|
|
36
|
+
* start: (name, attributes, parent) =>
|
|
37
|
+
* otel.startSpan(name, { attributes }, parent ? trace.setSpan(context.active(), parent) : context.active()),
|
|
38
|
+
* run: (span, fn) => context.with(trace.setSpan(context.active(), span), fn),
|
|
39
|
+
* end: (span, exit) => {
|
|
40
|
+
* if (exit._tag === "Failure" || exit._tag === "Die") span.setStatus({ code: SpanStatusCode.ERROR })
|
|
41
|
+
* span.end()
|
|
42
|
+
* },
|
|
43
|
+
* }
|
|
44
|
+
*
|
|
45
|
+
* await program.withSpan("checkout", { cart: id }).provideService(SpanTracer, tracer).run()
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export type SpanTracer<S = unknown> = {
|
|
49
|
+
/**
|
|
50
|
+
* Opens a span.
|
|
51
|
+
* @param name - The name given to `withSpan`
|
|
52
|
+
* @param attributes - The attributes given to `withSpan`, or `{}`
|
|
53
|
+
* @param parent - The span of the enclosing `withSpan` in this run, or `undefined` at the top.
|
|
54
|
+
* Fall back to the tracer's ambient context when it's `undefined`, so a run started inside
|
|
55
|
+
* another span, such as a request handler's, nests under it.
|
|
56
|
+
*/
|
|
57
|
+
start(name: string, attributes: SpanAttributes, parent: S | undefined): S;
|
|
58
|
+
/**
|
|
59
|
+
* Runs `fn` with `span` active, and returns what `fn` returns. The interpreter runs the whole
|
|
60
|
+
* body of `withSpan` inside it, so code there, including a log sink, sees the span through
|
|
61
|
+
* the tracer's own API. An OpenTelemetry bridge implements it with `context.with`, which needs
|
|
62
|
+
* a registered context manager, such as the `AsyncLocalStorageContextManager` the Node SDK
|
|
63
|
+
* registers. Without one, `context.with` still runs `fn`, but no span is active inside it.
|
|
64
|
+
*
|
|
65
|
+
* `fn` returns a promise under `run()` and a plain value under `runSync()`. Return it as is.
|
|
66
|
+
*/
|
|
67
|
+
run<T>(span: S, fn: () => T): T;
|
|
68
|
+
/**
|
|
69
|
+
* Closes a span with the body's outcome. A failure that arrives after the run was cancelled,
|
|
70
|
+
* such as an aborted `fetch` in a `race` loser, is reported as `Interrupted`.
|
|
71
|
+
*/
|
|
72
|
+
end(span: S, exit: Exit<unknown, unknown>): void;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* The service `withSpan` looks up. It needs no entry in an IO's requirements, because with no
|
|
76
|
+
* tracer provided `withSpan` does nothing.
|
|
77
|
+
*/
|
|
78
|
+
export declare const SpanTracer: Tag<SpanTracer>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Tag as e}from"./Tag.js";const t=e(`functype/SpanTracer`);export{t as SpanTracer};
|
package/dist/io/Tag.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { Type } from "../types/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Tag module - service identifiers for dependency injection.
|
|
4
|
+
* @module Tag
|
|
5
|
+
* @category IO
|
|
6
|
+
*
|
|
7
|
+
* Tags are used to identify services in a type-safe way.
|
|
8
|
+
* Each Tag has a unique identifier and carries the type of the service.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* A Tag identifies a service type and provides a unique identifier.
|
|
12
|
+
* Used for dependency injection with IO effects.
|
|
13
|
+
*
|
|
14
|
+
* @typeParam S - The service type this tag identifies
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* // Define service interfaces
|
|
19
|
+
* interface UserService {
|
|
20
|
+
* getUser(id: string): IO<never, Error, User>
|
|
21
|
+
* }
|
|
22
|
+
*
|
|
23
|
+
* // Create a tag for the service
|
|
24
|
+
* const UserService = Tag<UserService>("UserService")
|
|
25
|
+
*
|
|
26
|
+
* // Use in effects
|
|
27
|
+
* const getUser = (id: string) =>
|
|
28
|
+
* IO.service(UserService).flatMap(svc => svc.getUser(id))
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export interface Tag<S extends Type> {
|
|
32
|
+
/**
|
|
33
|
+
* Unique identifier for this tag
|
|
34
|
+
*/
|
|
35
|
+
readonly id: string;
|
|
36
|
+
/**
|
|
37
|
+
* Phantom type to carry the service type
|
|
38
|
+
* @internal
|
|
39
|
+
*/
|
|
40
|
+
readonly _S?: S;
|
|
41
|
+
/**
|
|
42
|
+
* Type brand to distinguish tags
|
|
43
|
+
* @internal
|
|
44
|
+
*/
|
|
45
|
+
readonly _tag: "Tag";
|
|
46
|
+
/**
|
|
47
|
+
* String representation
|
|
48
|
+
*/
|
|
49
|
+
toString(): string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Creates a Tag for identifying a service type.
|
|
53
|
+
*
|
|
54
|
+
* @param id - Unique identifier for this tag (usually the service name)
|
|
55
|
+
* @returns A Tag that can be used to request the service
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```typescript
|
|
59
|
+
* interface Logger {
|
|
60
|
+
* log(message: string): void
|
|
61
|
+
* }
|
|
62
|
+
*
|
|
63
|
+
* const Logger = Tag<Logger>("Logger")
|
|
64
|
+
*
|
|
65
|
+
* // Now Logger can be used to request the Logger service
|
|
66
|
+
* const program = IO.service(Logger).flatMap(logger =>
|
|
67
|
+
* IO.sync(() => logger.log("Hello!"))
|
|
68
|
+
* )
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export declare const Tag: <S extends Type>(id: string) => Tag<S>;
|
|
72
|
+
/**
|
|
73
|
+
* Type helper to extract the service type from a Tag
|
|
74
|
+
*/
|
|
75
|
+
export type TagService<T> = T extends Tag<infer S> ? S : never;
|
package/dist/io/Tag.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{define as e}from"../internal/define.js";const t=e()(`Tag`,{toString(){return`Tag(${this.id})`}}),n=e=>{let n=Object.create(t);return n._tag=`Tag`,n.id=e,Object.freeze(n)};export{n as Tag};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { Type } from "../types/index.js";
|
|
2
|
+
import { Context } from "./Context.js";
|
|
3
|
+
import { IO } from "./IO.js";
|
|
4
|
+
import { Tag } from "./Tag.js";
|
|
5
|
+
/**
|
|
6
|
+
* TestClock interface for controlling time in tests
|
|
7
|
+
*/
|
|
8
|
+
export interface TestClock {
|
|
9
|
+
/**
|
|
10
|
+
* Current virtual time in milliseconds
|
|
11
|
+
*/
|
|
12
|
+
readonly currentTime: number;
|
|
13
|
+
/**
|
|
14
|
+
* Advances the clock by the specified duration.
|
|
15
|
+
* All scheduled tasks with a time <= new current time will be executed.
|
|
16
|
+
* @param ms - Milliseconds to advance
|
|
17
|
+
*/
|
|
18
|
+
advance(ms: number): Promise<void>;
|
|
19
|
+
/**
|
|
20
|
+
* Sets the clock to a specific time.
|
|
21
|
+
* @param ms - The absolute time to set
|
|
22
|
+
*/
|
|
23
|
+
setTime(ms: number): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* Runs all pending tasks immediately.
|
|
26
|
+
*/
|
|
27
|
+
runAll(): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* Gets the number of pending scheduled tasks.
|
|
30
|
+
*/
|
|
31
|
+
readonly pendingCount: number;
|
|
32
|
+
/**
|
|
33
|
+
* Sleeps for the specified duration using virtual time.
|
|
34
|
+
* @param ms - Milliseconds to sleep
|
|
35
|
+
*/
|
|
36
|
+
sleep(ms: number): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Service tag for TestClock
|
|
40
|
+
*/
|
|
41
|
+
export declare const TestClockTag: Tag<TestClock>;
|
|
42
|
+
/**
|
|
43
|
+
* TestClock companion object with factory methods
|
|
44
|
+
*/
|
|
45
|
+
export declare const TestClock: {
|
|
46
|
+
/**
|
|
47
|
+
* Creates a new TestClock instance
|
|
48
|
+
*/
|
|
49
|
+
make: () => TestClock;
|
|
50
|
+
/**
|
|
51
|
+
* Tag for dependency injection
|
|
52
|
+
*/
|
|
53
|
+
tag: Tag<TestClock>;
|
|
54
|
+
/**
|
|
55
|
+
* Creates a test environment with a TestClock and runs the test function.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```typescript
|
|
59
|
+
* await TestClock.test(async (clock) => {
|
|
60
|
+
* const result = await IO.sleep(100).map(() => "done")
|
|
61
|
+
* .pipe(clock.runWithClock)
|
|
62
|
+
* expect(result).toBe("done")
|
|
63
|
+
* })
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
test: <A>(f: (clock: TestClock) => Promise<A>) => Promise<A>;
|
|
67
|
+
/**
|
|
68
|
+
* Creates an IO that accesses the TestClock from the environment.
|
|
69
|
+
*/
|
|
70
|
+
readonly get: IO<TestClock, never, TestClock>;
|
|
71
|
+
/**
|
|
72
|
+
* Creates an IO that advances the TestClock.
|
|
73
|
+
*/
|
|
74
|
+
advance: (ms: number) => IO<TestClock, never, void>;
|
|
75
|
+
/**
|
|
76
|
+
* Creates an IO that sets the TestClock time.
|
|
77
|
+
*/
|
|
78
|
+
setTime: (ms: number) => IO<TestClock, never, void>;
|
|
79
|
+
/**
|
|
80
|
+
* Creates an IO that runs all pending tasks.
|
|
81
|
+
*/
|
|
82
|
+
readonly runAll: IO<TestClock, never, void>;
|
|
83
|
+
/**
|
|
84
|
+
* Creates a context with a TestClock for testing.
|
|
85
|
+
*/
|
|
86
|
+
context: () => {
|
|
87
|
+
clock: TestClock;
|
|
88
|
+
context: ReturnType<typeof Context.make<TestClock>>;
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* TestContext provides a complete test environment with mocked services.
|
|
93
|
+
*/
|
|
94
|
+
export interface TestContext<R extends Type> {
|
|
95
|
+
/**
|
|
96
|
+
* The context containing test services
|
|
97
|
+
*/
|
|
98
|
+
readonly context: ReturnType<typeof Context.empty<R>>;
|
|
99
|
+
/**
|
|
100
|
+
* The TestClock for controlling time
|
|
101
|
+
*/
|
|
102
|
+
readonly clock: TestClock;
|
|
103
|
+
/**
|
|
104
|
+
* Adds a service to the test context
|
|
105
|
+
*/
|
|
106
|
+
withService<S extends Type>(tag: Tag<S>, service: S): TestContext<R & S>;
|
|
107
|
+
/**
|
|
108
|
+
* Provides the test context to an IO effect and runs it
|
|
109
|
+
*/
|
|
110
|
+
run<E extends Type, A extends Type>(effect: IO<R, E, A>): Promise<A>;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Creates a TestContext for testing IO effects with mocked services.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```typescript
|
|
117
|
+
* const ctx = TestContext.make()
|
|
118
|
+
* .withService(Logger, mockLogger)
|
|
119
|
+
* .withService(Database, mockDb)
|
|
120
|
+
*
|
|
121
|
+
* const result = await ctx.run(myProgram)
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export declare const TestContext: {
|
|
125
|
+
/**
|
|
126
|
+
* Creates a new empty TestContext
|
|
127
|
+
*/
|
|
128
|
+
make: <R extends Type = never>() => TestContext<R>;
|
|
129
|
+
/**
|
|
130
|
+
* Creates a TestContext with a TestClock already provided
|
|
131
|
+
*/
|
|
132
|
+
withClock: () => TestContext<TestClock>;
|
|
133
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Context as e}from"./Context.js";import{IO as t}from"./IO.js";import{Tag as n}from"./Tag.js";const r=()=>{let e=0,t=[],n=async()=>{for(t.sort((e,t)=>e.time-t.time);t.length>0&&t[0]!==void 0&&t[0].time<=e;){let e=t.shift();e&&(e.resolve(),await Promise.resolve())}};return{get currentTime(){return e},async advance(t){e+=t,await n()},async setTime(t){e=t,await n()},async runAll(){if(t.length>0){let n=t[t.length-1];n&&(e=n.time)}await n()},get pendingCount(){return t.length},sleep(n){return new Promise(r=>{t.push({time:e+n,resolve:r})})}}},i=n(`TestClock`),a={make:r,tag:i,test:async e=>e(r()),get get(){return t.service(i)},advance:e=>t.serviceWithIO(i,n=>t.async(()=>n.advance(e))),setTime:e=>t.serviceWithIO(i,n=>t.async(()=>n.setTime(e))),get runAll(){return t.serviceWithIO(i,e=>t.async(()=>e.runAll()))},context:()=>{let t=r();return{clock:t,context:e.make(i,t)}}},o={make:()=>{let t=r(),n=e.empty(),i={get context(){return n},get clock(){return t},withService(e,t){return n=n.add(e,t),i},async run(e){return e.provideContext(n).runOrThrow()}};return i},withClock:()=>{let e=r();return o.make().withService(i,e)}};export{a as TestClock,i as TestClockTag,o as TestContext};
|
package/dist/io/index.d.ts
CHANGED
|
@@ -1,2 +1,41 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* IO Effect module - lazy, composable effects with typed errors.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```typescript
|
|
6
|
+
* import { IO, Exit, Tag, Context, Layer } from 'functype/io'
|
|
7
|
+
*
|
|
8
|
+
* // Create effects
|
|
9
|
+
* const program = IO.sync(() => 42)
|
|
10
|
+
* .map(x => x * 2)
|
|
11
|
+
* .flatMap(x => IO.succeed(x + 1))
|
|
12
|
+
*
|
|
13
|
+
* // Run effects
|
|
14
|
+
* const result = await program.run()
|
|
15
|
+
* const exit = await program.runExit()
|
|
16
|
+
*
|
|
17
|
+
* // Dependency injection
|
|
18
|
+
* interface Logger {
|
|
19
|
+
* log(message: string): void
|
|
20
|
+
* }
|
|
21
|
+
* const Logger = Tag<Logger>("Logger")
|
|
22
|
+
*
|
|
23
|
+
* const logProgram = IO.service(Logger).flatMap(logger =>
|
|
24
|
+
* IO.sync(() => logger.log("Hello!"))
|
|
25
|
+
* )
|
|
26
|
+
*
|
|
27
|
+
* // Provide services
|
|
28
|
+
* logProgram.provideService(Logger, { log: console.log }).run()
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @module io
|
|
32
|
+
* @category IO
|
|
33
|
+
*/
|
|
34
|
+
import { Context, ContextServices, HasService } from "./Context.js";
|
|
35
|
+
import { DieExitOf, Exit, ExitBase, ExitCompanion, ExitTag, FailureExitOf, InterruptedExitOf, SuccessExitOf } from "./Exit.js";
|
|
36
|
+
import { IO, IOCompanion, InterruptedError, RIO, RepeatExhausted, Task, TimeoutError, UIO, UnsupportedSyncOperationError } from "./IO.js";
|
|
37
|
+
import { Layer, LayerError, LayerInput, LayerOutput } from "./Layer.js";
|
|
38
|
+
import { SpanAttributes, SpanTracer } from "./SpanTracer.js";
|
|
39
|
+
import { Tag, TagService } from "./Tag.js";
|
|
40
|
+
import { TestClock, TestClockTag, TestContext } from "./TestClock.js";
|
|
41
|
+
export { Context, type ContextServices, type Context as ContextType, type DieExitOf, Exit, type ExitBase, type ExitCompanion, type ExitTag, type Exit as ExitType, type FailureExitOf, type HasService, IO, type IOCompanion, type Task as IOTask, type IO as IOType, InterruptedError, type InterruptedExitOf, Layer, type LayerError, type LayerInput, type LayerOutput, type Layer as LayerType, type RIO, RepeatExhausted, type SpanAttributes, SpanTracer, type SuccessExitOf, Tag, type TagService, type Tag as TagType, TestClock, TestClockTag, type TestClock as TestClockType, TestContext, type TestContext as TestContextType, TimeoutError, type UIO, UnsupportedSyncOperationError };
|
package/dist/io/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Context as e}from"./Context.js";import{Exit as t}from"./Exit.js";import{IO as n,InterruptedError as r,RepeatExhausted as i,TimeoutError as a,UnsupportedSyncOperationError as o}from"./IO.js";import{Layer as s}from"./Layer.js";import{SpanTracer as c}from"./SpanTracer.js";import{Tag as l}from"./Tag.js";import{TestClock as u,TestClockTag as d,TestContext as f}from"./TestClock.js";export{e as Context,t as Exit,n as IO,r as InterruptedError,s as Layer,i as RepeatExhausted,c as SpanTracer,l as Tag,u as TestClock,d as TestClockTag,f as TestContext,a as TimeoutError,o as UnsupportedSyncOperationError};
|