@sanity-labs/xstate-react 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sanity Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # @sanity-labs/xstate-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React bindings for [XState](https://stately.ai/docs) v6, built on React's async APIs: sending an event is a transition, so machine updates render together with the transition they belong to, and controlled inputs stay in sync through `useOptimistic`.
4
+
5
+ ## Requirements
6
+
7
+ - `react` and `react-dom` `^19.3`. `addTransitionType` is stable from React 19.3.
8
+ - `xstate` `^6.0.0-beta`.
9
+
10
+ ```sh
11
+ pnpm add @sanity-labs/xstate-react xstate@beta
12
+ ```
13
+
14
+ The hooks have the same names and signatures as `@xstate/react` for XState v6.
15
+
16
+ ## Usage
17
+
18
+ ```tsx
19
+ import {useActor} from '@sanity-labs/xstate-react'
20
+ import {createMachine, types} from 'xstate'
21
+
22
+ const counterMachine = createMachine({
23
+ schemas: {
24
+ context: types<{count: number}>(),
25
+ events: {inc: types<void>()},
26
+ },
27
+ context: {count: 0},
28
+ on: {inc: ({context}) => ({context: {count: context.count + 1}})},
29
+ })
30
+
31
+ function Counter() {
32
+ const [snapshot, send, actor] = useActor(counterMachine)
33
+ return (
34
+ <button type="button" onClick={() => send({type: 'inc'})}>
35
+ {snapshot.context.count}
36
+ </button>
37
+ )
38
+ }
39
+ ```
40
+
41
+ - `useActor(logic, options)` creates an actor, starts it, and returns `[snapshot, send, actor]`. `useMachine` is a deprecated alias.
42
+ - `useActorRef(logic, options)` creates and starts an actor without subscribing to its snapshot.
43
+ - `useSelector(actor, selector, compare?)` re-renders only when the selected value changes. `shallowEqual` is exported for use as `compare`.
44
+ - `useSend(actor)` returns the same `send` that `useActor` returns, for an actor created with `useActorRef` or received as a prop.
45
+ - `createActorContext(logic, options)` returns `{Provider, useSelector, useSend, useActorRef}` for sharing one actor with a subtree.
46
+
47
+ Use `send` from these hooks rather than `actor.send`: it is the one that takes part in transitions and optimistic updates.
48
+
49
+ ### The first machine, and `key` to start over
50
+
51
+ The machine passed on the first render is used for the component's lifetime, and `input` is read once. Implementations passed with `machine.provide()` are picked up on every render, so they can close over props and state:
52
+
53
+ ```tsx
54
+ import {useActor} from '@sanity-labs/xstate-react'
55
+
56
+ function Checkout({onPaid}: {onPaid: () => void}) {
57
+ const [snapshot, send] = useActor(checkoutMachine.provide({actions: {notifyPaid: onPaid}}), {
58
+ input: {currency: 'EUR'},
59
+ })
60
+ // ...
61
+ }
62
+ ```
63
+
64
+ Props the machine should react to after mounting are events. Send them from an effect:
65
+
66
+ ```tsx
67
+ import {useActor} from '@sanity-labs/xstate-react'
68
+ import {useEffect} from 'react'
69
+
70
+ function Stepper({start, limit}: {start: number; limit: number}) {
71
+ const [snapshot, send] = useActor(stepperMachine, {input: {start}})
72
+ useEffect(() => {
73
+ send({type: 'limit.set', limit})
74
+ }, [send, limit])
75
+ // ...
76
+ }
77
+ ```
78
+
79
+ To start over with fresh `input`, or to switch to a different machine, give the component a new `key`. React then unmounts it, stops its actor, and mounts a new one:
80
+
81
+ ```tsx
82
+ <Stepper key={documentId} start={1} limit={10} />
83
+ ```
84
+
85
+ ### Transitions
86
+
87
+ `send` is a transition. The snapshot change it causes renders in the background, so a part of the tree that suspends on it keeps showing the previous snapshot instead of falling back to a `Suspense` boundary. Read `isPending` from `useTransition` to show that work is in progress.
88
+
89
+ Called inside `startTransition`, `send` joins that transition, including its `addTransitionType` types, so `<ViewTransition>` can animate the change:
90
+
91
+ ```tsx
92
+ import {useActor} from '@sanity-labs/xstate-react'
93
+ import {addTransitionType, startTransition, ViewTransition} from 'react'
94
+
95
+ function Slides() {
96
+ const [snapshot, send] = useActor(slidesMachine)
97
+ return (
98
+ <>
99
+ <ViewTransition key={snapshot.context.index} enter={{forward: 'slide-in'}}>
100
+ <Slide index={snapshot.context.index} />
101
+ </ViewTransition>
102
+ <button
103
+ type="button"
104
+ onClick={() =>
105
+ startTransition(() => {
106
+ addTransitionType('forward')
107
+ send({type: 'next'})
108
+ })
109
+ }
110
+ >
111
+ Next
112
+ </button>
113
+ </>
114
+ )
115
+ }
116
+ ```
117
+
118
+ As with any state update, a `send` after an `await` in an async transition is no longer part of it. Wrap it in `startTransition` again:
119
+
120
+ ```tsx
121
+ startTransition(async () => {
122
+ const draft = await saveDraft()
123
+ startTransition(() => {
124
+ send({type: 'draft.saved', draft})
125
+ })
126
+ })
127
+ ```
128
+
129
+ ### Controlled inputs
130
+
131
+ A controlled input has to show what was typed right away, but a transition renders later. When `send` is called outside a transition, as in an `onChange` handler, the event's outcome is computed with XState's `transition()` and shown with `useOptimistic` until the transition renders. The caret stays where it was:
132
+
133
+ ```tsx
134
+ import {useActor} from '@sanity-labs/xstate-react'
135
+
136
+ function Search() {
137
+ const [snapshot, send] = useActor(searchMachine)
138
+ return (
139
+ <input
140
+ value={snapshot.context.query}
141
+ onChange={(event) => send({type: 'query.change', query: event.target.value})}
142
+ />
143
+ )
144
+ }
145
+ ```
146
+
147
+ Components that manage their own optimistic state and call an action prop inside a transition work too. Pass `send` from the action:
148
+
149
+ ```tsx
150
+ import {createActorContext} from '@sanity-labs/xstate-react'
151
+
152
+ const Router = createActorContext(routerMachine)
153
+
154
+ function Filters() {
155
+ const tab = Router.useSelector((snapshot) => snapshot.context.tab)
156
+ const send = Router.useSend()
157
+ return <TabList activeTab={tab} changeAction={(value) => send({type: 'tab.set', value})} />
158
+ }
159
+ ```
160
+
161
+ ### Updates `send` did not cause
162
+
163
+ Delayed transitions, invoked promises and child actors change the snapshot without a `send`. By default these changes render as transitions too. Pass `updates: 'sync'` to render them as regular updates instead:
164
+
165
+ ```tsx
166
+ const [snapshot] = useActor(timerMachine, {updates: 'sync'})
167
+ ```
168
+
169
+ `send` is a transition either way.
170
+
171
+ ## License
172
+
173
+ MIT
@@ -0,0 +1,106 @@
1
+ import { ReactNode } from "react";
2
+ import { Actor, ActorOptions, AnyActorLogic, AnyActorRef, AnyStateMachine, ConditionalRequired, IsNotNever, Observer, RequiredActorOptionsFor, RequiredActorOptionsKeys, SnapshotFrom, StateFrom } from "xstate";
3
+ /**
4
+ * How snapshot changes that `send` did not cause, such as delayed transitions and invoked actors
5
+ * settling, reach React.
6
+ *
7
+ * - `'transition'` (default): as transition updates.
8
+ * - `'sync'`: as regular updates, with the priority of whatever triggered them.
9
+ *
10
+ * @public
11
+ */
12
+ type Updates = 'transition' | 'sync';
13
+ /** @public */
14
+ interface BindingOptions {
15
+ /**
16
+ * How snapshot changes that `send` did not cause, such as delayed transitions and invoked
17
+ * actors settling, reach React. Defaults to `'transition'`.
18
+ */
19
+ updates?: Updates;
20
+ }
21
+ /**
22
+ * `useActor`, `useActorRef` and `createActorContext` options: the actor's own options, read once
23
+ * when the actor is created, and how its snapshots reach React.
24
+ *
25
+ * @public
26
+ */
27
+ type HookOptions<TLogic extends AnyActorLogic> = ActorOptions<TLogic> & BindingOptions;
28
+ /**
29
+ * Creates an actor from `logic` (or uses an already-created `actor`, e.g. from `restoreActor`),
30
+ * starts it on mount and stops it on unmount. Create a passed actor once, e.g.
31
+ * `useState(() => restoreActor(machine, persisted))[0]`.
32
+ *
33
+ * The logic passed on the first render is used for the component's lifetime. To start over, or to
34
+ * switch to a different machine, change the component's `key`.
35
+ *
36
+ * @public
37
+ */
38
+ export declare function useActorRef<TLogic extends AnyActorLogic>(actor: Actor<TLogic>, observerOrListener?: Observer<SnapshotFrom<TLogic>> | ((value: SnapshotFrom<TLogic>) => void)): Actor<TLogic>;
39
+ /** @public */
40
+ export declare function useActorRef<TLogic extends AnyActorLogic>(logic: TLogic, ...[options, observerOrListener]: IsNotNever<RequiredActorOptionsKeys<TLogic>> extends true ? [options: HookOptions<TLogic> & RequiredActorOptionsFor<TLogic>, observerOrListener?: Observer<SnapshotFrom<TLogic>> | ((value: SnapshotFrom<TLogic>) => void)] : [options?: HookOptions<TLogic>, observerOrListener?: Observer<SnapshotFrom<TLogic>> | ((value: SnapshotFrom<TLogic>) => void)]): Actor<TLogic>;
41
+ /** @public */
42
+ interface ActorContext<TLogic extends AnyActorLogic> {
43
+ useSelector: <T>(selector: (snapshot: SnapshotFrom<TLogic>) => T, compare?: (a: T, b: T) => boolean) => T;
44
+ useActorRef: () => Actor<TLogic>;
45
+ /** The provided actor's `send`, with the same transition and optimistic behavior as `useActor`. */
46
+ useSend: () => Actor<TLogic>['send'];
47
+ Provider: (props: {
48
+ children: ReactNode;
49
+ options?: HookOptions<TLogic>;
50
+ logic?: TLogic;
51
+ /**
52
+ * An already-created actor (e.g. from `restoreActor`) to provide instead of creating one from
53
+ * `logic` and `options`. Create it once.
54
+ */
55
+ actor?: Actor<TLogic>;
56
+ }) => ReactNode;
57
+ }
58
+ /** @public */
59
+ export declare function createActorContext<TLogic extends AnyActorLogic>(actorLogic: TLogic, actorOptions?: HookOptions<TLogic>): ActorContext<TLogic>;
60
+ /** @public */
61
+ export declare function shallowEqual(objA: any, objB: any): boolean;
62
+ /**
63
+ * Creates an actor from `logic` (or uses an already-created `actor`, e.g. from `restoreActor`) and
64
+ * subscribes to its snapshot. Create a passed actor once, e.g.
65
+ * `useState(() => restoreActor(machine, persisted))[0]`.
66
+ *
67
+ * `send` is a transition: snapshot updates it causes render together with the transition it is
68
+ * called in, or in a transition of its own. Until that transition settles, the returned snapshot
69
+ * already shows the event's outcome, so a controlled input can call `send` in `onChange`.
70
+ *
71
+ * The logic passed on the first render is used for the component's lifetime, and `input` is read
72
+ * once. To start over, or to switch to a different machine, change the component's `key`.
73
+ *
74
+ * @public
75
+ */
76
+ export declare function useActor<TLogic extends AnyActorLogic>(actor: Actor<TLogic>): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>];
77
+ /** @public */
78
+ export declare function useActor<TLogic extends AnyActorLogic>(logic: TLogic, ...[options]: ConditionalRequired<[options?: HookOptions<TLogic> & RequiredActorOptionsFor<TLogic>], IsNotNever<RequiredActorOptionsKeys<TLogic>>>): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>];
79
+ /**
80
+ * @deprecated Use `useActor(machine, options)`.
81
+ * @public
82
+ */
83
+ export declare function useMachine<TMachine extends AnyStateMachine>(actor: Actor<TMachine>): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>];
84
+ /**
85
+ * @deprecated Use `useActor(machine, options)`.
86
+ * @public
87
+ */
88
+ export declare function useMachine<TMachine extends AnyStateMachine>(machine: TMachine, ...[options]: ConditionalRequired<[options?: HookOptions<TMachine> & RequiredActorOptionsFor<TMachine>], IsNotNever<RequiredActorOptionsKeys<TMachine>>>): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>];
89
+ /**
90
+ * Reads a value derived from an actor's snapshot, and re-renders only when `compare` says it
91
+ * changed.
92
+ *
93
+ * @public
94
+ */
95
+ export declare function useSelector<TActor extends Pick<AnyActorRef, 'subscribe' | 'getSnapshot'> | undefined, T>(actor: TActor, selector: (snapshot: TActor extends {
96
+ getSnapshot(): infer TSnapshot;
97
+ } ? TSnapshot : undefined) => T, compare?: (a: T, b: T) => boolean): T;
98
+ /**
99
+ * Returns the same `send` that `useActor` returns, for an actor created elsewhere, e.g. with
100
+ * `useActorRef` or `createActorContext`.
101
+ *
102
+ * @public
103
+ */
104
+ export declare function useSend<TActor extends AnyActorRef>(actor: TActor): TActor['send'];
105
+ export type { ActorContext, BindingOptions, HookOptions, Updates };
106
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/store.ts","../src/useActorRef.ts","../src/createActorContext.tsx","../src/shallowEqual.ts","../src/useActor.ts","../src/useMachine.ts","../src/useSelector.ts","../src/useSend.ts"],"mappings":";;;;;;;;;;;KAsBY;;UAGK;;;;;EAKf,UAAU;;;;;;;;KCNA,YAAY,eAAe,iBAAiB,aAAa,UAAU;;;;;;;;;;;wBAoJ/D,YAAY,eAAe,eACzC,OAAO,MAAM,SACb,qBAAqB,SAAS,aAAa,aAAa,OAAO,aAAa,oBAC3E,MAAM;;wBAEO,YAAY,eAAe,eACzC,OAAO,YACH,SAAS,qBAAqB,WAAW,yBAAyB,yBAEhE,SAAS,YAAY,UAAU,wBAAwB,SACvD,qBACI,SAAS,aAAa,aACpB,OAAO,aAAa,sBAG1B,UAAU,YAAY,SACtB,qBACI,SAAS,aAAa,aACpB,OAAO,aAAa,qBAE/B,MAAM;;UCxLQ,aAAa,eAAe;EAC3C,cAAc,GACZ,WAAW,UAAU,aAAa,YAAY,GAC9C,WAAW,GAAG,GAAG,GAAG,kBACjB;EACL,mBAAmB,MAAM;;EAEzB,eAAe,MAAM;EACrB,WAAW;IACT,UAAU;IACV,UAAU,YAAY;IACtB,QAAQ;;;;;IAKR,QAAQ,MAAM;QACV;;;wBAIQ,mBAAmB,eAAe,eAChD,YAAY,QACZ,eAAe,YAAY,UAC1B,aAAa;;wBCxBA,aAAa,WAAW;;;;;;;;;;;;;;;wBC+BxB,SAAS,eAAe,eACtC,OAAO,MAAM,WACX,aAAa,SAAS,MAAM,iBAAiB,MAAM;;wBAEvC,SAAS,eAAe,eACtC,OAAO,YACH,UAAU,qBACX,UAAU,YAAY,UAAU,wBAAwB,UACzD,WAAW,yBAAyB,aAEpC,aAAa,SAAS,MAAM,iBAAiB,MAAM;;;;;wBChCvC,WAAW,iBAAiB,iBAC1C,OAAO,MAAM,aACX,UAAU,WAAW,MAAM,mBAAmB,MAAM;;;;;wBAKxC,WAAW,iBAAiB,iBAC1C,SAAS,cACL,UAAU,qBACX,UAAU,YAAY,YAAY,wBAAwB,YAC3D,WAAW,yBAAyB,eAEpC,UAAU,WAAW,MAAM,mBAAmB,MAAM;;;;;;;wBCdxC,YACd,eAAe,KAAK,uDACpB,GAEA,OAAO,QACP,WACE,UAAU;EAAgB,qBAAqB;IAAa,0BACzD,GACL,WAAU,GAAG,GAAG,GAAG,gBAClB;;;;;;;wBCda,QAAQ,eAAe,aAAa,OAAO,SAAS"}
package/dist/index.js ADDED
@@ -0,0 +1,384 @@
1
+ import * as React from "react";
2
+ import { createContext, startTransition, use, useEffect, useEffectEvent, useInsertionEffect, useLayoutEffect, useMemo, useOptimistic, useRef, useState } from "react";
3
+ import { c } from "react/compiler-runtime";
4
+ import { Actor, _hotSwapActorLogic, _toObserver, createActor, transition } from "xstate";
5
+ import { jsx } from "react/jsx-runtime";
6
+ const internals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
7
+ function isInTransition() {
8
+ return internals?.T != null;
9
+ }
10
+ var ActorStore = class {
11
+ actor;
12
+ updates = "transition";
13
+ head;
14
+ /** The newest entry React has committed, which a component mounting outside a transition sees. */
15
+ committed;
16
+ seq = 0;
17
+ version = 0;
18
+ sending = 0;
19
+ listeners = /* @__PURE__ */ new Set();
20
+ lagging = /* @__PURE__ */ new Set();
21
+ unsubscribeActor;
22
+ constructor(actor) {
23
+ this.actor = actor, this.head = {
24
+ snapshot: actor.getSnapshot(),
25
+ seq: 0,
26
+ version: 0
27
+ }, this.committed = this.head;
28
+ }
29
+ subscribe(listener) {
30
+ if (this.listeners.add(listener), !this.unsubscribeActor) {
31
+ let subscription = this.actor.subscribe({
32
+ next: () => this.pull(),
33
+ error: () => this.pull()
34
+ });
35
+ this.unsubscribeActor = () => subscription.unsubscribe(), this.pull();
36
+ }
37
+ return () => {
38
+ this.listeners.delete(listener), this.listeners.size === 0 && (this.unsubscribeActor?.(), this.unsubscribeActor = void 0, this.committed = this.head);
39
+ };
40
+ }
41
+ commit(entry) {
42
+ entry.version > this.committed.version && (this.committed = entry);
43
+ }
44
+ /**
45
+ * Registers a reader that mounted showing `committed` while others were rendering a newer
46
+ * snapshot in a transition, to catch up when they commit it. Returns a function that unregisters.
47
+ */
48
+ lag(catchUp) {
49
+ return this.lagging.add(catchUp), () => this.lagging.delete(catchUp);
50
+ }
51
+ /** Called in the layout phase of a commit that included readers of the actor. */
52
+ catchUp() {
53
+ for (let catchUp of this.lagging) catchUp();
54
+ }
55
+ send = (event) => {
56
+ let seq = ++this.seq;
57
+ isInTransition() ? this.deliver(event) : startTransition(() => {
58
+ let logic = this.actor.logic;
59
+ if (logic) for (let listener of this.listeners) listener.optimistic({
60
+ logic,
61
+ event,
62
+ seq
63
+ });
64
+ this.deliver(event);
65
+ });
66
+ };
67
+ deliver(event) {
68
+ this.sending++;
69
+ try {
70
+ this.actor.send(event);
71
+ } finally {
72
+ this.sending--;
73
+ }
74
+ }
75
+ pull() {
76
+ let snapshot = this.actor.getSnapshot();
77
+ if (snapshot === this.head.snapshot) return;
78
+ if (this.head = {
79
+ snapshot,
80
+ seq: this.seq,
81
+ version: ++this.version
82
+ }, this.listeners.size === 0) {
83
+ this.committed = this.head;
84
+ return;
85
+ }
86
+ let sentInTransition = this.sending > 0, scheduled = !1;
87
+ for (let listener of this.listeners) scheduled = listener.update(this.head, sentInTransition) || scheduled;
88
+ scheduled || (this.committed = this.head);
89
+ }
90
+ };
91
+ const stores = /* @__PURE__ */ new WeakMap();
92
+ function getStore(actor) {
93
+ let store = stores.get(actor);
94
+ return store || (store = new ActorStore(actor), stores.set(actor, store)), store;
95
+ }
96
+ /**
97
+ * The `useOptimistic` reducer. React replays it on top of every new base until the transition that
98
+ * sent the event settles, and the actor has already processed the event by the time any base after
99
+ * the send is read. So an event the base already includes is skipped, instead of applied twice.
100
+ */
101
+ function reduceOptimistic(current, action) {
102
+ let base = action.fallback && action.fallback.version > current.version ? action.fallback : current;
103
+ if (base.seq >= action.seq) return base;
104
+ try {
105
+ let [snapshot] = transition(action.logic, base.snapshot, action.event);
106
+ return {
107
+ snapshot,
108
+ seq: base.seq,
109
+ version: base.version
110
+ };
111
+ } catch {
112
+ return base;
113
+ }
114
+ }
115
+ function isStateMachine(logic) {
116
+ return typeof logic.provide == "function" && !!logic.config && !!logic.sources;
117
+ }
118
+ function isActor(value) {
119
+ return value instanceof Actor;
120
+ }
121
+ function ownLogic(logic) {
122
+ return isStateMachine(logic) ? logic.provide({}) : logic;
123
+ }
124
+ function create(logic, options) {
125
+ let { updates, ...actorOptions } = options ?? {}, actor = createActor(logic, actorOptions);
126
+ return updates && (getStore(actor).updates = updates), actor;
127
+ }
128
+ function adoptLogic(actorRef, logic, refreshed, options, setActorRef) {
129
+ let currentLogic = actorRef.logic;
130
+ if (logic.config === currentLogic.config) isStateMachine(logic) && isStateMachine(currentLogic) && (currentLogic.sources = logic.sources);
131
+ else if (refreshed) {
132
+ let nextLogic = ownLogic(logic);
133
+ _hotSwapActorLogic(actorRef, nextLogic) || setActorRef(create(nextLogic, options));
134
+ }
135
+ }
136
+ function useIdleActorRef(logicOrActor, options) {
137
+ "use no memo";
138
+ let [actorRef, setActorRef] = useState(() => isActor(logicOrActor) ? logicOrActor : create(ownLogic(logicOrActor), options)), refreshSignal = useMemo(() => ({}), []), refreshSignalRef = useRef(refreshSignal);
139
+ return useLayoutEffect(() => {
140
+ let refreshed = refreshSignalRef.current !== refreshSignal;
141
+ refreshSignalRef.current = refreshSignal, isActor(logicOrActor) || adoptLogic(actorRef, logicOrActor, refreshed, options, setActorRef);
142
+ }, [
143
+ actorRef,
144
+ logicOrActor,
145
+ refreshSignal,
146
+ options
147
+ ]), [actorRef, setActorRef];
148
+ }
149
+ function useActorLifecycle(actorRef, setActorRef, createReplacement) {
150
+ let $ = c(9), t0;
151
+ $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = /* @__PURE__ */ new Map(), $[0] = t0) : t0 = $[0];
152
+ let pendingStopsRef = useRef(t0), t1;
153
+ $[1] !== createReplacement || $[2] !== setActorRef ? (t1 = () => setActorRef(createReplacement()), $[1] = createReplacement, $[2] = setActorRef, $[3] = t1) : t1 = $[3];
154
+ let replace = useEffectEvent(t1), t2;
155
+ $[4] !== actorRef || $[5] !== replace ? (t2 = () => {
156
+ let pendingStops = pendingStopsRef.current, cancelPendingStop = pendingStops.get(actorRef);
157
+ if (cancelPendingStop && (cancelPendingStop(), pendingStops.delete(actorRef)), actorRef._processingStatus === 2 && actorRef.getSnapshot()?.status === "stopped") replace();
158
+ else return actorRef.start(), () => {
159
+ let canceled = !1, cancel = () => {
160
+ canceled = !0;
161
+ };
162
+ pendingStops.set(actorRef, cancel), queueMicrotask(() => {
163
+ canceled || actorRef.stop(), pendingStops.get(actorRef) === cancel && pendingStops.delete(actorRef);
164
+ });
165
+ };
166
+ }, $[4] = actorRef, $[5] = replace, $[6] = t2) : t2 = $[6];
167
+ let t3;
168
+ $[7] === actorRef ? t3 = $[8] : (t3 = [actorRef], $[7] = actorRef, $[8] = t3), useEffect(t2, t3);
169
+ }
170
+ /** Creates an actor to replace a stopped one, keeping how its snapshots reach React. */
171
+ function recreate(actorRef, options) {
172
+ return create(actorRef.logic, {
173
+ ...options,
174
+ updates: getStore(actorRef).updates
175
+ });
176
+ }
177
+ function useActorRef(logicOrActor, ...t0) {
178
+ let $ = c(6), args = t0, readyActor = isActor(logicOrActor), options = readyActor ? void 0 : args[0], observerOrListener = readyActor ? args[0] : args[1], [actorRef, setActorRef] = useIdleActorRef(logicOrActor, options), t1, t2;
179
+ $[0] !== actorRef || $[1] !== observerOrListener ? (t1 = () => {
180
+ if (!observerOrListener) return;
181
+ let subscription = actorRef.subscribe(_toObserver(observerOrListener));
182
+ return () => subscription.unsubscribe();
183
+ }, t2 = [actorRef, observerOrListener], $[0] = actorRef, $[1] = observerOrListener, $[2] = t1, $[3] = t2) : (t1 = $[2], t2 = $[3]), useEffect(t1, t2);
184
+ let t3;
185
+ return $[4] === actorRef ? t3 = $[5] : (t3 = () => recreate(actorRef, actorRef.options), $[4] = actorRef, $[5] = t3), useActorLifecycle(actorRef, setActorRef, t3), actorRef;
186
+ }
187
+ const emptyEntry = {
188
+ snapshot: void 0,
189
+ seq: 0,
190
+ version: 0
191
+ };
192
+ function isErrored(snapshot) {
193
+ return !!snapshot && typeof snapshot == "object" && "status" in snapshot && snapshot.status === "error" && "error" in snapshot;
194
+ }
195
+ /**
196
+ * Reads `selector(snapshot)` from the actor behind `store`.
197
+ *
198
+ * The snapshot lives in React state, so an update that `send` or a transition causes renders, and
199
+ * commits, together with the rest of that transition. Events sent with the store's `send` are
200
+ * previewed with `useOptimistic` until the transition that sent them settles, which keeps
201
+ * controlled inputs in sync.
202
+ */
203
+ function useStoreSelection(store, selector, compare) {
204
+ let $ = c(31), t0;
205
+ $[0] !== selector || $[1] !== store ? (t0 = () => {
206
+ let entry = store?.head;
207
+ return {
208
+ store,
209
+ entry,
210
+ selected: selector(entry?.snapshot),
211
+ updated: !1
212
+ };
213
+ }, $[0] = selector, $[1] = store, $[2] = t0) : t0 = $[2];
214
+ let [state, setState] = useState(t0), current = state.store === store ? state : void 0, base = current ? current.entry : store?.head, [optimistic, addOptimistic] = useOptimistic(base ?? emptyEntry, reduceOptimistic), selectorRef = useRef(selector), compareRef = useRef(compare), stateRef = useRef(state), lagTargetRef = useRef(void 0), t1;
215
+ $[3] !== compare || $[4] !== selector || $[5] !== state ? (t1 = () => {
216
+ selectorRef.current = selector, compareRef.current = compare, stateRef.current = state;
217
+ }, $[3] = compare, $[4] = selector, $[5] = state, $[6] = t1) : t1 = $[6], useLayoutEffect(t1);
218
+ let t2, t3;
219
+ $[7] !== current || $[8] !== store ? (t2 = () => {
220
+ store && current?.updated && current.entry && store.commit(current.entry);
221
+ }, t3 = [store, current], $[7] = current, $[8] = store, $[9] = t2, $[10] = t3) : (t2 = $[9], t3 = $[10]), useInsertionEffect(t2, t3);
222
+ let t4, t5;
223
+ $[11] === store ? (t4 = $[12], t5 = $[13]) : (t4 = () => {
224
+ lagTargetRef.current = void 0;
225
+ let mounted = stateRef.current;
226
+ if (!store || mounted.store !== store || mounted.updated || mounted.entry === store.committed) return;
227
+ let target = mounted.entry;
228
+ lagTargetRef.current = target;
229
+ let show = (entry_0) => {
230
+ let next = {
231
+ store,
232
+ entry: entry_0,
233
+ selected: selectorRef.current(entry_0.snapshot),
234
+ updated: !0
235
+ };
236
+ stateRef.current = next, setState(next);
237
+ };
238
+ show(store.committed);
239
+ let stopLagging = store.lag(() => {
240
+ let { committed } = store;
241
+ committed.version > (stateRef.current.entry?.version ?? 0) && show(committed), (!target || committed.version >= target.version) && stopLagging();
242
+ });
243
+ return stopLagging;
244
+ }, t5 = [store], $[11] = store, $[12] = t4, $[13] = t5), useLayoutEffect(t4, t5);
245
+ let t6;
246
+ $[14] !== current?.updated || $[15] !== store ? (t6 = () => {
247
+ store && current?.updated && store.catchUp();
248
+ }, $[14] = current?.updated, $[15] = store, $[16] = t6) : t6 = $[16];
249
+ let t7;
250
+ $[17] !== current || $[18] !== store ? (t7 = [store, current], $[17] = current, $[18] = store, $[19] = t7) : t7 = $[19], useLayoutEffect(t6, t7);
251
+ let t8, t9;
252
+ $[20] === store ? (t8 = $[21], t9 = $[22]) : (t8 = () => {
253
+ if (!store) return;
254
+ let skipped, apply = function apply(entry_1, asTransition) {
255
+ let previous = stateRef.current;
256
+ if (previous.store === store && previous.entry === entry_1) return !1;
257
+ let selected = selectorRef.current(entry_1.snapshot);
258
+ if (previous.store === store && !isErrored(entry_1.snapshot) && compareRef.current(previous.selected, selected)) return skipped = entry_1, !1;
259
+ skipped = void 0;
260
+ let next_0 = {
261
+ store,
262
+ entry: entry_1,
263
+ selected,
264
+ updated: !0
265
+ };
266
+ return stateRef.current = next_0, asTransition ? startTransition(() => setState(next_0)) : setState(next_0), !0;
267
+ }, unsubscribe = store.subscribe({
268
+ update(entry_2, sentInTransition) {
269
+ return apply(entry_2, sentInTransition || store.updates === "transition");
270
+ },
271
+ optimistic(action) {
272
+ startTransition(() => addOptimistic({
273
+ ...action,
274
+ fallback: skipped
275
+ }));
276
+ }
277
+ }), seen = stateRef.current.store === store ? stateRef.current.entry : void 0, known = Math.max(seen?.version ?? -1, lagTargetRef.current?.version ?? -1);
278
+ return store.head.version > known && apply(store.head, store.updates === "transition"), unsubscribe;
279
+ }, t9 = [store, addOptimistic], $[20] = store, $[21] = t8, $[22] = t9), useEffect(t8, t9);
280
+ let entry_3 = optimistic === emptyEntry ? void 0 : optimistic, snapshot = entry_3?.snapshot;
281
+ if (isErrored(snapshot)) throw snapshot.error;
282
+ if (current && entry_3 === current.entry) {
283
+ let t10;
284
+ if ($[23] !== compare || $[24] !== current.selected || $[25] !== selector || $[26] !== snapshot) {
285
+ let selected_0 = selector(snapshot);
286
+ t10 = compare(current.selected, selected_0) ? current.selected : selected_0, $[23] = compare, $[24] = current.selected, $[25] = selector, $[26] = snapshot, $[27] = t10;
287
+ } else t10 = $[27];
288
+ return t10;
289
+ }
290
+ let t10;
291
+ return $[28] !== selector || $[29] !== snapshot ? (t10 = selector(snapshot), $[28] = selector, $[29] = snapshot, $[30] = t10) : t10 = $[30], t10;
292
+ }
293
+ function defaultCompare(a, b) {
294
+ return a === b;
295
+ }
296
+ /**
297
+ * Reads a value derived from an actor's snapshot, and re-renders only when `compare` says it
298
+ * changed.
299
+ *
300
+ * @public
301
+ */
302
+ function useSelector(actor, selector, t0) {
303
+ let $ = c(2), compare = t0 === void 0 ? defaultCompare : t0, t1;
304
+ return $[0] === actor ? t1 = $[1] : (t1 = actor ? getStore(actor) : void 0, $[0] = actor, $[1] = t1), useStoreSelection(t1, selector, compare);
305
+ }
306
+ /**
307
+ * Returns the same `send` that `useActor` returns, for an actor created elsewhere, e.g. with
308
+ * `useActorRef` or `createActorContext`.
309
+ *
310
+ * @public
311
+ */
312
+ function useSend(actor) {
313
+ let $ = c(2), t0;
314
+ return $[0] === actor ? t0 = $[1] : (t0 = getStore(actor), $[0] = actor, $[1] = t0), t0.send;
315
+ }
316
+ /** @public */
317
+ function createActorContext(actorLogic, actorOptions) {
318
+ let ReactContext = createContext(null);
319
+ function Provider({ children, logic: providedLogic = actorLogic, options: providedOptions, actor: providedActor }) {
320
+ let actor = useActorRef(providedActor ?? providedLogic, providedActor ? void 0 : {
321
+ ...actorOptions,
322
+ ...providedOptions
323
+ });
324
+ return /* @__PURE__ */ jsx(ReactContext, {
325
+ value: actor,
326
+ children
327
+ });
328
+ }
329
+ Provider.displayName = "ActorProvider";
330
+ function useContext() {
331
+ let actor = use(ReactContext);
332
+ if (!actor) throw Error(`You used a hook from "${Provider.displayName}" but it's not inside a <${Provider.displayName}> component.`);
333
+ return actor;
334
+ }
335
+ function useSelector$1(selector, compare) {
336
+ return useSelector(useContext(), selector, compare);
337
+ }
338
+ function useSend$1() {
339
+ return useSend(useContext());
340
+ }
341
+ return {
342
+ Provider,
343
+ useActorRef: useContext,
344
+ useSelector: useSelector$1,
345
+ useSend: useSend$1
346
+ };
347
+ }
348
+ function is(x, y) {
349
+ return x === y ? x !== 0 || y !== 0 || 1 / x == 1 / y : x !== x && y !== y;
350
+ }
351
+ /** @public */
352
+ function shallowEqual(objA, objB) {
353
+ if (is(objA, objB)) return !0;
354
+ if (typeof objA != "object" || !objA || typeof objB != "object" || !objB) return !1;
355
+ let keysA = Object.keys(objA), keysB = Object.keys(objB);
356
+ if (keysA.length !== keysB.length) return !1;
357
+ for (let key of keysA) if (!Object.prototype.hasOwnProperty.call(objB, key) || !is(objA[key], objB[key])) return !1;
358
+ return !0;
359
+ }
360
+ function identity(value) {
361
+ return value;
362
+ }
363
+ function useActor(logic, options) {
364
+ let $ = c(12), t0;
365
+ $[0] === logic ? t0 = $[1] : (t0 = isActor(logic), $[0] = logic, $[1] = t0);
366
+ let readyActor = t0;
367
+ if (!readyActor && logic && "send" in logic && typeof logic.send == "function") throw Error("useActor() expects actor logic (e.g. a machine), but received an ActorRef. Pass an Actor created with createActor()/restoreActor(), or use the useSelector(actorRef, ...) hook to read an ActorRef's snapshot.");
368
+ let [actorRef, setActorRef] = useIdleActorRef(logic, options), t1;
369
+ $[2] === actorRef ? t1 = $[3] : (t1 = getStore(actorRef), $[2] = actorRef, $[3] = t1);
370
+ let store = t1, snapshot = useStoreSelection(store, identity, Object.is), t2;
371
+ $[4] !== actorRef || $[5] !== options || $[6] !== readyActor ? (t2 = () => recreate(actorRef, readyActor ? actorRef.options : options), $[4] = actorRef, $[5] = options, $[6] = readyActor, $[7] = t2) : t2 = $[7], useActorLifecycle(actorRef, setActorRef, t2);
372
+ let t3 = store.send, t4;
373
+ return $[8] !== actorRef || $[9] !== snapshot || $[10] !== t3 ? (t4 = [
374
+ snapshot,
375
+ t3,
376
+ actorRef
377
+ ], $[8] = actorRef, $[9] = snapshot, $[10] = t3, $[11] = t4) : t4 = $[11], t4;
378
+ }
379
+ function useMachine(machine, options) {
380
+ return useActor(machine, options);
381
+ }
382
+ export { createActorContext, shallowEqual, useActor, useActorRef, useMachine, useSelector, useSend };
383
+
384
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["new Map<Actor<TLogic>, () => void>()","() => setActorRef(createReplacement())","() => {\n const pendingStops = pendingStopsRef.current\n const cancelPendingStop = pendingStops.get(actorRef)\n if (cancelPendingStop) {\n cancelPendingStop()\n pendingStops.delete(actorRef)\n }\n\n // A stopped actor cannot be restarted, so one that stopped before this effect reconnected is\n // replaced.\n if (\n (actorRef as any)._processingStatus === 2 &&\n (actorRef.getSnapshot() as any)?.status === 'stopped'\n ) {\n replace()\n return\n }\n\n actorRef.start()\n // Stopping waits a microtask so that StrictMode's simulated unmount and remount, and a move\n // within the tree, keep the running actor.\n return () => {\n let canceled = false\n const cancel = () => {\n canceled = true\n }\n pendingStops.set(actorRef, cancel)\n queueMicrotask(() => {\n if (!canceled) {\n actorRef.stop()\n }\n if (pendingStops.get(actorRef) === cancel) {\n pendingStops.delete(actorRef)\n }\n })\n }\n }","[actorRef]","...args: any[]","() => {\n if (!observerOrListener) {\n return\n }\n const subscription = actorRef.subscribe(toObserver(observerOrListener))\n return () => subscription.unsubscribe()\n }","[actorRef, observerOrListener]","() => recreate(actorRef, actorRef.options)","hotSwapActorLogic","toObserver","() => {\n const entry = store?.head\n return {store, entry, selected: selector(entry?.snapshot), updated: false}\n }","store?.head","() => {\n selectorRef.current = selector\n compareRef.current = compare\n stateRef.current = state\n }","() => {\n if (store && current?.updated && current.entry) {\n store.commit(current.entry)\n }\n }","[store, current]","current?.updated","() => {\n lagTargetRef.current = undefined\n const mounted = stateRef.current\n if (!store || mounted.store !== store || mounted.updated || mounted.entry === store.committed) {\n return\n }\n const target = mounted.entry\n lagTargetRef.current = target\n const show = (entry: Entry) => {\n const next: State<T> = {\n store,\n entry,\n selected: selectorRef.current(entry.snapshot),\n updated: true,\n }\n stateRef.current = next\n setState(next)\n }\n show(store.committed)\n const stopLagging = store.lag(() => {\n const {committed} = store\n if (committed.version > (stateRef.current.entry?.version ?? 0)) {\n show(committed)\n }\n if (!target || committed.version >= target.version) {\n stopLagging()\n }\n })\n return stopLagging\n }","[store]","entry","() => {\n if (store && current?.updated) {\n store.catchUp()\n }\n }","updated","() => {\n if (!store) {\n return\n }\n let skipped: Entry | undefined\n\n function apply(entry: Entry, asTransition: boolean): boolean {\n const previous = stateRef.current\n if (previous.store === store && previous.entry === entry) {\n return false\n }\n const selected = selectorRef.current(entry.snapshot)\n // The selection did not change, so there is nothing to render. The entry is still the\n // newest base for previewing events this component did not render the outcome of.\n if (\n previous.store === store &&\n !isErrored(entry.snapshot) &&\n compareRef.current(previous.selected, selected)\n ) {\n skipped = entry\n return false\n }\n skipped = undefined\n const next: State<T> = {store, entry, selected, updated: true}\n stateRef.current = next\n if (asTransition) {\n startTransition(() => setState(next))\n } else {\n setState(next)\n }\n return true\n }\n\n const unsubscribe = store.subscribe({\n update(entry, sentInTransition) {\n return apply(entry, sentInTransition || store.updates === 'transition')\n },\n optimistic(action) {\n startTransition(() => addOptimistic({...action, fallback: skipped} as OptimisticAction))\n },\n })\n // The snapshot may have changed between render and subscribing.\n const seen = stateRef.current.store === store ? stateRef.current.entry : undefined\n const known = Math.max(seen?.version ?? -1, lagTargetRef.current?.version ?? -1)\n if (store.head.version > known) {\n apply(store.head, store.updates === 'transition')\n }\n return unsubscribe\n }","[store, addOptimistic]","next","compare(current.selected, selected) ? current.selected : selected","selected","selector(snapshot)","compare: (a: T, b: T) => boolean = defaultCompare","actor ? getStore(actor) : undefined","store","getStore(actor)","_jsx","useSelector","useSelectorUnbound","useSend","useSendUnbound","isActor(logic)","getStore(actorRef)","useMemo(() => getStore(actorRef), [actorRef])","() =>\n recreate(actorRef, readyActor ? actorRef.options : options)","actorRef.options","store.send as Actor<TLogic>['send']","[snapshot, store.send as Actor<TLogic>['send'], actorRef]"],"sources":["../src/store.ts","../src/useActorRef.ts","../src/useStoreSelection.ts","../src/useSelector.ts","../src/useSend.ts","../src/createActorContext.tsx","../src/shallowEqual.ts","../src/useActor.ts","../src/useMachine.ts"],"sourcesContent":["import * as React from 'react'\nimport {startTransition} from 'react'\nimport {transition, type AnyActorLogic, type AnyActorRef} from 'xstate'\n\n// React has no public way to ask whether code runs inside `startTransition`. Its client internals\n// hold the current transition in `T`.\nconst internals: {T: unknown} | undefined = (React as any)\n .__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE\n\nfunction isInTransition(): boolean {\n return internals?.T != null\n}\n\n/**\n * How snapshot changes that `send` did not cause, such as delayed transitions and invoked actors\n * settling, reach React.\n *\n * - `'transition'` (default): as transition updates.\n * - `'sync'`: as regular updates, with the priority of whatever triggered them.\n *\n * @public\n */\nexport type Updates = 'transition' | 'sync'\n\n/** @public */\nexport interface BindingOptions {\n /**\n * How snapshot changes that `send` did not cause, such as delayed transitions and invoked\n * actors settling, reach React. Defaults to `'transition'`.\n */\n updates?: Updates\n}\n\ntype ReadableActor = Pick<AnyActorRef, 'subscribe' | 'getSnapshot'>\n\nexport interface Entry {\n readonly snapshot: unknown\n /** The number of events sent through the store that the snapshot already includes. */\n readonly seq: number\n /** Increases with every snapshot the actor emits, to order entries that share a `seq`. */\n readonly version: number\n}\n\nexport interface OptimisticAction {\n readonly logic: AnyActorLogic\n readonly event: unknown\n readonly seq: number\n /** A newer base than the hook's state, for hooks that skipped updates their selector ignored. */\n readonly fallback: Entry | undefined\n}\n\nexport interface Listener {\n /** Returns whether the listener scheduled a render for the entry. */\n update(entry: Entry, sentInTransition: boolean): boolean\n optimistic(action: Omit<OptimisticAction, 'fallback'>): void\n}\n\nexport class ActorStore {\n readonly actor: ReadableActor\n updates: Updates = 'transition'\n head: Entry\n /** The newest entry React has committed, which a component mounting outside a transition sees. */\n committed: Entry\n private seq = 0\n private version = 0\n private sending = 0\n private readonly listeners = new Set<Listener>()\n private readonly lagging = new Set<() => void>()\n private unsubscribeActor: (() => void) | undefined\n\n constructor(actor: ReadableActor) {\n this.actor = actor\n this.head = {snapshot: actor.getSnapshot(), seq: 0, version: 0}\n this.committed = this.head\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener)\n if (!this.unsubscribeActor) {\n const subscription = this.actor.subscribe({\n next: () => this.pull(),\n error: () => this.pull(),\n })\n this.unsubscribeActor = () => subscription.unsubscribe()\n this.pull()\n }\n return () => {\n this.listeners.delete(listener)\n if (this.listeners.size === 0) {\n this.unsubscribeActor?.()\n this.unsubscribeActor = undefined\n this.committed = this.head\n }\n }\n }\n\n commit(entry: Entry): void {\n if (entry.version > this.committed.version) {\n this.committed = entry\n }\n }\n\n /**\n * Registers a reader that mounted showing `committed` while others were rendering a newer\n * snapshot in a transition, to catch up when they commit it. Returns a function that unregisters.\n */\n lag(catchUp: () => void): () => void {\n this.lagging.add(catchUp)\n return () => this.lagging.delete(catchUp)\n }\n\n /** Called in the layout phase of a commit that included readers of the actor. */\n catchUp(): void {\n for (const catchUp of this.lagging) {\n catchUp()\n }\n }\n\n send = (event: unknown): void => {\n const seq = ++this.seq\n if (isInTransition()) {\n this.deliver(event)\n return\n }\n // An urgent send, like one from a controlled input's `onChange`: the outcome is previewed with\n // `useOptimistic`, rebased on what is committed, while the snapshot itself updates in a\n // transition.\n startTransition(() => {\n const logic = (this.actor as {logic?: AnyActorLogic}).logic\n if (logic) {\n for (const listener of this.listeners) {\n listener.optimistic({logic, event, seq})\n }\n }\n this.deliver(event)\n })\n }\n\n private deliver(event: unknown): void {\n this.sending++\n try {\n ;(this.actor as AnyActorRef).send(event)\n } finally {\n this.sending--\n }\n }\n\n private pull(): void {\n const snapshot = this.actor.getSnapshot()\n if (snapshot === this.head.snapshot) {\n return\n }\n this.head = {snapshot, seq: this.seq, version: ++this.version}\n if (this.listeners.size === 0) {\n this.committed = this.head\n return\n }\n const sentInTransition = this.sending > 0\n let scheduled = false\n for (const listener of this.listeners) {\n scheduled = listener.update(this.head, sentInTransition) || scheduled\n }\n // No reader renders anything different, so React already shows this snapshot.\n if (!scheduled) {\n this.committed = this.head\n }\n }\n}\n\nconst stores = new WeakMap<ReadableActor, ActorStore>()\n\nexport function getStore(actor: ReadableActor): ActorStore {\n let store = stores.get(actor)\n if (!store) {\n store = new ActorStore(actor)\n stores.set(actor, store)\n }\n return store\n}\n\n/**\n * The `useOptimistic` reducer. React replays it on top of every new base until the transition that\n * sent the event settles, and the actor has already processed the event by the time any base after\n * the send is read. So an event the base already includes is skipped, instead of applied twice.\n */\nexport function reduceOptimistic(current: Entry, action: OptimisticAction): Entry {\n const base =\n action.fallback && action.fallback.version > current.version ? action.fallback : current\n if (base.seq >= action.seq) {\n return base\n }\n try {\n const [snapshot] = transition(action.logic, base.snapshot as never, action.event as never)\n return {snapshot, seq: base.seq, version: base.version}\n } catch {\n // The running actor reports the error itself; the preview falls back to the base.\n return base\n }\n}\n","import {useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState} from 'react'\nimport {\n _hotSwapActorLogic as hotSwapActorLogic,\n _toObserver as toObserver,\n Actor,\n createActor,\n type ActorOptions,\n type AnyActorLogic,\n type AnyStateMachine,\n type IsNotNever,\n type Observer,\n type RequiredActorOptionsFor,\n type RequiredActorOptionsKeys,\n type SnapshotFrom,\n} from 'xstate'\n\nimport {getStore, type BindingOptions} from './store'\n\n/**\n * `useActor`, `useActorRef` and `createActorContext` options: the actor's own options, read once\n * when the actor is created, and how its snapshots reach React.\n *\n * @public\n */\nexport type HookOptions<TLogic extends AnyActorLogic> = ActorOptions<TLogic> & BindingOptions\n\nfunction isStateMachine(logic: AnyActorLogic): logic is AnyStateMachine {\n return (\n typeof (logic as any).provide === 'function' &&\n !!(logic as any).config &&\n !!(logic as any).sources\n )\n}\n\nexport function isActor(value: unknown): value is Actor<AnyActorLogic> {\n return value instanceof Actor\n}\n\n// The hook updates the sources of its machine on later renders. A per-hook copy keeps those\n// updates from reaching the caller's machine, which other actors may share.\nfunction ownLogic<TLogic extends AnyActorLogic>(logic: TLogic): TLogic {\n return isStateMachine(logic) ? (logic.provide({}) as any) : logic\n}\n\nfunction create<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options: HookOptions<TLogic> | undefined,\n): Actor<TLogic> {\n const {updates, ...actorOptions} = options ?? {}\n const actor = createActor(logic, actorOptions as ActorOptions<TLogic>)\n if (updates) {\n getStore(actor).updates = updates\n }\n return actor\n}\n\nfunction adoptLogic<TLogic extends AnyActorLogic>(\n actorRef: Actor<TLogic>,\n logic: TLogic,\n refreshed: boolean,\n options: HookOptions<TLogic> | undefined,\n setActorRef: (actorRef: Actor<TLogic>) => void,\n): void {\n const currentLogic = actorRef.logic\n if ((logic as any).config === (currentLogic as any).config) {\n if (isStateMachine(logic) && isStateMachine(currentLogic)) {\n currentLogic.sources = logic.sources\n }\n return\n }\n // Fast Refresh re-evaluated the module that defines the machine: keep the running actor and\n // carry its live snapshot over, or start a fresh actor if it cannot be carried.\n if (refreshed) {\n const nextLogic = ownLogic(logic)\n if (!hotSwapActorLogic(actorRef, nextLogic as any as AnyStateMachine)) {\n setActorRef(create(nextLogic, options))\n }\n }\n}\n\nexport function useIdleActorRef<TLogic extends AnyActorLogic>(\n logicOrActor: TLogic | Actor<TLogic>,\n options: HookOptions<TLogic> | undefined,\n): [Actor<TLogic>, (actorRef: Actor<TLogic>) => void] {\n // React Compiler would turn the `useMemo` below into a cache slot that Fast Refresh never resets.\n 'use no memo'\n const [actorRef, setActorRef] = useState(() =>\n isActor(logicOrActor) ? logicOrActor : create(ownLogic(logicOrActor), options),\n )\n // Its identity changes only when React Fast Refresh re-renders this component: Fast Refresh\n // ignores dependency lists while it applies an update.\n const refreshSignal = useMemo(() => ({}), [])\n const refreshSignalRef = useRef(refreshSignal)\n\n // The logic passed on the first render is used for the hook's lifetime. Later renders only\n // contribute implementations provided with `machine.provide()` for the same machine config.\n useLayoutEffect(() => {\n const refreshed = refreshSignalRef.current !== refreshSignal\n refreshSignalRef.current = refreshSignal\n if (!isActor(logicOrActor)) {\n adoptLogic(actorRef, logicOrActor, refreshed, options, setActorRef)\n }\n }, [actorRef, logicOrActor, refreshSignal, options])\n\n return [actorRef, setActorRef]\n}\n\nexport function useActorLifecycle<TLogic extends AnyActorLogic>(\n actorRef: Actor<TLogic>,\n setActorRef: (actorRef: Actor<TLogic>) => void,\n createReplacement: () => Actor<TLogic>,\n): void {\n const pendingStopsRef = useRef(new Map<Actor<TLogic>, () => void>())\n const replace = useEffectEvent(() => setActorRef(createReplacement()))\n\n useEffect(() => {\n const pendingStops = pendingStopsRef.current\n const cancelPendingStop = pendingStops.get(actorRef)\n if (cancelPendingStop) {\n cancelPendingStop()\n pendingStops.delete(actorRef)\n }\n\n // A stopped actor cannot be restarted, so one that stopped before this effect reconnected is\n // replaced.\n if (\n (actorRef as any)._processingStatus === 2 &&\n (actorRef.getSnapshot() as any)?.status === 'stopped'\n ) {\n replace()\n return\n }\n\n actorRef.start()\n // Stopping waits a microtask so that StrictMode's simulated unmount and remount, and a move\n // within the tree, keep the running actor.\n return () => {\n let canceled = false\n const cancel = () => {\n canceled = true\n }\n pendingStops.set(actorRef, cancel)\n queueMicrotask(() => {\n if (!canceled) {\n actorRef.stop()\n }\n if (pendingStops.get(actorRef) === cancel) {\n pendingStops.delete(actorRef)\n }\n })\n }\n }, [actorRef])\n}\n\n/** Creates an actor to replace a stopped one, keeping how its snapshots reach React. */\nexport function recreate<TLogic extends AnyActorLogic>(\n actorRef: Actor<TLogic>,\n options: ActorOptions<TLogic> | undefined,\n): Actor<TLogic> {\n return create(actorRef.logic, {...options, updates: getStore(actorRef).updates})\n}\n\n/**\n * Creates an actor from `logic` (or uses an already-created `actor`, e.g. from `restoreActor`),\n * starts it on mount and stops it on unmount. Create a passed actor once, e.g.\n * `useState(() => restoreActor(machine, persisted))[0]`.\n *\n * The logic passed on the first render is used for the component's lifetime. To start over, or to\n * switch to a different machine, change the component's `key`.\n *\n * @public\n */\nexport function useActorRef<TLogic extends AnyActorLogic>(\n actor: Actor<TLogic>,\n observerOrListener?: Observer<SnapshotFrom<TLogic>> | ((value: SnapshotFrom<TLogic>) => void),\n): Actor<TLogic>\n/** @public */\nexport function useActorRef<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options, observerOrListener]: IsNotNever<RequiredActorOptionsKeys<TLogic>> extends true\n ? [\n options: HookOptions<TLogic> & RequiredActorOptionsFor<TLogic>,\n observerOrListener?:\n | Observer<SnapshotFrom<TLogic>>\n | ((value: SnapshotFrom<TLogic>) => void),\n ]\n : [\n options?: HookOptions<TLogic>,\n observerOrListener?:\n | Observer<SnapshotFrom<TLogic>>\n | ((value: SnapshotFrom<TLogic>) => void),\n ]\n): Actor<TLogic>\nexport function useActorRef(\n logicOrActor: AnyActorLogic | Actor<AnyActorLogic>,\n ...args: any[]\n): Actor<AnyActorLogic> {\n const readyActor = isActor(logicOrActor)\n const options: HookOptions<AnyActorLogic> | undefined = readyActor ? undefined : args[0]\n const observerOrListener: Observer<unknown> | ((value: unknown) => void) | undefined = readyActor\n ? args[0]\n : args[1]\n const [actorRef, setActorRef] = useIdleActorRef(logicOrActor, options)\n\n useEffect(() => {\n if (!observerOrListener) {\n return\n }\n const subscription = actorRef.subscribe(toObserver(observerOrListener))\n return () => subscription.unsubscribe()\n }, [actorRef, observerOrListener])\n\n useActorLifecycle(actorRef, setActorRef, () => recreate(actorRef, actorRef.options))\n\n return actorRef\n}\n","import {\n startTransition,\n useEffect,\n useInsertionEffect,\n useLayoutEffect,\n useOptimistic,\n useRef,\n useState,\n} from 'react'\n\nimport {reduceOptimistic, type ActorStore, type Entry, type OptimisticAction} from './store'\n\ninterface State<T> {\n readonly store: ActorStore | undefined\n readonly entry: Entry | undefined\n readonly selected: T\n /** Whether `entry` came from a snapshot change rather than from mounting. */\n readonly updated: boolean\n}\n\nconst emptyEntry: Entry = {snapshot: undefined, seq: 0, version: 0}\n\nfunction isErrored(snapshot: unknown): snapshot is {error: unknown} {\n return (\n !!snapshot &&\n typeof snapshot === 'object' &&\n 'status' in snapshot &&\n snapshot.status === 'error' &&\n 'error' in snapshot\n )\n}\n\n/**\n * Reads `selector(snapshot)` from the actor behind `store`.\n *\n * The snapshot lives in React state, so an update that `send` or a transition causes renders, and\n * commits, together with the rest of that transition. Events sent with the store's `send` are\n * previewed with `useOptimistic` until the transition that sent them settles, which keeps\n * controlled inputs in sync.\n */\nexport function useStoreSelection<T>(\n store: ActorStore | undefined,\n selector: (snapshot: any) => T,\n compare: (a: T, b: T) => boolean,\n): T {\n const [state, setState] = useState<State<T>>(() => {\n const entry = store?.head\n return {store, entry, selected: selector(entry?.snapshot), updated: false}\n })\n const current = state.store === store ? state : undefined\n const base = current ? current.entry : store?.head\n const [optimistic, addOptimistic] = useOptimistic(base ?? emptyEntry, reduceOptimistic)\n\n const selectorRef = useRef(selector)\n const compareRef = useRef(compare)\n const stateRef = useRef(state)\n const lagTargetRef = useRef<Entry | undefined>(undefined)\n useLayoutEffect(() => {\n selectorRef.current = selector\n compareRef.current = compare\n stateRef.current = state\n })\n\n // Insertion effects of a commit all run before its layout effects, so by the time a component\n // that mounts in this commit checks `store.committed`, it already includes this commit.\n useInsertionEffect(() => {\n if (store && current?.updated && current.entry) {\n store.commit(current.entry)\n }\n }, [store, current])\n\n // A component that mounts while a transition is changing the actor renders that transition's\n // snapshot, which is right only if the transition is the render that mounts it. Otherwise it\n // shows the committed snapshot before paint, and catches up when the other readers commit.\n // Only the snapshot the component mounted with is checked, so it is read from `stateRef`.\n useLayoutEffect(() => {\n lagTargetRef.current = undefined\n const mounted = stateRef.current\n if (!store || mounted.store !== store || mounted.updated || mounted.entry === store.committed) {\n return\n }\n const target = mounted.entry\n lagTargetRef.current = target\n const show = (entry: Entry) => {\n const next: State<T> = {\n store,\n entry,\n selected: selectorRef.current(entry.snapshot),\n updated: true,\n }\n stateRef.current = next\n setState(next)\n }\n show(store.committed)\n const stopLagging = store.lag(() => {\n const {committed} = store\n if (committed.version > (stateRef.current.entry?.version ?? 0)) {\n show(committed)\n }\n if (!target || committed.version >= target.version) {\n stopLagging()\n }\n })\n return stopLagging\n }, [store])\n\n useLayoutEffect(() => {\n if (store && current?.updated) {\n store.catchUp()\n }\n }, [store, current])\n\n useEffect(() => {\n if (!store) {\n return\n }\n let skipped: Entry | undefined\n\n function apply(entry: Entry, asTransition: boolean): boolean {\n const previous = stateRef.current\n if (previous.store === store && previous.entry === entry) {\n return false\n }\n const selected = selectorRef.current(entry.snapshot)\n // The selection did not change, so there is nothing to render. The entry is still the\n // newest base for previewing events this component did not render the outcome of.\n if (\n previous.store === store &&\n !isErrored(entry.snapshot) &&\n compareRef.current(previous.selected, selected)\n ) {\n skipped = entry\n return false\n }\n skipped = undefined\n const next: State<T> = {store, entry, selected, updated: true}\n stateRef.current = next\n if (asTransition) {\n startTransition(() => setState(next))\n } else {\n setState(next)\n }\n return true\n }\n\n const unsubscribe = store.subscribe({\n update(entry, sentInTransition) {\n return apply(entry, sentInTransition || store.updates === 'transition')\n },\n optimistic(action) {\n startTransition(() => addOptimistic({...action, fallback: skipped} as OptimisticAction))\n },\n })\n // The snapshot may have changed between render and subscribing.\n const seen = stateRef.current.store === store ? stateRef.current.entry : undefined\n const known = Math.max(seen?.version ?? -1, lagTargetRef.current?.version ?? -1)\n if (store.head.version > known) {\n apply(store.head, store.updates === 'transition')\n }\n return unsubscribe\n }, [store, addOptimistic])\n\n const entry = optimistic === emptyEntry ? undefined : optimistic\n const snapshot = entry?.snapshot\n if (isErrored(snapshot)) {\n throw snapshot.error\n }\n if (current && entry === current.entry) {\n const selected = selector(snapshot)\n return compare(current.selected, selected) ? current.selected : selected\n }\n return selector(snapshot)\n}\n","import {useMemo} from 'react'\nimport type {AnyActorRef} from 'xstate'\n\nimport {getStore} from './store'\nimport {useStoreSelection} from './useStoreSelection'\n\nfunction defaultCompare<T>(a: T, b: T) {\n return a === b\n}\n\n/**\n * Reads a value derived from an actor's snapshot, and re-renders only when `compare` says it\n * changed.\n *\n * @public\n */\nexport function useSelector<\n TActor extends Pick<AnyActorRef, 'subscribe' | 'getSnapshot'> | undefined,\n T,\n>(\n actor: TActor,\n selector: (\n snapshot: TActor extends {getSnapshot(): infer TSnapshot} ? TSnapshot : undefined,\n ) => T,\n compare: (a: T, b: T) => boolean = defaultCompare,\n): T {\n const store = useMemo(() => (actor ? getStore(actor) : undefined), [actor])\n return useStoreSelection(store, selector, compare)\n}\n","import {useMemo} from 'react'\nimport type {AnyActorRef} from 'xstate'\n\nimport {getStore} from './store'\n\n/**\n * Returns the same `send` that `useActor` returns, for an actor created elsewhere, e.g. with\n * `useActorRef` or `createActorContext`.\n *\n * @public\n */\nexport function useSend<TActor extends AnyActorRef>(actor: TActor): TActor['send'] {\n return useMemo(() => getStore(actor).send, [actor]) as TActor['send']\n}\n","import {createContext, use, type ReactNode} from 'react'\nimport type {Actor, AnyActorLogic, SnapshotFrom} from 'xstate'\n\nimport {useActorRef, type HookOptions} from './useActorRef'\nimport {useSelector as useSelectorUnbound} from './useSelector'\nimport {useSend as useSendUnbound} from './useSend'\n\n/** @public */\nexport interface ActorContext<TLogic extends AnyActorLogic> {\n useSelector: <T>(\n selector: (snapshot: SnapshotFrom<TLogic>) => T,\n compare?: (a: T, b: T) => boolean,\n ) => T\n useActorRef: () => Actor<TLogic>\n /** The provided actor's `send`, with the same transition and optimistic behavior as `useActor`. */\n useSend: () => Actor<TLogic>['send']\n Provider: (props: {\n children: ReactNode\n options?: HookOptions<TLogic>\n logic?: TLogic\n /**\n * An already-created actor (e.g. from `restoreActor`) to provide instead of creating one from\n * `logic` and `options`. Create it once.\n */\n actor?: Actor<TLogic>\n }) => ReactNode\n}\n\n/** @public */\nexport function createActorContext<TLogic extends AnyActorLogic>(\n actorLogic: TLogic,\n actorOptions?: HookOptions<TLogic>,\n): ActorContext<TLogic> {\n const ReactContext = createContext<Actor<TLogic> | null>(null)\n\n function Provider({\n children,\n logic: providedLogic = actorLogic,\n options: providedOptions,\n actor: providedActor,\n }: {\n children: ReactNode\n logic?: TLogic\n options?: HookOptions<TLogic>\n actor?: Actor<TLogic>\n }) {\n const actor = (useActorRef as any)(\n providedActor ?? providedLogic,\n providedActor ? undefined : {...actorOptions, ...providedOptions},\n ) as Actor<TLogic>\n\n return <ReactContext value={actor}>{children}</ReactContext>\n }\n\n Provider.displayName = `ActorProvider`\n\n function useContext(): Actor<TLogic> {\n const actor = use(ReactContext)\n if (!actor) {\n throw new Error(\n `You used a hook from \"${Provider.displayName}\" but it's not inside a <${Provider.displayName}> component.`,\n )\n }\n return actor\n }\n\n function useSelector<T>(\n selector: (snapshot: SnapshotFrom<TLogic>) => T,\n compare?: (a: T, b: T) => boolean,\n ): T {\n return useSelectorUnbound(useContext(), selector, compare)\n }\n\n function useSend(): Actor<TLogic>['send'] {\n return useSendUnbound(useContext())\n }\n\n return {Provider, useActorRef: useContext, useSelector, useSend}\n}\n","function is(x: unknown, y: unknown) {\n if (x === y) {\n return x !== 0 || y !== 0 || 1 / x === 1 / y\n }\n return x !== x && y !== y\n}\n\n/** @public */\nexport function shallowEqual(objA: any, objB: any): boolean {\n if (is(objA, objB)) {\n return true\n }\n if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {\n return false\n }\n const keysA = Object.keys(objA)\n const keysB = Object.keys(objB)\n if (keysA.length !== keysB.length) {\n return false\n }\n for (const key of keysA) {\n if (!Object.prototype.hasOwnProperty.call(objB, key) || !is(objA[key], objB[key])) {\n return false\n }\n }\n return true\n}\n","import {useMemo} from 'react'\nimport type {\n Actor,\n AnyActorLogic,\n ConditionalRequired,\n IsNotNever,\n RequiredActorOptionsFor,\n RequiredActorOptionsKeys,\n SnapshotFrom,\n} from 'xstate'\n\nimport {getStore} from './store'\nimport {\n isActor,\n recreate,\n useActorLifecycle,\n useIdleActorRef,\n type HookOptions,\n} from './useActorRef'\nimport {useStoreSelection} from './useStoreSelection'\n\nfunction identity<T>(value: T): T {\n return value\n}\n\n/**\n * Creates an actor from `logic` (or uses an already-created `actor`, e.g. from `restoreActor`) and\n * subscribes to its snapshot. Create a passed actor once, e.g.\n * `useState(() => restoreActor(machine, persisted))[0]`.\n *\n * `send` is a transition: snapshot updates it causes render together with the transition it is\n * called in, or in a transition of its own. Until that transition settles, the returned snapshot\n * already shows the event's outcome, so a controlled input can call `send` in `onChange`.\n *\n * The logic passed on the first render is used for the component's lifetime, and `input` is read\n * once. To start over, or to switch to a different machine, change the component's `key`.\n *\n * @public\n */\nexport function useActor<TLogic extends AnyActorLogic>(\n actor: Actor<TLogic>,\n): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>]\n/** @public */\nexport function useActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: ConditionalRequired<\n [options?: HookOptions<TLogic> & RequiredActorOptionsFor<TLogic>],\n IsNotNever<RequiredActorOptionsKeys<TLogic>>\n >\n): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>]\nexport function useActor<TLogic extends AnyActorLogic>(\n logic: TLogic | Actor<TLogic>,\n options?: HookOptions<TLogic>,\n): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>] {\n const readyActor = isActor(logic)\n if (!readyActor && !!logic && 'send' in logic && typeof logic.send === 'function') {\n throw new Error(\n `useActor() expects actor logic (e.g. a machine), but received an ActorRef. Pass an Actor created with createActor()/restoreActor(), or use the useSelector(actorRef, ...) hook to read an ActorRef's snapshot.`,\n )\n }\n\n const [actorRef, setActorRef] = useIdleActorRef(logic, options)\n const store = useMemo(() => getStore(actorRef), [actorRef])\n const snapshot = useStoreSelection(store, identity, Object.is) as SnapshotFrom<TLogic>\n\n useActorLifecycle(actorRef, setActorRef, () =>\n recreate(actorRef, readyActor ? actorRef.options : options),\n )\n\n return [snapshot, store.send as Actor<TLogic>['send'], actorRef]\n}\n","import type {\n Actor,\n AnyStateMachine,\n ConditionalRequired,\n IsNotNever,\n RequiredActorOptionsFor,\n RequiredActorOptionsKeys,\n StateFrom,\n} from 'xstate'\n\nimport {useActor} from './useActor'\nimport type {HookOptions} from './useActorRef'\n\n/**\n * @deprecated Use `useActor(machine, options)`.\n * @public\n */\nexport function useMachine<TMachine extends AnyStateMachine>(\n actor: Actor<TMachine>,\n): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>]\n/**\n * @deprecated Use `useActor(machine, options)`.\n * @public\n */\nexport function useMachine<TMachine extends AnyStateMachine>(\n machine: TMachine,\n ...[options]: ConditionalRequired<\n [options?: HookOptions<TMachine> & RequiredActorOptionsFor<TMachine>],\n IsNotNever<RequiredActorOptionsKeys<TMachine>>\n >\n): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>]\nexport function useMachine<TMachine extends AnyStateMachine>(\n machine: TMachine | Actor<TMachine>,\n options?: HookOptions<TMachine>,\n): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>] {\n return (useActor as any)(machine, options)\n}\n"],"mappings":";;;;;AAMA,MAAM,YAAuC,MAC1C;AAEH,SAAS,iBAA0B;CACjC,OAAO,WAAW,KAAK;AACzB;AA8CA,IAAa,aAAb,MAAwB;CACb;CACT,UAAmB;CACnB;;CAEA;CACQ,MAAM;CACN,UAAU;CACV,UAAU;CACD,4BAAY,IAAI,IAAc;CAC9B,0BAAU,IAAI,IAAgB;CACvC;CAER,YAAY,OAAsB;EAChC,KAAK,QAAQ,OACb,KAAK,OAAO;GAAC,UAAU,MAAM,YAAY;GAAG,KAAK;GAAG,SAAS;EAAC,GAC9D,KAAK,YAAY,KAAK;CACxB;CAEA,UAAU,UAAgC;EAExC,IADA,KAAK,UAAU,IAAI,QAAQ,GACvB,CAAC,KAAK,kBAAkB;GAC1B,IAAM,eAAe,KAAK,MAAM,UAAU;IACxC,YAAY,KAAK,KAAK;IACtB,aAAa,KAAK,KAAK;GACzB,CAAC;GACD,KAAK,yBAAyB,aAAa,YAAY,GACvD,KAAK,KAAK;EACZ;EACA,aAAa;GACX,KAAK,UAAU,OAAO,QAAQ,GAC1B,KAAK,UAAU,SAAS,MAC1B,KAAK,mBAAmB,GACxB,KAAK,mBAAmB,KAAA,GACxB,KAAK,YAAY,KAAK;EAE1B;CACF;CAEA,OAAO,OAAoB;EACrB,MAAM,UAAU,KAAK,UAAU,YACjC,KAAK,YAAY;CAErB;;;;;CAMA,IAAI,SAAiC;EAEnC,OADA,KAAK,QAAQ,IAAI,OAAO,SACX,KAAK,QAAQ,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AM,QAAS,YACrE,MAAU,MACR,gNACF;CAGF,IAAM,CAAC,UAAU,eAAe,gBAAgB,OAAO,OAAO,GAClCC;CAAS,EAAA,OAAA,W,aAATA,KAAAA,SAAS,QAAQ,GAAR,EAAA,KAAA,U;CAArC,IAAM,QAAQC,IACR,WAAW,kBAAkB,OAAO,UAAU,OAAO,EAAE,GAEpBC;CACPC,EAAAA,OAAAA,YAAAA,EAAAA,OAAmB,WAAA,EAAA,OAAhC,cADoBD,WACvC,SAAS,UAAU,aAAa,SAAS,UAAU,OAAO,GAA1BC,EAAAA,KAAAA,UAAmB,EAAA,KAAA,SAAhC,EAAA,KAAA,Y,wBADrB,kBAAkB,UAAU,aAAaD,EAEzC;CAEkBE,IAAAA,KAAAA,MAAM,MAAjBC;CAAP,OAAuD,EAAA,OAAA,YAAA,EAAA,OAA/C,YAAA,EAAA,QAAUD,MAAXC,KAAAA;EAAC;EAAUD;EAAqC;CAAQ,GAAR,EAAA,KAAA,UAA/C,EAAA,KAAA,UAAUA,EAAAA,MAAAA,I,0BAAXC;AACT;ACvCA,SAAgB,WACd,SACA,SACiE;CACjE,OAAQ,SAAiB,SAAS,OAAO;AAC3C"}
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@sanity-labs/xstate-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "React 19 bindings for XState v6, built for transitions and useOptimistic",
5
+ "keywords": [
6
+ "concurrent",
7
+ "hooks",
8
+ "react",
9
+ "react19",
10
+ "state-machine",
11
+ "statechart",
12
+ "transitions",
13
+ "useOptimistic",
14
+ "xstate"
15
+ ],
16
+ "homepage": "https://github.com/sanity-labs/xstate#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/sanity-labs/xstate/issues"
19
+ },
20
+ "license": "MIT",
21
+ "author": "Sanity.io <hello@sanity.io>",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/sanity-labs/xstate.git",
25
+ "directory": "packages/xstate-react"
26
+ },
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "type": "module",
31
+ "sideEffects": false,
32
+ "types": "./dist/index.d.ts",
33
+ "exports": {
34
+ ".": "./dist/index.js",
35
+ "./package.json": "./package.json"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "devDependencies": {
41
+ "@sanity/tsconfig": "^2.2.1",
42
+ "@sanity/tsdown-config": "^0.33.0",
43
+ "@testing-library/dom": "^10.4.2",
44
+ "@testing-library/react": "^16.3.3",
45
+ "@types/node": "^26.6.11",
46
+ "@types/react": "^19.3.3",
47
+ "@types/react-dom": "^19.3.0",
48
+ "@vitejs/plugin-react": "^6.3.0",
49
+ "jsdom": "^31.0.1",
50
+ "oxc-transform-react": "^0.158.0",
51
+ "publint": "^0.3.25",
52
+ "react": "^19.3.1",
53
+ "react-dom": "^19.3.1",
54
+ "rxjs": "^7.8.2",
55
+ "tsdown": "^0.23.7",
56
+ "typescript": "7.0.2",
57
+ "vite": "^8.3.8",
58
+ "vitest": "^5.1.2",
59
+ "xstate": "6.0.0-beta.5",
60
+ "zod": "^3.25.76"
61
+ },
62
+ "peerDependencies": {
63
+ "react": "^19.3",
64
+ "xstate": "^6.0.0-beta"
65
+ },
66
+ "engines": {
67
+ "node": "^22.18.0 || >=24.11.0"
68
+ },
69
+ "scripts": {
70
+ "build": "tsdown",
71
+ "test": "vitest run --typecheck",
72
+ "watch": "tsdown --watch"
73
+ }
6
74
  }