UNPKG

n3

Version:

Lightning fast, asynchronous, streaming Turtle / N3 / RDF library.

1 lines 274 kB
(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){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _Util=require("./Util");const BASE_UNSUPPORTED=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i;const SUFFIX_SUPPORTED=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/;const CURRENT="./";const PARENT="../";const QUERY="?";const FRAGMENT="#";class BaseIRI{constructor(base){this.base=base;this._baseLength=0;this._baseMatcher=null;this._pathReplacements=new Array(base.length+1)}static supports(base){return!BASE_UNSUPPORTED.test(base)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!BaseIRI.supports(this.base))return this._baseMatcher=/.^/;const scheme=/^[^:]*:\/*/.exec(this.base)[0];const regexHead=["^",(0,_Util.escapeRegex)(scheme)];const regexTail=[];const segments=[],segmenter=/[^/?#]*([/?#])/y;let segment,query=0,fragment=0,last=segmenter.lastIndex=scheme.length;while(!query&&!fragment&&(segment=segmenter.exec(this.base))){if(segment[1]===FRAGMENT)fragment=segmenter.lastIndex-1;else{regexHead.push((0,_Util.escapeRegex)(segment[0]),"(?:");regexTail.push(")?");if(segment[1]!==QUERY)segments.push(last=segmenter.lastIndex);else{query=last=segmenter.lastIndex;fragment=this.base.indexOf(FRAGMENT,query);this._pathReplacements[query]=QUERY}}}for(let i=0;i<segments.length;i++)this._pathReplacements[segments[i]]=PARENT.repeat(segments.length-i-1);this._pathReplacements[segments[segments.length-1]]=CURRENT;this._baseLength=fragment>0?fragment:this.base.length;regexHead.push((0,_Util.escapeRegex)(this.base.substring(last,this._baseLength)),query?"(?:#|$)":"(?:[?#]|$)");return this._baseMatcher=new RegExp([...regexHead,...regexTail].join(""))}toRelative(iri){const match=this._getBaseMatcher().exec(iri);if(!match)return iri;const length=match[0].length;if(length===this._baseLength&&length===iri.length)return"";const parentPath=this._pathReplacements[length];if(parentPath){const suffix=iri.substring(length);if(parentPath!==QUERY&&!SUFFIX_SUPPORTED.test(suffix))return iri;if(parentPath===CURRENT&&/^[^?#]/.test(suffix))return suffix;return parentPath+suffix}return iri.substring(length-1)}}exports.default=BaseIRI},{"./Util":13}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;const 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/";var _default=exports.default={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`,isImpliedBy:`${SWAP}log#isImpliedBy`}}},{}],3:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.Variable=exports.Triple=exports.Term=exports.Quad=exports.NamedNode=exports.Literal=exports.DefaultGraph=exports.BlankNode=void 0;exports.escapeQuotes=escapeQuotes;exports.fromQuad=fromQuad;exports.fromTerm=fromTerm;exports.termFromId=termFromId;exports.termToId=termToId;exports.unescapeQuotes=unescapeQuotes;var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const{rdf,xsd}=_IRIs.default;let DEFAULTGRAPH;let _blankNodeCounter=0;const escapedLiteral=/^"(.*".*)(?="[^"]*$)/;const DataFactory={namedNode:namedNode,blankNode:blankNode,variable:variable,literal:literal,defaultGraph:defaultGraph,quad:quad,triple:quad,fromTerm:fromTerm,fromQuad:fromQuad};var _default=exports.default=DataFactory;class Term{constructor(id){this.id=id}get value(){return this.id}equals(other){if(other instanceof Term)return this.id===other.id;return!!other&&this.termType===other.termType&&this.value===other.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}exports.Term=Term;class NamedNode extends Term{get termType(){return"NamedNode"}}exports.NamedNode=NamedNode;class Literal extends Term{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const id=this.id;let atPos=id.lastIndexOf('"')+1;return atPos<id.length&&id[atPos++]==="@"?id.substr(atPos).toLowerCase():""}get datatype(){return new NamedNode(this.datatypeString)}get datatypeString(){const id=this.id,dtPos=id.lastIndexOf('"')+1;const char=dtPos<id.length?id[dtPos]:"";return char==="^"?id.substr(dtPos+2):char!=="@"?xsd.string:rdf.langString}equals(other){if(other instanceof Literal)return this.id===other.id;return!!other&&!!other.datatype&&this.termType===other.termType&&this.value===other.value&&this.language===other.language&&this.datatype.value===other.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}exports.Literal=Literal;class BlankNode extends Term{constructor(name){super(`_:${name}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}exports.BlankNode=BlankNode;class Variable extends Term{constructor(name){super(`?${name}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}exports.Variable=Variable;class DefaultGraph extends Term{constructor(){super("");return DEFAULTGRAPH||this}get termType(){return"DefaultGraph"}equals(other){return this===other||!!other&&this.termType===other.termType}}exports.DefaultGraph=DefaultGraph;DEFAULTGRAPH=new DefaultGraph;function termFromId(id,factory,nested){factory=factory||DataFactory;if(!id)return factory.defaultGraph();switch(id[0]){case"?":return factory.variable(id.substr(1));case"_":return factory.blankNode(id.substr(2));case'"':if(factory===DataFactory)return new Literal(id);if(id[id.length-1]==='"')return factory.literal(id.substr(1,id.length-2));const 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)));case"[":id=JSON.parse(id);break;default:if(!nested||!Array.isArray(id)){return factory.namedNode(id)}}return factory.quad(termFromId(id[0],factory,true),termFromId(id[1],factory,true),termFromId(id[2],factory,true),id[3]&&termFromId(id[3],factory,true))}function termToId(term,nested){if(typeof term==="string")return term;if(term instanceof Term&&term.termType!=="Quad")return term.id;if(!term)return DEFAULTGRAPH.id;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}`:""}`;case"Quad":const res=[termToId(term.subject,true),termToId(term.predicate,true),termToId(term.object,true)];if(term.graph&&term.graph.termType!=="DefaultGraph"){res.push(termToId(term.graph,true))}return nested?res:JSON.stringify(res);default:throw new Error(`Unexpected termType: ${term.termType}`)}}class Quad extends Term{constructor(subject,predicate,object,graph){super("");this._subject=subject;this._predicate=predicate;this._object=object;this._graph=graph||DEFAULTGRAPH}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(other){return!!other&&this._subject.equals(other.subject)&&this._predicate.equals(other.predicate)&&this._object.equals(other.object)&&this._graph.equals(other.graph)}}exports.Triple=exports.Quad=Quad;function escapeQuotes(id){return id.replace(escapedLiteral,(_,quoted)=>`"${quoted.replace(/"/g,'""')}`)}function unescapeQuotes(id){return id.replace(escapedLiteral,(_,quoted)=>`"${quoted.replace(/""/g,'"')}`)}function namedNode(iri){return new NamedNode(iri)}function blankNode(name){return new BlankNode(name||`n3-${_blankNodeCounter++}`)}function literal(value,languageOrDataType){if(typeof languageOrDataType==="string")return new Literal(`"${value}"@${languageOrDataType.toLowerCase()}`);let datatype=languageOrDataType?languageOrDataType.value:"";if(datatype===""){if(typeof value==="boolean")datatype=xsd.boolean;else if(typeof value==="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"}}}return datatype===""||datatype===xsd.string?new Literal(`"${value}"`):new Literal(`"${value}"^^${datatype}`)}function variable(name){return new Variable(name)}function defaultGraph(){return DEFAULTGRAPH}function quad(subject,predicate,object,graph){return new Quad(subject,predicate,object,graph)}function fromTerm(term){if(term instanceof Term)return term;switch(term.termType){case"NamedNode":return namedNode(term.value);case"BlankNode":return blankNode(term.value);case"Variable":return variable(term.value);case"DefaultGraph":return DEFAULTGRAPH;case"Literal":return literal(term.value,term.language||term.datatype);case"Quad":return fromQuad(term);default:throw new Error(`Unexpected termType: ${term.termType}`)}}function fromQuad(inQuad){if(inQuad instanceof Quad)return inQuad;if(inQuad.termType!=="Quad")throw new Error(`Unexpected termType: ${inQuad.termType}`);return quad(fromTerm(inQuad.subject),fromTerm(inQuad.predicate),fromTerm(inQuad.object),fromTerm(inQuad.graph))}},{"./IRIs":2}],4:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _buffer=require("buffer");var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const{xsd}=_IRIs.default;const escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g;const escapeReplacements={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"};const illegalIriChars=/[\x00-\x20<>\\"\{\}\|\^\`]/;const lineModeRegExps={_iri:true,_unescapedIri:true,_simpleQuotedString:true,_langcode:true,_blank:true,_newline:true,_comment:true,_whitespace:true,_endOfFile:true};const invalidRegExp=/$0^/;class N3Lexer{constructor(options){this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/;this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/;this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/;this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/;this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i;this._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<])/;this._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#()\[\]\{\}"'<>]))/;this._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#()\[\]\{\}"'<>])/;this._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#()\[\]\{\}"'<>]))/;this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/;this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/;this._keyword=/^@[a-z]+(?=[\s#<:])/i;this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i;this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/;this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/;this._comment=/#([^\n\r]*)/;this._whitespace=/^[ \t]+/;this._endOfFile=/^(?:#[^\n\r]*)?$/;options=options||{};this._isImpliedBy=options.isImpliedBy;if(this._lineMode=!!options.lineMode){this._n3Mode=false;for(const key in this){if(!(key in lineModeRegExps)&&this[key]instanceof RegExp)this[key]=invalidRegExp}}else{this._n3Mode=options.n3!==false}this.comments=!!options.comments;this._literalClosingPos=0}_tokenizeToEnd(callback,inputFinished){let input=this._input;let currentLineLength=input.length;while(true){let whiteSpaceMatch,comment;while(whiteSpaceMatch=this._newline.exec(input)){if(this.comments&&(comment=this._comment.exec(whiteSpaceMatch[0])))emitToken("comment",comment[1],"",this._line,whiteSpaceMatch[0].length);input=input.substr(whiteSpaceMatch[0].length,input.length);currentLineLength=input.length;this._line++}if(!whiteSpaceMatch&&(whiteSpaceMatch=this._whitespace.exec(input)))input=input.substr(whiteSpaceMatch[0].length,input.length);if(this._endOfFile.test(input)){if(inputFinished){if(this.comments&&(comment=this._comment.exec(input)))emitToken("comment",comment[1],"",this._line,input.length);input=null;emitToken("eof","","",this._line,0)}return this._input=input}const line=this._line,firstChar=input[0];let type="",value="",prefix="",match=null,matchLength=0,inconclusive=false;switch(firstChar){case"^":if(input.length<3)break;else if(input[1]==="^"){this._previousMarker="^^";input=input.substr(2);if(input[0]!=="<"){inconclusive=true;break}}else{if(this._n3Mode){matchLength=1;type="^"}break}case"<":if(match=this._unescapedIri.exec(input))type="IRI",value=match[1];else if(match=this._iri.exec(input)){value=this._unescape(match[1]);if(value===null||illegalIriChars.test(value))return reportSyntaxError(this);type="IRI"}else if(input.length>1&&input[1]==="<")type="<<",matchLength=2;else if(this._n3Mode&&input.length>1&&input[1]==="="){matchLength=2;if(this._isImpliedBy)type="abbreviation",value="<";else type="inverse",value=">"}break;case">":if(input.length>1&&input[1]===">")type=">>",matchLength=2;break;case"_":if((match=this._blank.exec(input))||inputFinished&&(match=this._blank.exec(`${input} `)))type="blank",prefix="_",value=match[1];break;case'"':if(match=this._simpleQuotedString.exec(input))value=match[1];else{({value,matchLength}=this._parseLiteral(input));if(value===null)return reportSyntaxError(this)}if(match!==null||matchLength!==0){type="literal";this._literalClosingPos=0}break;case"'":if(!this._lineMode){if(match=this._simpleApostropheString.exec(input))value=match[1];else{({value,matchLength}=this._parseLiteral(input));if(value===null)return reportSyntaxError(this)}if(match!==null||matchLength!==0){type="literal";this._literalClosingPos=0}}break;case"?":if(this._n3Mode&&(match=this._variable.exec(input)))type="var",value=match[0];break;case"@":if(this._previousMarker==="literal"&&(match=this._langcode.exec(input)))type="langcode",value=match[1];else if(match=this._keyword.exec(input))type=match[0];break;case".":if(input.length===1?inputFinished:input[1]<"0"||input[1]>"9"){type=".";matchLength=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":if(match=this._number.exec(input)||inputFinished&&(match=this._number.exec(`${input} `))){type="literal",value=match[0];prefix=typeof match[1]==="string"?xsd.double:typeof match[2]==="string"?xsd.decimal:xsd.integer}break;case"B":case"b":case"p":case"P":case"G":case"g":if(match=this._sparqlKeyword.exec(input))type=match[0].toUpperCase();else inconclusive=true;break;case"f":case"t":if(match=this._boolean.exec(input))type="literal",value=match[0],prefix=xsd.boolean;else inconclusive=true;break;case"a":if(match=this._shortPredicates.exec(input))type="abbreviation",value="a";else inconclusive=true;break;case"=":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"}":if(!this._lineMode){matchLength=1;type=firstChar}break;case"{":if(!this._lineMode&&input.length>=2){if(input[1]==="|")type="{|",matchLength=2;else type=firstChar,matchLength=1}break;case"|":if(input.length>=2&&input[1]==="}")type="|}",matchLength=2;break;default:inconclusive=true}if(inconclusive){if((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(match=this._prefix.exec(input)))type="prefix",value=match[1]||"";else if((match=this._prefixed.exec(input))||inputFinished&&(match=this._prefixed.exec(`${input} `)))type="prefixed",prefix=match[1]||"",value=this._unescape(match[2])}if(this._previousMarker==="^^"){switch(type){case"prefixed":type="type";break;case"IRI":type="typeIRI";break;default:type=""}}if(!type){if(inputFinished||!/^'''|^"""/.test(input)&&/\n|\r/.test(input))return reportSyntaxError(this);else return this._input=input}const length=matchLength||match[0].length;const token=emitToken(type,value,prefix,line,length);this.previousToken=token;this._previousMarker=type;input=input.substr(length,input.length)}function emitToken(type,value,prefix,line,length){const start=input?currentLineLength-input.length:currentLineLength;const end=start+length;const token={type:type,value:value,prefix:prefix,line:line,start:start,end:end};callback(null,token);return token}function reportSyntaxError(self){callback(self._syntaxError(/^\S*/.exec(input)[0]))}}_unescape(item){let invalid=false;const replaced=item.replace(escapeSequence,(sequence,unicode4,unicode8,escapedChar)=>{if(typeof unicode4==="string")return String.fromCharCode(Number.parseInt(unicode4,16));if(typeof unicode8==="string"){let charCode=Number.parseInt(unicode8,16);return charCode<=65535?String.fromCharCode(Number.parseInt(unicode8,16)):String.fromCharCode(55296+((charCode-=65536)>>10),56320+(charCode&1023))}if(escapedChar in escapeReplacements)return escapeReplacements[escapedChar];invalid=true;return""});return invalid?null:replaced}_parseLiteral(input){if(input.length>=3){const opening=input.match(/^(?:"""|"|'''|'|)/)[0];const openingLength=opening.length;let closingPos=Math.max(this._literalClosingPos,openingLength);while((closingPos=input.indexOf(opening,closingPos))>0){let backslashCount=0;while(input[closingPos-backslashCount-1]==="\\")backslashCount++;if(backslashCount%2===0){const raw=input.substring(openingLength,closingPos);const lines=raw.split(/\r\n|\r|\n/).length-1;const matchLength=closingPos+openingLength;if(openingLength===1&&lines!==0||openingLength===3&&this._lineMode)break;this._line+=lines;return{value:this._unescape(raw),matchLength:matchLength}}closingPos++}this._literalClosingPos=input.length-openingLength+1}return{value:"",matchLength:0}}_syntaxError(issue){this._input=null;const err=new Error(`Unexpected "${issue}" on line ${this._line}.`);err.context={token:undefined,line:this._line,previousToken:this.previousToken};return err}_readStartingBom(input){return input.startsWith("\ufeff")?input.substr(1):input}tokenize(input,callback){this._line=1;if(typeof input==="string"){this._input=this._readStartingBom(input);if(typeof callback==="function")queueMicrotask(()=>this._tokenizeToEnd(callback,true));else{const tokens=[];let error;this._tokenizeToEnd((e,t)=>e?error=e:tokens.push(t),true);if(error)throw error;return tokens}}else{this._pendingBuffer=null;if(typeof input.setEncoding==="function")input.setEncoding("utf8");input.on("data",data=>{if(this._input!==null&&data.length!==0){if(this._pendingBuffer){data=_buffer.Buffer.concat([this._pendingBuffer,data]);this._pendingBuffer=null}if(data[data.length-1]&128){this._pendingBuffer=data}else{if(typeof this._input==="undefined")this._input=this._readStartingBom(typeof data==="string"?data:data.toString());else this._input+=data;this._tokenizeToEnd(callback,false)}}});input.on("end",()=>{if(typeof this._input==="string")this._tokenizeToEnd(callback,true)});input.on("error",callback)}}}exports.default=N3Lexer},{"./IRIs":2,buffer:17}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _N3Lexer=_interopRequireDefault(require("./N3Lexer"));var _N3DataFactory=_interopRequireDefault(require("./N3DataFactory"));var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}let blankNodePrefix=0;class N3Parser{constructor(options){this._contextStack=[];this._graph=null;options=options||{};this._setBase(options.baseIRI);options.factory&&initDataFactory(this,options.factory);const format=typeof options.format==="string"?options.format.match(/\w*$/)[0].toLowerCase():"",isTurtle=/turtle/.test(format),isTriG=/trig/.test(format),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);this._isImpliedBy=options.isImpliedBy;this._supportsRDFStar=format===""||/star|\*$/.test(format);if(isLineMode)this._resolveRelativeIRI=iri=>{return null};this._blankNodePrefix=typeof options.blankNodePrefix!=="string"?"":options.blankNodePrefix.replace(/^(?!_:)/,"_:");this._lexer=options.lexer||new _N3Lexer.default({lineMode:isLineMode,n3:isN3,isImpliedBy:this._isImpliedBy});this._explicitQuantifiers=!!options.explicitQuantifiers}static _resetBlankNodePrefix(){blankNodePrefix=0}_setBase(baseIRI){if(!baseIRI){this._base="";this._basePath=""}else{const fragmentPos=baseIRI.indexOf("#");if(fragmentPos>=0)baseIRI=baseIRI.substr(0,fragmentPos);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(type,graph,subject,predicate,object){const n3Mode=this._n3Mode;this._contextStack.push({type:type,subject:subject,predicate:predicate,object:object,graph:graph,inverse:n3Mode?this._inversePredicate:false,blankPrefix:n3Mode?this._prefixes._:"",quantified:n3Mode?this._quantified:null});if(n3Mode){this._inversePredicate=false;this._prefixes._=this._graph?`${this._graph.value}.`:".";this._quantified=Object.create(this._quantified)}}_restoreContext(type,token){const context=this._contextStack.pop();if(!context||context.type!==type)return this._error(`Unexpected ${token.type}`,token);this._subject=context.subject;this._predicate=context.predicate;this._object=context.object;this._graph=context.graph;if(this._n3Mode){this._inversePredicate=context.inverse;this._prefixes._=context.blankPrefix;this._quantified=context.quantified}}_readInTopContext(token){switch(token.type){case"eof":if(this._graph!==null)return this._error("Unclosed graph",token);delete this._prefixes._;return this._callback(null,null,this._prefixes);case"PREFIX":this._sparqlStyle=true;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=true;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs){this._graph="";this._subject=null;return this._readSubject}case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(token)}}_readEntity(token,quantifier){let value;switch(token.type){case"IRI":case"typeIRI":const iri=this._resolveIRI(token.value);if(iri===null)return this._error("Invalid IRI",token);value=this._factory.namedNode(iri);break;case"type":case"prefixed":const prefix=this._prefixes[token.prefix];if(prefix===undefined)return this._error(`Undefined prefix "${token.prefix}:"`,token);value=this._factory.namedNode(prefix+token.value);break;case"blank":value=this._factory.blankNode(this._prefixes[token.prefix]+token.value);break;case"var":value=this._factory.variable(token.value.substr(1));break;default:return this._error(`Expected entity but got ${token.type}`,token)}if(!quantifier&&this._n3Mode&&value.id in this._quantified)value=this._quantified[value.id];return value}_readSubject(token){this._predicate=null;switch(token.type){case"[":this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null);return this._readBlankNodeHead;case"(":this._saveContext("list",this._graph,this.RDF_NIL,null,null);this._subject=null;return this._readListItem;case"{":if(!this._n3Mode)return this._error("Unexpected graph",token);this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null);return this._readSubject;case"}":return this._readPunctuation(token);case"@forSome":if(!this._n3Mode)return this._error('Unexpected "@forSome"',token);this._subject=null;this._predicate=this.N3_FORSOME;this._quantifier="blankNode";return this._readQuantifierList;case"@forAll":if(!this._n3Mode)return this._error('Unexpected "@forAll"',token);this._subject=null;this._predicate=this.N3_FORALL;this._quantifier="variable";return this._readQuantifierList;case"literal":if(!this._n3Mode)return this._error("Unexpected literal",token);if(token.prefix.length===0){this._literalValue=token.value;return this._completeSubjectLiteral}else this._subject=this._factory.literal(token.value,this._factory.namedNode(token.prefix));break;case"<<":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",token);this._saveContext("<<",this._graph,null,null,null);this._graph=null;return this._readSubject;default:if((this._subject=this._readEntity(token))===undefined)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(token){const type=token.type;switch(type){case"inverse":this._inversePredicate=true;case"abbreviation":this._predicate=this.ABBREVIATIONS[token.value];break;case".":case"]":case"}":if(this._predicate===null)return this._error(`Unexpected ${type}`,token);this._subject=null;return type==="]"?this._readBlankNodeTail(token):this._readPunctuation(token);case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",token);case"[":if(this._n3Mode){this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null);return this._readBlankNodeHead}case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",token);default:if((this._predicate=this._readEntity(token))===undefined)return}return this._readObject}_readObject(token){switch(token.type){case"literal":if(token.prefix.length===0){this._literalValue=token.value;return this._readDataTypeOrLang}else this._object=this._factory.literal(token.value,this._factory.namedNode(token.prefix));break;case"[":this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode());return this._readBlankNodeHead;case"(":this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL);this._subject=null;return this._readListItem;case"{":if(!this._n3Mode)return this._error("Unexpected graph",token);this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode());return this._readSubject;case"<<":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",token);this._saveContext("<<",this._graph,this._subject,this._predicate,null);this._graph=null;return this._readSubject;default:if((this._object=this._readEntity(token))===undefined)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(token){return token.type==="{"?this._readGraph(token):this._readPredicate(token)}_readGraph(token){if(token.type!=="{")return this._error(`Expected graph but got ${token.type}`,token);this._graph=this._subject,this._subject=null;return this._readSubject}_readBlankNodeHead(token){if(token.type==="]"){this._subject=null;return this._readBlankNodeTail(token)}else{this._predicate=null;return this._readPredicate(token)}}_readBlankNodeTail(token){if(token.type!=="]")return this._readBlankNodePunctuation(token);if(this._subject!==null)this._emit(this._subject,this._predicate,this._object,this._graph);const empty=this._predicate===null;this._restoreContext("blank",token);if(this._object!==null)return this._getContextEndReader();else if(this._predicate!==null)return this._readObject;else return empty?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(token){switch(token.type){case".":case"}":this._subject=null;return this._readPunctuation(token);default:return this._readPredicate(token)}}_readListItem(token){let item=null,list=null,next=this._readListItem;const previousList=this._subject,stack=this._contextStack,parent=stack[stack.length-1];switch(token.type){case"[":this._saveContext("blank",this._graph,list=this._factory.blankNode(),this.RDF_FIRST,this._subject=item=this._factory.blankNode());next=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,list=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL);this._subject=null;break;case")":this._restoreContext("list",token);if(stack.length!==0&&stack[stack.length-1].type==="list")this._emit(this._subject,this._predicate,this._object,this._graph);if(this._predicate===null){next=this._readPredicate;if(this._subject===this.RDF_NIL)return next}else{next=this._getContextEndReader();if(this._object===this.RDF_NIL)return next}list=this.RDF_NIL;break;case"literal":if(token.prefix.length===0){this._literalValue=token.value;next=this._readListItemDataTypeOrLang}else{item=this._factory.literal(token.value,this._factory.namedNode(token.prefix));next=this._getContextEndReader()}break;case"{":if(!this._n3Mode)return this._error("Unexpected graph",token);this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode());return this._readSubject;default:if((item=this._readEntity(token))===undefined)return}if(list===null)this._subject=list=this._factory.blankNode();if(previousList===null){if(parent.predicate===null)parent.subject=list;else parent.object=list}else{this._emit(previousList,this.RDF_REST,list,this._graph)}if(item!==null){if(this._n3Mode&&(token.type==="IRI"||token.type==="prefixed")){this._saveContext("item",this._graph,list,this.RDF_FIRST,item);this._subject=item,this._predicate=null;return this._getPathReader(this._readListItem)}this._emit(list,this.RDF_FIRST,item,this._graph)}return next}_readDataTypeOrLang(token){return this._completeObjectLiteral(token,false)}_readListItemDataTypeOrLang(token){return this._completeObjectLiteral(token,true)}_completeLiteral(token){let literal=this._factory.literal(this._literalValue);switch(token.type){case"type":case"typeIRI":const datatype=this._readEntity(token);if(datatype===undefined)return;literal=this._factory.literal(this._literalValue,datatype);token=null;break;case"langcode":literal=this._factory.literal(this._literalValue,token.value);token=null;break}return{token:token,literal:literal}}_completeSubjectLiteral(token){this._subject=this._completeLiteral(token).literal;return this._readPredicateOrNamedGraph}_completeObjectLiteral(token,listItem){const completed=this._completeLiteral(token);if(!completed)return;this._object=completed.literal;if(listItem)this._emit(this._subject,this.RDF_FIRST,this._object,this._graph);if(completed.token===null)return this._getContextEndReader();else{this._readCallback=this._getContextEndReader();return this._readCallback(completed.token)}}_readFormulaTail(token){if(token.type!=="}")return this._readPunctuation(token);if(this._subject!==null)this._emit(this._subject,this._predicate,this._object,this._graph);this._restoreContext("formula",token);return this._object===null?this._readPredicate:this._getContextEndReader()}_readPunctuation(token){let next,graph=this._graph;const subject=this._subject,inversePredicate=this._inversePredicate;switch(token.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",token);if(this._n3Mode)return this._readFormulaTail(token);this._graph=null;case".":this._subject=null;next=this._contextStack.length?this._readSubject:this._readInTopContext;if(inversePredicate)this._inversePredicate=false;break;case";":next=this._readPredicate;break;case",":next=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",token);const predicate=this._predicate,object=this._object;this._subject=this._factory.quad(subject,predicate,object,this.DEFAULTGRAPH);next=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",token);this._subject=null;next=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(graph=this._readEntity(token))!==undefined){next=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,token)}if(subject!==null){const predicate=this._predicate,object=this._object;if(!inversePredicate)this._emit(subject,predicate,object,graph);else this._emit(object,predicate,subject,graph)}return next}_readBlankNodePunctuation(token){let next;switch(token.type){case";":next=this._readPredicate;break;case",":next=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,token)}this._emit(this._subject,this._predicate,this._object,this._graph);return next}_readQuadPunctuation(token){if(token.type!==".")return this._error("Expected dot to follow quad",token);return this._readInTopContext}_readPrefix(token){if(token.type!=="prefix")return this._error("Expected prefix to follow @prefix",token);this._prefix=token.value;return this._readPrefixIRI}_readPrefixIRI(token){if(token.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,token);const prefixNode=this._readEntity(token);this._prefixes[this._prefix]=prefixNode.value;this._prefixCallback(this._prefix,prefixNode);return this._readDeclarationPunctuation}_readBaseIRI(token){const iri=token.type==="IRI"&&this._resolveIRI(token.value);if(!iri)return this._error("Expected valid IRI to follow base declaration",token);this._setBase(iri);return this._readDeclarationPunctuation}_readNamedGraphLabel(token){switch(token.type){case"IRI":case"blank":case"prefixed":return this._readSubject(token),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",token)}}_readNamedGraphBlankLabel(token){if(token.type!=="]")return this._error("Invalid graph label",token);this._subject=this._factory.blankNode();return this._readGraph}_readDeclarationPunctuation(token){if(this._sparqlStyle){this._sparqlStyle=false;return this._readInTopContext(token)}if(token.type!==".")return this._error("Expected declaration to end with a dot",token);return this._readInTopContext}_readQuantifierList(token){let entity;switch(token.type){case"IRI":case"prefixed":if((entity=this._readEntity(token,true))!==undefined)break;default:return this._error(`Unexpected ${token.type}`,token)}if(!this._explicitQuantifiers)this._quantified[entity.id]=this._factory[this._quantifier](this._factory.blankNode().value);else{if(this._subject===null)this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH);else this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH);this._emit(this._subject,this.RDF_FIRST,entity,this.QUANTIFIERS_GRAPH)}return this._readQuantifierPunctuation}_readQuantifierPunctuation(token){if(token.type===",")return this._readQuantifierList;else{if(this._explicitQuantifiers){this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH);this._subject=null}this._readCallback=this._getContextEndReader();return this._readCallback(token)}}_getPathReader(afterPath){this._afterPath=afterPath;return this._readPath}_readPath(token){switch(token.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const stack=this._contextStack,parent=stack.length&&stack[stack.length-1];if(parent&&parent.type==="item"){const item=this._subject;this._restoreContext("item",token);this._emit(this._subject,this.RDF_FIRST,item,this._graph)}return this._afterPath(token)}}_readForwardPath(token){let subject,predicate;const object=this._factory.blankNode();if((predicate=this._readEntity(token))===undefined)return;if(this._predicate===null)subject=this._subject,this._subject=object;else subject=this._object,this._object=object;this._emit(subject,predicate,object,this._graph);return this._readPath}_readBackwardPath(token){const subject=this._factory.blankNode();let predicate,object;if((predicate=this._readEntity(token))===undefined)return;if(this._predicate===null)object=this._subject,this._subject=subject;else object=this._object,this._object=subject;this._emit(subject,predicate,object,this._graph);return this._readPath}_readRDFStarTailOrGraph(token){if(token.type!==">>"){if(this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(token))!==undefined)return this._readRDFStarTail;return this._error(`Expected >> to follow "${this._object.id}"`,token)}return this._readRDFStarTail(token)}_readRDFStarTail(token){if(token.type!==">>")return this._error(`Expected >> but got ${token.type}`,token);const quad=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);this._restoreContext("<<",token);if(this._subject===null){this._subject=quad;return this._readPredicate}else{this._object=quad;return this._getContextEndReader()}}_getContextEndReader(){const contextStack=this._contextStack;if(!contextStack.length)return this._readPunctuation;switch(contextStack[contextStack.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(subject,predicate,object,graph){this._callback(null,this._factory.quad(subject,predicate,object,graph||this.DEFAULTGRAPH))}_error(message,token){const err=new Error(`${message} on line ${token.line}.`);err.context={token:token,line:token.line,previousToken:this._lexer.previousToken};this._callback(err);this._callback=noop}_resolveIRI(iri){return/^[a-z][a-z0-9+.-]*:/i.test(iri)?iri:this._resolveRelativeIRI(iri)}_resolveRelativeIRI(iri){if(!iri.length)return this._base;switch(iri[0]){case"#":return this._base+iri;case"?":return this._base.replace(/(?:\?.*)?$/,iri);case"/":return(iri[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(iri);default:return/^[^/:]*:/.test(iri)?null:this._removeDotSegments(this._basePath+iri)}}_removeDotSegments(iri){if(!/(^|\/)\.\.?($|[/#?])/.test(iri))return iri;const length=iri.length;let result="",i=-1,pathStart=-1,segmentStart=0,next="/";while(i<length){switch(next){case":":if(pathStart<0){if(iri[++i]==="/"&&iri[++i]==="/")while((pathStart=i+1)<length&&iri[pathStart]!=="/")i=pathStart}break;case"?":case"#":i=length;break;case"/":if(iri[i+1]==="."){next=iri[++i+1];switch(next){case"/":result+=iri.substring(segmentStart,i-1);segmentStart=i+1;break;case undefined:case"?":case"#":return result+iri.substring(segmentStart,i)+iri.substr(i+1);case".":next=iri[++i+1];if(next===undefined||next==="/"||next==="?"||next==="#"){result+=iri.substring(segmentStart,i-2);if((segmentStart=result.lastIndexOf("/"))>=pathStart)result=result.substr(0,segmentStart);if(next!=="/")return`${result}/${iri.substr(i+1)}`;segmentStart=i+1}}}}next=iri[++i]}return result+iri.substring(segmentStart)}parse(input,quadCallback,prefixCallback){let onQuad,onPrefix,onComment;if(quadCallback&&(quadCallback.onQuad||quadCallback.onPrefix||quadCallback.onComment)){onQuad=quadCallback.onQuad;onPrefix=quadCallback.onPrefix;onComment=quadCallback.onComment}else{onQuad=quadCallback;onPrefix=prefixCallback}this._readCallback=this._readInTopContext;this._sparqlStyle=false;this._prefixes=Object.create(null);this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`;this._prefixCallback=onPrefix||noop;this._inversePredicate=false;this._quantified=Object.create(null);if(!onQuad){const quads=[];let error;this._callback=(e,t)=>{e?error=e:t&&quads.push(t)};this._lexer.tokenize(input).every(token=>{return this._readCallback=this._readCallback(token)});if(error)throw error;return quads}let processNextToken=(error,token)=>{if(error!==null)this._callback(error),this._callback=noop;else if(this._readCallback)this._readCallback=this._readCallback(token)};if(onComment){this._lexer.comments=true;processNextToken=(error,token)=>{if(error!==null)this._callback(error),this._callback=noop;else if(this._readCallback){if(token.type==="comment")onComment(token.value);else this._readCallback=this._readCallback(token)}}}this._callback=onQuad;this._lexer.tokenize(input,processNextToken)}}exports.default=N3Parser;function noop(){}function initDataFactory(parser,factory){parser._factory=factory;parser.DEFAULTGRAPH=factory.defaultGraph();parser.RDF_FIRST=factory.namedNode(_IRIs.default.rdf.first);parser.RDF_REST=factory.namedNode(_IRIs.default.rdf.rest);parser.RDF_NIL=factory.namedNode(_IRIs.default.rdf.nil);parser.N3_FORALL=factory.namedNode(_IRIs.default.r.forAll);parser.N3_FORSOME=factory.namedNode(_IRIs.default.r.forSome);parser.ABBREVIATIONS={a:factory.namedNode(_IRIs.default.rdf.type),"=":factory.namedNode(_IRIs.default.owl.sameAs),">":factory.namedNode(_IRIs.default.log.implies),"<":factory.namedNode(_IRIs.default.log.isImpliedBy)};parser.QUANTIFIERS_GRAPH=factory.namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,_N3DataFactory.default)},{"./IRIs":2,"./N3DataFactory":3,"./N3Lexer":4}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;exports.getRulesFromDataset=getRulesFromDataset;var _N3DataFactory=_interopRequireDefault(require("./N3DataFactory"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function getRulesFromDataset(dataset){const rules=[];for(const{subject,object}of dataset.match(null,_N3DataFactory.default.namedNode("http://www.w3.org/2000/10/swap/log#implies"),null,_N3DataFactory.default.defaultGraph())){const premise=[...dataset.match(null,null,null,subject)];const conclusion=[...dataset.match(null,null,null,object)];rules.push({premise:premise,conclusion:conclusion})}return rules}class N3Reasoner{constructor(store){this._store=store}_add(subject,predicate,object,graphItem,cb){if(!this._store._addToIndex(graphItem.subjects,subject,predicate,object))return;this._store._addToIndex(graphItem.predicates,predicate,object,subject);this._store._addToIndex(graphItem.objects,object,subject,predicate);cb()}_evaluatePremise(rule,content,cb,i=0){let v1,v2,value,index1,index2;const[val0,val1,val2]=rule.premise[i].value,index=content[rule.premise[i].content];const v0=!(value=val0.value);for(value in v0?index:{[value]:index[value]}){if(index1=index[value]){if(v0)val0.value=Number(value);v1=!(value=val1.value);for(value in v1?index1:{[value]:index1[value]}){if(index2=index1[value]){if(v1)val1.value=Number(value);v2=!(value=val2.value);for(value in v2?index2:{[value]:index2[value]}){if(v2)val2.value=Number(value);if(i===rule.premise.length-1)rule.conclusion.forEach(c=>{this._add(c.subject.value,c.predicate.value,c.object.value,content,()=>{cb(c)})});else this._evaluatePremise(rule,content,cb,i+1)}if(v2)val2.value=null}}if(v1)val1.value=null}}if(v0)val0.value=null}_evaluateRules(rules,content,cb){for(let i=0;i<rules.length;i++){this._evaluatePremise(rules[i],content,cb)}}_reasonGraphNaive(rules,content){const newRules=[];function addRule(conclusion){if(conclusion.next)conclusion.next.forEach(rule=>{newRules.push([conclusion.subject.value,conclusion.predicate.value,conclusion.object.value,rule])})}const addConclusions=conclusion=>{conclusion.forEach(c=>{this._add(c.subject.value,c.predicate.value,c.object.value,content,()=>{addRule(c)})})};this._evaluateRules(rules,content,addRule);let r;while((r=newRules.pop())!==undefined){const[subject,predicate,object,rule]=r;const v1=rule.basePremise.subject.value;if(!v1)rule.basePremise.subject.value=subject;const v2=rule.basePremise.predicate.value;if(!v2)rule.basePremise.predicate.value=predicate;const v3=rule.basePremise.object.value;if(!v3)rule.basePremise.object.value=object;if(rule.premise.length===0){addConclusions(rule.conclusion)}else{this._evaluatePremise(rule,content,addRule)}if(!v1)rule.basePremise.subject.value=null;if(!v2)rule.basePremise.predicate.value=null;if(!v3)rule.basePremise.object.value=null}}_createRule({premise,conclusion}){const varMapping={};const toId=value=>value.termType==="Variable"?varMapping[value.value]=varMapping[value.value]||{}:{value:this._store._termToNewNumericId(value)};const t=term=>({subject:toId(term.subject),predicate:toId(term.predicate),object:toId(term.object)});return{premise:premise.map(p=>t(p)),conclusion:conclusion.map(p=>t(p)),variables:Object.values(varMapping)}}reason(rules){if(!Array.isArray(rules)){rules=getRulesFromDataset(rules)}rules=rules.map(rule=>this._createRule(rule));for(const r1 of rules){for(const r2 of rules){for(let i=0;i<r2.premise.length;i++){const p=r2.premise[i];for(const c of r1.conclusion){if(termEq(p.subject,c.subject)&&termEq(p.predicate,c.predicate)&&termEq(p.object,c.object)){const set=new Set;const premise=[];p.subject.value=p.subject.value||1;p.object.value=p.object.value||1;p.predicate.value=p.predicate.value||1;for(let j=0;j<r2.premise.length;j++){if(j!==i){premise.push(getIndex(r2.premise[j],set))}}(c.next=c.next||[]).push({premise:premise,conclusion:r2.conclusion,basePremise:p})}r2.variables.forEach(v=>{v.value=null})}}}}for(const rule of rules){const set=new Set;rule.premise=rule.premise.map(p=>getIndex(p,set))}const graphs=this._store._getGraphs();for(const graphId in graphs){this._reasonGraphNaive(rules,graphs[graphId])}this._store._size=null}}exports.default=N3Reasoner;function getIndex({subject,predicate,object},set){const s=subject.value||set.has(subject)||(set.add(subject),false);const p=predicate.value||set.has(predicate)||(set.add(predicate),false);const o=object.value||set.has(object)||(set.add(object),false);return!s&&p?{content:"predicates",value:[predicate,object,subject]}:o?{content:"objects",value:[object,subject,predicate]}:{content:"subjects",value:[subject,predicate,object]}}function termEq(t1,t2){if(t1.value===null){t1.value=t2.value}return t1.value===t2.value}},{"./N3DataFactory":3}],7:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.N3EntityIndex=void 0;var _readableStream=require("readable-stream");var _N3DataFactory=_interopRequireWildcard(require("./N3DataFactory"));var _IRIs=_interopRequireDefault(require("./IRIs"));var _N3Util=require("./N3Util");var _N3Writer=_interopRequireDefault(require("./N3Writer"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&{}.hasOwnProperty.call(e,