Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
10 changes: 10 additions & 0 deletions .changeset/shy-worms-sniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'xstate': minor
---

Add partial descriptor support to `assertEvent(…)`

```ts
// Matches any event with a type that starts with `FEEDBACK.`
assertEvent(event, 'FEEDBACK.*');
```
17 changes: 11 additions & 6 deletions packages/core/src/assert.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { EventObject } from './types.ts';
import { toArray } from './utils.ts';
import { EventDescriptor, EventObject, ExtractEvent } from './types.ts';
import { matchesEventDescriptor, toArray } from './utils.ts';

/**
* Asserts that the given event object is of the specified type or types. Throws
Expand All @@ -26,13 +26,18 @@ import { toArray } from './utils.ts';
*/
export function assertEvent<
TEvent extends EventObject,
TAssertedType extends TEvent['type']
TAssertedDescriptor extends EventDescriptor<TEvent>
>(
event: TEvent,
type: TAssertedType | TAssertedType[]
): asserts event is TEvent & { type: TAssertedType } {
type: TAssertedDescriptor | readonly TAssertedDescriptor[]
): asserts event is ExtractEvent<TEvent, TAssertedDescriptor> {
const types = toArray(type);
if (!types.includes(event.type as any)) {

const matches = types.some((descriptor) =>
matchesEventDescriptor(event.type, descriptor as string)
);

if (!matches) {
const typesText =
types.length === 1
? `type "${types[0]}"`
Expand Down
51 changes: 4 additions & 47 deletions packages/core/src/stateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
WILDCARD
} from './constants.ts';
import { evaluateGuard } from './guards.ts';
import { matchesEventDescriptor } from './utils.ts';
import {
ActionArgs,
AnyEventObject,
Expand Down Expand Up @@ -213,53 +214,9 @@ export function getCandidates<TEvent extends EventObject>(
const candidates =
stateNode.transitions.get(receivedEventType) ||
[...stateNode.transitions.keys()]
.filter((eventDescriptor) => {
// check if transition is a wildcard transition,
// which matches any non-transient events
if (eventDescriptor === WILDCARD) {
return true;
}

if (!eventDescriptor.endsWith('.*')) {
return false;
}

if (isDevelopment && /.*\*.+/.test(eventDescriptor)) {
console.warn(
`Wildcards can only be the last token of an event descriptor (e.g., "event.*") or the entire event descriptor ("*"). Check the "${eventDescriptor}" event.`
);
}

const partialEventTokens = eventDescriptor.split('.');
const eventTokens = receivedEventType.split('.');

for (
let tokenIndex = 0;
tokenIndex < partialEventTokens.length;
tokenIndex++
) {
const partialEventToken = partialEventTokens[tokenIndex];
const eventToken = eventTokens[tokenIndex];

if (partialEventToken === '*') {
const isLastToken = tokenIndex === partialEventTokens.length - 1;

if (isDevelopment && !isLastToken) {
console.warn(
`Infix wildcards in transition events are not allowed. Check the "${eventDescriptor}" transition.`
);
}

return isLastToken;
}

if (partialEventToken !== eventToken) {
return false;
}
}

return true;
})
.filter((eventDescriptor) =>
matchesEventDescriptor(receivedEventType, eventDescriptor)
)
.sort((a, b) => b.length - a.length)
.flatMap((key) => stateNode.transitions.get(key)!);

Expand Down
67 changes: 66 additions & 1 deletion packages/core/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import isDevelopment from '#is-development';
import { isMachineSnapshot } from './State.ts';
import type { StateNode } from './StateNode.ts';
import { TARGETLESS_KEY } from './constants.ts';
import { TARGETLESS_KEY, WILDCARD } from './constants.ts';
import type {
AnyActorRef,
AnyEventObject,
Expand Down Expand Up @@ -279,3 +279,68 @@ export function resolveReferencedActor(machine: AnyStateMachine, src: string) {
export function getAllOwnEventDescriptors(snapshot: AnyMachineSnapshot) {
return [...new Set([...snapshot._nodes.flatMap((sn) => sn.ownEvents)])];
}

/**
* Checks if an event type matches an event descriptor, supporting wildcards.
* Event descriptors can be:
*
* - Exact matches: "event.type"
* - Wildcard: "*"
* - Partial matches: "event.*"
*
* @param eventType - The actual event type string
* @param descriptor - The event descriptor to match against
* @returns True if the event type matches the descriptor
*/
export function matchesEventDescriptor(
eventType: string,
descriptor: string
): boolean {
if (descriptor === eventType) {
return true;
}

if (descriptor === WILDCARD) {
return true;
}

if (!descriptor.endsWith('.*')) {
return false;
}

if (isDevelopment && /.*\*.+/.test(descriptor)) {
console.warn(
`Wildcards can only be the last token of an event descriptor (e.g., "event.*") or the entire event descriptor ("*"). Check the "${descriptor}" event.`
);
}

const partialEventTokens = descriptor.split('.');
const eventTokens = eventType.split('.');

for (
let tokenIndex = 0;
tokenIndex < partialEventTokens.length;
tokenIndex++
) {
const partialEventToken = partialEventTokens[tokenIndex];
const eventToken = eventTokens[tokenIndex];

if (partialEventToken === '*') {
const isLastToken = tokenIndex === partialEventTokens.length - 1;

if (isDevelopment && !isLastToken) {
console.warn(
`Infix wildcards in transition events are not allowed. Check the "${descriptor}" transition.`
);
}

return isLastToken;
}

if (partialEventToken !== eventToken) {
return false;
}
}

return true;
}
81 changes: 80 additions & 1 deletion packages/core/test/eventDescriptors.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createMachine, createActor } from '../src/index';
import { createMachine, createActor, setup, assertEvent } from '../src/index';

describe('event descriptors', () => {
it('should fallback to using wildcard transition definition (if specified)', () => {
Expand Down Expand Up @@ -354,4 +354,83 @@ describe('event descriptors', () => {
]
`);
});

it('should allow assertEvent to use partial descriptors', () => {
type FeedbackEvents =
| {
type: 'FEEDBACK.MESSAGE';
message: string;
}
| {
type: 'FEEDBACK.RATE';
rate: number;
}
| { type: 'OTHER' };

const handleEventSpy = vi.fn();
const machine = setup({
types: {
events: {} as FeedbackEvents
},
actions: {
handleEvent: ({ event }: { event: FeedbackEvents }) => {
assertEvent(event, 'FEEDBACK.*');

if (event.type === 'FEEDBACK.MESSAGE') {
event.message satisfies string;
} else {
event.rate satisfies number;
}

handleEventSpy(event);
}
}
}).createMachine({
initial: 'listening',
states: {
listening: {
on: {
'FEEDBACK.*': {
actions: 'handleEvent'
}
}
}
}
});

const actor = createActor(machine).start();
actor.send({ type: 'FEEDBACK.MESSAGE', message: 'hello' });
actor.send({ type: 'FEEDBACK.RATE', rate: 5 });

expect(handleEventSpy).toHaveBeenCalledTimes(2);
expect(handleEventSpy).toHaveBeenNthCalledWith(1, {
type: 'FEEDBACK.MESSAGE',
message: 'hello'
});
expect(handleEventSpy).toHaveBeenNthCalledWith(2, {
type: 'FEEDBACK.RATE',
rate: 5
});
});

it('should throw if assertEvent partial descriptor does not match', () => {
type FeedbackEvents =
| {
type: 'FEEDBACK.MESSAGE';
message: string;
}
| {
type: 'FEEDBACK.RATE';
rate: number;
}
| { type: 'OTHER' };

const nonFeedbackEvent = { type: 'OTHER' } as FeedbackEvents;

expect(() =>
assertEvent(nonFeedbackEvent, 'FEEDBACK.*')
).toThrowErrorMatchingInlineSnapshot(
`[Error: Expected event {"type":"OTHER"} to have type "FEEDBACK.*"]`
);
});
});