-
Notifications
You must be signed in to change notification settings - Fork 146
/
fetcher.ts
2204 lines (1938 loc) · 69.1 KB
/
fetcher.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global $SolidTestEnvironment */
/**
*
* Project: rdflib.js
*
* @file: fetcher.js
*
* Description: contains functions for requesting/fetching/retracting
* This implements quite a lot of the web architecture.
* A fetcher is bound to a specific quad store, into which
* it loads stuff and into which it writes its metadata
* @@ The metadata could be optionally a separate graph
*
* - implements semantics of HTTP headers, Internet Content Types
* - selects parsers for rdf/xml, n3, rdfa, grddl
*
* TO do:
* - Implement a runtime registry for parsers and serializers
* -
*/
/**
* Things to test: callbacks on request, refresh, retract
* loading from HTTP, HTTPS, FTP, FILE, others?
* To do:
* Firing up a mail client for mid: (message:) URLs
*/
import IndexedFormula from './store'
import log from './log'
import N3Parser from './n3parser'
import RDFlibNamedNode from './named-node'
import Namespace from './namespace'
import rdfParse from './parse'
import { parseRDFaDOM } from './rdfaparser'
import RDFParser from './rdfxmlparser'
import * as Uri from './uri'
import { isCollection, isNamedNode} from './utils/terms'
import * as Util from './utils-js'
import serialize from './serialize'
import crossFetch, { Headers } from 'cross-fetch'
import {
ContentType, TurtleContentType, RDFXMLContentType, XHTMLContentType
} from './types'
import { termValue } from './utils/termValue'
import {
BlankNode,
RdfJsDataFactory,
Quad_Graph,
NamedNode,
Quad_Predicate,
Quad_Subject
} from './tf-types'
import jsonldParser from './jsonldparser'
const Parsable = {
'text/n3': true,
'text/turtle': true,
'application/rdf+xml': true,
'application/xhtml+xml': true,
'text/html': true,
'application/ld+json': true
}
// This is a minimal set to allow the use of damaged servers if necessary
const CONTENT_TYPE_BY_EXT = {
'rdf': RDFXMLContentType,
'owl': RDFXMLContentType,
'n3': 'text/n3',
'ttl': 'text/turtle',
'nt': 'text/n3',
'acl': 'text/n3',
'html': 'text/html',
'xml': 'text/xml'
}
// Convenience namespaces needed in this module.
// These are deliberately not exported as the user application should
// make its own list and not rely on the prefixes used here,
// and not be tempted to add to them, and them clash with those of another
// application.
const getNS = (factory?: RdfJsDataFactory) => {
return {
link: Namespace('http://www.w3.org/2007/ont/link#', factory),
http: Namespace('http://www.w3.org/2007/ont/http#', factory),
httph: Namespace('http://www.w3.org/2007/ont/httph#', factory), // headers
rdf: Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#', factory),
rdfs: Namespace('http://www.w3.org/2000/01/rdf-schema#', factory),
dc: Namespace('http://purl.org/dc/elements/1.1/', factory),
ldp: Namespace('http://www.w3.org/ns/ldp#', factory)
}
}
const ns = getNS()
export interface FetchError extends Error {
statusText?: string
status?: StatusValues
response?: ExtendedResponse
}
/** An extended interface of Response, since RDFlib.js adds some properties. */
export interface ExtendedResponse extends Response {
/** String representation of the Body */
responseText?: string
/** Identifier of the reqest */
req?: Quad_Subject
size?: number
timeout?: number
/** Used in UpdateManager.updateDav */
error?: string
}
/** tell typescript that a 'panes' child may exist on Window */
declare global {
interface Window {
panes?: any
solidFetcher?: any
solidFetch?: any
}
var solidFetcher: Function
var solidFetch: Function
}
declare var $SolidTestEnvironment: {
localSiteMap?: any
}
type UserCallback = (
ok: boolean,
message: string,
response?: any
) => void
type HTTPMethods = 'GET' | 'PUT' | 'POST' | 'PATCH' | 'HEAD' | 'DELETE' | 'CONNECT' | 'TRACE' | 'OPTIONS'
/** All valid inputs for initFetchOptions */
export type Options = Partial<AutoInitOptions>
/** Initiated by initFetchOptions, which runs on load */
export interface AutoInitOptions extends RequestInit{
/** The used Fetch function */
fetch?: Fetch
/**
* Referring term, the resource which
* referred to this (for tracking bad links).
* The document in which this link was found.
*/
referringTerm?: NamedNode
/** Provided content type (for writes) */
contentType?: string
/**
* Override the incoming header to
* force the data to be treated as this content-type (for reads)
*/
forceContentType?: ContentType
/**
* Load the data even if loaded before.
* Also sets the `Cache-Control:` header to `no-cache`
*/
force?: boolean
/**
* Original uri to preserve
* through proxying etc (`xhr.original`).
*/
baseURI: string
/**
* Whether this request is a retry via
* a proxy (generally done from an error handler)
*/
proxyUsed?: boolean
actualProxyURI?: string
/** flag for XHR/CORS etc */
withCredentials?: boolean
/** Before we parse new data, clear old, but only on status 200 responses */
clearPreviousData?: boolean
/** Prevents the addition of various metadata triples (about the fetch request) to the store*/
noMeta?: boolean
noRDFa?: boolean
handlers?: Handler[]
timeout?: number
method?: HTTPMethods
retriedWithNoCredentials?: boolean
requestedURI?: string
// Seems to be required in some functions, such as XHTML parse and RedirectToProxy
resource: Quad_Subject
/** The serialized resource in the body*/
// Used for storing metadata of requests
original: NamedNode
// Like requeststatus? Can contain text with error.
data?: string
// Probably an identifier for request?s
req: BlankNode
// Might be the same as Options.data
body?: string
headers: HeadersInit
credentials?: 'include' | 'omit'
}
class Handler {
// TODO: Document, type
response: ExtendedResponse
// TODO: Document, type
dom: Document
static pattern: RegExp
constructor (response: ExtendedResponse, dom?: Document) {
this.response = response
// The type assertion operator here might need to be removed.
this.dom = dom!
}
}
class RDFXMLHandler extends Handler {
static toString () {
return 'RDFXMLHandler'
}
static register (fetcher: Fetcher) {
fetcher.mediatypes[RDFXMLContentType] = {
'q': 0.9
}
}
parse (
fetcher: Fetcher,
/** An XML String */
responseText: String,
/** Requires .original */
options: {
original: Quad_Subject
req: Quad_Subject
} & Options,
) {
let kb = fetcher.store
if (!this.dom) {
this.dom = Util.parseXML(responseText)
}
let root = this.dom.documentElement
if (root.nodeName === 'parsererror') { // Mozilla only See issue/issue110
// have to fail the request
return fetcher.failFetch(options, 'Badly formed XML in ' +
options.resource!.value, 'parse_error')
}
let parser = new RDFParser(kb)
try {
parser.parse(this.dom, options.original.value, options.original)
} catch (err) {
return fetcher.failFetch(options, 'Syntax error parsing RDF/XML! ' + err,
'parse_error')
}
if (!options.noMeta) {
kb.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode)
}
return fetcher.doneFetch(options, this.response)
}
}
RDFXMLHandler.pattern = new RegExp('application/rdf\\+xml')
class XHTMLHandler extends Handler {
static toString () {
return 'XHTMLHandler'
}
static register (fetcher: Fetcher) {
fetcher.mediatypes[XHTMLContentType] = {}
}
parse (
fetcher: Fetcher,
responseText: string,
options: {
resource: Quad_Subject
original: Quad_Subject
} & Options,
): Promise<FetchError> | ExtendedResponse {
let relation, reverse: boolean
if (!this.dom) {
this.dom = Util.parseXML(responseText)
}
let kb = fetcher.store
// dc:title
let title = this.dom.getElementsByTagName('title')
if (title.length > 0) {
kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(title[0].textContent as string),
options.resource)
// log.info("Inferring title of " + xhr.resource)
}
// link rel
let links = this.dom.getElementsByTagName('link')
for (let x = links.length - 1; x >= 0; x--) { // @@ rev
relation = links[x].getAttribute('rel')
reverse = false
if (!relation) {
relation = links[x].getAttribute('rev')
reverse = true
}
if (relation) {
fetcher.linkData(options.original, relation,
links[x].getAttribute('href') as string, options.resource, reverse)
}
}
// Data Islands
let scripts = this.dom.getElementsByTagName('script')
for (let i = 0; i < scripts.length; i++) {
let contentType = scripts[i].getAttribute('type')
if (Parsable[contentType!]) {
// @ts-ignore incompatibility between Store.add and Formula.add
rdfParse(scripts[i].textContent as string, kb, options.original.value, contentType)
// @ts-ignore incompatibility between Store.add and Formula.add
rdfParse(scripts[i].textContent as string, kb, options.original.value, contentType)
}
}
if (!options.noMeta) {
kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode)
}
if (!options.noRDFa && parseRDFaDOM) { // enable by default
try {
parseRDFaDOM(this.dom, kb, options.original.value)
} catch (err) {
// @ts-ignore
let msg = 'Error trying to parse ' + options.resource + ' as RDFa:\n' + err + ':\n' + err.stack
return fetcher.failFetch(options as AutoInitOptions, msg, 'parse_error')
}
}
return fetcher.doneFetch(options as AutoInitOptions, this.response)
}
}
XHTMLHandler.pattern = new RegExp('application/xhtml')
class XMLHandler extends Handler {
static toString () {
return 'XMLHandler'
}
static register (fetcher: Fetcher) {
fetcher.mediatypes['text/xml'] = { 'q': 0.5 }
fetcher.mediatypes['application/xml'] = { 'q': 0.5 }
}
static isElement(node: Node): node is Element {
return node.nodeType === Node.ELEMENT_NODE;
}
parse (
fetcher: Fetcher,
responseText: string,
options: {
original: Quad_Subject
req: BlankNode
resource: Quad_Subject
} & Options,
): ExtendedResponse | Promise<FetchError> {
let dom = Util.parseXML(responseText)
// XML Semantics defined by root element namespace
// figure out the root element
for (let c = 0; c < dom.childNodes.length; c++) {
const node = dom.childNodes[c]
// is this node an element?
if (XMLHandler.isElement(node)) {
// We've found the first element, it's the root
let ns = node.namespaceURI
// Is it RDF/XML?
if (ns && ns === ns['rdf']) {
fetcher.addStatus(options.req,
'Has XML root element in the RDF namespace, so assume RDF/XML.')
let rdfHandler = new RDFXMLHandler(this.response, dom)
return rdfHandler.parse(fetcher, responseText, options)
}
break
}
}
// Or it could be XHTML?
// Maybe it has an XHTML DOCTYPE?
if (dom.doctype) {
// log.info("We found a DOCTYPE in " + xhr.resource)
if (dom.doctype.name === 'html' &&
dom.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/) &&
dom.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)) {
fetcher.addStatus(options.req,
'Has XHTML DOCTYPE. Switching to XHTML Handler.\n')
let xhtmlHandler = new XHTMLHandler(this.response, dom)
return xhtmlHandler.parse(fetcher, responseText, options)
}
}
// Or what about an XHTML namespace?
let html = dom.getElementsByTagName('html')[0]
if (html) {
let xmlns = html.getAttribute('xmlns')
if (xmlns && xmlns.match(/^http:\/\/www.w3.org\/1999\/xhtml/)) {
fetcher.addStatus(options.req,
'Has a default namespace for ' + 'XHTML. Switching to XHTMLHandler.\n')
let xhtmlHandler = new XHTMLHandler(this.response, dom)
return xhtmlHandler.parse(fetcher, responseText, options)
}
}
// At this point we should check the namespace document (cache it!) and
// look for a GRDDL transform
// @@ Get namespace document <n>, parse it, look for <n> grddl:namespaceTransform ?y
// Apply ?y to dom
// We give up. What dialect is this?
return fetcher.failFetch(options,
'Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n' +
responseText.slice(0, 80), 901)
}
}
XMLHandler.pattern = new RegExp('(text|application)/(.*)xml')
class HTMLHandler extends Handler {
static toString () {
return 'HTMLHandler'
}
static register (fetcher: Fetcher) {
fetcher.mediatypes['text/html'] = {
'q': 0.9
}
}
parse (
fetcher: Fetcher,
responseText: string,
options: {
req: BlankNode,
resource: Quad_Subject,
original: Quad_Subject,
} & Options
): Promise<FetchError> | ExtendedResponse {
let kb = fetcher.store
// We only handle XHTML so we have to figure out if this is XML
// log.info("Sniffing HTML " + xhr.resource + " for XHTML.")
if (isXML(responseText)) {
fetcher.addStatus(options.req, "Has an XML declaration. We'll assume " +
"it's XHTML as the content-type was text/html.\n")
let xhtmlHandler = new XHTMLHandler(this.response)
return xhtmlHandler.parse(fetcher, responseText, options)
}
// DOCTYPE html
if (isXHTML(responseText)) {
fetcher.addStatus(options.req,
'Has XHTML DOCTYPE. Switching to XHTMLHandler.\n')
let xhtmlHandler = new XHTMLHandler(this.response)
return xhtmlHandler.parse(fetcher, responseText, options)
}
// xmlns
if (isXMLNS(responseText)) {
fetcher.addStatus(options.req,
'Has default namespace for XHTML, so switching to XHTMLHandler.\n')
let xhtmlHandler = new XHTMLHandler(this.response)
return xhtmlHandler.parse(fetcher, responseText, options)
}
// dc:title
// no need to escape '/' here
let titleMatch = (new RegExp('<title>([\\s\\S]+?)</title>', 'im')).exec(responseText)
if (titleMatch) {
kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(titleMatch[1]),
options.resource) // think about xml:lang later
}
kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode)
fetcher.addStatus(options.req, 'non-XML HTML document, not parsed for data.')
return fetcher.doneFetch(options, this.response)
}
}
HTMLHandler.pattern = new RegExp('text/html')
class JsonLdHandler extends Handler {
static toString () {
return 'JsonLdHandler'
}
static register (fetcher: Fetcher) {
fetcher.mediatypes['application/ld+json'] = {
'q': 0.9
}
}
parse (
fetcher: Fetcher,
responseText: string,
options: {
req: Quad_Subject
original: Quad_Subject
resource: Quad_Subject
} & Options,
response: ExtendedResponse
): Promise<ExtendedResponse | FetchError> {
const kb = fetcher.store
return new Promise((resolve, reject) => {
try {
jsonldParser (responseText, kb, options.original.value, () => {
resolve(fetcher.doneFetch(options, response))
})
} catch (err) {
const msg = 'Error trying to parse ' + options.resource +
' as JSON-LD:\n' + err // not err.stack -- irrelevant
resolve(fetcher.failFetch(options, msg, 'parse_error', response))
}
})
}
}
JsonLdHandler.pattern = /application\/ld\+json/
class TextHandler extends Handler {
static toString () {
return 'TextHandler'
}
static register (fetcher: Fetcher) {
fetcher.mediatypes['text/plain'] = {
'q': 0.5
}
}
parse (
fetcher: Fetcher,
responseText: string,
options: {
req: Quad_Subject
original: Quad_Subject
resource: Quad_Subject
} & Options
): ExtendedResponse | Promise<FetchError> {
// We only speak dialects of XML right now. Is this XML?
// Look for an XML declaration
if (isXML(responseText)) {
fetcher.addStatus(options.req, 'Warning: ' + options.resource +
" has an XML declaration. We'll assume " +
"it's XML but its content-type wasn't XML.\n")
let xmlHandler = new XMLHandler(this.response)
return xmlHandler.parse(fetcher, responseText, options)
}
// Look for an XML declaration
if (responseText.slice(0, 500).match(/xmlns:/)) {
fetcher.addStatus(options.req, "May have an XML namespace. We'll assume " +
"it's XML but its content-type wasn't XML.\n")
let xmlHandler = new XMLHandler(this.response)
return xmlHandler.parse(fetcher, responseText, options)
}
// We give up finding semantics - this is not an error, just no data
fetcher.addStatus(options.req, 'Plain text document, no known RDF semantics.')
return fetcher.doneFetch(options, this.response)
}
}
TextHandler.pattern = new RegExp('text/plain')
class N3Handler extends Handler {
static toString () {
return 'N3Handler'
}
static register (fetcher: Fetcher) {
fetcher.mediatypes['text/n3'] = {
'q': '1.0'
} // as per 2008 spec
/*
fetcher.mediatypes['application/x-turtle'] = {
'q': 1.0
} // pre 2008
*/
fetcher.mediatypes['text/turtle'] = {
'q': 1.0
} // post 2008
}
parse (
fetcher: Fetcher,
responseText: string,
options: {
original: NamedNode
req: Quad_Subject
} & Options,
response: ExtendedResponse
): ExtendedResponse | Promise<FetchError> {
// Parse the text of this N3 file
let kb = fetcher.store
let p = N3Parser(kb, kb, options.original.value, options.original.value,
null, null, '', null)
// p.loadBuf(xhr.responseText)
try {
p.loadBuf(responseText)
} catch (err) {
let msg = 'Error trying to parse ' + options.resource +
' as Notation3:\n' + err // not err.stack -- irrelevant
return fetcher.failFetch(options, msg, 'parse_error', response)
}
fetcher.addStatus(options.req, 'N3 parsed: ' + p.statementCount + ' triples in ' + p.lines + ' lines.')
fetcher.store.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode)
return fetcher.doneFetch(options, this.response)
}
}
N3Handler.pattern = new RegExp('(application|text)/(x-)?(rdf\\+)?(n3|turtle)')
const defaultHandlers = {
RDFXMLHandler, XHTMLHandler, XMLHandler, HTMLHandler, TextHandler, N3Handler, JsonLdHandler
}
function isXHTML (responseText) {
const docTypeStart = responseText.indexOf('<!DOCTYPE html')
const docTypeEnd = responseText.indexOf('>')
if (docTypeStart === -1 || docTypeEnd === -1 || docTypeStart > docTypeEnd) {
return false
}
return responseText.substr(docTypeStart, docTypeEnd - docTypeStart).indexOf('XHTML') !== -1
}
function isXML (responseText: string): boolean {
const match = responseText.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)
return !!match
}
function isXMLNS (responseText: string): boolean {
const match = responseText.match(/[^(<html)]*<html\s+[^<]*xmlns=['"]http:\/\/www.w3.org\/1999\/xhtml["'][^<]*>/)
return !!match
}
type StatusValues =
/** No record of web access or record reset */
undefined |
/** Has been requested, fetch in progress */
true |
/** Received, OK */
'done' |
/** Not logged in */
401 |
/** HTTP status unauthorized */
403 |
/** Not found, resource does not exist */
404 |
/** In attempt to counter CORS problems retried */
'redirected' |
/** If it did fail */
'failed' |
'parse_error' |
/**
* URI is not a protocol Fetcher can deal with
* other strings mean various other errors.
*/
'unsupported_protocol' |
'timeout' |
/** Any other HTTP status code */
number
interface MediatypesMap {
[id: string]: {
// Either string '1.0' or number 1.0 is allowed
'q'?: number | string
};
}
interface RequestedMap {
[uri: string]: StatusValues
}
interface TimeOutsMap {
[uri: string]: number[]
}
interface FetchQueue {
[uri: string]: Promise<ExtendedResponse>
}
interface FetchCallbacks {
[uri: string]: UserCallback[]
}
interface BooleanMap {
[uri: string]: boolean
}
// Not sure about the shapes of this. Response? FetchError?
type Result = Response
/** Differs from normal Fetch, has an extended Response type */
type Fetch = (input: RequestInfo, init?: RequestInit) => Promise<ExtendedResponse>;
interface CallbackifyInterface {
fireCallbacks: Function
}
/** Fetcher
*
* The Fetcher object is a helper object for a quadstore
* which turns it from an offline store to an online store.
* The fetcher deals with loading data files rom the web,
* figuring how to parse them. It will also refresh, remove, the data
* and put back the data to the web.
*/
export default class Fetcher implements CallbackifyInterface {
store: IndexedFormula
timeout: number
_fetch: Fetch
mediatypes: MediatypesMap
/** Denoting this session */
appNode: NamedNode
/**
* this.requested[uri] states:
* undefined no record of web access or records reset
* true has been requested, fetch in progress
* 'done' received, Ok
* 401 Not logged in
* 403 HTTP status unauthorized
* 404 Resource does not exist. Can be created etc.
* 'redirected' In attempt to counter CORS problems retried.
* 'parse_error' Parse error
* 'unsupported_protocol' URI is not a protocol Fetcher can deal with
* other strings mean various other errors.
*/
requested: RequestedMap
/** List of timeouts associated with a requested URL */
timeouts: TimeOutsMap
/** Redirected from *key uri* to *value uri* */
redirectedTo: Record<string, string>
fetchQueue: FetchQueue
/** fetchCallbacks[uri].push(callback) */
fetchCallbacks: FetchCallbacks
/** Keep track of explicit 404s -> we can overwrite etc */
nonexistent: BooleanMap
lookedUp: BooleanMap
handlers: Array<typeof Handler>
ns: { [k: string]: (ln: string) => Quad_Predicate }
static HANDLERS: {
[handlerName: number]: Handler
}
static CONTENT_TYPE_BY_EXT: Record<string, string>
// TODO: Document this
static crossSiteProxyTemplate: any
/** Methods added by calling Util.callbackify in the constructor*/
fireCallbacks!: Function
constructor (store: IndexedFormula, options: Options = {}) {
this.store = store || new IndexedFormula()
this.ns = getNS(this.store.rdfFactory)
this.timeout = options.timeout || 30000
// solidFetcher is deprecated
this._fetch = options.fetch
|| (typeof global !== 'undefined' && (global.solidFetcher || global.solidFetch))
|| (typeof window !== 'undefined' && (window.solidFetcher || window.solidFetch))
|| crossFetch
if (!this._fetch) {
throw new Error('No _fetch function available for Fetcher')
}
// This is the name of the graph we store all the HTTP metadata in
this.appNode = this.store.sym('chrome://TheCurrentSession')
// this.appNode = this.store.rdfFactory.blankNode() // Needs to have a URI in tests
this.store.fetcher = this // Bi-linked
this.requested = {}
this.timeouts = {}
this.redirectedTo = {}
this.fetchQueue = {}
this.fetchCallbacks = {}
this.nonexistent = {}
this.lookedUp = {}
this.handlers = []
this.mediatypes = {
'image/*': { 'q': 0.9 },
'*/*': { 'q': 0.1 } // Must allow access to random content
}
// Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail',
// 'refresh', 'retract', 'done'])
// In switching to fetch(), 'recv', 'headers' and 'load' do not make sense
Util.callbackify(this, ['request', 'fail', 'refresh', 'retract', 'done'])
Object.keys(options.handlers || defaultHandlers).map(key => this.addHandler(defaultHandlers[key]))
}
static crossSiteProxy (uri: string): undefined | any {
if (Fetcher.crossSiteProxyTemplate) {
return Fetcher.crossSiteProxyTemplate
.replace('{uri}', encodeURIComponent(uri))
} else {
return undefined
}
}
static offlineOverride (uri: string): string {
// Map the URI to a localhost proxy if we are running on localhost
// This is used for working offline, e.g. on planes.
// Is the script itself is running in localhost, then access all
// data in a localhost mirror.
// Do not remove without checking with TimBL
let requestedURI = uri
var UI
if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) &&
UI.preferences && UI.preferences.get('offlineModeUsingLocalhost')) {
if (requestedURI.slice(0, 7) === 'http://' && requestedURI.slice(7, 17) !== 'localhost/') {
requestedURI = 'http://localhost/' + requestedURI.slice(7)
log.warn('Localhost kludge for offline use: actually getting <' +
requestedURI + '>')
} else {
// log.warn("Localhost kludge NOT USED <" + requestedURI + ">")
}
} else {
// log.warn("Localhost kludge OFF offline use: actually getting <" +
// requestedURI + ">")
}
return requestedURI
}
static proxyIfNecessary (uri: string) {
var UI
if (
typeof window !== 'undefined' &&
(window as any).panes &&
(UI = (window as any).panes.UI) &&
UI.isExtension
) {
return uri
} // Extension does not need proxy
if (typeof $SolidTestEnvironment !== 'undefined' &&
$SolidTestEnvironment.localSiteMap) {
// nested dictionaries of URI parts from origin down
let hostpath = uri.split('/').slice(2) // the bit after the //
const lookup = (parts, index) => {
let z = index[parts.shift()]
if (!z) { return null }
if (typeof z === 'string') {
return z + parts.join('/')
}
if (!parts) { return null }
return lookup(parts, z)
}
const y = lookup(hostpath, $SolidTestEnvironment.localSiteMap)
if (y) {
return y
}
}
// browser does 2014 on as https browser script not trusted
// If the web app origin is https: then the mixed content rules
// prevent it loading insecure http: stuff so we need proxy.
if (Fetcher.crossSiteProxyTemplate &&
typeof document !== 'undefined' && document.location &&
('' + document.location).slice(0, 6) === 'https:' && // origin is secure
uri.slice(0, 5) === 'http:') { // requested data is not
return Fetcher.crossSiteProxyTemplate
.replace('{uri}', encodeURIComponent(uri))
}
return uri
}
/**
* Tests whether the uri's protocol is supported by the Fetcher.
* @param uri
*/
static unsupportedProtocol (uri: string): boolean {
let pcol = Uri.protocol(uri)
return (pcol === 'tel' || pcol === 'mailto' || pcol === 'urn')
}
/** Decide on credentials using old XXHR api or new fetch() one
* @param requestedURI
* @param options
*/
static setCredentials (requestedURI: string, options: Options = {}) {
// 2014 CORS problem:
// XMLHttpRequest cannot load http://www.w3.org/People/Berners-Lee/card.
// A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin'
// header when the credentials flag is true.
// @ Many ontology files under http: and need CORS wildcard ->
// can't have credentials
if (options.credentials === undefined) { // Caller using new fetch convention
if (options.withCredentials !== undefined) { // XHR style is what Fetcher specified before
options.credentials = options.withCredentials ? 'include' : 'omit'
} else {
options.credentials = 'include' // default is to be logged on
}
}
}
/**
* Promise-based load function
*
* Loads a web resource or resources into the store.
*
* A resource may be given as NamedNode object, or as a plain URI.
* an array of resources will be given, in which they will be fetched in parallel.
* By default, the HTTP headers are recorded also, in the same store, in a separate graph.
* This allows code like editable() for example to test things about the resource.
*
* @param uri {Array<RDFlibNamedNode>|Array<string>|RDFlibNamedNode|string}
*
* @param [options={}] {Object}
*
* @param [options.fetch] {Function}
*
* @param [options.referringTerm] {RDFlibNamedNode} Referring term, the resource which
* referred to this (for tracking bad links)
*
* @param [options.contentType] {string} Provided content type (for writes)
*
* @param [options.forceContentType] {string} Override the incoming header to
* force the data to be treated as this content-type (for reads)
*
* @param [options.force] {boolean} Load the data even if loaded before.
* Also sets the `Cache-Control:` header to `no-cache`
*
* @param [options.baseURI=docuri] {Node|string} Original uri to preserve
* through proxying etc (`xhr.original`).
*
* @param [options.proxyUsed] {boolean} Whether this request is a retry via
* a proxy (generally done from an error handler)
*
* @param [options.withCredentials] {boolean} flag for XHR/CORS etc
*
* @param [options.clearPreviousData] {boolean} Before we parse new data,
* clear old, but only on status 200 responses
*
* @param [options.noMeta] {boolean} Prevents the addition of various metadata
* triples (about the fetch request) to the store
*
* @param [options.noRDFa] {boolean}
*
* @returns {Promise<Result>}
*/
load <T extends NamedNode | string | Array<string | NamedNode>>(
uri: T,
options: Options = {}
): T extends Array<string | NamedNode> ? Promise<Result[]> : Promise<Result> {
options = Object.assign({}, options) // Take a copy as we add stuff to the options!!
if (uri instanceof Array) {
return Promise.all(uri.map((x) => {
return this.load(x, Object.assign({}, options)) as unknown as Promise<Result>
})) as T extends Array<string | NamedNode> ? Promise<Result[]> : Promise<Result>
}
const uriIn: NamedNode | string = uri as NamedNode
let docuri = termValue(uriIn)
docuri = docuri.split('#')[0]
options = this.initFetchOptions(docuri, options)
// if metadata flaged clear cache and removeDocument
const meta = this.appNode
const kb = this.store
const requests = kb.statementsMatching(undefined, this.ns.link('requestedURI'), kb.sym(docuri), meta).map(st => st.subject)
for (const request of requests) {
const response = kb.any(request, this.ns.link('response'), null, meta) as Quad_Subject
if (response != undefined) { // ts
const quad = kb.statementsMatching(response, this.ns.link('outOfDate'), true as any, meta)
kb.remove(quad)
options.force = true
options.clearPreviousData = true
}
}
const initialisedOptions = this.initFetchOptions(docuri, options)
return this.pendingFetchPromise(docuri, initialisedOptions.baseURI, initialisedOptions) as any
}
async pendingFetchPromise (
uri: string,
originalUri: string,
options: AutoInitOptions
): Promise<Result> {