/** * @since 1.0.0 */ /* eslint-disable @typescript-eslint/no-empty-object-type */ import * as Reactivity from "@effect/experimental/Reactivity" import * as KeyValueStore from "@effect/platform/KeyValueStore" import * as Arr from "effect/Array" import { NoSuchElementException } from "effect/Cause" import * as Cause from "effect/Cause" import * as Channel from "effect/Channel" import * as Chunk from "effect/Chunk" import * as EffectContext from "effect/Context" import * as Duration from "effect/Duration" import * as Effect from "effect/Effect" import * as Either from "effect/Either" import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" import * as FiberId from "effect/FiberId" import * as FiberRef from "effect/FiberRef" import type { LazyArg } from "effect/Function" import { constant, constVoid, dual, pipe } from "effect/Function" import { globalValue } from "effect/GlobalValue" import * as Inspectable from "effect/Inspectable" import * as Layer from "effect/Layer" import * as MutableHashMap from "effect/MutableHashMap" import * as Option from "effect/Option" import { type Pipeable, pipeArguments } from "effect/Pipeable" import { hasProperty, isObject } from "effect/Predicate" import type { ReadonlyRecord } from "effect/Record" import * as Runtime from "effect/Runtime" import * as Schema from "effect/Schema" import * as Scope from "effect/Scope" import * as Stream from "effect/Stream" import * as Subscribable from "effect/Subscribable" import * as SubscriptionRef from "effect/SubscriptionRef" import type { NoInfer } from "effect/Types" import * as internalRegistry from "./internal/registry.js" import { runCallbackSync } from "./internal/runtime.js" import * as Registry from "./Registry.js" import { AtomRegistry as AtomRegistry } from "./Registry.js" import * as Result from "./Result.js" const TypeId: TypeId = "~effect-atom/atom/Atom" type TypeId = "~effect-atom/atom/Atom" /** * @since 1.0.0 * @category models */ export interface Atom extends Pipeable, Inspectable.Inspectable { readonly [TypeId]: TypeId readonly keepAlive: boolean readonly lazy: boolean readonly read: (get: Context) => A readonly refresh?: (f: (atom: Atom) => void) => void readonly label?: readonly [name: string, stack: string] readonly idleTTL?: number } /** * @since 1.0.0 * @category Guards */ export const isAtom = (u: unknown): u is Atom => hasProperty(u, TypeId) /** * @since 1.0.0 */ export type Type> = T extends Atom ? A : never /** * @since 1.0.0 */ export type Success> = T extends Atom> ? A : never /** * @since 1.0.0 */ export type PullSuccess> = T extends Atom> ? A : never /** * @since 1.0.0 */ export type Failure> = T extends Atom> ? E : never /** * @since 1.0.0 */ export type WithoutSerializable> = T extends Writable ? Writable : Atom> type WritableTypeId = "~effect-atom/atom/Atom/Writable" const WritableTypeId: WritableTypeId = "~effect-atom/atom/Atom/Writable" /** * @since 1.0.0 * @category models */ export interface Writable extends Atom { readonly [WritableTypeId]: WritableTypeId readonly write: (ctx: WriteContext, value: W) => void } /** * @since 1.0.0 * @category context */ export interface Context { (atom: Atom): A get(this: Context, atom: Atom): A result(this: Context, atom: Atom>, options?: { readonly suspendOnWaiting?: boolean | undefined }): Effect.Effect resultOnce(this: Context, atom: Atom>, options?: { readonly suspendOnWaiting?: boolean | undefined }): Effect.Effect once(this: Context, atom: Atom): A addFinalizer(this: Context, f: () => void): void mount(this: Context, atom: Atom): void refresh(this: Context, atom: Atom): void refreshSelf(this: Context): void self(this: Context): Option.Option setSelf(this: Context, a: A): void set(this: Context, atom: Writable, value: W): void setResult(this: Context, atom: Writable, W>, value: W): Effect.Effect some(this: Context, atom: Atom>): Effect.Effect someOnce(this: Context, atom: Atom>): Effect.Effect stream(this: Context, atom: Atom, options?: { readonly withoutInitialValue?: boolean readonly bufferSize?: number }): Stream.Stream streamResult(this: Context, atom: Atom>, options?: { readonly withoutInitialValue?: boolean readonly bufferSize?: number }): Stream.Stream subscribe(this: Context, atom: Atom, f: (_: A) => void, options?: { readonly immediate?: boolean }): void readonly registry: Registry.Registry } /** * @since 1.0.0 * @category context */ export interface WriteContext { get(this: WriteContext, atom: Atom): T refreshSelf(this: WriteContext): void setSelf(this: WriteContext, a: A): void set(this: WriteContext, atom: Writable, value: W): void } /** * @since 1.0.0 * @category combinators */ export const setIdleTTL: { (duration: Duration.DurationInput): >(self: A) => A >(self: A, duration: Duration.DurationInput): A } = dual< (duration: Duration.DurationInput) => >(self: A) => A, >(self: A, duration: Duration.DurationInput) => A >(2, (self, durationInput) => { const duration = Duration.decode(durationInput) const isFinite = Duration.isFinite(duration) return Object.assign(Object.create(Object.getPrototypeOf(self)), { ...self, keepAlive: !isFinite, idleTTL: isFinite ? Duration.toMillis(duration) : undefined }) }) const removeTtl = setIdleTTL(0) const AtomProto = { [TypeId]: TypeId, pipe() { return pipeArguments(this, arguments) }, toJSON(this: Atom) { return { _id: "Atom", keepAlive: this.keepAlive, lazy: this.lazy, label: this.label } }, toString() { return Inspectable.format(this) }, [Inspectable.NodeInspectSymbol](this: Atom) { return this.toJSON() } } as const const RuntimeProto = { ...AtomProto, atom(this: AtomRuntime, arg: any, options?: { readonly initialValue?: unknown }) { const read = makeRead(arg, options) return readable((get) => { const previous = get.self>() const runtimeResult = get(this) if (runtimeResult._tag !== "Success") { return Result.replacePrevious(runtimeResult, previous) } return read(get, runtimeResult.value) }) }, fn(this: AtomRuntime, arg: any, options?: { readonly initialValue?: unknown readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined readonly concurrent?: boolean | undefined }) { if (arguments.length === 0) { return (arg: any, options?: {}) => makeFnRuntime(this, arg, options) } return makeFnRuntime(this, arg, options) }, pull(this: AtomRuntime, arg: any, options?: { readonly disableAccumulation?: boolean readonly initialValue?: ReadonlyArray }) { const pullSignal = removeTtl(state(0)) const pullAtom = readable((get) => { const previous = get.self>() const runtimeResult = get(this) if (runtimeResult._tag !== "Success") { return Result.replacePrevious(runtimeResult, previous) } return makeEffect( get, makeStreamPullEffect(get, pullSignal, arg, options), Result.initial(true), runtimeResult.value ) }) return makeStreamPull(pullSignal, pullAtom) }, subscriptionRef(this: AtomRuntime, ref: any) { return makeSubRef( removeTtl(readable((get) => { const previous = get.self>() const runtimeResult = get(this) if (runtimeResult._tag !== "Success") { return Result.replacePrevious(runtimeResult, previous) } const value = typeof ref === "function" ? ref(get) : ref return SubscriptionRef.SubscriptionRefTypeId in value ? value : makeEffect(get, value, Result.initial(true), runtimeResult.value) })), (get, ref) => { const runtime = Result.getOrThrow(get(this)) return readSubscribable(get, ref, runtime) } ) }, subscribable(this: AtomRuntime, arg: any) { return makeSubscribable( readable((get) => { const previous = get.self>() const runtimeResult = get(this) if (runtimeResult._tag !== "Success") { return Result.replacePrevious(runtimeResult, previous) } const value = typeof arg === "function" ? arg(get) : arg return Subscribable.isSubscribable(value) ? value as Subscribable.Subscribable : makeEffect(get, value, Result.initial(true), runtimeResult.value) }), (get, ref) => { const runtime = Result.getOrThrow(get(this)) return readSubscribable(get, ref, runtime) } ) } } const makeFnRuntime = ( self: AtomRuntime, arg: ( arg: any, get: FnContext ) => | Effect.Effect | Stream.Stream, options?: { readonly initialValue?: unknown readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined } ) => { const [read, write, argAtom] = makeResultFn( options?.reactivityKeys ? ((a: any, get: FnContext) => { const effect = arg(a, get) return Effect.isEffect(effect) ? Reactivity.mutation(effect, options.reactivityKeys!) : Stream.ensuring(effect, Reactivity.invalidate(options.reactivityKeys!)) }) as any : arg, options ) return writable((get) => { get.get(argAtom) const previous = get.self>() const runtimeResult = get.get(self) if (runtimeResult._tag !== "Success") { return Result.replacePrevious(runtimeResult, previous) } return read(get, runtimeResult.value) }, write) } const WritableProto = { ...AtomProto, [WritableTypeId]: WritableTypeId } as const /** * @since 1.0.0 * @category refinements */ export const isWritable = (atom: Atom): atom is Writable => WritableTypeId in atom /** * @since 1.0.0 * @category constructors */ export const readable = ( read: (get: Context) => A, refresh?: (f: (atom: Atom) => void) => void ): Atom => { const self = Object.create(AtomProto) self.keepAlive = false self.lazy = true self.read = read self.refresh = refresh return self } /** * @since 1.0.0 * @category constructors */ export const writable = ( read: (get: Context) => R, write: (ctx: WriteContext, value: W) => void, refresh?: (f: (atom: Atom) => void) => void ): Writable => { const self = Object.create(WritableProto) self.keepAlive = false self.lazy = true self.read = read self.write = write self.refresh = refresh return self } function constSetSelf(ctx: WriteContext, value: A) { ctx.setSelf(value) } // ----------------------------------------------------------------------------- // constructors // ----------------------------------------------------------------------------- /** * @since 1.0.0 * @category constructors */ export const make: { (create: (get: Context) => Effect.Effect, options?: { readonly initialValue?: A }): Atom> (effect: Effect.Effect, options?: { readonly initialValue?: A }): Atom> (create: (get: Context) => Stream.Stream, options?: { readonly initialValue?: A }): Atom> (stream: Stream.Stream, options?: { readonly initialValue?: A }): Atom> (create: (get: Context) => A): Atom (initialValue: A): Writable } = (arg: any, options?: { readonly initialValue?: unknown }) => { const readOrAtom = makeRead(arg, options) if (TypeId in readOrAtom) { return readOrAtom as any } return readable(readOrAtom) } // ----------------------------------------------------------------------------- // constructors - effect // ----------------------------------------------------------------------------- const isDataType = (u: object): u is Option.Option | Either.Either => Option.TypeId in u || Either.TypeId in u const makeRead: { (effect: Effect.Effect, options?: { readonly initialValue?: A }): (get: Context, runtime?: Runtime.Runtime) => Result.Result (create: (get: Context) => Effect.Effect, options?: { readonly initialValue?: A }): (get: Context, runtime?: Runtime.Runtime) => Result.Result (stream: Stream.Stream, options?: { readonly initialValue?: A }): (get: Context, runtime?: Runtime.Runtime) => Result.Result (create: (get: Context) => Stream.Stream, options?: { readonly initialValue?: A }): (get: Context, runtime?: Runtime.Runtime) => Result.Result (create: (get: Context) => A): (get: Context, runtime?: Runtime.Runtime) => A (initialValue: A): Writable } = ( arg: | Effect.Effect | ((get: Context) => Effect.Effect) | Stream.Stream | ((get: Context) => Stream.Stream) | ((get: Context) => A) | A, options?: { readonly initialValue?: unknown } ) => { if (typeof arg === "function" && !Effect.isEffect(arg) && !(Stream.StreamTypeId in arg)) { const create = arg as (get: Context) => any return function(get: Context, providedRuntime?: Runtime.Runtime) { const value = create(get) if (isObject(value)) { if (isDataType(value)) { return value } else if (Effect.EffectTypeId in value) { return effect(get, value as any, options, providedRuntime) } else if (Stream.StreamTypeId in value) { return stream(get, value as any, options, providedRuntime) } } return value } } else if (isObject(arg)) { if (isDataType(arg)) { return state(arg) } else if (Effect.EffectTypeId in arg) { return function(get: Context, providedRuntime?: Runtime.Runtime) { return effect(get, arg as any, options, providedRuntime) } } else if (Stream.StreamTypeId in arg) { return function(get: Context, providedRuntime?: Runtime.Runtime) { return stream(get, arg as any, options, providedRuntime) } } } return state(arg) as any } const state = ( initialValue: A ): Writable => writable(function(_get) { return initialValue }, constSetSelf) const effect = ( get: Context, effect: Effect.Effect, options?: { readonly initialValue?: A; readonly uninterruptible?: boolean }, runtime?: Runtime.Runtime ): Result.Result => { const initialValue = options?.initialValue !== undefined ? Result.success(options.initialValue) : Result.initial() return makeEffect(get, effect, initialValue, runtime, options?.uninterruptible) } function makeEffect( ctx: Context, effect: Effect.Effect, initialValue: Result.Result, runtime = Runtime.defaultRuntime, uninterruptible = false ): Result.Result { const previous = ctx.self>() const scope = Effect.runSync(Scope.make()) ctx.addFinalizer(() => { Effect.runFork(Scope.close(scope, Exit.void)) }) const contextMap = new Map(runtime.context.unsafeMap) contextMap.set(Scope.Scope.key, scope) contextMap.set(AtomRegistry.key, ctx.registry) const scopedRuntime = Runtime.make({ context: EffectContext.unsafeMake(contextMap), fiberRefs: runtime.fiberRefs, runtimeFlags: runtime.runtimeFlags }) let syncResult: Result.Result | undefined let isAsync = false const cancel = runCallbackSync(scopedRuntime)( effect, function(exit) { syncResult = Result.fromExitWithPrevious(exit, previous) if (isAsync) { ctx.setSelf(syncResult) } }, uninterruptible ) isAsync = true if (cancel !== undefined) { ctx.addFinalizer(cancel) } if (syncResult !== undefined) { return syncResult } else if (previous._tag === "Some") { return Result.waitingFrom(previous) } return Result.waiting(initialValue) } // ----------------------------------------------------------------------------- // context // ----------------------------------------------------------------------------- /** * @since 1.0.0 * @category models */ export interface AtomRuntime extends Atom, ER>> { readonly factory: RuntimeFactory readonly layer: Atom> readonly atom: { ( create: (get: Context) => Effect.Effect, options?: { readonly initialValue?: A } ): Atom> (effect: Effect.Effect, options?: { readonly initialValue?: A }): Atom> (create: (get: Context) => Stream.Stream, options?: { readonly initialValue?: A }): Atom> (stream: Stream.Stream, options?: { readonly initialValue?: A }): Atom> } readonly fn: { (): { ( fn: (arg: Arg, get: FnContext) => Effect.Effect, options?: { readonly initialValue?: A | undefined readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined readonly concurrent?: boolean | undefined } ): AtomResultFn ( fn: (arg: Arg, get: FnContext) => Stream.Stream, options?: { readonly initialValue?: A | undefined readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined readonly concurrent?: boolean | undefined } ): AtomResultFn } ( fn: (arg: Arg, get: FnContext) => Effect.Effect, options?: { readonly initialValue?: A | undefined readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined readonly concurrent?: boolean | undefined } ): AtomResultFn ( fn: (arg: Arg, get: FnContext) => Stream.Stream, options?: { readonly initialValue?: A | undefined readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined readonly concurrent?: boolean | undefined } ): AtomResultFn } readonly pull: ( create: | ((get: Context) => Stream.Stream) | Stream.Stream, options?: { readonly disableAccumulation?: boolean readonly initialValue?: ReadonlyArray } ) => Writable, void> readonly subscriptionRef: ( create: | Effect.Effect, E, Scope.Scope | R | AtomRegistry | Reactivity.Reactivity> | (( get: Context ) => Effect.Effect, E, Scope.Scope | R | AtomRegistry | Reactivity.Reactivity>) ) => Writable, A> readonly subscribable: ( create: | Effect.Effect, E1, Scope.Scope | R | AtomRegistry | Reactivity.Reactivity> | (( get: Context ) => Effect.Effect< Subscribable.Subscribable, E1, Scope.Scope | R | AtomRegistry | Reactivity.Reactivity >) ) => Atom> } /** * @since 1.0.0 * @category models */ export interface RuntimeFactory { ( create: | Layer.Layer | ((get: Context) => Layer.Layer) ): AtomRuntime readonly memoMap: Layer.MemoMap readonly addGlobalLayer: (layer: Layer.Layer) => void /** * Uses the `Reactivity` service from the runtime to refresh the atom whenever * the keys change. */ readonly withReactivity: ( keys: ReadonlyArray | ReadonlyRecord> ) => >(atom: A) => A } /** * @since 1.0.0 * @category constructors */ export const context: (options: { readonly memoMap: Layer.MemoMap }) => RuntimeFactory = (options) => { let globalLayer: Layer.Layer = Reactivity.layer function factory( create: | Layer.Layer | ((get: Context) => Layer.Layer) ): AtomRuntime { const self = Object.create(RuntimeProto) self.keepAlive = false self.lazy = true self.refresh = undefined self.factory = factory const layerAtom = keepAlive( typeof create === "function" ? readable((get) => Layer.provideMerge(create(get), globalLayer)) : readable(() => Layer.provideMerge(create, globalLayer)) ) self.layer = layerAtom self.read = function read(get: Context) { const layer = get(layerAtom) const build = Effect.flatMap( Effect.flatMap(Effect.scope, (scope) => Layer.buildWithMemoMap(layer, options.memoMap, scope)), (context) => Effect.provide(Effect.runtime(), context) ) return effect(get, build, { uninterruptible: true }) } return self } factory.memoMap = options.memoMap factory.addGlobalLayer = (layer: Layer.Layer) => { globalLayer = Layer.provideMerge(globalLayer, Layer.provide(layer, Reactivity.layer)) } const reactivityAtom = removeTtl(make( Effect.scopeWith((scope) => Layer.buildWithMemoMap(Reactivity.layer, options.memoMap, scope)).pipe( Effect.map(EffectContext.get(Reactivity.Reactivity)) ) )) factory.withReactivity = (keys: ReadonlyArray | ReadonlyRecord>) => >(atom: A): A => transform(atom, (get) => { const reactivity = Result.getOrThrow(get(reactivityAtom)) get.addFinalizer(reactivity.unsafeRegister(keys, () => { get.refresh(atom) })) get.subscribe(atom, (value) => get.setSelf(value)) return get.once(atom) }) as any as A return factory } /** * @since 1.0.0 * @category context */ export const defaultMemoMap: Layer.MemoMap = globalValue( "@effect-atom/atom/Atom/defaultMemoMap", () => Effect.runSync(Layer.makeMemoMap) ) /** * @since 1.0.0 * @category context */ export const runtime: RuntimeFactory = globalValue( "@effect-atom/atom/Atom/defaultContext", () => context({ memoMap: defaultMemoMap }) ) /** * An alias to `Rx.runtime.withReactivity`, for refreshing an atom whenever the * keys change in the `Reactivity` service. * * @since 1.0.0 * @category Reactivity */ export const withReactivity: ( keys: ReadonlyArray | ReadonlyRecord> ) => >(atom: A) => A = runtime.withReactivity // ----------------------------------------------------------------------------- // constructors - stream // ----------------------------------------------------------------------------- const stream = ( get: Context, stream: Stream.Stream, options?: { readonly initialValue?: A }, runtime?: Runtime.Runtime ): Result.Result => { const initialValue = options?.initialValue !== undefined ? Result.success(options.initialValue) : Result.initial() return makeStream(get, stream, initialValue, runtime) } function makeStream( ctx: Context, stream: Stream.Stream, initialValue: Result.Result, runtime = Runtime.defaultRuntime ): Result.Result { const previous = ctx.self>() const writer: Channel.Channel, never, E> = Channel.readWithCause({ onInput(input: Chunk.Chunk) { return Channel.suspend(() => { const last = Chunk.last(input) if (last._tag === "Some") { ctx.setSelf(Result.success(last.value, { waiting: true })) } return writer }) }, onFailure(cause: Cause.Cause) { return Channel.sync(() => { ctx.setSelf(Result.failureWithPrevious(cause, { previous: ctx.self>() })) }) }, onDone(_done: unknown) { return Channel.sync(() => { pipe( ctx.self>(), Option.flatMap(Result.value), Option.match({ onNone: () => ctx.setSelf( Result.failWithPrevious(new NoSuchElementException(), { previous: ctx.self>() }) ), onSome: (a) => ctx.setSelf(Result.success(a)) }) ) }) } }) const registryRuntime = Runtime.make({ context: EffectContext.add(runtime.context, AtomRegistry, ctx.registry), fiberRefs: runtime.fiberRefs, runtimeFlags: runtime.runtimeFlags }) const cancel = runCallbackSync(registryRuntime)( Channel.runDrain(Channel.pipeTo(Stream.toChannel(stream), writer)), constVoid, false ) if (cancel !== undefined) { ctx.addFinalizer(cancel) } if (previous._tag === "Some") { return Result.waitingFrom(previous) } return Result.waiting(initialValue) } // ----------------------------------------------------------------------------- // constructors - subscription ref // ----------------------------------------------------------------------------- /** @internal */ const readSubscribable = ( get: Context, sub: | Subscribable.Subscribable | Result.Result, any>, runtime = Runtime.defaultRuntime ) => { if (Subscribable.TypeId in sub) { get.addFinalizer( sub.changes.pipe( Stream.runForEach((value) => { get.setSelf(value) return Effect.void }), Runtime.runCallback(runtime) ) ) return Runtime.runSync(runtime)(sub.get) } else if (sub._tag !== "Success") { return sub } return makeStream(get, sub.value.changes, Result.initial(true), runtime) } const makeSubRef = ( refAtom: Atom | Result.Result, any>>, read: ( get: Context, ref: SubscriptionRef.SubscriptionRef | Result.Success, any> ) => any ) => { function write(ctx: WriteContext>, value: any) { const ref = ctx.get(refAtom) if (SubscriptionRef.SubscriptionRefTypeId in ref) { Effect.runSync(SubscriptionRef.set(ref, value)) } else if (Result.isSuccess(ref)) { Effect.runSync(SubscriptionRef.set(ref.value, value)) } } return writable((get) => { const ref = get(refAtom) if (SubscriptionRef.SubscriptionRefTypeId in ref) { return read(get, ref) } else if (Result.isSuccess(ref)) { return read(get, ref) } return ref }, write) } /** * @since 1.0.0 * @category constructors */ export const subscriptionRef: { (ref: SubscriptionRef.SubscriptionRef | ((get: Context) => SubscriptionRef.SubscriptionRef)): Writable ( effect: | Effect.Effect, E, Scope.Scope | AtomRegistry> | ((get: Context) => Effect.Effect, E, Scope.Scope | AtomRegistry>) ): Writable, A> } = ( ref: | SubscriptionRef.SubscriptionRef | ((get: Context) => SubscriptionRef.SubscriptionRef) | Effect.Effect, any, Scope.Scope | AtomRegistry> | ((get: Context) => Effect.Effect, any, Scope.Scope | AtomRegistry>) ) => makeSubRef( readable((get) => { const value = typeof ref === "function" ? ref(get) : ref return SubscriptionRef.SubscriptionRefTypeId in value ? value : makeEffect(get, value, Result.initial(true)) }), readSubscribable ) as any // ----------------------------------------------------------------------------- // constructors - subscribable // ----------------------------------------------------------------------------- /** * @since 1.0.0 * @category constructors */ export const subscribable: { ( ref: Subscribable.Subscribable | ((get: Context) => Subscribable.Subscribable) ): Atom ( effect: | Effect.Effect, E, Scope.Scope | AtomRegistry> | ((get: Context) => Effect.Effect, E, Scope.Scope | AtomRegistry>) ): Atom> } = ( ref: | Subscribable.Subscribable | ((get: Context) => Subscribable.Subscribable) | Effect.Effect, any, Scope.Scope | AtomRegistry> | ((get: Context) => Effect.Effect, any, Scope.Scope | AtomRegistry>) ) => makeSubscribable( readable((get) => { const value = typeof ref === "function" ? ref(get) : ref return Subscribable.isSubscribable(value) ? value : makeEffect(get, value, Result.initial(true)) }), readSubscribable ) const makeSubscribable = ( subAtom: Atom | Result.Result, any>>, read: ( get: Context, sub: Subscribable.Subscribable | Result.Success, any> ) => any ) => readable((get) => { const sub = get(subAtom) if (Subscribable.isSubscribable(sub)) { return read(get, sub) } else if (Result.isSuccess(sub)) { return read(get, sub) } return sub }) // ----------------------------------------------------------------------------- // constructors - functions // ----------------------------------------------------------------------------- /** * @since 1.0.0 * @category models */ export interface FnContext { (atom: Atom): A result(this: FnContext, atom: Atom>, options?: { readonly suspendOnWaiting?: boolean | undefined }): Effect.Effect addFinalizer(this: FnContext, f: () => void): void mount(this: FnContext, atom: Atom): void refresh(this: FnContext, atom: Atom): void self(this: FnContext): Option.Option setSelf(this: FnContext, a: A): void set(this: FnContext, atom: Writable, value: W): void setResult(this: FnContext, atom: Writable, W>, value: W): Effect.Effect some(this: FnContext, atom: Atom>): Effect.Effect stream(this: FnContext, atom: Atom, options?: { readonly withoutInitialValue?: boolean readonly bufferSize?: number }): Stream.Stream streamResult(this: FnContext, atom: Atom>, options?: { readonly withoutInitialValue?: boolean readonly bufferSize?: number }): Stream.Stream subscribe(this: FnContext, atom: Atom, f: (_: A) => void, options?: { readonly immediate?: boolean }): void readonly registry: Registry.Registry } /** * @since 1.0.0 * @category constructors */ export const fnSync: { (): { ( f: (arg: Arg, get: FnContext) => A ): Writable, Arg> ( f: (arg: Arg, get: FnContext) => A, options: { readonly initialValue: A } ): Writable } ( f: (arg: Arg, get: FnContext) => A ): Writable, Arg> ( f: (arg: Arg, get: FnContext) => A, options: { readonly initialValue: A } ): Writable } = function(...args: ReadonlyArray) { if (args.length === 0) { return makeFnSync } return makeFnSync(...args as [any, any]) as any } const makeFnSync = (f: (arg: Arg, get: FnContext) => A, options?: { readonly initialValue?: A }): Writable | A, Arg> => { const argAtom = removeTtl(state<[number, Arg]>([0, undefined as any])) const hasInitialValue = options?.initialValue !== undefined return writable(function(get) { ;(get as any).isFn = true const [counter, arg] = get.get(argAtom) if (counter === 0) { return hasInitialValue ? options.initialValue : Option.none() } return hasInitialValue ? f(arg, get) : Option.some(f(arg, get)) }, function(ctx, arg) { batch(() => { ctx.set(argAtom, [ctx.get(argAtom)[0] + 1, arg as Arg]) ctx.refreshSelf() }) }) } /** * @since 1.0.0 * @category models */ export interface AtomResultFn extends Writable, Arg | Reset | Interrupt> {} /** * @since 1.0.0 * @category symbols */ export const Reset = Symbol.for("@effect-atom/atom/Atom/Reset") /** * @since 1.0.0 * @category symbols */ export type Reset = typeof Reset /** * @since 1.0.0 * @category symbols */ export const Interrupt = Symbol.for("@effect-atom/atom/Atom/Interrupt") /** * @since 1.0.0 * @category symbols */ export type Interrupt = typeof Interrupt /** * @since 1.0.0 * @category constructors */ export const fn: { (): (fn: (arg: Arg, get: FnContext) => Effect.Effect, options?: { readonly initialValue?: A | undefined readonly concurrent?: boolean | undefined }) => AtomResultFn (fn: (arg: Arg, get: FnContext) => Effect.Effect, options?: { readonly initialValue?: A | undefined readonly concurrent?: boolean | undefined }): AtomResultFn (): (fn: (arg: Arg, get: FnContext) => Stream.Stream, options?: { readonly initialValue?: A | undefined readonly concurrent?: boolean | undefined }) => AtomResultFn (fn: (arg: Arg, get: FnContext) => Stream.Stream, options?: { readonly initialValue?: A | undefined readonly concurrent?: boolean | undefined }): AtomResultFn } = function(...args: ReadonlyArray) { if (args.length === 0) { return makeFn } return makeFn(...args as [any, any]) as any } const makeFn = ( f: (arg: Arg, get: FnContext) => Stream.Stream | Effect.Effect, options?: { readonly initialValue?: A | undefined readonly concurrent?: boolean | undefined } ): AtomResultFn => { const [read, write] = makeResultFn(f, options) return writable(read, write) as any } function makeResultFn( f: (arg: Arg, get: FnContext) => Effect.Effect | Stream.Stream, options?: { readonly initialValue?: A readonly concurrent?: boolean | undefined } ) { const argAtom = removeTtl(state<[number, Arg | Interrupt]>([0, undefined as any])) const initialValue = options?.initialValue !== undefined ? Result.success(options.initialValue) : Result.initial() const fibersAtom = options?.concurrent ? removeTtl(readable((get) => { const fibers = new Set>() get.addFinalizer(() => fibers.forEach((f) => f.unsafeInterruptAsFork(FiberId.none))) return fibers })) : undefined function read(get: Context, runtime?: Runtime.Runtime): Result.Result { const fibers = fibersAtom ? get(fibersAtom) : undefined ;(get as any).isFn = true const [counter, arg] = get.get(argAtom) if (counter === 0) { return initialValue } else if (arg === Interrupt) { return Result.failureWithPrevious(Cause.interrupt(FiberId.none), { previous: get.self() }) } let value = f(arg, get) if (Effect.EffectTypeId in value) { if (fibers) { const eff = value value = Effect.flatMap(Effect.runtime(), (r) => { const fiber = Runtime.runFork(r, eff) fibers.add(fiber) const arr = Array.from(fibers) fiber.addObserver(() => fibers.delete(fiber)) return joinAll(arr) }) } return makeEffect(get, value as any, initialValue, runtime, false) } return makeStream(get, value, initialValue, runtime) } function write(ctx: WriteContext>, arg: Arg | Reset | Interrupt) { batch(() => { if (arg === Reset) { ctx.set(argAtom, [0, undefined as any]) } else if (arg === Interrupt) { ctx.set(argAtom, [ctx.get(argAtom)[0] + 1, Interrupt]) } else { ctx.set(argAtom, [ctx.get(argAtom)[0] + 1, arg]) } ctx.refreshSelf() }) } return [read, write, argAtom] as const } const joinAll = (fibers: ReadonlyArray>) => Effect.async((resume) => { let i = 0 let cause: Cause.Cause | undefined let exit: Exit.Exit | undefined function onExit(exit_: Exit.Exit, inLoop = false) { if (exit_._tag === "Failure") { cause = cause ? Cause.parallel(exit_.cause, cause) : exit_.cause } else if (!cause) { exit = exit_ } i++ if (!inLoop) loop() } function loop() { while (i < fibers.length) { const fiber = fibers[i] const exit = fiber.unsafePoll() if (!exit) return fiber.addObserver(onExit) onExit(exit, true) } resume(cause ? Exit.failCause(cause) : exit ? exit : Exit.failCause(Cause.empty)) } loop() return Effect.sync(() => { if (i < fibers.length) { fibers[i].removeObserver(onExit) } }) }) /** * @since 1.0.0 * @category models */ export type PullResult = Result.Result<{ readonly done: boolean readonly items: Arr.NonEmptyArray }, E | Cause.NoSuchElementException> /** * @since 1.0.0 * @category constructors */ export const pull = ( create: ((get: Context) => Stream.Stream) | Stream.Stream, options?: { readonly disableAccumulation?: boolean | undefined } ): Writable, void> => { const pullSignal = removeTtl(state(0)) const pullAtom = readable(makeRead(function(get) { return makeStreamPullEffect(get, pullSignal, create, options) })) return makeStreamPull(pullSignal, pullAtom) } const makeStreamPullEffect = ( get: Context, pullSignal: Atom, create: Stream.Stream | ((get: Context) => Stream.Stream), options?: { readonly disableAccumulation?: boolean } ): Effect.Effect< { readonly done: boolean; readonly items: Arr.NonEmptyArray }, E | Cause.NoSuchElementException, Scope.Scope | AtomRegistry > => Effect.flatMap( Channel.toPull( Stream.toChannel(typeof create === "function" ? create(get) : create) ), (pullChunk) => { const semaphore = Effect.unsafeMakeSemaphore(1) const fiber = Option.getOrThrow(Fiber.getCurrentFiber()) const context = fiber.currentContext as EffectContext.Context let acc = Chunk.empty() const pull: Effect.Effect< { done: boolean items: Arr.NonEmptyArray }, NoSuchElementException | E, Registry.AtomRegistry > = Effect.flatMap( Effect.locally( Effect.suspend(() => pullChunk), FiberRef.currentContext, context ), Either.match({ onLeft: (): Effect.Effect< { done: boolean; items: Arr.NonEmptyArray }, NoSuchElementException > => { const items = Chunk.toReadonlyArray(acc) as Array if (!Arr.isNonEmptyArray(items)) { return Effect.fail(new Cause.NoSuchElementException(`Atom.pull: no items`)) } return Effect.succeed({ done: true, items }) }, onRight(chunk) { let items: Chunk.Chunk if (options?.disableAccumulation) { items = chunk } else { items = Chunk.appendAll(acc, chunk) acc = items } const arr = Chunk.toReadonlyArray(items) as Array if (!Arr.isNonEmptyArray(arr)) { return pull } return Effect.succeed({ done: false, items: arr }) } }) ) const pullWithSemaphore = semaphore.withPermits(1)(pull) const runCallback = runCallbackSync(Runtime.make({ context, fiberRefs: fiber.getFiberRefs(), runtimeFlags: Runtime.defaultRuntime.runtimeFlags })) const cancels = new Set<() => void>() get.addFinalizer(() => { for (const cancel of cancels) cancel() }) get.once(pullSignal) get.subscribe(pullSignal, () => { get.setSelf(Result.waitingFrom(get.self>())) let cancel: (() => void) | undefined // eslint-disable-next-line prefer-const cancel = runCallback(pullWithSemaphore, (exit) => { if (cancel) cancels.delete(cancel) const result = Result.fromExitWithPrevious(exit, get.self()) const pending = cancels.size > 0 get.setSelf(pending ? Result.waiting(result) : result) }) if (cancel) cancels.add(cancel) }) return pull } ) const makeStreamPull = ( pullSignal: Writable, pullAtom: Atom> ) => writable(pullAtom.read, function(ctx, _) { ctx.set(pullSignal, ctx.get(pullSignal) + 1) }) /** * @since 1.0.0 * @category constructors */ export const family = typeof WeakRef === "undefined" || typeof FinalizationRegistry === "undefined" ? ( f: (arg: Arg) => T ): (arg: Arg) => T => { const atoms = MutableHashMap.empty() return function(arg) { const atomEntry = MutableHashMap.get(atoms, arg) if (atomEntry._tag === "Some") { return atomEntry.value } const newAtom = f(arg) MutableHashMap.set(atoms, arg, newAtom) return newAtom } } : ( f: (arg: Arg) => T ): (arg: Arg) => T => { const atoms = MutableHashMap.empty>() const registry = new FinalizationRegistry((arg) => { MutableHashMap.remove(atoms, arg) }) return function(arg) { const atomEntry = MutableHashMap.get(atoms, arg).pipe( Option.flatMapNullable((ref) => ref.deref()) ) if (atomEntry._tag === "Some") { return atomEntry.value } const newAtom = f(arg) MutableHashMap.set(atoms, arg, new WeakRef(newAtom)) registry.register(newAtom, arg) return newAtom } } /** * @since 1.0.0 * @category combinators */ export const withFallback: { ( fallback: Atom> ): >>( self: R ) => [R] extends [Writable] ? Writable> | A2, Result.Result.Failure> | E2>, RW> : Atom> | A2, Result.Result.Failure> | E2>> >, A2, E2>( self: R, fallback: Atom> ): [R] extends [Writable] ? Writable> | A2, Result.Result.Failure> | E2>, RW> : Atom> | A2, Result.Result.Failure> | E2>> } = dual(2, >, A2, E2>( self: R, fallback: Atom> ): [R] extends [Writable] ? Writable> | A2, Result.Result.Failure> | E2>, RW> : Atom> | A2, Result.Result.Failure> | E2>> => { function withFallback(get: Context) { const result = get(self) if (result._tag === "Initial") { return Result.waiting(get(fallback)) } return result } return isWritable(self) ? writable( withFallback, self.write, self.refresh ?? function(refresh) { refresh(self) } ) as any : readable( withFallback, self.refresh ?? function(refresh) { refresh(self) } ) as any }) /** * @since 1.0.0 * @category combinators */ export const keepAlive = >(self: A): A => Object.assign(Object.create(Object.getPrototypeOf(self)), { ...self, keepAlive: true }) /** * Reverts the `keepAlive` behavior of a reactive value, allowing it to be * disposed of when not in use. * * Note that Atom's have this behavior by default. * * @since 1.0.0 * @category combinators */ export const autoDispose = >(self: A): A => Object.assign(Object.create(Object.getPrototypeOf(self)), { ...self, keepAlive: false }) /** * @since 1.0.0 * @category combinators */ export const setLazy: { (lazy: boolean): >(self: A) => A >(self: A, lazy: boolean): A } = dual(2, >(self: A, lazy: boolean) => Object.assign(Object.create(Object.getPrototypeOf(self)), { ...self, lazy })) /** * @since 1.0.0 * @category combinators */ export const withLabel: { (name: string): >(self: A) => A >(self: A, name: string): A } = dual< (name: string) => >(self: A) => A, >(self: A, name: string) => A >(2, (self, name) => Object.assign(Object.create(Object.getPrototypeOf(self)), { ...self, label: [name, new Error().stack?.split("\n")[5] ?? ""] })) /** * @since 1.0.0 * @category combinators */ export const initialValue: { (initialValue: A): (self: Atom) => readonly [Atom, A] (self: Atom, initialValue: A): readonly [Atom, A] } = dual< (initialValue: A) => (self: Atom) => readonly [Atom, A], (self: Atom, initialValue: A) => readonly [Atom, A] >(2, (self, initialValue) => [self, initialValue]) /** * @since 1.0.0 * @category combinators */ export const transform: { , B>( f: (get: Context) => B ): (self: R) => [R] extends [Writable] ? Writable : Atom , B>( self: R, f: (get: Context) => B ): [R] extends [Writable] ? Writable : Atom } = dual( 2, ((self: Atom, f: (get: Context) => B): Atom => isWritable(self) ? writable( f, function(ctx, value) { ctx.set(self, value) }, self.refresh ?? function(refresh) { refresh(self) } ) : readable( f, self.refresh ?? function(refresh) { refresh(self) } )) as any ) /** * @since 1.0.0 * @category combinators */ export const map: { , B>( f: (_: Type) => B ): (self: R) => [R] extends [Writable] ? Writable : Atom , B>( self: R, f: (_: Type) => B ): [R] extends [Writable] ? Writable : Atom } = dual( 2, (self: Atom, f: (_: A) => B): Atom => transform(self, (get) => f(get(self))) ) /** * @since 1.0.0 * @category combinators */ export const mapResult: { >, B>( f: (_: Result.Result.Success>) => B ): ( self: R ) => [R] extends [Writable] ? Writable>>, RW> : Atom>>> >, B>( self: R, f: (_: Result.Result.Success>) => B ): [R] extends [Writable] ? Writable>>, RW> : Atom>>> } = dual(2, >, B>( self: R, f: (_: Result.Result.Success>) => B ): [R] extends [Writable] ? Writable>>, RW> : Atom>>> => map(self, Result.map(f))) /** * @since 1.0.0 * @category combinators */ export const debounce: { (duration: Duration.DurationInput): >(self: A) => WithoutSerializable >(self: A, duration: Duration.DurationInput): WithoutSerializable } = dual( 2, (self: Atom, duration: Duration.DurationInput): Atom => { const millis = Duration.toMillis(duration) return transform(self, function(get) { let timeout: number | undefined let value = get.once(self) function update() { timeout = undefined get.setSelf(value) } get.addFinalizer(function() { if (timeout) clearTimeout(timeout) }) get.subscribe(self, function(val) { value = val if (timeout) clearTimeout(timeout) timeout = setTimeout(update, millis) }) return value }) } ) /** * @since 1.0.0 * @category Optimistic */ export const optimistic = (self: Atom): Writable>> => { let counter = 0 const writeAtom = removeTtl(state( [ counter, undefined as any as Atom> ] as const )) return writable( (get) => { let lastValue = get.once(self) let needsRefresh = false get.subscribe(self, (value) => { lastValue = value if (transitions.size > 0) { return } needsRefresh = false if (!Result.isResult(value)) { return get.setSelf(value) } const current = Option.getOrUndefined(get.self>())! switch (value._tag) { case "Initial": { if (Result.isInitial(current)) { get.setSelf(value) } return } case "Success": { if (Result.isSuccess(current)) { if (!value.waiting && value.timestamp >= current.timestamp) { get.setSelf(value) } } else { get.setSelf(value) } return } case "Failure": { return get.setSelf(value) } } }) const transitions = new Set>>() const cancels = new Set<() => void>() get.subscribe(writeAtom, ([, atom]) => { if (transitions.has(atom)) return transitions.add(atom) let cancel: (() => void) | undefined // eslint-disable-next-line prefer-const cancel = get.registry.subscribe(atom, (result) => { if (Result.isSuccess(result) && result.waiting) { return get.setSelf(result.value) } transitions.delete(atom) if (cancel) { cancels.delete(cancel) cancel() } if (!needsRefresh && !Result.isFailure(result)) { needsRefresh = true } if (transitions.size === 0) { if (needsRefresh) { needsRefresh = false get.refresh(self) } else { get.setSelf(lastValue) } } }, { immediate: true }) if (transitions.has(atom)) { cancels.add(cancel) } else { cancel() } }) get.addFinalizer(() => { for (const cancel of cancels) cancel() transitions.clear() cancels.clear() }) return lastValue }, (ctx, atom) => ctx.set(writeAtom, [++counter, atom]), (refresh) => refresh(self) ) } /** * @since 1.0.0 * @category Optimistic */ export const optimisticFn: { ( options: { readonly reducer: (current: NoInfer, update: OW) => NoInfer readonly fn: | AtomResultFn | ((set: (result: NoInfer) => void) => AtomResultFn) } ): ( self: Writable>> ) => AtomResultFn ( self: Writable>>, options: { readonly reducer: (current: NoInfer, update: OW) => NoInfer readonly fn: | AtomResultFn | ((set: (result: NoInfer) => void) => AtomResultFn) } ): AtomResultFn } = dual(2, ( self: Writable>>, options: { readonly reducer: (current: NoInfer, update: OW) => NoInfer readonly fn: | AtomResultFn | ((set: (result: NoInfer) => void) => AtomResultFn) } ): AtomResultFn => { const transition = removeTtl(state>(Result.initial())) return fn((arg: OW, get) => { let value = options.reducer(get(self), arg) if (Result.isResult(value)) { value = Result.waiting(value, { touch: true }) } get.set(transition, Result.success(value, { waiting: true })) get.set(self, transition) const fn = typeof options.fn === "function" ? autoDispose(options.fn((value) => get.set( transition, Result.success(Result.isResult(value) ? Result.waiting(value) : value, { waiting: true }) ) )) : options.fn get.set(fn, arg) return Effect.async((resume) => { get.subscribe(fn, (result) => { if (result._tag === "Initial" || result.waiting) return get.set(transition, Result.map(result, () => value)) resume(Result.toExit(result) as any) }, { immediate: true }) }) }) }) /** * @since 1.0.0 * @category batching */ export const batch: (f: () => void) => void = internalRegistry.batch // ----------------------------------------------------------------------------- // Focus // ----------------------------------------------------------------------------- /** * @since 1.0.0 * @category Focus */ export const windowFocusSignal: Atom = readable((get) => { let count = 0 function update() { if (document.visibilityState === "visible") { get.setSelf(++count) } } window.addEventListener("visibilitychange", update) get.addFinalizer(() => { window.removeEventListener("visibilitychange", update) }) return count }) /** * @since 1.0.0 * @category Focus */ export const makeRefreshOnSignal = <_>(signal: Atom<_>) => >(self: A): WithoutSerializable => transform(self, (get) => { get.once(signal) get.subscribe(signal, (_) => get.refresh(self)) get.subscribe(self, (value) => get.setSelf(value)) return get.once(self) }) as any /** * @since 1.0.0 * @category Focus */ export const refreshOnWindowFocus: >(self: A) => WithoutSerializable = makeRefreshOnSignal( windowFocusSignal ) // ----------------------------------------------------------------------------- // KeyValueStore // ----------------------------------------------------------------------------- /** * @since 1.0.0 * @category KeyValueStore */ export const kvs = (options: { readonly runtime: AtomRuntime readonly key: string readonly schema: Schema.Schema readonly defaultValue: LazyArg }): Writable => { const setAtom = options.runtime.fn( Effect.fnUntraced(function*(value: A) { const store = (yield* KeyValueStore.KeyValueStore).forSchema( options.schema ) yield* store.set(options.key, value) }) ) const resultAtom = options.runtime.atom( Effect.flatMap( KeyValueStore.KeyValueStore, (store) => store.forSchema(options.schema).get(options.key) ) ) return writable( (get) => { get.mount(setAtom) get.subscribe(resultAtom, (result) => { if (!Result.isSuccess(result)) return if (Option.isSome(result.value)) { get.setSelf(result.value.value) } else { const value = Option.getOrElse(get.self(), options.defaultValue) get.setSelf(value) get.set(setAtom, value) } }, { immediate: true }) return Option.getOrElse(get.self(), options.defaultValue) }, (ctx, value: A) => { ctx.set(setAtom, value as any) ctx.setSelf(value) } ) } // ----------------------------------------------------------------------------- // URL search params // ----------------------------------------------------------------------------- /** * Create an Atom that reads and writes a URL search parameter. * * Note: If you pass a schema, it has to be synchronous and have no context. * * @since 1.0.0 * @category URL search params */ export const searchParam = (name: string, options?: { readonly schema?: Schema.Schema }): Writable<[A] extends [never] ? string : Option.Option> => { const decode = options?.schema && Schema.decodeEither(options.schema) const encode = options?.schema && Schema.encodeEither(options.schema) return writable( (get) => { if (typeof window === "undefined") { return decode ? Option.none() : "" } const handleUpdate = () => { if (searchParamState.updating) return const searchParams = new URLSearchParams(window.location.search) const newValue = searchParams.get(name) || "" if (decode) { get.setSelf(Either.getRight(decode(newValue as I))) } else if (newValue !== Option.getOrUndefined(get.self())) { get.setSelf(newValue) } } window.addEventListener("popstate", handleUpdate) window.addEventListener("pushstate", handleUpdate) get.addFinalizer(() => { window.removeEventListener("popstate", handleUpdate) window.removeEventListener("pushstate", handleUpdate) }) const value = new URLSearchParams(window.location.search).get(name) || "" return decode ? Either.getRight(decode(value as I)) : value as any }, (ctx, value: any) => { if (typeof window === "undefined") { ctx.setSelf(value) return } if (encode) { const encoded = Option.flatMap(value, (v) => Either.getRight(encode(v as A))) searchParamState.updates.set(name, Option.getOrElse(encoded, () => "")) value = Option.zipRight(encoded, value) } else { searchParamState.updates.set(name, value) } ctx.setSelf(value) if (searchParamState.timeout) { clearTimeout(searchParamState.timeout) } searchParamState.timeout = setTimeout(updateSearchParams, 500) } ) } const searchParamState = { timeout: undefined as number | undefined, updates: new Map(), updating: false } function updateSearchParams() { searchParamState.timeout = undefined searchParamState.updating = true const searchParams = new URLSearchParams(window.location.search) for (const [key, value] of searchParamState.updates.entries()) { if (value.length > 0) { searchParams.set(key, value) } else { searchParams.delete(key) } } searchParamState.updates.clear() const newUrl = `${window.location.pathname}?${searchParams.toString()}` window.history.pushState({}, "", newUrl) searchParamState.updating = false } // ----------------------------------------------------------------------------- // conversions // ----------------------------------------------------------------------------- /** * @since 1.0.0 * @category Conversions */ export const toStream = (self: Atom): Stream.Stream => Stream.unwrap(Effect.map(AtomRegistry, Registry.toStream(self))) /** * @since 1.0.0 * @category Conversions */ export const toStreamResult = (self: Atom>): Stream.Stream => Stream.unwrap(Effect.map(AtomRegistry, Registry.toStreamResult(self))) /** * @since 1.0.0 * @category Conversions */ export const get = (self: Atom): Effect.Effect => Effect.map(AtomRegistry, (_) => _.get(self)) /** * @since 1.0.0 * @category Conversions */ export const modify: { ( f: (_: R) => [returnValue: A, nextValue: W] ): (self: Writable) => Effect.Effect (self: Writable, f: (_: R) => [returnValue: A, nextValue: W]): Effect.Effect } = dual( 2, (self: Writable, f: (_: R) => [returnValue: A, nextValue: W]): Effect.Effect => Effect.map(AtomRegistry, (_) => _.modify(self, f)) ) /** * @since 1.0.0 * @category Conversions */ export const set: { (value: W): (self: Writable) => Effect.Effect (self: Writable, value: W): Effect.Effect } = dual( 2, (self: Writable, value: W): Effect.Effect => Effect.map(AtomRegistry, (_) => _.set(self, value)) ) /** * @since 1.0.0 * @category Conversions */ export const update: { (f: (_: R) => W): (self: Writable) => Effect.Effect (self: Writable, f: (_: R) => W): Effect.Effect } = dual( 2, (self: Writable, f: (_: R) => W): Effect.Effect => Effect.map(AtomRegistry, (_) => _.update(self, f)) ) /** * @since 1.0.0 * @category Conversions */ export const getResult = ( self: Atom>, options?: { readonly suspendOnWaiting?: boolean | undefined } ): Effect.Effect => Effect.flatMap(AtomRegistry, Registry.getResult(self, options)) /** * @since 1.0.0 * @category Conversions */ export const refresh = (self: Atom): Effect.Effect => Effect.map(AtomRegistry, (_) => _.refresh(self)) // ----------------------------------------------------------------------------- // Serializable // ----------------------------------------------------------------------------- /** * @since 1.0.0 * @category Serializable */ export const SerializableTypeId: SerializableTypeId = "~effect-atom/atom/Atom/Serializable" /** * @since 1.0.0 * @category Serializable */ export type SerializableTypeId = "~effect-atom/atom/Atom/Serializable" /** * @since 1.0.0 * @category Serializable */ export interface Serializable { readonly [SerializableTypeId]: { readonly key: string readonly encode: (value: S["Type"]) => S["Encoded"] readonly decode: (value: S["Encoded"]) => S["Type"] } } /** * @since 1.0.0 * @category Serializable */ export const isSerializable = (self: Atom): self is Atom & Serializable => SerializableTypeId in self /** * @since 1.0.0 * @category combinators */ export const serializable: { , S extends Schema.Schema, any>>(options: { readonly key: string readonly schema: S }): (self: R) => R & Serializable , S extends Schema.Schema, any>>(self: R, options: { readonly key: string readonly schema: S }): R & Serializable } = dual(2, , A, I>(self: R, options: { readonly key: string readonly schema: Schema.Schema }): R & Serializable => Object.assign(Object.create(Object.getPrototypeOf(self)), { ...self, label: self.label ?? [options.key, new Error().stack?.split("\n")[5] ?? ""], [SerializableTypeId]: { key: options.key, encode: Schema.encodeSync(options.schema), decode: Schema.decodeSync(options.schema) } })) /** * @since 1.0.0 * @category ServerValue */ export const ServerValueTypeId = "~effect-atom/atom/Atom/ServerValue" as const /** * Overrides the value of an Atom when read on the server. * * @since 1.0.0 * @category ServerValue */ export const withServerValue: { >(read: (get: (atom: Atom) => A) => Type): (self: A) => A >(self: A, read: (get: (atom: Atom) => A) => Type): A } = dual( 2, >(self: A, read: (get: (atom: Atom) => A) => Type): A => Object.assign(Object.create(Object.getPrototypeOf(self)), { ...self, [ServerValueTypeId]: read }) ) /** * Sets the Atom's server value to `Result.initial(true)`. * * @since 1.0.0 * @category ServerValue */ export const withServerValueInitial = >>(self: A): A => withServerValue(self, constant(Result.initial(true)) as any) /** * @since 1.0.0 * @category ServerValue */ export const getServerValue: { (registry: Registry.Registry): (self: Atom) => A (self: Atom, registry: Registry.Registry): A } = dual( 2, (self: Atom, registry: Registry.Registry): A => ServerValueTypeId in self ? (self as any)[ServerValueTypeId]((atom: Atom) => registry.get(atom)) : registry.get(self) )