import { Parser , DefaultHandler , Node , Text , Tag , ElementType , } from "htmlparser" ; export const parseHtml = ( html ) : Promise < Tag > => { return new Promise ( ( resolve , reject ) => { const handler = new DefaultHandler ( ( error , dom ) => { error ? reject ( error ) : resolve ( { type : ElementType . Tag , name : "#root" , children : dom } ) ; } , { verbose : false } ) ; const parser = new Parser ( handler ) ; parser . parseComplete ( html ) ; } ) ; } ; const entities = { "&" : [ "amp" , "AMP" , "#x0026" , "#38" , "#038" ] , '"' : [ "quot" , "QUOT" , "#x00022" , "#34" , "#034" ] , "'" : [ "apos" , "#x00027" , "#39" , "#039" ] , } ; export const decodeHtml = ( s ) : string => { return Object . keys ( entities ) . reduce ( ( decoded , replace ) => { const sequences = entities [ replace ] ; return decoded . replace ( new RegExp ( `(&(?:${ sequences . join ( "|" ) });)` , `g` ) , replace ) ; } , s ) ; } ; const isTextNode = ( node ) : node is Text => { return node . type === ElementType . Text ; } ; const isTagNode = ( node ) : node is Tag => { return node . type === ElementType . Tag ; } ; export const getTags = ( node , tagName ) : Tag [ ] => ( node . children || [ ] ) . filter ( isTagNode ) . filter ( ( node ) => node . name === tagName ) ; export const getTag = ( node , tagName ) : Tag => getTags ( node , tagName ) [ 0 ] ; export const getText = ( node ) : string => node ?. children ? node . children . filter ( isTextNode ) [ 0 ] . data : "" ; export const attributes = ( node ) : { [ key ] : string ; } => node . attribs || { } ;