-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonparser.ts
59 lines (47 loc) · 1.66 KB
/
jsonparser.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
import Tokenizer, { TokenizerOptions } from "./tokenizer.js";
import TokenParser, { TokenParserOptions } from "./tokenparser.js";
import { ParsedElementInfo } from "./utils/types/parsedElementInfo.js";
import { ParsedTokenInfo } from "./utils/types/parsedTokenInfo.js";
export interface JSONParserOptions
extends TokenizerOptions,
TokenParserOptions {}
export default class JSONParser {
private tokenizer: Tokenizer;
private tokenParser: TokenParser;
constructor(opts: JSONParserOptions = {}) {
this.tokenizer = new Tokenizer(opts);
this.tokenParser = new TokenParser(opts);
this.tokenizer.onToken = this.tokenParser.write.bind(this.tokenParser);
this.tokenizer.onEnd = () => {
if (!this.tokenParser.isEnded) this.tokenParser.end();
};
this.tokenParser.onError = this.tokenizer.error.bind(this.tokenizer);
this.tokenParser.onEnd = () => {
if (!this.tokenizer.isEnded) this.tokenizer.end();
};
}
public get isEnded(): boolean {
return this.tokenizer.isEnded && this.tokenParser.isEnded;
}
public write(input: Iterable<number> | string): void {
this.tokenizer.write(input);
}
public end(): void {
this.tokenizer.end();
}
public set onToken(cb: (parsedTokenInfo: ParsedTokenInfo) => void) {
this.tokenizer.onToken = cb;
}
public set onValue(cb: (parsedElementInfo: ParsedElementInfo) => void) {
this.tokenParser.onValue = cb;
}
public set onError(cb: (err: Error) => void) {
this.tokenizer.onError = cb;
}
public set onEnd(cb: () => void) {
this.tokenParser.onEnd = () => {
if (!this.tokenizer.isEnded) this.tokenizer.end();
cb.call(this.tokenParser);
};
}
}