rdflib 2.2.19 → 2.2.20-1f25cea3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lists.ts ADDED
@@ -0,0 +1,121 @@
1
+ /* Lists form conversion
2
+ */
3
+
4
+
5
+ // import DataFactory from './factories/extended-term-factory'
6
+ // import jsonldParser from './jsonldparser'
7
+ // @ts-ignore is this injected?
8
+ import { Parser as N3jsParser } from 'n3' // @@ Goal: remove this dependency
9
+ // import N3Parser from './n3parser'
10
+ // import { parseRDFaDOM } from './rdfaparser'
11
+ // import RDFParser from './rdfxmlparser'
12
+ // import sparqlUpdateParser from './patch-parser'
13
+ // import * as Util from './utils-js'
14
+ import Node from './node-internal'
15
+ // import BlankNode from './blank-node'
16
+ // import NamedNode from './named-node'
17
+ import Collection from './collection'
18
+ import Statement from './statement'
19
+ // import Formula from './formula'
20
+ import Store from './store'
21
+ // import { ContentType, TurtleContentType, N3ContentType, RDFXMLContentType, XHTMLContentType, HTMLContentType, SPARQLUpdateContentType, SPARQLUpdateSingleMatchContentType, JSONLDContentType, NQuadsContentType, NQuadsAltContentType } from './types'
22
+
23
+ // import { Quad } from './tf-types'
24
+
25
+ import {BlankNode, NamedNode, Quad, Term,} from './tf-types'
26
+ import Namespace from './namespace'
27
+
28
+ const RDF = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
29
+
30
+ /* Replace a given node with another node throughout a given document
31
+ *
32
+ * we do the predicate as well for complenesss though we don't expect Collections to use it
33
+ */
34
+ export function substituteInDoc (store:Store, x:Term, y:Term, doc?: NamedNode ) {
35
+ // console.log(`substituteInDoc put ${x} for ${y} in ${doc}}`)
36
+ for (const quad of store.statementsMatching(y as any, null, null, doc as any)) {
37
+ const newStatement = new Statement(x as any, quad.predicate, quad.object, doc as any)
38
+ store.remove(quad)
39
+ store.add(newStatement)
40
+ }
41
+ for (const quad of store.statementsMatching(null, y as any, null, doc) as any) {
42
+ store.remove(quad)
43
+ // console.log(` substituteInDoc predicate ${x} in ${quad}}`)
44
+ store.add(new Statement(quad.subject, x as any, quad.object, doc as any))
45
+ }
46
+ for (const quad of store.statementsMatching(null, null, y as any, doc) as any) {
47
+ store.remove(quad)
48
+ store.add(new Statement(quad.subject, quad.predicate, x as any, doc as any))
49
+ }
50
+ }
51
+
52
+ /* Change all lone rdf:nil nodes into empty Collections
53
+ */
54
+ export function substituteNillsInDoc (store:Store, doc?: NamedNode) {
55
+ const x = RDF('nil')
56
+ for (const quad of store.statementsMatching(x as any, null, null, doc as any)) {
57
+ store.remove(quad)
58
+ const y = new Collection()
59
+ store.add(new Statement(y as any, quad.predicate, quad.object, doc as any))
60
+ }
61
+ for (const quad of store.statementsMatching(null, null, x as any, doc) as any) {
62
+ if (!quad.predicate.sameTerm(RDF('rest'))) { // If not a tail
63
+ store.remove(quad)
64
+ const y = new Collection()
65
+ store.add(new Statement(quad.subject, quad.predicate, y as any, doc as any))
66
+ }
67
+ }
68
+ }
69
+ /**
70
+ * Convert lists reified as rdf:first, rest
71
+ * Normal method is sync.
72
+ * Unfortunately jsdonld is currently written to need to be called async.
73
+ * Hence the mess below with executeCallback.
74
+ * @param store - The quadstore
75
+ * @param doc - The document in which the conversion is done
76
+ */
77
+
78
+
79
+ export function convertFirstRestNil (
80
+ store: Store,
81
+ doc: NamedNode | undefined, // Do whole store?
82
+ ) {
83
+
84
+ function preceding (ele:BlankNode, listSoFar: Node[], trash: Quad[]): undefined {
85
+
86
+ const rests = store.statementsMatching(ele, RDF('rest'), null, doc)
87
+ if (rests.length !== 1) throw new Error(`Bad list structure: no rest at ${ele}`)
88
+
89
+ const firsts = store.statementsMatching(ele, RDF('first'), null, doc)
90
+ if (firsts.length !== 1) throw new Error(`Bad list structure: rest but ${firsts.length} firsts at ${ele}`)
91
+ const value = firsts[0].object
92
+ const total = [value].concat(listSoFar as any)
93
+ // console.log(' List now is: ', total)
94
+ const totalTrash = trash.concat(rests).concat(firsts)
95
+
96
+ const pres = store.statementsMatching(null, RDF('rest'), ele, doc)
97
+ if (pres.length === 0) { // Head of the list
98
+ const newList = new Collection(total)
99
+ store.remove(totalTrash)
100
+ // Replace old list with new list:
101
+ substituteInDoc(store, newList, ele, doc)
102
+ return
103
+ }
104
+ if (pres.length !== 1) throw new Error(`Bad list structure: ${pres.length} pres at ${ele}`)
105
+ const pre = pres[0].subject
106
+ if (pre.termType !== 'BlankNode') throw new Error(`Bad list element node ${pre} type: ${pre.termType} `)
107
+
108
+ preceding(pre, total, totalTrash)
109
+ return
110
+ }
111
+
112
+ substituteNillsInDoc(store, doc) // lone ones only
113
+
114
+ const tails = store.statementsMatching(null, RDF('rest'), RDF('nil'), doc)
115
+ tails.forEach(tail => {
116
+ if (tail.subject.termType !== 'BlankNode')
117
+ throw new Error(`Bad list element node ${tail.subject} type: ${tail.subject.termType} `)
118
+ preceding(tail.subject, [], [])
119
+ })
120
+
121
+ }
package/src/serializer.js CHANGED
@@ -40,7 +40,7 @@ export class Serializer {
40
40
  this.keywords = ['a'] // The only one we generate at the moment
41
41
  this.prefixchars = 'abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
42
42
  this.incoming = null // Array not calculated yet
43
- this.formulas = [] // remebering original formulae from hashes
43
+ this.formulas = [] // remembering original formulae from hashes
44
44
  this.store = store
45
45
  this.rdfFactory = store.rdfFactory || CanonicalDataFactory
46
46
  this.xsd = createXSD(this.rdfFactory)
@@ -74,7 +74,7 @@ export class Serializer {
74
74
  }
75
75
 
76
76
  /**
77
- * Defines a set of [prefix, namespace] pairs to be uised by this Serializer instance.
77
+ * Defines a set of [prefix, namespace] pairs to be used by this Serializer instance.
78
78
  * Overrides previous prefixes if any
79
79
  * @param namespaces
80
80
  * @return {Serializer}
@@ -536,7 +536,7 @@ export class Serializer {
536
536
  case 'http://www.w3.org/2001/XMLSchema#integer':
537
537
  return val
538
538
 
539
- case 'http://www.w3.org/2001/XMLSchema#decimal': // In urtle must have dot
539
+ case 'http://www.w3.org/2001/XMLSchema#decimal': // In Turtle, must have dot
540
540
  if (val.indexOf('.') < 0) val += '.0'
541
541
  return val
542
542
 
@@ -561,6 +561,8 @@ export class Serializer {
561
561
  return str
562
562
  case 'NamedNode':
563
563
  return this.symbolToN3(expr)
564
+ case 'DefaultGraph':
565
+ return '';
564
566
  default:
565
567
  throw new Error('Internal: atomicTermToN3 cannot handle ' + expr + ' of termType: ' + expr.termType)
566
568
  }
@@ -1031,4 +1033,4 @@ function backslashUify (str) {
1031
1033
  }
1032
1034
  }
1033
1035
  return res
1034
- }
1036
+ }
package/src/statement.ts CHANGED
@@ -137,6 +137,13 @@ export default class Statement<
137
137
 
138
138
  /** Creates a string representation of this statement */
139
139
  toString (): string {
140
+ /*
141
+ return [
142
+ this.subject.toString(),
143
+ this.predicate.toString(),
144
+ this.object.toString(),
145
+ ].join(' ') + ' .'
146
+ */
140
147
  return this.toNT()
141
148
  }
142
149
  }
