/
Parser.ts
80 lines (64 loc) · 1.76 KB
/
Parser.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
import { Fetch } from './types'
import { Screen } from './Screen'
type DOMParserConstructor = typeof DOMParser
export interface IParserOptions {
/**
* WHATWG-compatible `fetch` function.
*/
fetch?: Fetch
/**
* XML/HTML parser from string into DOM Document.
*/
DOMParser?: DOMParserConstructor
}
const { defaultFetch } = Screen
const DefaultDOMParser = typeof DOMParser !== 'undefined'
? DOMParser
: undefined
export class Parser {
private readonly fetch: Fetch
private readonly DOMParser: DOMParserConstructor
constructor({
fetch = defaultFetch,
DOMParser = DefaultDOMParser
}: IParserOptions = {}) {
if (!fetch) {
throw new Error(`Can't find 'fetch' in 'globalThis', please provide it via options`)
}
if (!DOMParser) {
throw new Error(`Can't find 'DOMParser' in 'globalThis', please provide it via options`)
}
this.fetch = fetch
this.DOMParser = DOMParser
}
async parse(resource: string) {
if (resource.startsWith('<')) {
return this.parseFromString(resource)
}
return this.load(resource)
}
parseFromString(xml: string) {
const parser = new this.DOMParser()
try {
return this.checkDocument(
parser.parseFromString(xml, 'image/svg+xml')
)
} catch (err) {
return this.checkDocument(
parser.parseFromString(xml, 'text/xml')
)
}
}
private checkDocument(document: Document) {
const parserError = document.getElementsByTagName('parsererror')[0]
if (parserError) {
throw new Error(parserError.textContent || 'Unknown parse error')
}
return document
}
async load(url: string) {
const response = await this.fetch(url)
const xml = await response.text()
return this.parseFromString(xml)
}
}