Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[@xstate/store] Add store.inspect(…) #5027

Merged
merged 3 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/sweet-tools-compare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@xstate/store': minor
---

You can now inspect XState stores using the `.inspect(inspector)` method:

```ts
import { someStore } from './someStore';

someStore.inspect((inspEv) => {
console.log(inspEv);
// logs "@xstate.event" events and "@xstate.snapshot" events
// whenever an event is sent to the store
});
// The "@xstate.actor" event is immediately logged
```
3 changes: 2 additions & 1 deletion packages/core/src/inspection.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
ActorRefLike,
AnyActorRef,
AnyEventObject,
AnyTransitionDefinition,
Expand All @@ -21,7 +22,7 @@ interface BaseInspectionEventProperties {
* - For event events, this is the target `actorRef` (recipient of event).
* - For actor events, this is the `actorRef` of the registered actor.
*/
actorRef: AnyActorRef;
actorRef: ActorRefLike;
}

export interface InspectedSnapshotEvent extends BaseInspectionEventProperties {
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1981,6 +1981,11 @@ export interface ActorRef<

export type AnyActorRef = ActorRef<any, any, any>;

export type ActorRefLike = Pick<
AnyActorRef,
'sessionId' | 'send' | 'getSnapshot'
>;

export type UnknownActorRef = ActorRef<Snapshot<unknown>, EventObject>;

export type ActorLogicFrom<T> = ReturnTypeOrValue<T> extends infer R
Expand Down
54 changes: 54 additions & 0 deletions packages/xstate-store/src/store.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { InspectionEvent } from 'xstate';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@xstate/store doesn't depend on xstate, you can't reach for its types here

import {
Recipe,
EventPayloadMap,
Expand Down Expand Up @@ -41,6 +42,11 @@ function setter<TContext extends StoreContext>(
return recipe(context);
}

const inspectionObservers = new WeakMap<
Store<any, any>,
Set<Observer<InspectionEvent>>
>();

function createStoreCore<
TContext extends StoreContext,
TEventPayloadMap extends EventPayloadMap
Expand Down Expand Up @@ -76,11 +82,31 @@ function createStoreCore<
function receive(event: StoreEvent) {
currentSnapshot = transition(currentSnapshot, event);

inspectionObservers.get(store)?.forEach((observer) => {
observer.next?.({
type: '@xstate.snapshot',
event,
snapshot: currentSnapshot,
actorRef: store,
rootId: store.sessionId
});
});

observers?.forEach((o) => o.next?.(currentSnapshot));
}

const store: Store<TContext, StoreEvent> = {
sessionId: 'test',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:cough: :cough:

send(event) {
inspectionObservers.get(store)?.forEach((observer) => {
observer.next?.({
type: '@xstate.event',
event,
sourceRef: undefined,
actorRef: store,
rootId: store.sessionId
});
});
receive(event as unknown as StoreEvent);
},
getSnapshot() {
Expand All @@ -102,6 +128,34 @@ function createStoreCore<
},
[symbolObservable](): InteropSubscribable<StoreSnapshot<TContext>> {
return this;
},
inspect: (observerOrFn) => {
const observer = toObserver(observerOrFn);
inspectionObservers.set(
store,
inspectionObservers.get(store) ?? new Set()
);
inspectionObservers.get(store)!.add(observer);

observer.next?.({
type: '@xstate.actor',
actorRef: store,
rootId: store.sessionId
});

observer.next?.({
type: '@xstate.snapshot',
snapshot: initialSnapshot,
event: { type: '@xstate.init' },
actorRef: store,
rootId: store.sessionId
});

return {
unsubscribe() {
return inspectionObservers.get(store)?.delete(observer);
}
};
}
};

Expand Down
15 changes: 15 additions & 0 deletions packages/xstate-store/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { InspectionEvent } from 'xstate';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


export type EventPayloadMap = Record<string, {} | null | undefined>;

export type ExtractEventsFromPayloadMap<T extends EventPayloadMap> = Values<{
Expand Down Expand Up @@ -64,6 +66,19 @@ export interface Store<TContext, Ev extends EventObject>
send: (event: Ev) => void;
getSnapshot: () => StoreSnapshot<TContext>;
getInitialSnapshot: () => StoreSnapshot<TContext>;
/**
* Subscribes to [inspection events](https://stately.ai/docs/inspection) from
* the store.
*
* Inspectors that call `store.inspect(…)` will immediately receive an
* "@xstate.actor" inspection event.
*/
inspect: (
observer:
| Observer<InspectionEvent>
| ((inspectionEvent: InspectionEvent) => void)
) => Subscription;
sessionId: string;
}

export type SnapshotFromStore<TStore extends Store<any, any>> =
Expand Down
37 changes: 37 additions & 0 deletions packages/xstate-store/test/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,40 @@ it('can be observed', () => {

expect(counts).toEqual([1, 2, 3]);
});

it('can be inspected', () => {
const store = createStore(
{
count: 0
},
{
inc: {
count: (ctx) => ctx.count + 1
}
}
);

const evs: any[] = [];

store.inspect((ev) => evs.push(ev));

store.send({ type: 'inc' });

expect(evs).toEqual([
expect.objectContaining({
type: '@xstate.actor'
}),
expect.objectContaining({
type: '@xstate.snapshot',
snapshot: expect.objectContaining({ context: { count: 0 } })
}),
expect.objectContaining({
type: '@xstate.event',
event: { type: 'inc' }
}),
expect.objectContaining({
type: '@xstate.snapshot',
snapshot: expect.objectContaining({ context: { count: 1 } })
})
]);
});
Loading