Skip to content

Commit 7336851

Browse files
committed
🚧 First Pass at BehavioralFsm Types
1 parent 98e3832 commit 7336851

File tree

5 files changed

+248
-2
lines changed

5 files changed

+248
-2
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,4 @@ desktop.ini
1818
report/
1919
coverage/
2020
bower/
21+
.vscode

package.json

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,8 @@
137137
"open": "~0.0.4",
138138
"should": "^6.0.3",
139139
"sinon": "~1.11.0",
140-
"source-map-loader": "^0.1.5"
140+
"source-map-loader": "^0.1.5",
141+
"typescript": "^3.5.2"
141142
},
142143
"licenses": [
143144
{
@@ -151,6 +152,7 @@
151152
],
152153
"scripts": {
153154
"build": "gulp",
155+
"build-types": "tsc",
154156
"start": "gulp server",
155157
"test": "./node_modules/mocha/bin/mocha -r spec/helpers/node-setup.js spec",
156158
"mocha": "gulp mocha",
@@ -159,5 +161,6 @@
159161
"lint": "gulp lint",
160162
"format": "gulp format",
161163
"watch": "gulp watch"
162-
}
164+
},
165+
"types": "./types/index.d.ts"
163166
}

tsconfig.json

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
{
2+
"compilerOptions": {
3+
/* Basic Options */
4+
// "incremental": true, /* Enable incremental compilation */
5+
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
6+
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
7+
// "lib": [], /* Specify library files to be included in the compilation. */
8+
// "allowJs": true, /* Allow javascript files to be compiled. */
9+
// "checkJs": true, /* Report errors in .js files. */
10+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
11+
// "declaration": true, /* Generates corresponding '.d.ts' file. */
12+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
13+
// "sourceMap": true, /* Generates corresponding '.map' file. */
14+
// "outFile": "./", /* Concatenate and emit output to single file. */
15+
// "outDir": "./", /* Redirect output structure to the directory. */
16+
"rootDir": "./types", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
17+
// "composite": true, /* Enable project compilation */
18+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
19+
// "removeComments": true, /* Do not emit comments to output. */
20+
"noEmit": true, /* Do not emit outputs. */
21+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
22+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
23+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
24+
25+
/* Strict Type-Checking Options */
26+
"strict": true, /* Enable all strict type-checking options. */
27+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
28+
// "strictNullChecks": true, /* Enable strict null checks. */
29+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
30+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
31+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
32+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
33+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
34+
35+
/* Additional Checks */
36+
// "noUnusedLocals": true, /* Report errors on unused locals. */
37+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
38+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
39+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
40+
41+
/* Module Resolution Options */
42+
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
43+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
44+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
45+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
46+
// "typeRoots": [], /* List of folders to include type definitions from. */
47+
// "types": [], /* Type declaration files to be included in compilation. */
48+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
49+
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
50+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
51+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
52+
53+
/* Source Map Options */
54+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
55+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
56+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
57+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
58+
59+
/* Experimental Options */
60+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
61+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
62+
}
63+
}

