* Parse the SVG the way a consumer does. * * `DOMParser` is not in Node, so this is a hand-rolled well-formedness check: * every tag balanced, every attribute quoted, no stray `<` or `&` in text. That * is exactly the class of bug an un-escaped symbol name (`Map `, `a && b`) * would introdu
(svg: string)
| 158 | * would introduce, and it is the one that makes GitHub refuse the file. |
| 159 | */ |
| 160 | function assertWellFormed(svg: string): void { |
| 161 | const stack: string[] = []; |
| 162 | const tag = /<(\/?)([a-zA-Z:]+)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g; |
| 163 | let at = 0; |
| 164 | let match: RegExpExecArray | null; |
| 165 | while ((match = tag.exec(svg)) !== null) { |
| 166 | const between = svg.slice(at, match.index); |
| 167 | expect(between, `unescaped < or & in text: ${JSON.stringify(between)}`).not.toMatch( |
| 168 | /[<]|&(?!(amp|lt|gt|quot|apos|#\d+);)/ |
| 169 | ); |
| 170 | at = match.index + match[0].length; |
| 171 | const [, closing, name, attrs, selfClosing] = match; |
| 172 | // Every attribute is name="value" with a balanced pair of quotes. |
| 173 | const quotes = (attrs as string).split('"').length - 1; |
| 174 | expect(quotes % 2, `unbalanced quotes in <${name} ${attrs}>`).toBe(0); |
| 175 | if (closing === '/') { |
| 176 | expect(stack.pop(), 'closing tag with no opener').toBe(name); |
| 177 | } else if (selfClosing !== '/') { |
| 178 | stack.push(name as string); |
| 179 | } |
| 180 | } |
| 181 | expect(stack, 'unclosed tags').toEqual([]); |
| 182 | } |
| 183 | |
| 184 | function viewBox(svg: string): { width: number; height: number } { |
| 185 | const box = /viewBox="0 0 (\d+(?:\.\d+)?) (\d+(?:\.\d+)?)"/.exec(svg); |
no test coverage detected