-
Notifications
You must be signed in to change notification settings - Fork 5
/
MessageParser.ts
1103 lines (1001 loc) · 32 KB
/
MessageParser.ts
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Logger } from "../../Logger";
import { AbilityCause, AbilityEvent, ActivateEvent, AnyBattleEvent, BoostEvent,
CantEvent, Cause, CureStatusEvent, CureTeamEvent, DamageEvent, EndEvent,
FaintEvent, isBattleEventPrefix, MoveEvent, MustRechargeEvent, PrepareEvent,
SetHPEvent, SingleTurnEvent, StartEvent, StatusEvent, SwitchEvent, TieEvent,
TurnEvent, UpkeepEvent, WinEvent } from "../dispatcher/BattleEvent";
import { BattleInitMessage } from "../dispatcher/Message";
import { BoostableStatName, isMajorStatus, isPlayerId, MajorStatus, PlayerID,
PokemonDetails, PokemonID, PokemonStatus } from "../helpers";
import { Parser } from "./Parser";
/**
* Parses messages sent from the server. Instead of producing some kind of
* syntax tree, this parser executes event listeners or callbacks whenever it
* has successfully parsed a message.
*/
export class MessageParser extends Parser
{
/** @override */
public get room(): string
{
return this._room;
}
/** The current line separated into words. */
private get line(): string[]
{
return this.lines[this.lineN];
}
/** Logger object. */
private readonly logger: Logger;
/** Current room we're parsing messages from. */
private _room: string;
/** Message split up into lines and words. Words are separated by a `|`. */
private lines: string[][];
/** Current word index we're parsing at. */
private wordN: number;
/** Current line index we're parsing at. */
private lineN: number;
/**
* Creates a MessageParser.
* @param logger Logger object.
*/
constructor(logger: Logger)
{
super();
this.logger = logger;
}
/** @override */
public async parse(message: string): Promise<void>
{
// start with parsing the room name if possible
// format: >roomname
let pos: number;
if (message.startsWith(">"))
{
pos = message.indexOf("\n", 1);
if (pos === -1)
{
pos = message.length;
}
this._room = message.substring(1, pos);
}
else
{
pos = 0;
this._room = "";
}
this.lines = message
// omit room name as we get into the actual messages
.substr(pos)
// split each message into lines
.split("\n")
// split each line into word segments
// since message lines start with a pipe character, omit that
// when parsing the words or we'll get an empty string for the
// first word of every line
.map(line => line.substr(1).split("|"));
this.wordN = 0;
this.lineN = 0;
while (this.lineN < this.lines.length) await this.parseMessage();
}
/**
* Parses a single message line. After being fully parsed, the `line` field
* should point to the next unparsed line.
* @returns A promise that resolves once the listener is executed.
*/
private async parseMessage(): Promise<void>
{
const word = this.nextWord();
switch (word)
{
// taken from PROTOCOL.md in github.com/Zarel/Pokemon-Showdown
// room initialization
case "init": // joined a room
return this.parseInit();
case "deinit": // left a room
return this.parseDeInit();
// global messages
case "challstr": // login key
return this.parseChallstr();
case "updateuser": // user info changed
return this.parseUpdateUser();
case "updatechallenges": // change in incoming/outgoing challenges
return this.parseUpdateChallenges();
// battle initialization
case "player": // initialize battle/player data
return this.parseBattleInit();
// battle progress
case "request": // move/switch request
return this.parseRequest();
case "error": // e.g. invalid move/switch choice
return this.parseError();
default:
if (["drag", "move", "switch"].includes(word) ||
isBattleEventPrefix(word))
{
return this.parseBattleProgress();
}
// ignore
else this.nextLine();
}
}
/** Advances the `line` field to the next line. */
private nextLine(): void
{
this.wordN = 0;
++this.lineN;
}
/** Gets the current word being parsed. */
private peekWord(): string
{
return this.line[this.wordN];
}
/** Gets the current word then advances to the next one. */
private nextWord(): string
{
return this.line[this.wordN++];
}
/** Gets the last parsed word. */
private previousWord(): string
{
return this.line[this.wordN - 1];
}
/** Backtracks the word index within the current line. */
private unGetWord(): void
{
--this.wordN;
if (this.wordN < 0) this.wordN = 0;
}
/**
* Checks whether we're out of lines to parse. If this is true, subsequent
* calls to `peekWord()`, `nextWord()`, `previousWord()`, and `isEol()` may
* cause an error.
*/
private isEnd(): boolean
{
return this.lineN >= this.lines.length;
}
/**
* Checks whether we're out of words to parse in the current line. If this
* is true, calls to `peekWord()`, `nextWord()`, and `previousWord()`, may
* return undefined.
*/
private isEol(): boolean
{
return this.wordN >= this.line.length;
}
/**
* Gets all words of the given line strung together.
* @param wordN Index at which to start concatenating words.
* @param lineN Line index used to get the words. Omit to assume the current
* line.
*/
private getRestOfLine(wordN = this.wordN, lineN = this.lineN): string
{
return this.lines[lineN].slice(wordN).join("|");
}
/**
* Parses a `challstr` message.
*
* Format:
* @example
* |challstr|<challstr>
*/
private parseChallstr(): Promise<void>
{
const challstr = this.getRestOfLine();
this.nextLine();
return this.dispatch("challstr", {challstr});
}
/**
* Parses a `deinit` message.
*
* Format:
* @example
* |deinit
*/
private parseDeInit(): Promise<void>
{
this.nextLine();
return this.dispatch("deinit", {});
}
/**
* Parses an `error` message.
*
* Format:
* @example
* |error|[reason] <description>
*/
private parseError(): Promise<void>
{
const reason = this.getRestOfLine();
this.nextLine();
return this.dispatch("error", {reason});
}
/**
* Parses an `init` message.
*
* Format:
* @example
* |init|<chat or battle>
*/
private parseInit(): Promise<void>
{
const type = this.nextWord();
this.nextLine();
// ignore invalid messages
// TODO: don't ignore, instead print warnings to log from static parsers
// and message parsers (must be testable)
if (type !== "chat" && type !== "battle") return Promise.resolve();
return this.dispatch("init", {type});
}
/**
* Parses a `request` message. The JSON data in the RequestArgs need to have
* their side pokemon details parsed first.
*
* Format:
* @example
* |request|<unparsed RequestArgs json>
*/
private parseRequest(): Promise<void>
{
const text = this.getRestOfLine();
const args = MessageParser.parseJSON(text);
this.nextLine();
if (!args)
{
this.logger.error(`Invalid request message json ${text}`);
return Promise.resolve();
}
// some info is encoded in a string that needs to be further parsed
for (const mon of args.side.pokemon)
{
// ident, details, and condition fields are the same format as
// the data from a |switch| message
const ident = MessageParser.parsePokemonID(mon.ident,
/*pos*/ false);
if (!ident) this.logger.error(`Invalid PokemonID "${mon.ident}"`);
mon.ident = ident;
const details = MessageParser.parsePokemonDetails(mon.details);
if (!details)
{
this.logger.error(`Invalid PokemonDetails "${mon.details}"`);
}
mon.details = details;
const condition = MessageParser.parsePokemonStatus(mon.condition);
if (!condition)
{
this.logger.error(`Invalid PokemonStatus "${mon.condition}"`);
}
mon.condition = condition;
if (!ident || !details || !condition) return Promise.resolve();
}
return this.dispatch("request", args);
}
/**
* Parses an `updatechallenges` message.
*
* Format:
* @example
* |updatechallenges|<UpdateChallengesArgs json>
*/
private parseUpdateChallenges(): Promise<void>
{
const args = MessageParser.parseJSON(this.getRestOfLine());
this.nextLine();
// ignore invalid messages
if (!args) return Promise.resolve();
return this.dispatch("updatechallenges", args);
}
/**
* Parses an `updateuser` message.
*
* Format:
* @example
* |updateuser|<our username>|<0 if guest, 1 otherwise>|<avatarId>
*/
private parseUpdateUser(): Promise<void>
{
const username = this.nextWord();
const word = this.nextWord();
const isGuest = word ? !MessageParser.parseInt(word) : null;
this.nextLine();
// ignore invalid messages
if (!username || !isGuest) return Promise.resolve();
return this.dispatch("updateuser", {username, isGuest});
}
/**
* Parses the initial battle initialization multiline message.
*
* Format:
* @example
* |player|<our PlayerID>|<our username>|<avatar id>
* |teamsize|p1|<team size>
* |teamsize|p2|<team size>
* |gametype|<game type>
* |gen|<gen #>
* <...>
* |start
* <initial BattleEvents>
* |turn|1
*/
private parseBattleInit(): Promise<void>
{
let id: PlayerID | undefined;
let username: string | undefined;
let teamSizes: {[P in PlayerID]: number} | undefined;
let gameType: string | undefined;
let gen: number | undefined;
const events: AnyBattleEvent[] = [];
// first prefix word was already parsed
this.unGetWord();
while (!this.isEnd())
{
const prefix = this.nextWord();
switch (prefix)
{
case "player":
{
const idWord = this.nextWord();
const playerId = MessageParser.parsePlayerId(idWord);
const playerName = this.nextWord();
if (playerId && playerName)
{
id = playerId;
username = playerName;
}
if (!playerId)
{
this.logger.error(`Invalid PlayerID ${idWord}`);
}
if (!playerName) this.logger.error("No player name given");
this.nextLine();
break;
}
case "teamsize":
{
const idWord = this.nextWord();
const teamId = MessageParser.parsePlayerId(idWord);
const sizeWord = this.nextWord();
const teamSize = MessageParser.parseInt(sizeWord);
if (!teamSizes)
{
teamSizes = {} as BattleInitMessage["teamSizes"];
}
if (teamId && teamSize) teamSizes[teamId] = teamSize;
if (!teamId)
{
this.logger.error(`Invalid PlayerID ${idWord}`);
}
if (!teamSize)
{
this.logger.error(`Invalid team size ${sizeWord}`);
}
this.nextLine();
break;
}
case "gametype":
gameType = this.nextWord();
if (!gameType) this.logger.error("No game type given");
this.nextLine();
break;
case "gen":
{
const genWord = this.nextWord();
const genNum = MessageParser.parseInt(genWord);
if (genNum) gen = genNum;
else this.logger.error(`Invalid gen num ${genWord}`);
this.nextLine();
break;
}
// TODO: team preview
default:
if (isBattleEventPrefix(prefix))
{
// start of initial events
events.push(...this.parseBattleEvents());
}
// ignore
else this.nextLine();
}
}
// ignore invalid messages
if (!id || !username || !teamSizes ||
(!teamSizes.p1 || !teamSizes.p2) || !gameType || !gen)
{
this.logger.debug("Ignoring invalid battleinit message");
return Promise.resolve();
}
return this.dispatch("battleinit",
{id, username, teamSizes, gameType, gen, events});
}
/**
* Parses a battle progress multiline message. Composed of multiple
* BattleEvents.
*/
private parseBattleProgress(): Promise<void>
{
return this.dispatch("battleprogress",
{events: this.parseBattleEvents()});
}
/**
* Parses BattleEvent messages until the end of the message string.
* @returns An array of parsed BattleEvents.
*/
private parseBattleEvents(): AnyBattleEvent[]
{
// requires prefix to not have been parsed yet
this.unGetWord();
const events: AnyBattleEvent[] = [];
while (!this.isEnd())
{
const event = this.parseBattleEvent();
if (event) events.push(event);
}
return events;
}
/** Parses a BattleEvent with optional Cause suffix at the end. */
private parseBattleEvent(): AnyBattleEvent | null
{
const event = this.parseBattleEventHelper();
let cause: Cause | null | undefined;
if (event)
{
while (!cause && !this.isEol()) cause = this.parseCause();
if (cause) event.cause = cause;
}
this.nextLine();
return event;
}
/**
* Parses a BattleEvent. Each `parseXEvent()` method must assume that the
* prefix was already parsed, and should not advance the line index yet.
* @returns A BattleEvent, or null if invalid.
*/
private parseBattleEventHelper(): AnyBattleEvent | null
{
switch (this.nextWord())
{
case "-ability": return this.parseAbilityEvent();
case "-activate": return this.parseActivateEvent();
case "-boost": case "-unboost": return this.parseBoostEvent();
case "cant": return this.parseCantEvent();
case "-curestatus": return this.parseCureStatusEvent();
case "-cureteam": return this.parseCureTeamEvent();
case "-damage": case "-heal": return this.parseDamageEvent();
case "-end": return this.parseEndEvent();
case "faint": return this.parseFaintEvent();
case "move": return this.parseMoveEvent();
case "-mustrecharge": return this.parseMustRechargeEvent();
case "-prepare": return this.parsePrepareEvent();
case "-sethp": return this.parseSetHPEvent();
case "-singleturn": return this.parseSingleTurnEvent();
case "-start": return this.parseStartEvent();
case "-status": return this.parseStatusEvent();
case "switch": case "drag": return this.parseSwitchEvent();
case "tie": return this.parseTieEvent();
case "turn": return this.parseTurnEvent();
case "upkeep": return this.parseUpkeepEvent();
case "win": return this.parseWinEvent();
default: return null;
}
}
/**
* Parses an AbilityEvent.
*
* Format:
* @example
* |-ability|<PokemonID>|<ability name>
*
* @returns An AbilityEvent, or null if invalid.
*/
private parseAbilityEvent(): AbilityEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const ability = this.nextWord();
if (!id || !ability) return null;
return {type: "ability", id, ability};
}
/**
* Parses an ActivateEvent.
*
* Format:
* @example
* |-activate|<PokemonID>|<volatile status>
*
* @returns An ActivateEvent, or null if invalid.
*/
private parseActivateEvent(): ActivateEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const volatile = this.nextWord();
if (!id || !volatile) return null;
return {type: "activate", id, volatile};
}
/**
* Parses a BoostEvent.
*
* Format:
* @example
* |<-boost or -unboost>|<PokemonID>|<stat name>|<amount>
*
* @returns A BoostEvent, or null if invalid.
*/
private parseBoostEvent(): BoostEvent | null
{
const prefix = this.previousWord();
const id = MessageParser.parsePokemonID(this.nextWord());
const stat = this.nextWord() as BoostableStatName;
let amount = MessageParser.parseInt(this.nextWord());
if (!id || !stat || !amount) return null;
if (prefix === "-unboost") amount = -amount;
return {type: "boost", id, stat, amount};
}
/**
* Parses a CantEvent.
*
* Format:
* @example
* |cant|<PokemonID>|<reason>|<move (optional)>
*
* @returns A CantEvent, or null if invalid.
*/
private parseCantEvent(): CantEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const reason = this.nextWord();
const moveName = this.nextWord();
if (!id || !reason) return null;
if (!moveName) return {type: "cant", id, reason};
return {type: "cant", id, reason, moveName};
}
/**
* Parses a CureStatusEvent.
*
* Format:
* @example
* |-curestatus|<PokemonID>|<cured MajorStatus>
*
* @returns A CureStatusEvent, or null if invalid.
*/
private parseCureStatusEvent(): CureStatusEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const majorStatus = MessageParser.parseMajorStatus(this.nextWord());
if (!id || !majorStatus) return null;
return {type: "curestatus", id, majorStatus};
}
/**
* Parses a CureTeamEvent.
*
* Format:
* @example
* |-cureteam|<PokemonID>
*
* @returns A CureTeamEvent, or null if invalid.
*/
private parseCureTeamEvent(): CureTeamEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
if (!id) return null;
return {type: "cureteam", id};
}
/**
* Parses a DamageEvent.
*
* Format:
* @example
* |<-damage or -heal>|<PokemonID>|<new PokemonStatus>
*
* @returns A DamageEvent, or null if invalid.
*/
private parseDamageEvent(): DamageEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const status = MessageParser.parsePokemonStatus(this.nextWord());
if (!id || !status) return null;
return {type: "damage", id, status};
}
/**
* Parses an EndEvent.
*
* Format:
* @example
* |-end|<PokemonID>|<volatile status>
*
* @returns An EndEvent, or null if invalid.
*/
private parseEndEvent(): EndEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const volatile = this.nextWord();
if (!id || !volatile) return null;
return {type: "end", id, volatile};
}
/**
* Parses a FaintEvent.
*
* Format:
* @example
* |faint|<PokemonID>
*
* @returns A FaintEvent, or null if invalid.
*/
private parseFaintEvent(): FaintEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
if (!id) return null;
return {type: "faint", id};
}
/**
* Parses a MoveEvent.
*
* Format:
* @example
* |move|<user PokemonID>|<move name>|<target PokemonID>
*
* // Optional message suffixes:
* |[miss]
* |[from]<effect name>
*
* @returns A MoveEvent, or null if invalid.
*/
private parseMoveEvent(): MoveEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const moveName = this.nextWord();
const targetId = MessageParser.parsePokemonID(this.nextWord());
if (!id || !moveName || !targetId) return null;
return {type: "move", id, moveName, targetId};
}
/**
* Parses a MustRechargeEvent.
*
* Format:
* @example
* |-mustrecharge|<PokemonID>
*
* @returns A MustRechargeEvent, or null if invalid.
*/
private parseMustRechargeEvent(): MustRechargeEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
if (!id) return null;
return {type: "mustrecharge", id};
}
/**
* Parses a PrepareEvent.
*
* Format:
* @example
* |-prepare|<user PokemonID>|<move name>|<target PokemonID>
*
* @returns A PrepareEvent, or null if invalid.
*/
private parsePrepareEvent(): PrepareEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const moveName = this.nextWord();
const targetId = MessageParser.parsePokemonID(this.nextWord());
if (!id || !moveName || !targetId) return null;
return {type: "prepare", id, moveName, targetId};
}
/**
* Parses a SetHPEvent.
*
* Format:
* @example
* |-sethp|<PokemonID 1>|<PokemonStatus 1>|<PokemonID 2>|<PokemonStatus 2>
*
* @returns A SetHPEvent, or null if invalid.
*/
private parseSetHPEvent(): SetHPEvent | null
{
const event: SetHPEvent = {type: "sethp", newHPs: []};
while (!this.isEol())
{
const id = MessageParser.parsePokemonID(this.nextWord());
const status = MessageParser.parsePokemonStatus(this.nextWord());
if (!id || !status) break;
event.newHPs.push({id, status});
}
return event;
}
/**
* Parses a SingleTurnEvent.
*
* Format:
* @example
* |-singleturn|<PokemonID>|<status>
*
* @returns A SingleTurn, or null if invalid.
*/
private parseSingleTurnEvent(): SingleTurnEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const status = this.nextWord();
if (!id || !status) return null;
return {type: "singleturn", id, status};
}
/**
* Parses a StartEvent.
*
* Format:
* @example
* |-start|<PokemonID>|<volatile>|<other args>
*
* // optional message suffixes:
* [fatigue]
*
* @returns A StartEvent, or null if invalid.
*/
private parseStartEvent(): StartEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const volatile = this.nextWord();
const otherArgs: string[] = [];
let cause: Cause | null = null;
while (!this.isEol())
{
const s = this.peekWord();
if (!cause) cause = this.parseCause();
if (!cause) otherArgs.push(s);
}
if (!id || !volatile) return null;
if (cause) return {type: "start", id, volatile, otherArgs, cause};
return {type: "start", id, volatile, otherArgs};
}
/**
* Parses a StatusEvent.
*
* Format:
* @example
* |-status|<PokemonID>|<new MajorStatus>
*
* @returns A StatusEvent, or null if invalid.
*/
private parseStatusEvent(): StatusEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const majorStatus = MessageParser.parseMajorStatus(this.nextWord());
if (!id || !majorStatus) return null;
return {type: "status", id, majorStatus};
}
/**
* Parses a SwitchEvent.
*
* Format:
* @example
* |<switch or drag>|<replacing PokemonID>|<PokemonDetails>|<PokemonStatus>
*
* @returns A SwitchInEvent, or null if invalid.
*/
private parseSwitchEvent(): SwitchEvent | null
{
const id = MessageParser.parsePokemonID(this.nextWord());
const details = MessageParser.parsePokemonDetails(this.nextWord());
const status = MessageParser.parsePokemonStatus(this.nextWord());
if (!id || !details || !status) return null;
return {type: "switch", id, details, status};
}
/**
* Parses an UpkeepEvent.
*
* Format:
* @example
* |upkeep
*
* @returns An UpkeepEvent.
*/
private parseUpkeepEvent(): UpkeepEvent
{
return {type: "upkeep"};
}
/**
* Parses a TurnEvent.
*
* Format:
* @example
* |turn|<new turn number>
*
* @returns A TurnEvent, or null if invalid.
*/
private parseTurnEvent(): TurnEvent | null
{
const num = MessageParser.parseInt(this.nextWord());
if (!num) return null;
return {type: "turn", num};
}
/**
* Parses a TieEvent.
*
* Format:
* @example
* |tie
*
* @returns A TieEvent.
*/
private parseTieEvent(): TieEvent
{
return {type: "tie"};
}
/**
* Parses a WinEvent.
*
* Format:
* @example
* |win|<username>
*
* @returns A WinEvent.
*/
private parseWinEvent(): WinEvent
{
return {type: "win", winner: this.getRestOfLine()};
}
/**
* Parses an event Cause.
* @returns A Cause, or null if invalid.
*/
private parseCause(): Cause | null
{
const str = this.nextWord();
if (!str) return null;
if (str.startsWith("[from] ability: "))
{
const result: AbilityCause =
{
type: "ability", ability: str.substr("[from] ability: ".length)
};
// parse possible "of" suffix
const next = this.peekWord();
if (next && next.startsWith("[of] "))
{
const id = MessageParser.parsePokemonID(
next.substr("[of] ".length));
if (id)
{
this.nextWord();
result.of = id;
}
}
return result;
}
if (str === "[fatigue]") return {type: "fatigue"};
if (str.startsWith("[from] item: "))
{
return {type: "item", item: str.substr("[from] item: ".length)};
}
if (str === "[from]lockedmove") return {type: "lockedmove"};
return null;
}
/**
* Parses a PlayerID.
* @param id String to parse.
* @returns A valid PlayerID, or null if invalid.
*/
private static parsePlayerId(id?: string): PlayerID | null
{
return isPlayerId(id) ? id : null;
}
/**
* Parses an integer.
* @param n String to parse.
* @returns An integer, or null if invalid.
*/
private static parseInt(n?: string): number | null
{
if (n)
{
const parsed = parseInt(n, 10);
return isNaN(parsed) ? null : parsed;
}
return null;
}
/**
* Parses a JSON object.
* @param obj String to parse.
* @returns An object, or null if invalid.
*/
private static parseJSON(obj?: string): any
{
// any falsy type (empty string, null, etc) is invalid
return obj ? JSON.parse(obj) : null;
}
/**
* Parses a Pokemon ID in the form `<position>: <name>`. Position is in the
* format `<owner><pos>`, where owner determines who's side the pokemon is
* on and pos is its position on that side (applicable in non-single
* battles). Name is just the Pokemon's nickname.
* @param id Unparsed pokemon ID.