license import { flat } from '../utils/flat.js' ; import { ArtifactDecoder } from './artifact-decoder.js' ; import { ARArtifact } from './schema/extension-ar-artifacts.js' ; import { JsonLd } from './schema/json-ld.js' ; export class ArtifactLoader { private readonly decoder = new ArtifactDecoder ( ) ; async fromUrl ( url ) { const response = await fetch ( url . toString ( ) ) ; if ( ! response . ok ) { throw Error ( `Fetch failure for ${ url } with status: ${ response . statusText }` ) ; } const contentType = response . headers . get ( 'content-type' ) ; if ( ! contentType ) { return [ ] ; } if ( contentType . indexOf ( 'application/json' ) !== - 1 || contentType . indexOf ( 'application/ld+json' ) !== - 1 ) { const json = await response . json ( ) ; return this . fromJson ( json ) ; } else { const html = await response . text ( ) ; const parser = new DOMParser ( ) ; const doc = parser . parseFromString ( html , 'text/html' ) ; return this . fromElement ( doc , url ) ; } } async fromHtmlUrl ( url ) { const response = await fetch ( url . toString ( ) ) ; if ( ! response . ok ) { throw Error ( `Fetch failure for ${ url } with status: ${ response . statusText }` ) ; } const html = await response . text ( ) ; const parser = new DOMParser ( ) ; const doc = parser . parseFromString ( html , 'text/html' ) ; return this . fromElement ( doc , url ) ; } async fromJsonUrl ( url ) { const response = await fetch ( url . toString ( ) ) ; if ( ! response . ok ) { throw Error ( `Fetch failure for ${ url } with status: ${ response . statusText }` ) ; } const json = await response . json ( ) ; return this . fromJson ( json ) ; } async fromElement ( el , url ) { const ret = [ ] ; const inlineScripts = el . querySelectorAll ( 'script[type=\'application/ld+json\']:not([src])' ) ; for ( const jsonldScript of inlineScripts ) { if ( ! jsonldScript . textContent ) { continue ; } try { const jsonld = JSON . parse ( jsonldScript . textContent ) ; ret . push ( this . fromJson ( jsonld ) ) ; } catch ( ex ) { } } const externalScripts = el . querySelectorAll ( 'script[type=\'application/ld+json\'][src]' ) ; for ( const jsonldScript of externalScripts ) { const src = jsonldScript . getAttribute ( 'src' ) as string ; try { const url2 = new URL ( src , url ) ; ret . push ( this . fromJsonUrl ( url2 ) ) ; } catch ( ex ) { } } const jsonldLinks = el . querySelectorAll ( 'link[rel=\'alternate\'][type=\'application/ld+json\'][href]' ) ; for ( const jsonldLink of jsonldLinks ) { const href = jsonldLink . getAttribute ( 'href' ) as string ; try { const url2 = new URL ( href , url ) ; ret . push ( this . fromJsonUrl ( url2 ) ) ; } catch ( ex ) { } } return flat ( await Promise . all ( ret ) ) ; } async fromJson ( json ) { return this . decoder . decode ( json ) ; } }