package/src/store.ts CHANGED
@@ -23,12 +23,14 @@ import Formula, { FormulaOpts } from './formula'
23
23
  import { ArrayIndexOf } from './utils'
24
24
  import { RDFArrayRemove } from './utils-js'
25
25
  import {
26
+ isRDFlibSubject,
27
+ isRDFlibPredicate,
26
28
  isRDFlibObject,
27
29
  isStore,
28
30
  isGraph,
29
- isPredicate,
31
+ // isPredicate,
30
32
  isQuad,
31
- isSubject
33
+ // isSubject
32
34
  } from './utils/terms'
33
35
  import Node from './node'
34
36
  import Variable from './variable'
@@ -429,10 +431,10 @@ export default class IndexedFormula extends Formula { // IN future - allow pass
429
431
  pred = Node.fromValue(pred)
430
432
  const objNode = Node.fromValue(obj) as Term
431
433
  why = Node.fromValue(why)
432
- if (!isSubject(subj)) {
434
+ if (!isRDFlibSubject(subj)) {
433
435
  throw new Error('Subject is not a subject type')
434
436
  }
435
- if (!isPredicate(pred)) {
437
+ if (!isRDFlibPredicate(pred)) {
436
438
  throw new Error(`Predicate ${pred} is not a predicate type`)
437
439
  }
438
440
  if (!isRDFlibObject(objNode)) {
@@ -920,9 +922,7 @@ export default class IndexedFormula extends Formula { // IN future - allow pass
920
922
  object?: Quad_Object | null,
921
923
  graph?: Quad_Graph | null
922
924
  ): IndexedFormula {
923
- this.removeStatements(
924
- this.statementsMatching(subject, predicate, object, graph)
925
- )
925
+ this.removeMany(subject, predicate, object, graph)
926
926
  return this
927
927
  }
928
928
 
@@ -5,26 +5,16 @@
5
5
  ** 2010-12-07 TimBL addred local file write code
6
6
  */
7
7
  import IndexedFormula from './store'
8
- import { docpart } from './uri'
9
- import Fetcher from './fetcher'
8
+ import {docpart, join as uriJoin} from './uri'
9
+ import Fetcher, {Options} from './fetcher'
10
10
  import Namespace from './namespace'
11
11
  import Serializer from './serializer'
12
- import { join as uriJoin } from './uri'
13
- import { isStore, isBlankNode } from './utils/terms'
12
+ import {isBlankNode, isStore} from './utils/terms'
14
13
  import * as Util from './utils-js'
15
14
  import Statement from './statement'
16
15
  import RDFlibNamedNode from './named-node'
17
- import { termValue } from './utils/termValue'
18
- import {
19
- BlankNode,
20
- NamedNode,
21
- Quad_Graph,
22
- Quad_Object,
23
- Quad_Predicate,
24
- Quad_Subject,
25
- Quad,
26
- Term,
27
- } from './tf-types'
16
+ import {termValue} from './utils/termValue'
17
+ import {BlankNode, NamedNode, Quad, Quad_Graph, Quad_Object, Quad_Predicate, Quad_Subject, Term,} from './tf-types'
28
18
 
29
19
  interface UpdateManagerFormula extends IndexedFormula {
30
20
  fetcher: Fetcher
@@ -205,6 +195,10 @@ export default class UpdateManager {
205
195
  this.anonymize(stmt.object) + ' .'
206
196
  }
207
197
 
198
+ nTriples(stmt) {
199
+ return `${stmt.subject.toNT()} ${stmt.predicate.toNT()} ${stmt.object.toNT()} .`
200
+ }
201
+
208
202
  /**
209
203
  * Returns a list of all bnodes occurring in a statement
210
204
  * @private
@@ -365,7 +359,8 @@ export default class UpdateManager {
365
359
  fire (
366
360
  uri: string,
367
361
  query: string,
368
- callbackFunction: CallBackFunction
362
+ callbackFunction: CallBackFunction,
363
+ options: Options = {}
369
364
  ): Promise<void> {
370
365
  return Promise.resolve()
371
366
  .then(() => {
@@ -374,11 +369,9 @@ export default class UpdateManager {
374
369
  }
375
370
  // console.log('UpdateManager: sending update to <' + uri + '>')
376
371
 
377
- let options = {
378
- noMeta: true,
379
- contentType: 'application/sparql-update',
380
- body: query
381
- }
372
+ options.noMeta = true;
373
+ options.contentType = 'application/sparql-update';
374
+ options.body = query;
382
375
 
383
376
  return this.store.fetcher.webOperation('PATCH', uri, options)
384
377
  })
@@ -696,7 +689,7 @@ export default class UpdateManager {
696
689
  thisUpdater.update(deletions.filter(st => st.why.equals(doc)),
697
690
  insertions.filter(st => st.why.equals(doc))))
698
691
  if (updates.length > 1) {
699
- console.log(`@@ updateMany to ${updates.length}: ${uniqueDocs}`)
692
+ // console.log(`@@ updateMany to ${updates.length}: ${uniqueDocs}`)
700
693
  }
701
694
  return Promise.all(updates)
702
695
  }
@@ -709,6 +702,7 @@ export default class UpdateManager {
709
702
  * @param insertions - Statement or statements to be inserted.
710
703
  * @param callback - called as callbackFunction(uri, success, errorbody)
711
704
  * OR returns a promise
705
+ * @param options - Options for the fetch call
712
706
  */
713
707
  update(
714
708
  deletions: ReadonlyArray<Statement>,
@@ -719,7 +713,8 @@ export default class UpdateManager {
719
713
  errorBody?: string,
720
714
  response?: Response | Error
721
715
  ) => void,
722
- secondTry?: boolean
716
+ secondTry?: boolean,
717
+ options: Options = {}
723
718
  ): void | Promise<void> {
724
719
  if (!callback) {
725
720
  var thisUpdater = this
@@ -730,7 +725,7 @@ export default class UpdateManager {
730
725
  } else {
731
726
  resolve()
732
727
  }
733
- }) // callbackFunction
728
+ }, secondTry, options) // callbackFunction
734
729
  }) // promise
735
730
  } // if
