-
Notifications
You must be signed in to change notification settings - Fork 4
/
n3-bundle.js
9496 lines (8256 loc) · 294 KB
/
n3-bundle.js
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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.N3 = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
var N3 = require('n3');
exports.N3 = N3;
},{"n3":2}],2:[function(require,module,exports){
module.exports = {
DataFactory: require('./lib/N3DataFactory'),
Lexer: require('./lib/N3Lexer'),
Parser: require('./lib/N3Parser'),
Writer: require('./lib/N3Writer'),
Store: require('./lib/N3Store'),
StreamParser: require('./lib/N3StreamParser'),
StreamWriter: require('./lib/N3StreamWriter'),
Util: require('./lib/N3Util'),
};
},{"./lib/N3DataFactory":4,"./lib/N3Lexer":5,"./lib/N3Parser":6,"./lib/N3Store":7,"./lib/N3StreamParser":8,"./lib/N3StreamWriter":9,"./lib/N3Util":10,"./lib/N3Writer":11}],3:[function(require,module,exports){
var RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
XSD = 'http://www.w3.org/2001/XMLSchema#',
SWAP = 'http://www.w3.org/2000/10/swap/';
module.exports = {
xsd: {
decimal: XSD + 'decimal',
boolean: XSD + 'boolean',
double: XSD + 'double',
integer: XSD + 'integer',
string: XSD + 'string',
},
rdf: {
type: RDF + 'type',
nil: RDF + 'nil',
first: RDF + 'first',
rest: RDF + 'rest',
langString: RDF + 'langString',
},
owl: {
sameAs: 'http://www.w3.org/2002/07/owl#sameAs',
},
r: {
forSome: SWAP + 'reify#forSome',
forAll: SWAP + 'reify#forAll',
},
log: {
implies: SWAP + 'log#implies',
},
};
},{}],4:[function(require,module,exports){
// N3.js implementations of the RDF/JS core data types
// See https://github.com/rdfjs/representation-task-force/blob/master/interface-spec.md
var namespaces = require('./IRIs');
var rdf = namespaces.rdf,
xsd = namespaces.xsd;
var DataFactory, DEFAULTGRAPH;
var _blankNodeCounter = 0;
// ## Term constructor
function Term(id) {
if (!(this instanceof Term))
return new Term(id);
this.id = id;
}
// ### Makes this class a subclass of the given type
Term.subclass = function subclass(Type, name) {
Type.prototype = Object.create(this.prototype, {
constructor: { value: Type },
termType: {
enumerable: true,
value: name,
},
});
Type.subclass = subclass;
};
// ### Returns whether this object represents the same term as the other
Term.prototype.equals = function (other) {
// If both terms were created by this library,
// equality can be computed through ids
if (other instanceof Term)
return this.id === other.id;
// Otherwise, compare term type and value
return !!other && this.termType === other.termType &&
this.value === other.value;
};
// ### Returns a plain object representation of this term
Term.prototype.toJSON = function () {
return {
termType: this.termType,
value: this.value,
};
};
// ### Constructs a term from the given internal string ID
function fromId(id, factory) {
factory = factory || DataFactory;
// Falsy value or empty string indicate the default graph
if (!id)
return factory.defaultGraph();
// Identify the term type based on the first character
switch (id[0]) {
case '_': return factory.blankNode(id.substr(2));
case '?': return factory.variable(id.substr(1));
case '"':
// Shortcut for internal literals
if (factory === DataFactory)
return new Literal(id);
// Literal without datatype or language
if (id[id.length - 1] === '"')
return factory.literal(id.substr(1, id.length - 2));
// Literal with datatype or language
var endPos = id.lastIndexOf('"', id.length - 1);
return factory.literal(id.substr(1, endPos - 1),
id[endPos + 1] === '@' ? id.substr(endPos + 2)
: factory.namedNode(id.substr(endPos + 3)));
default: return factory.namedNode(id);
}
}
// ### Constructs an internal string ID from the given term or ID string
function toId(term) {
if (typeof term === 'string')
return term;
if (term instanceof Term)
return term.id;
if (!term)
return DEFAULTGRAPH.value;
// Term instantiated with another library
switch (term.termType) {
case 'NamedNode': return term.value;
case 'BlankNode': return '_:' + term.value;
case 'Variable': return '?' + term.value;
case 'DefaultGraph': return '';
case 'Literal': return '"' + term.value + '"' +
(term.language ? '@' + term.language :
(term.datatype && term.datatype.value !== xsd.string ? '^^' + term.datatype.value : ''));
default: throw new Error('Unexpected termType: ' + term.termType);
}
}
// ## NamedNode constructor
function NamedNode(iri) {
if (!(this instanceof NamedNode))
return new NamedNode(iri);
this.id = iri;
}
Term.subclass(NamedNode, 'NamedNode');
// ### The IRI of this named node
Object.defineProperty(NamedNode.prototype, 'value', {
enumerable: true,
get: function () { return this.id; },
});
// ## BlankNode constructor
function BlankNode(name) {
if (!(this instanceof BlankNode))
return new BlankNode(name);
this.id = '_:' + name;
}
Term.subclass(BlankNode, 'BlankNode');
// ### The name of this blank node
Object.defineProperty(BlankNode.prototype, 'value', {
enumerable: true,
get: function () { return this.id.substr(2); },
});
// ## Variable constructor
function Variable(name) {
if (!(this instanceof Variable))
return new Variable(name);
this.id = '?' + name;
}
Term.subclass(Variable, 'Variable');
// ### The name of this variable
Object.defineProperty(Variable.prototype, 'value', {
enumerable: true,
get: function () { return this.id.substr(1); },
});
// ## Literal constructor
function Literal(id) {
if (!(this instanceof Literal))
return new Literal(id);
this.id = id;
}
Term.subclass(Literal, 'Literal');
// ### The text value of this literal
Object.defineProperty(Literal.prototype, 'value', {
enumerable: true,
get: function () {
return this.id.substring(1, this.id.lastIndexOf('"'));
},
});
// ### The language of this literal
Object.defineProperty(Literal.prototype, 'language', {
enumerable: true,
get: function () {
// Find the last quotation mark (e.g., '"abc"@en-us')
var id = this.id, atPos = id.lastIndexOf('"') + 1;
// If "@" it follows, return the remaining substring; empty otherwise
return atPos < id.length && id[atPos++] === '@' ? id.substr(atPos).toLowerCase() : '';
},
});
// ### The datatype IRI of this literal
Object.defineProperty(Literal.prototype, 'datatype', {
enumerable: true,
get: function () {
return new NamedNode(this.datatypeString);
},
});
// ### The datatype string of this literal
Object.defineProperty(Literal.prototype, 'datatypeString', {
enumerable: true,
get: function () {
// Find the last quotation mark (e.g., '"abc"^^http://ex.org/types#t')
var id = this.id, dtPos = id.lastIndexOf('"') + 1, ch;
// If "^" it follows, return the remaining substring
return dtPos < id.length && (ch = id[dtPos]) === '^' ? id.substr(dtPos + 2) :
// If "@" follows, return rdf:langString; xsd:string otherwise
(ch !== '@' ? xsd.string : rdf.langString);
},
});
// ### Returns whether this object represents the same term as the other
Literal.prototype.equals = function (other) {
// If both literals were created by this library,
// equality can be computed through ids
if (other instanceof Literal)
return this.id === other.id;
// Otherwise, compare term type, value, language, and datatype
return !!other && !!other.datatype &&
this.termType === other.termType &&
this.value === other.value &&
this.language === other.language &&
this.datatype.value === other.datatype.value;
};
// ### Returns a plain object representation of this term
Literal.prototype.toJSON = function () {
return {
termType: this.termType,
value: this.value,
language: this.language,
datatype: { termType: 'NamedNode', value: this.datatypeString },
};
};
// ## DefaultGraph singleton
function DefaultGraph() {
return DEFAULTGRAPH || this;
}
Term.subclass(DefaultGraph, 'DefaultGraph');
// Initialize singleton
DEFAULTGRAPH = new DefaultGraph();
DEFAULTGRAPH.id = '';
// ### The empty string
Object.defineProperty(DefaultGraph.prototype, 'value', {
enumerable: true,
value: '',
});
// ### Returns whether this object represents the same term as the other
DefaultGraph.prototype.equals = function (other) {
// If both terms were created by this library,
// equality can be computed through strict equality;
// otherwise, compare term types.
return (this === other) || (!!other && (this.termType === other.termType));
};
// ## Quad constructor
function Quad(subject, predicate, object, graph) {
if (!(this instanceof Quad))
return new Quad(subject, predicate, object, graph);
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.graph = graph || DEFAULTGRAPH;
}
// ### Returns a plain object representation of this quad
Quad.prototype.toJSON = function () {
return {
subject: this.subject.toJSON(),
predicate: this.predicate.toJSON(),
object: this.object.toJSON(),
graph: this.graph.toJSON(),
};
};
// ### Returns whether this object represents the same quad as the other
Quad.prototype.equals = function (other) {
return !!other && this.subject.equals(other.subject) &&
this.predicate.equals(other.predicate) &&
this.object.equals(other.object) &&
this.graph.equals(other.graph);
};
// ## DataFactory functions
// ### Creates an IRI
function namedNode(iri) {
return new NamedNode(iri);
}
// ### Creates a blank node
function blankNode(name) {
if (!name)
name = 'n3-' + _blankNodeCounter++;
return new BlankNode(name);
}
// ### Creates a literal
function literal(value, languageOrDataType) {
// Create a language-tagged string
if (typeof languageOrDataType === 'string')
return new Literal('"' + value + '"@' + languageOrDataType.toLowerCase());
// Create a datatyped literal
var datatype = languageOrDataType && languageOrDataType.value || '';
if (!datatype) {
switch (typeof value) {
// Convert a boolean
case 'boolean':
datatype = xsd.boolean;
break;
// Convert an integer or double
case 'number':
if (Number.isFinite(value))
datatype = Number.isInteger(value) ? xsd.integer : xsd.double;
else {
datatype = xsd.double;
if (!Number.isNaN(value))
value = value > 0 ? 'INF' : '-INF';
}
break;
// No datatype, so convert a plain string
default:
return new Literal('"' + value + '"');
}
}
return new Literal('"' + value + '"^^' + datatype);
}
// ### Creates a variable
function variable(name) {
return new Variable(name);
}
// ### Returns the default graph
function defaultGraph() {
return DEFAULTGRAPH;
}
// ### Creates a quad
function quad(subject, predicate, object, graph) {
return new Quad(subject, predicate, object, graph);
}
// ## Module exports
module.exports = DataFactory = {
// ### Public factory functions
namedNode: namedNode,
blankNode: blankNode,
variable: variable,
literal: literal,
defaultGraph: defaultGraph,
quad: quad,
triple: quad,
// ### Internal datatype constructors
internal: {
Term: Term,
NamedNode: NamedNode,
BlankNode: BlankNode,
Variable: Variable,
Literal: Literal,
DefaultGraph: DefaultGraph,
Quad: Quad,
Triple: Quad,
fromId: fromId,
toId: toId,
},
};
},{"./IRIs":3}],5:[function(require,module,exports){
(function (Buffer,setImmediate){
// **N3Lexer** tokenizes N3 documents.
var xsd = require('./IRIs').xsd;
var fromCharCode = String.fromCharCode;
var immediately = typeof setImmediate === 'function' ? setImmediate :
function setImmediate(func) { setTimeout(func, 0); };
// Regular expression and replacement string to escape N3 strings.
// Note how we catch invalid unicode sequences separately (they will trigger an error).
var escapeSequence = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\[uU]|\\(.)/g;
var escapeReplacements = {
'\\': '\\', "'": "'", '"': '"',
'n': '\n', 'r': '\r', 't': '\t', 'f': '\f', 'b': '\b',
'_': '_', '~': '~', '.': '.', '-': '-', '!': '!', '$': '$', '&': '&',
'(': '(', ')': ')', '*': '*', '+': '+', ',': ',', ';': ';', '=': '=',
'/': '/', '?': '?', '#': '#', '@': '@', '%': '%',
};
var illegalIriChars = /[\x00-\x20<>\\"\{\}\|\^\`]/;
var lineModeRegExps = {
_iri: true,
_unescapedIri: true,
_unescapedQuote: true,
_singleQuote: true,
_langcode: true,
_blank: true,
_newline: true,
_comment: true,
_whitespace: true,
_endOfFile: true,
};
var invalidRegExp = /$0^/;
// ## Constructor
function N3Lexer(options) {
if (!(this instanceof N3Lexer))
return new N3Lexer(options);
options = options || {};
// In line mode (N-Triples or N-Quads), only simple features may be parsed
if (this._lineMode = !!options.lineMode) {
this._n3Mode = false;
// Don't tokenize special literals
for (var key in this) {
if (!(key in lineModeRegExps) && this[key] instanceof RegExp)
this[key] = invalidRegExp;
}
}
// When not in line mode, enable N3 functionality by default
else {
this._n3Mode = options.n3 !== false;
}
// Don't output comment tokens by default
this._comments = !!options.comments;
}
N3Lexer.prototype = {
// ## Regular expressions
// It's slightly faster to have these as properties than as in-scope variables
_iri: /^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/, // IRI with escape sequences; needs sanity check after unescaping
_unescapedIri: /^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/, // IRI without escape sequences; no unescaping
_unescapedQuote: /^"([^"\\\r\n]+)"/, // non-empty string without escape sequences
_unescapedApos: /^'([^'\\\r\n]+)'/,
_singleQuote: /^"((?:[^"\\\r\n]|\\.)*)"(?=[^"])/,
_singleApos: /^'((?:[^'\\\r\n]|\\.)*)'(?=[^'])/,
_tripleQuote: /^"""([^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*)"""/,
_tripleApos: /^'''([^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*)'''/,
_langcode: /^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,
_prefix: /^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,
_prefixed: /^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<]))/,
_variable: /^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<])/,
_blank: /^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<]))/,
_number: /^[\-+]?(?:\d+\.?\d*([eE](?:[\-\+])?\d+)|\d*\.?\d+)(?=\.?[,;:\s#()\[\]\{\}"'<])/,
_boolean: /^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<])/,
_keyword: /^@[a-z]+(?=[\s#<:])/i,
_sparqlKeyword: /^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,
_shortPredicates: /^a(?=\s+|<)/,
_newline: /^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,
_comment: /#([^\n\r]*)/,
_whitespace: /^[ \t]+/,
_endOfFile: /^(?:#[^\n\r]*)?$/,
// ## Private methods
// ### `_tokenizeToEnd` tokenizes as for as possible, emitting tokens through the callback
_tokenizeToEnd: function (callback, inputFinished) {
// Continue parsing as far as possible; the loop will return eventually
var input = this._input, outputComments = this._comments;
while (true) {
// Count and skip whitespace lines
var whiteSpaceMatch, comment;
while (whiteSpaceMatch = this._newline.exec(input)) {
// Try to find a comment
if (outputComments && (comment = this._comment.exec(whiteSpaceMatch[0])))
callback(null, { line: this._line, type: 'comment', value: comment[1], prefix: '' });
// Advance the input
input = input.substr(whiteSpaceMatch[0].length, input.length);
this._line++;
}
// Skip whitespace on current line
if (whiteSpaceMatch = this._whitespace.exec(input))
input = input.substr(whiteSpaceMatch[0].length, input.length);
// Stop for now if we're at the end
if (this._endOfFile.test(input)) {
// If the input is finished, emit EOF
if (inputFinished) {
// Try to find a final comment
if (outputComments && (comment = this._comment.exec(input)))
callback(null, { line: this._line, type: 'comment', value: comment[1], prefix: '' });
callback(input = null, { line: this._line, type: 'eof', value: '', prefix: '' });
}
return this._input = input;
}
// Look for specific token types based on the first character
var line = this._line, type = '', value = '', prefix = '',
firstChar = input[0], match = null, matchLength = 0, inconclusive = false;
switch (firstChar) {
case '^':
// We need at least 3 tokens lookahead to distinguish ^^<IRI> and ^^pre:fixed
if (input.length < 3)
break;
// Try to match a type
else if (input[1] === '^') {
this._previousMarker = '^^';
// Move to type IRI or prefixed name
input = input.substr(2);
if (input[0] !== '<') {
inconclusive = true;
break;
}
}
// If no type, it must be a path expression
else {
if (this._n3Mode) {
matchLength = 1;
type = '^';
}
break;
}
// Fall through in case the type is an IRI
case '<':
// Try to find a full IRI without escape sequences
if (match = this._unescapedIri.exec(input))
type = 'IRI', value = match[1];
// Try to find a full IRI with escape sequences
else if (match = this._iri.exec(input)) {
value = this._unescape(match[1]);
if (value === null || illegalIriChars.test(value))
return reportSyntaxError(this);
type = 'IRI';
}
// Try to find a backwards implication arrow
else if (this._n3Mode && input.length > 1 && input[1] === '=')
type = 'inverse', matchLength = 2, value = '>';
break;
case '_':
// Try to find a blank node. Since it can contain (but not end with) a dot,
// we always need a non-dot character before deciding it is a blank node.
// Therefore, try inserting a space if we're at the end of the input.
if ((match = this._blank.exec(input)) ||
inputFinished && (match = this._blank.exec(input + ' ')))
type = 'blank', prefix = '_', value = match[1];
break;
case '"':
// Try to find a literal without escape sequences
if (match = this._unescapedQuote.exec(input))
value = match[1];
// Before attempting more complex string patterns, try to detect a closing quote
else if (input.indexOf('"', 1) > 0) {
// Try to find any other literal wrapped in a pair of quotes
if (match = this._singleQuote.exec(input))
value = this._unescape(match[1]);
// Try to find a literal wrapped in three pairs of quotes
else if (match = this._tripleQuote.exec(input)) {
value = match[1];
// Advance line counter
this._line += value.split(/\r\n|\r|\n/).length - 1;
value = this._unescape(value);
}
if (value === null)
return reportSyntaxError(this);
}
if (match !== null)
type = 'literal';
break;
case "'":
// Try to find a literal without escape sequences
if (match = this._unescapedApos.exec(input))
value = match[1];
// Before attempting more complex string patterns, try to detect a closing apostrophe
else if (input.indexOf("'", 1) > 0) {
// Try to find any other literal wrapped in a pair of apostrophes
if (match = this._singleApos.exec(input))
value = this._unescape(match[1]);
// Try to find a literal wrapped in three pairs of apostrophes
else if (match = this._tripleApos.exec(input)) {
value = match[1];
// Advance line counter
this._line += value.split(/\r\n|\r|\n/).length - 1;
value = this._unescape(value);
}
if (value === null)
return reportSyntaxError(this);
}
if (match !== null)
type = 'literal';
break;
case '?':
// Try to find a variable
if (this._n3Mode && (match = this._variable.exec(input)))
type = 'var', value = match[0];
break;
case '@':
// Try to find a language code
if (this._previousMarker === 'literal' && (match = this._langcode.exec(input)))
type = 'langcode', value = match[1];
// Try to find a keyword
else if (match = this._keyword.exec(input))
type = match[0];
break;
case '.':
// Try to find a dot as punctuation
if (input.length === 1 ? inputFinished : (input[1] < '0' || input[1] > '9')) {
type = '.';
matchLength = 1;
break;
}
// Fall through to numerical case (could be a decimal dot)
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '+':
case '-':
// Try to find a number. Since it can contain (but not end with) a dot,
// we always need a non-dot character before deciding it is a number.
// Therefore, try inserting a space if we're at the end of the input.
if (match = this._number.exec(input) ||
inputFinished && (match = this._number.exec(input + ' '))) {
type = 'literal', value = match[0];
prefix = (match[1] ? xsd.double :
(/^[+\-]?\d+$/.test(match[0]) ? xsd.integer : xsd.decimal));
}
break;
case 'B':
case 'b':
case 'p':
case 'P':
case 'G':
case 'g':
// Try to find a SPARQL-style keyword
if (match = this._sparqlKeyword.exec(input))
type = match[0].toUpperCase();
else
inconclusive = true;
break;
case 'f':
case 't':
// Try to match a boolean
if (match = this._boolean.exec(input))
type = 'literal', value = match[0], prefix = xsd.boolean;
else
inconclusive = true;
break;
case 'a':
// Try to find an abbreviated predicate
if (match = this._shortPredicates.exec(input))
type = 'abbreviation', value = 'a';
else
inconclusive = true;
break;
case '=':
// Try to find an implication arrow or equals sign
if (this._n3Mode && input.length > 1) {
type = 'abbreviation';
if (input[1] !== '>')
matchLength = 1, value = '=';
else
matchLength = 2, value = '>';
}
break;
case '!':
if (!this._n3Mode)
break;
case ',':
case ';':
case '[':
case ']':
case '(':
case ')':
case '{':
case '}':
if (!this._lineMode) {
matchLength = 1;
type = firstChar;
}
break;
default:
inconclusive = true;
}
// Some first characters do not allow an immediate decision, so inspect more
if (inconclusive) {
// Try to find a prefix
if ((this._previousMarker === '@prefix' || this._previousMarker === 'PREFIX') &&
(match = this._prefix.exec(input)))
type = 'prefix', value = match[1] || '';
// Try to find a prefixed name. Since it can contain (but not end with) a dot,
// we always need a non-dot character before deciding it is a prefixed name.
// Therefore, try inserting a space if we're at the end of the input.
else if ((match = this._prefixed.exec(input)) ||
inputFinished && (match = this._prefixed.exec(input + ' ')))
type = 'prefixed', prefix = match[1] || '', value = this._unescape(match[2]);
}
// A type token is special: it can only be emitted after an IRI or prefixed name is read
if (this._previousMarker === '^^') {
switch (type) {
case 'prefixed': type = 'type'; break;
case 'IRI': type = 'typeIRI'; break;
default: type = '';
}
}
// What if nothing of the above was found?
if (!type) {
// We could be in streaming mode, and then we just wait for more input to arrive.
// Otherwise, a syntax error has occurred in the input.
// One exception: error on an unaccounted linebreak (= not inside a triple-quoted literal).
if (inputFinished || (!/^'''|^"""/.test(input) && /\n|\r/.test(input)))
return reportSyntaxError(this);
else
return this._input = input;
}
// Emit the parsed token
var token = { line: line, type: type, value: value, prefix: prefix };
callback(null, token);
this.previousToken = token;
this._previousMarker = type;
// Advance to next part to tokenize
input = input.substr(matchLength || match[0].length, input.length);
}
// Signals the syntax error through the callback
function reportSyntaxError(self) { callback(self._syntaxError(/^\S*/.exec(input)[0])); }
},
// ### `_unescape` replaces N3 escape codes by their corresponding characters
_unescape: function (item) {
try {
return item.replace(escapeSequence, function (sequence, unicode4, unicode8, escapedChar) {
var charCode;
if (unicode4) {
charCode = parseInt(unicode4, 16);
if (isNaN(charCode)) throw new Error(); // can never happen (regex), but helps performance
return fromCharCode(charCode);
}
else if (unicode8) {
charCode = parseInt(unicode8, 16);
if (isNaN(charCode)) throw new Error(); // can never happen (regex), but helps performance
if (charCode <= 0xFFFF) return fromCharCode(charCode);
return fromCharCode(0xD800 + ((charCode -= 0x10000) / 0x400), 0xDC00 + (charCode & 0x3FF));
}
else {
var replacement = escapeReplacements[escapedChar];
if (!replacement)
throw new Error();
return replacement;
}
});
}
catch (error) { return null; }
},
// ### `_syntaxError` creates a syntax error for the given issue
_syntaxError: function (issue) {
this._input = null;
var err = new Error('Unexpected "' + issue + '" on line ' + this._line + '.');
err.context = {
token: undefined,
line: this._line,
previousToken: this.previousToken,
};
return err;
},
// ## Public methods
// ### `tokenize` starts the transformation of an N3 document into an array of tokens.
// The input can be a string or a stream.
tokenize: function (input, callback) {
var self = this;
this._line = 1;
// If the input is a string, continuously emit tokens through the callback until the end
if (typeof input === 'string') {
this._input = input;
// If a callback was passed, asynchronously call it
if (typeof callback === 'function')
immediately(function () { self._tokenizeToEnd(callback, true); });
// If no callback was passed, tokenize synchronously and return
else {
var tokens = [], error;
this._tokenizeToEnd(function (e, t) { e ? (error = e) : tokens.push(t); }, true);
if (error) throw error;
return tokens;
}
}
// Otherwise, the input must be a stream
else {
this._input = '';
this._pendingBuffer = null;
if (typeof input.setEncoding === 'function')
input.setEncoding('utf8');
// Adds the data chunk to the buffer and parses as far as possible
input.on('data', function (data) {
if (self._input !== null && data.length !== 0) {
// Prepend any previous pending writes
if (self._pendingBuffer) {
data = Buffer.concat([self._pendingBuffer, data]);
self._pendingBuffer = null;
}
// Hold if the buffer ends in an incomplete unicode sequence
if (data[data.length - 1] & 0x80) {
self._pendingBuffer = data;
}
// Otherwise, tokenize as far as possible
else {
self._input += data;
self._tokenizeToEnd(callback, false);
}
}
});
// Parses until the end
input.on('end', function () {
if (self._input !== null)
self._tokenizeToEnd(callback, true);
});
input.on('error', callback);
}
},
};
// ## Exports
module.exports = N3Lexer;
}).call(this,require("buffer").Buffer,require("timers").setImmediate)
},{"./IRIs":3,"buffer":14,"timers":39}],6:[function(require,module,exports){
// **N3Parser** parses N3 documents.
var N3Lexer = require('./N3Lexer'),
DataFactory = require('./N3DataFactory'),
namespaces = require('./IRIs');
// The next ID for new blank nodes
var blankNodePrefix = 0, blankNodeCount = 0;
// ## Constructor
function N3Parser(options) {
if (!(this instanceof N3Parser))
return new N3Parser(options);
this._contextStack = [];
this._graph = null;
// Set the document IRI
options = options || {};
this._setBase(options.baseIRI);
options.factory && initDataFactory(this, options.factory);
// Set supported features depending on the format
var format = (typeof options.format === 'string') ?
options.format.match(/\w*$/)[0].toLowerCase() : '',
isTurtle = format === 'turtle', isTriG = format === 'trig',
isNTriples = /triple/.test(format), isNQuads = /quad/.test(format),
isN3 = this._n3Mode = /n3/.test(format),
isLineMode = isNTriples || isNQuads;
if (!(this._supportsNamedGraphs = !(isTurtle || isN3)))
this._readPredicateOrNamedGraph = this._readPredicate;
this._supportsQuads = !(isTurtle || isTriG || isNTriples || isN3);
// Disable relative IRIs in N-Triples or N-Quads mode
if (isLineMode)
this._resolveRelativeIRI = function (iri) { return ''; };
this._blankNodePrefix = typeof options.blankNodePrefix !== 'string' ? '' :
options.blankNodePrefix.replace(/^(?!_:)/, '_:');
this._lexer = options.lexer || new N3Lexer({ lineMode: isLineMode, n3: isN3 });
// Disable explicit quantifiers by default
this._explicitQuantifiers = !!options.explicitQuantifiers;
}
// ## Private class methods
// ### `_resetBlankNodeIds` restarts blank node identification
N3Parser._resetBlankNodeIds = function () {
blankNodePrefix = blankNodeCount = 0;
};
N3Parser.prototype = {
// ## Private methods
// ### `_blank` creates a new blank node
_blank: function () {
return this._blankNode('b' + blankNodeCount++);
},
// ### `_setBase` sets the base IRI to resolve relative IRIs
_setBase: function (baseIRI) {
if (!baseIRI)
this._base = null;
else {
// Remove fragment if present
var fragmentPos = baseIRI.indexOf('#');
if (fragmentPos >= 0)
baseIRI = baseIRI.substr(0, fragmentPos);
// Set base IRI and its components
this._base = baseIRI;
this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI :
baseIRI.replace(/[^\/?]*(?:\?.*)?$/, '');
baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i);
this._baseRoot = baseIRI[0];
this._baseScheme = baseIRI[1];
}
},
// ### `_saveContext` stores the current parsing context
// when entering a new scope (list, blank node, formula)
_saveContext: function (type, graph, subject, predicate, object) {
var n3Mode = this._n3Mode;
this._contextStack.push({
subject: subject, predicate: predicate, object: object,
graph: graph, type: type,
inverse: n3Mode ? this._inversePredicate : false,
blankPrefix: n3Mode ? this._prefixes._ : '',
quantified: n3Mode ? this._quantified : null,
});
// The settings below only apply to N3 streams
if (n3Mode) {
// Every new scope resets the predicate direction
this._inversePredicate = false;
// In N3, blank nodes are scoped to a formula
// (using a dot as separator, as a blank node label cannot start with it)
this._prefixes._ = (this._graph ? this._graph.id.substr(2) + '.' : '.');
// Quantifiers are scoped to a formula
this._quantified = Object.create(this._quantified);
}
},
// ### `_restoreContext` restores the parent context
// when leaving a scope (list, blank node, formula)
_restoreContext: function () {
var context = this._contextStack.pop(), n3Mode = this._n3Mode;
this._subject = context.subject;
this._predicate = context.predicate;
this._object = context.object;
this._graph = context.graph;
// The settings below only apply to N3 streams
if (n3Mode) {
this._inversePredicate = context.inverse;
this._prefixes._ = context.blankPrefix;
this._quantified = context.quantified;
}
},
// ### `_readInTopContext` reads a token when in the top context
_readInTopContext: function (token) {
switch (token.type) {
// If an EOF token arrives in the top context, signal that we're done
case 'eof':
if (this._graph !== null)