-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
286 lines (245 loc) · 7.76 KB
/
index.ts
File metadata and controls
286 lines (245 loc) · 7.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import Hypercore from "hypercore";
import { Duplex } from "streamx";
// Core type definitions with proper generic constraints
export type MachineConfig<
TContext extends Record<string, any> = Record<string, any>,
TStates extends Record<string, StateConfig<TContext>> = Record<
string,
StateConfig<TContext>
>,
> = {
initial: keyof TStates;
context: TContext;
states: TStates;
};
export type StateConfig<TContext extends Record<string, any>> = {
on: Record<string, TransitionConfig<TContext>>;
};
export type TransitionConfig<TContext extends Record<string, any>> = {
target: string;
action: (ctx: TContext, ...args: any[]) => void | Promise<void>;
};
// Type utilities for extracting information from machine definitions
export type ExtractContext<T> =
T extends MachineConfig<infer C, any> ? C : never;
export type ExtractStates<T> =
T extends MachineConfig<any, infer S> ? keyof S : never;
type ExtractActions<T> =
T extends MachineConfig<any, infer S>
? S extends Record<string, { on: Record<infer E, any> }>
? E
: never
: never;
// Extract action parameter types for specific actions
type ExtractActionParams<T, E extends string> =
T extends MachineConfig<any, infer S>
? {
[K in keyof S]: S[K] extends {
on: Record<E, { action: (ctx: any, ...args: infer P) => any }>;
}
? P extends [infer First, ...any[]]
? First
: undefined
: never;
}[keyof S]
: never;
// Extract all action signatures from a machine
type ExtractActionSignatures<T> =
T extends MachineConfig<any, infer S>
? {
[K in ExtractActions<T>]: ExtractActionParams<
T,
K extends string ? K : never
> extends never
? undefined
: ExtractActionParams<T, K extends string ? K : never>;
}
: never;
// Improved createMachine function with better type inference
export function createMachine<
TContext extends Record<string, any>,
TStates extends Record<string, StateConfig<TContext>>,
>(
config: MachineConfig<TContext, TStates> & {
initial: keyof TStates;
context: TContext;
states: TStates;
},
): MachineConfig<TContext, TStates> {
return config;
}
// Utility function to infer action types and payloads
export function inferActions<T extends MachineConfig<any, any>>(
machine: T,
): ExtractActionSignatures<T> {
const result = {} as any;
// Collect all action names from all states
for (const stateName in machine.states) {
const state = machine.states[stateName];
for (const action in state.on) {
result[action] = undefined; // Placeholder for type inference
}
}
return result as ExtractActionSignatures<T>;
}
export type Infer<T extends MachineConfig<any, any>> = ReturnType<
typeof inferActions<T>
>;
export type ActionMessage<T extends MachineConfig<any, any>> = {
[E in ExtractActions<T> & string]: ExtractActionParams<T, E> extends never
? { action: E; value?: undefined }
: undefined extends ExtractActionParams<T, E>
? { action: E; value?: ExtractActionParams<T, E> }
: { action: E; value: ExtractActionParams<T, E> };
}[ExtractActions<T> & string];
export type StateMessage<T extends MachineConfig<any, any>> = {
previousState?: ExtractStates<T>;
state: ExtractStates<T>;
context: ExtractContext<T>;
};
interface CoremachineOptions {
eager?: boolean;
}
export class Coremachine<T extends MachineConfig<any, any>> extends Duplex<
ActionMessage<T>,
StateMessage<T>
> {
private _core: Hypercore;
private _machine: T;
private _state: ExtractStates<T>;
private _context: ExtractContext<T>;
private _currentIndex: number | null = null;
private _eager = false;
constructor(core: Hypercore, machine: T, opts: CoremachineOptions = {}) {
super();
this._core = core;
this._machine = machine;
this._state = machine.initial as any;
this._context = structuredClone(machine.context);
this._eager = Boolean(opts.eager);
}
_open(cb: (err?: Error | null) => void) {
this._core
.ready()
.then(async () => {
let lastState: {
state: ExtractStates<T>;
context: ExtractContext<T>;
} | null = null;
if (this._core.length > 0) {
lastState = await this._core.get(this._core.length - 1);
this._state = lastState.state;
this._context = lastState.context;
}
const currentState = this._machine.states[this._state];
if (currentState?.on.enter?.target) {
this._state = currentState.on.enter.target;
}
if (currentState?.on.enter?.action) {
await currentState.on.enter.action(this._context, this._state);
}
if (this._eager) {
// @ts-ignore
this.push({
previousState: lastState?.state || null,
state: this._state,
context: this._context,
});
}
cb();
})
.catch(cb);
}
_write(chunk: ActionMessage<T>, cb: (err?: Error | null) => void) {
this.action(chunk.action, chunk.value)
.then(() => cb())
.catch((e) => cb(e));
}
_read(cb: (err?: Error | null) => void) {
cb();
}
_destroy(cb: (err?: Error | null) => void) {
this._core.close().then(() => cb(), cb);
}
async action<E extends ExtractActions<T>>(
action: E,
value?: ExtractActionParams<T, E extends string ? E : never>,
): Promise<{
state: ExtractStates<T>;
context: ExtractContext<T>;
}> {
const previousState = this._state;
const currentState = this._machine.states[this._state];
const transition =
currentState?.on[action as string] ||
this._machine.states.all?.[action as string];
if (!transition) {
throw new Error(
`Invalid action: ${String(action)} for state ${this._state as string}`,
);
}
if (currentState.on.exit?.action) {
await currentState.on.exit.action(this._context, this._state);
}
await transition.action(this._context, value);
await this._core.append({
state: transition.target || this._state,
context: this._context,
});
this._state = (transition.target as ExtractStates<T>) || this._state;
// handle enter action if exists in state definition
if (this._machine.states[this._state].on.enter?.action) {
await this._machine.states[this._state].on.enter.action(
this._context,
this._state,
);
}
// @ts-ignore
this.push({
previousState,
state: this._state,
context: this._context,
});
return { state: this._state, context: this._context };
}
async forward() {
const newIndex =
this._currentIndex === null
? this._core.length - 2
: this._currentIndex + 1;
if (this._core.length > newIndex && newIndex < this._core.length) {
const nextState = await this._core.get(newIndex);
this._state = nextState.state;
this._context = nextState.context;
this._currentIndex = newIndex;
}
}
async backward() {
const newIndex =
this._currentIndex === null
? this._core.length - 2
: this._currentIndex - 1;
if (this._core.length > newIndex && newIndex >= 0) {
const lastState = await this._core.get(newIndex);
this._state = lastState.state;
this._context = lastState.context;
this._currentIndex = newIndex;
}
}
truncate(newLength: number) {
return this._core.truncate(newLength);
}
get state(): ExtractStates<T> {
return this._state;
}
get context(): ExtractContext<T> {
return this._context;
}
get isEmpty() {
return this._core.length === 0;
}
getAvailableActions(): Array<ExtractActions<T>> {
const currentState = this._machine.states[this._state];
return Object.keys(currentState?.on || {}) as Array<ExtractActions<T>>;
}
}