types/BehaviorialFsmTests.ts

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import {
2+
BehavioralFsm,
3+
BehavioralFsmInstance,
4+
StateTransitions,
5+
BehavioralFsmHandler
6+
} from 'machina';
7+
8+
type SignalStates = 'uninitialized'
9+
| 'green'
10+
| 'green-interruptible'
11+
| 'yellow'
12+
| 'red';
13+
14+
interface LightInstance extends BehavioralFsmInstance<SignalStates> {
15+
location: string;
16+
direction: string;
17+
timer?: number;
18+
}
19+
20+
const states: StateTransitions<LightInstance, SignalStates> = {
21+
uninitialized: {
22+
'*': function(client) {
23+
this.deferUntilTransition(client);
24+
this.transition(client, 'green');
25+
}
26+
},
27+
28+
green: {
29+
_onEnter: function(client) {
30+
client.timer = setTimeout(() => {
31+
this.handle(client, 'timeout');
32+
}, 30000);
33+
34+
this.emit('vehicles', { client: client, status: 'green' });
35+
},
36+
37+
timeout: 'green-interruptible',
38+
39+
pedestrianWaiting: function(client) {
40+
this.deferUntilTransition(client, 'green-interruptible');
41+
},
42+
43+
_onExit: function(client) {
44+
clearTimeout(client.timer);
45+
}
46+
},
47+
48+
'green-interruptible': {
49+
pedestrianWaiting: 'yellow'
50+
},
51+
52+
yellow: {
53+
_onEnter: function(client) {
54+
client.timer = setTimeout(() => {
55+
this.handle(client, 'timeout');
56+
}, 5000);
57+
58+
this.emit('vehicles', { client: client, status: 'yellow' });
59+
},
60+
61+
timeout: 'red',
62+
63+
_onExit: function(client) {
64+
clearTimeout(client.timer);
65+
}
66+
},
67+
68+
red: {
69+
_onEnter: function(client) {
70+
client.timer = setTimeout(() => {
71+
this.handle(client, 'timeout');
72+
}, 1000);
73+
},
74+
75+
_reset: 'green',
76+
77+
_onExit: function(client) {
78+
clearTimeout(client.timer);
79+
}
80+
}
81+
}
82+
83+
interface Handlers {
84+
reset: BehavioralFsmHandler<LightInstance, SignalStates>;
85+
pedestrianWaiting: BehavioralFsmHandler<LightInstance, SignalStates>;
86+
}
87+
88+
const handlers: Handlers = {
89+
reset: function(client) {
90+
this.handle(client, '_reset');
91+
},
92+
93+
pedestrianWaiting: function(client) {
94+
this.handle(client, 'pedestrianWaiting');
95+
}
96+
}
97+
98+
type VehicleSignalFsm = Handlers & BehavioralFsm<LightInstance, SignalStates>;
99+
100+
const vehicleSignal = new BehavioralFsm<LightInstance, SignalStates>({
101+
initialize: function(options: object) {
102+
for (const key in options) {
103+
console.log(key);
104+
}
105+
},
106+
107+
namespace: 'vehicle-signal',
108+
initialState: 'unitialized',
109+
states,
110+
111+
...handlers
112+
}) as VehicleSignalFsm;
113+
114+
const light1: LightInstance = { location: 'Dijsktra Ave & Hunt Blvd', direction: 'north-south' };
115+
const light2: LightInstance = { location: 'Dijsktra Ave & Hunt Blvd', direction: 'east-west' };
116+
117+
vehicleSignal.pedestrianWaiting(light1);
118+
vehicleSignal.pedestrianWaiting(light2);

types/index.d.ts

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
declare module 'machina' {
2+
interface BehavioralFsmInstance<S> {
3+
__machina__?: {
4+
[namespace: string]: {
5+
targetReplayState: S;
6+
state: S;
7+
priorState: S;
8+
priorAction: string;
9+
currentAction: string;
10+
currentActionArgs: any[];
11+
inputQueue: any[];
12+
inExitHandler: boolean;
13+
}
14+
}
15+
}
16+
17+
type TransitionHandler<T, S> = BehavioralFsmHandler<T, S> | S;
18+
19+
interface StateTransitions<T, S> {
20+
[state: string]: {
21+
'*'?: TransitionHandler<T, S>;
22+
_onEnter?: TransitionHandler<T, S>;
23+
_onExit?: TransitionHandler<T, S>;
24+
timeout?: TransitionHandler<T, S>;
25+
26+
[handler: string]: TransitionHandler<T, S> | undefined;
27+
}
28+
}
29+
30+
interface BehavioralFsmHandler<T extends BehavioralFsmInstance<S>, S> {
31+
(this: BehavioralFsm<T, S>, client: T, ...additionalProps: any[]): any;
32+
}
33+
34+
interface BehavioralFsmOptions<T extends BehavioralFsmInstance<S>, S, M = StateTransitions<T, S>> {
35+
namespace: string;
36+
initialState: string;
37+
38+
states: M;
39+
40+
[handler: string]: string | M | BehavioralFsmHandler<T, S>;
41+
}
42+
43+
class BehavioralFsm<T extends BehavioralFsmInstance<S>, S> {
44+
constructor(options: BehavioralFsmOptions<T, S>);
45+
46+
static extend
47+
<T extends BehavioralFsmInstance<S>, S>
48+
(options: object): BehavioralFsm<T, S>;
49+
50+
initialize(options: object): void;
51+
52+
deferUntilTransition(client: T, state?: S): void;
53+
54+
handle(client: T, action: string, ...additionalProps: any[]): void;
55+
transition(client: T, state: S): void;
56+
57+
emit(event: string, options?: any): void;
58+
off(event: string, callback?: (data?: any) => void): void;
59+
on(event: string, callback: (data?: any) => void): void;
60+
}
61+
}

0 commit comments

Comments
 (0)