736
731
 
@@ -787,10 +782,10 @@ export default class UpdateManager {
787
782
  }
788
783
  // console.log(`Update: have not loaded ${doc} before: loading now...`);
789
784
  (this.store.fetcher.load(doc) as Promise<Response>).then(response => {
790
- this.update(deletions, insertions, callback, true)
785
+ this.update(deletions, insertions, callback, true, options)
791
786
  }, err => {
792
787
  if (err.response.status === 404) { // nonexistent files are fine
793
- this.update(deletions, insertions, callback, true)
788
+ this.update(deletions, insertions, callback, true, options)
794
789
  } else {
795
790
  throw new Error(`Update: Can't get updatability status ${doc} before patching: ${err}`)
796
791
  }
@@ -831,7 +826,7 @@ export default class UpdateManager {
831
826
  if (ds.length) query += ' ; '
832
827
  query += 'INSERT DATA { '
833
828
  for (let i = 0; i < is.length; i++) {
834
- query += this.anonymizeNT(is[i]) + '\n'
829
+ query += this.nTriples(is[i]) + '\n'
835
830
  }
836
831
  query += ' }\n'
837
832
  }
@@ -845,9 +840,10 @@ export default class UpdateManager {
845
840
 
846
841
  this.fire(doc.value, query, (uri, success, body, response) => {
847
842
  (response as any).elapsedTimeMs = Date.now() - startTime
848
- console.log(' UpdateManager: Return ' +
843
+ /* console.log(' UpdateManager: Return ' +
849
844
  (success ? 'success ' : 'FAILURE ') + (response as Response).status +
850
845
  ' elapsed ' + (response as any).elapsedTimeMs + 'ms')
846
+ */
851
847
  if (success) {
852
848
  try {
853
849
  kb.remove(ds)
@@ -869,13 +865,13 @@ export default class UpdateManager {
869
865
  // console.log('delayed downstream action:')
870
866
  downstreamAction(doc)
871
867
  }
872
- })
868
+ }, options)
873
869
  } else if ((protocol as string).indexOf('DAV') >= 0) {
874
- this.updateDav(doc, ds, is, callback)
870
+ this.updateDav(doc, ds, is, callback, options)
875
871
  } else {
876
872
  if ((protocol as string).indexOf('LOCALFILE') >= 0) {
877
873
  try {
878
- this.updateLocalFile(doc, ds, is, callback)
874
+ this.updateLocalFile(doc, ds, is, callback, options)
879
875
  } catch (e) {
880
876
  callback(doc.value, false,
881
877
  'Exception trying to write back file <' + doc.value + '>\n'
@@ -896,7 +892,8 @@ export default class UpdateManager {
896
892
  doc: Quad_Subject,
897
893
  ds,
898
894
  is,
899
- callbackFunction
895
+ callbackFunction,
896
+ options: Options = {}
900
897
  ): null | Promise<void> {
901
898
  let kb = this.store
902
899
  // The code below is derived from Kenny's UpdateCenter.js
@@ -929,11 +926,9 @@ export default class UpdateManager {
929
926
  targetURI = uriJoin(candidateTarget.value, targetURI)
930
927
  }
931
928
 
932
- let options = {
933
- contentType,
934
- noMeta: true,
935
- body: documentString
936
- }
929
+ options.contentType = contentType
930
+ options.noMeta = true
931
+ options.body = documentString
937
932
 
938
933
  return kb.fetcher.webOperation('PUT', targetURI, options)
939
934
  .then(response => {
@@ -962,8 +957,9 @@ export default class UpdateManager {
962
957
  * @param ds
963
958
  * @param is
964
959
  * @param callbackFunction
960
+ * @param options
965
961
  */
966
- updateLocalFile (doc: NamedNode, ds, is, callbackFunction): void {
962
+ updateLocalFile (doc: NamedNode, ds, is, callbackFunction, options: Options = {}): void {
967
963
  const kb = this.store
968
964
  // console.log('Writing back to local file\n')
969
965
 
@@ -988,12 +984,10 @@ export default class UpdateManager {
988
984
  throw new Error('File extension .' + ext + ' not supported for data write')
989
985
  }
990
986
 
991
- const documentString = this.serialize(doc.value, newSts, contentType)
987
+ options.body = this.serialize(doc.value, newSts, contentType);
988
+ options.contentType = contentType;
992
989
 
993
- kb.fetcher.webOperation('PUT',doc.value,{
994
- "body" : documentString,
995
- contentType : contentType,
996
- }).then( (response)=>{
990
+ kb.fetcher.webOperation('PUT', doc.value, options).then( (response)=>{
997
991
  if(!response.ok) return callbackFunction(doc.value,false,response.error)
998
992
  for (let i = 0; i < ds.length; i++) {
999
993
  kb.remove(ds[i]);
@@ -33,7 +33,7 @@ export function isCollection(obj: any): obj is Collection<any> {
33
33
  && (obj as Term).termType === CollectionTermType
34
34
  }
35
35
 
36
- /** TypeGuard for valid RDFlib Object types, also allows Collections */
36
+ /** TypeGuard for valid RDFlib Object types, also allows Collections, Graphs */
37
37
  export function isRDFlibObject(obj: any): obj is ObjectType {
38
38
  return obj && Object.prototype.hasOwnProperty.call(obj, 'termType') && (
39
39
  obj.termType === NamedNodeTermType ||
@@ -45,6 +45,28 @@ export function isRDFlibObject(obj: any): obj is ObjectType {
45
45
  )
46
46
  }
47
47
 
48
+ /** TypeGuard for valid RDFlib Subject types, same as Object as RDFLib symmetrical.
49
+ */
50
+ export function isRDFlibSubject(obj: any): obj is ObjectType {
51
+ return obj && Object.prototype.hasOwnProperty.call(obj, 'termType') && (
52
+ obj.termType === NamedNodeTermType ||
53
+ obj.termType === VariableTermType ||
54
+ obj.termType === BlankNodeTermType ||
55
+ obj.termType === CollectionTermType ||
56
+ obj.termType === LiteralTermType ||
57
+ obj.termType === GraphTermType
58
+ )
59
+ }
60
+
61
+ /** TypeGuard for valid RDF/JS spec Predicate types */
62
+ export function isRDFlibPredicate(obj: any): obj is Quad_Predicate {
63
+ return isTerm(obj) && (
64
+ obj.termType === NamedNodeTermType ||
65
+ obj.termType === BlankNodeTermType ||
66
+ obj.termType === VariableTermType
67
+ )
68
+ }
69
+
48
70
  /** TypeGuard for RDFLib Variables */
49
71
  export function isVariable(obj: any): obj is Variable {
50
72
  return isTerm(obj)