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

Upgrade TS to 3.8.3 and simplify transition config types #1103

Merged
merged 10 commits into from
Apr 4, 2020
Merged
Show file tree
Hide file tree
Changes from 9 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
5 changes: 5 additions & 0 deletions .changeset/curvy-planets-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'xstate': minor
---

Upgraded TypeScript to 3.8.3. This also addresses #1015 and simplifies the `TransitionConfigArray` and `TransitionConfigMap` types.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
"ts-jest": "^24.1.9",
"tslint": "^5.11.0",
"typedoc": "^0.15.2",
"typescript": "^3.7.5",
"typescript": "^3.8.3",
"vuepress": "^1.2.0",
"vuepress-plugin-export": "^0.2.0",
"webpack-dev-middleware": "^3.6.0"
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
"rxjs": "^6.5.1",
"ts-jest": "^24.1.9",
"tslib": "^1.10.0",
"typescript": "^3.7.5",
"typescript": "^3.8.3",
"xml-js": "^1.6.11"
}
}
65 changes: 31 additions & 34 deletions packages/core/src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,14 @@ export class Interpreter<
* - `clock` uses the global `setTimeout` and `clearTimeout` functions
* - `logger` uses the global `console.log()` method
*/
public static defaultOptions: InterpreterOptions = (global => ({
public static defaultOptions: InterpreterOptions = ((global) => ({
execute: true,
deferEvents: true,
clock: {
setTimeout: (fn, ms) => {
return global.setTimeout.call(null, fn, ms);
},
clearTimeout: id => {
clearTimeout: (id) => {
return global.clearTimeout.call(null, id);
}
},
Expand Down Expand Up @@ -294,7 +294,7 @@ export class Interpreter<
if (this.state.configuration && isDone) {
// get final child state node
const finalChildStateNode = state.configuration.find(
sn => sn.type === 'final' && sn.parent === this.machine
(sn) => sn.type === 'final' && sn.parent === this.machine
);

const doneData =
Expand Down Expand Up @@ -505,7 +505,7 @@ export class Interpreter<
}

// Stop all children
this.children.forEach(child => {
this.children.forEach((child) => {
if (isFunction(child.stop)) {
child.stop();
}
Expand Down Expand Up @@ -634,7 +634,7 @@ export class Interpreter<
});

batchedActions.push(
...(nextState.actions.map(a =>
...(nextState.actions.map((a) =>
bindActionToState(a, nextState)
) as Array<ActionObject<TContext, TEvent>>)
);
Expand Down Expand Up @@ -714,7 +714,7 @@ export class Interpreter<
if (
_event.name.indexOf(actionTypes.errorPlatform) === 0 &&
!this.state.nextEvents.some(
nextEvent => nextEvent.indexOf(actionTypes.errorPlatform) === 0
(nextEvent) => nextEvent.indexOf(actionTypes.errorPlatform) === 0
)
) {
throw (_event.data as any).data;
Expand All @@ -740,16 +740,13 @@ export class Interpreter<
}
}
private defer(sendAction: SendActionObject<TContext, TEvent>): void {
this.delayedEventsMap[sendAction.id] = this.clock.setTimeout(
() => {
if (sendAction.to) {
this.sendTo(sendAction._event, sendAction.to);
} else {
this.send(sendAction._event);
}
},
sendAction.delay as number
);
this.delayedEventsMap[sendAction.id] = this.clock.setTimeout(() => {
if (sendAction.to) {
this.sendTo(sendAction._event, sendAction.to);
} else {
this.send(sendAction._event);
}
}, sendAction.delay as number);
}
private cancel(sendId: string | number): void {
this.clock.clearTimeout(this.delayedEventsMap[sendId]);
Expand Down Expand Up @@ -781,7 +778,7 @@ export class Interpreter<
this.parent.send({
type: 'xstate.error',
data: err
});
} as EventObject);
}

throw err;
Expand Down Expand Up @@ -968,7 +965,7 @@ export class Interpreter<
};

if (resolvedOptions.sync) {
childService.onTransition(state => {
childService.onTransition((state) => {
this.send(actionTypes.update as any, {
state,
id: childService.id
Expand All @@ -978,17 +975,17 @@ export class Interpreter<

const actor = childService;

this.children.set(childService.id, actor as Actor<
State<TChildContext, TChildEvent>,
TChildEvent
>);
this.children.set(
childService.id,
actor as Actor<State<TChildContext, TChildEvent>, TChildEvent>
);

if (resolvedOptions.autoForward) {
this.forwardTo.add(childService.id);
}

childService
.onDone(doneEvent => {
.onDone((doneEvent) => {
this.removeChild(childService.id);
this.send(toSCXMLEvent(doneEvent as any, { origin: childService.id }));
})
Expand All @@ -1000,15 +997,15 @@ export class Interpreter<
let canceled = false;

promise.then(
response => {
(response) => {
if (!canceled) {
this.removeChild(id);
this.send(
toSCXMLEvent(doneInvoke(id, response) as any, { origin: id })
);
}
},
errorData => {
(errorData) => {
if (!canceled) {
this.removeChild(id);
const errorEvent = error(id, errorData);
Expand Down Expand Up @@ -1038,7 +1035,7 @@ export class Interpreter<
subscribe: (next, handleError, complete) => {
let unsubscribed = false;
promise.then(
response => {
(response) => {
if (unsubscribed) {
return;
}
Expand All @@ -1048,7 +1045,7 @@ export class Interpreter<
}
complete && complete();
},
err => {
(err) => {
if (unsubscribed) {
return;
}
Expand Down Expand Up @@ -1078,7 +1075,7 @@ export class Interpreter<
const listeners = new Set<(e: EventObject) => void>();

const receive = (e: TEvent) => {
listeners.forEach(listener => listener(e));
listeners.forEach((listener) => listener(e));
if (canceled) {
return;
}
Expand All @@ -1088,7 +1085,7 @@ export class Interpreter<
let callbackStop;

try {
callbackStop = callback(receive, newListener => {
callbackStop = callback(receive, (newListener) => {
receivers.add(newListener);
});
} catch (err) {
Expand All @@ -1103,8 +1100,8 @@ export class Interpreter<

const actor = {
id,
send: event => receivers.forEach(receiver => receiver(event)),
subscribe: next => {
send: (event) => receivers.forEach((receiver) => receiver(event)),
subscribe: (next) => {
listeners.add(next);

return {
Expand Down Expand Up @@ -1133,10 +1130,10 @@ export class Interpreter<
id: string
): Actor {
const subscription = source.subscribe(
value => {
(value) => {
this.send(toSCXMLEvent(value, { origin: id }));
},
err => {
(err) => {
this.removeChild(id);
this.send(toSCXMLEvent(error(id, err) as any, { origin: id }));
},
Expand Down Expand Up @@ -1285,7 +1282,7 @@ export function spawn(
): Actor {
const resolvedOptions = resolveSpawnOptions(nameOrOptions);

return withServiceScope(undefined, service => {
return withServiceScope(undefined, (service) => {
if (!IS_PRODUCTION) {
warn(
!!service,
Expand Down
46 changes: 27 additions & 19 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,32 +321,40 @@ export type StatesDefinition<
>;
};

export type TransitionConfigTargetShortcut<
export type TransitionConfigTarget<TContext, TEvent extends EventObject> =
| string
| undefined
| StateNode<TContext, any, TEvent>;

export type TransitionConfigOrTarget<
TContext,
TEvent extends EventObject
> = string | undefined | StateNode<TContext, any, TEvent>;
> = SingleOrArray<
TransitionConfigTarget<TContext, TEvent> | TransitionConfig<TContext, TEvent>
>;

type TransitionsConfigMap<TContext, TEvent extends EventObject> = {
[K in TEvent['type'] | NullEvent['type'] | '*']?: SingleOrArray<
| TransitionConfigTargetShortcut<TContext, TEvent>
| (TransitionConfig<
TContext,
K extends TEvent['type'] ? Extract<TEvent, { type: K }> : EventObject
> & {
event?: undefined;
})
[K in TEvent['type']]?: TransitionConfigOrTarget<
TContext,
TEvent extends { type: K } ? TEvent : never
>;
} & {
''?: TransitionConfigOrTarget<TContext, TEvent>;
} & {
'*'?: TransitionConfigOrTarget<TContext, TEvent>;
};

type TransitionsConfigArray<TContext, TEvent extends EventObject> = Array<
{
[K in TEvent['type'] | NullEvent['type'] | '*']: TransitionConfig<
TContext,
K extends TEvent['type'] ? Extract<TEvent, { type: K }> : EventObject
> & {
event: K;
};
}[TEvent['type'] | NullEvent['type'] | '*']
| {
[K in TEvent['type']]: TransitionConfig<
TContext,
TEvent extends { type: K } ? TEvent : never
> & {
event: K;
};
}[TEvent['type']]
| (TransitionConfig<TContext, TEvent> & { event: '' })
| (TransitionConfig<TContext, TEvent> & { event: '*' })
>;

export type TransitionsConfig<TContext, TEvent extends EventObject> =
Expand Down Expand Up @@ -905,7 +913,7 @@ export interface PureAction<TContext, TEvent extends EventObject>
export interface ChooseAction<TContext, TEvent extends EventObject>
extends ActionObject<TContext, TEvent> {
type: ActionTypes.Choose;
conds: ChooseConditon<TContext, TEvent>[];
conds: Array<ChooseConditon<TContext, TEvent>>;
}

export interface TransitionDefinition<TContext, TEvent extends EventObject>
Expand Down
22 changes: 11 additions & 11 deletions packages/core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
StateLike,
EventData,
TransitionConfig,
TransitionConfigTargetShortcut,
TransitionConfigTarget,
NullEvent,
SingleOrArray,
Guard,
Expand Down Expand Up @@ -59,7 +59,7 @@ export function matchesState(
return parentStateValue in childStateValue;
}

return keys(parentStateValue).every(key => {
return keys(parentStateValue).every((key) => {
if (!(key in childStateValue)) {
return false;
}
Expand Down Expand Up @@ -113,10 +113,10 @@ export function toStatePath(
export function isStateLike(state: any): state is StateLike<any> {
return (
typeof state === 'object' &&
('value' in state &&
'context' in state &&
'event' in state &&
'_event' in state)
'value' in state &&
'context' in state &&
'event' in state &&
'_event' in state
);
}

Expand Down Expand Up @@ -225,7 +225,7 @@ export function nestedPath<T extends Record<string, any>>(
props: string[],
accessorProp: keyof T
): (object: T) => T {
return object => {
return (object) => {
let result: T = object;

for (const prop of props) {
Expand All @@ -246,7 +246,7 @@ export function toStatePaths(stateValue: StateValue | undefined): string[][] {
}

const result = flatten(
keys(stateValue).map(key => {
keys(stateValue).map((key) => {
const subStateValue = stateValue[key];

if (
Expand All @@ -256,7 +256,7 @@ export function toStatePaths(stateValue: StateValue | undefined): string[][] {
return [[key]];
}

return toStatePaths(stateValue[key]).map(subPath => {
return toStatePaths(stateValue[key]).map((subPath) => {
return [key].concat(subPath);
});
})
Expand Down Expand Up @@ -584,14 +584,14 @@ export function toTransitionConfigArray<TContext, TEvent extends EventObject>(
event: TEvent['type'] | NullEvent['type'] | '*',
configLike: SingleOrArray<
| TransitionConfig<TContext, TEvent>
| TransitionConfigTargetShortcut<TContext, TEvent>
| TransitionConfigTarget<TContext, TEvent>
>
): Array<
TransitionConfig<TContext, TEvent> & {
event: TEvent['type'] | NullEvent['type'] | '*';
}
> {
const transitions = toArrayStrict(configLike).map(transitionLike => {
const transitions = toArrayStrict(configLike).map((transitionLike) => {
if (
typeof transitionLike === 'undefined' ||
typeof transitionLike === 'string' ||
Expand Down
7 changes: 5 additions & 2 deletions packages/core/test/actionCreators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { toSCXMLEvent } from '../src/utils';
const { actionTypes } = actions;

describe('action creators', () => {
['start', 'stop'].forEach(actionKey => {
['start', 'stop'].forEach((actionKey) => {
describe(`${actionKey}()`, () => {
it('should accept a string action', () => {
const action = actions[actionKey]('test');
Expand Down Expand Up @@ -111,7 +111,10 @@ describe('action creators', () => {
const resolvedAction = actions.resolveSend(
action,
{ delay: 100 },
toSCXMLEvent({ type: 'EVENT', value: 50 })
toSCXMLEvent({ type: 'EVENT', value: 50 } as {
type: 'EVENT';
value: number;
})
);

expect(resolvedAction.delay).toEqual(150);
Expand Down
Loading