11// utils -> retrieve
22
33import fetch from 'cross-fetch'
4+ import { XMLParser } from 'fast-xml-parser'
45
56const profetch = async ( url , options = { } ) => {
67 const { proxy = { } , signal = null } = options
@@ -15,6 +16,20 @@ const profetch = async (url, options = {}) => {
1516 return res
1617}
1718
19+ const getCharsetFromText = ( text ) => {
20+ try {
21+ const firstLine = text . split ( '\n' ) [ 0 ] . trim ( ) . replace ( '<?' , '<' ) . replace ( '?>' , '>' )
22+ const parser = new XMLParser ( {
23+ ignoreAttributes : false ,
24+ } )
25+ let obj = parser . parse ( firstLine )
26+ const { xml : root = { } } = obj
27+ return root [ '@_encoding' ] || 'utf8'
28+ } catch {
29+ return 'utf8'
30+ }
31+ }
32+
1833export default async ( url , options = { } ) => {
1934 const {
2035 headers = {
@@ -35,9 +50,10 @@ export default async (url, options = {}) => {
3550 const buffer = await res . arrayBuffer ( )
3651 const text = buffer ? Buffer . from ( buffer ) . toString ( ) . trim ( ) : ''
3752
53+ console . log ( contentType )
3854 if ( / ( \+ | \/ ) ( x m l | h t m l ) / . test ( contentType ) ) {
3955 const arr = contentType . split ( 'charset=' )
40- const charset = arr . length === 2 ? arr [ 1 ] . trim ( ) : 'utf8'
56+ let charset = arr . length === 2 ? arr [ 1 ] . trim ( ) : getCharsetFromText ( text )
4157 const decoder = new TextDecoder ( charset )
4258 const xml = decoder . decode ( buffer )
4359 return { type : 'xml' , text : xml . trim ( ) , status, contentType }
0 commit comments