rdflib 2.2.10 → 2.2.12-5f141ca2
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/.babelrc +0 -0
- package/README.md +1 -0
- package/changes.txt +0 -0
- package/dist/rdflib.min.js +62 -0
- package/dist/rdflib.min.js.map +1 -0
- package/esm/blank-node.js +137 -0
- package/esm/class-order.js +12 -0
- package/esm/collection.js +173 -0
- package/esm/convert.js +61 -0
- package/esm/default-graph.js +57 -0
- package/esm/empty.js +46 -0
- package/esm/factories/canonical-data-factory.js +204 -0
- package/esm/factories/extended-term-factory.js +55 -0
- package/esm/factories/factory-types.js +18 -0
- package/esm/factories/rdflib-data-factory.js +55 -0
- package/esm/fetcher.js +2180 -0
- package/esm/formula.js +987 -0
- package/esm/index.js +64 -0
- package/esm/jsonldparser.js +122 -0
- package/esm/jsonparser.js +60 -0
- package/esm/literal.js +236 -0
- package/esm/log.js +13 -0
- package/esm/n3parser.js +1854 -0
- package/esm/named-node.js +154 -0
- package/esm/namespace.js +17 -0
- package/esm/node-internal.js +151 -0
- package/esm/node.js +46 -0
- package/esm/parse.js +138 -0
- package/esm/patch-parser.js +110 -0
- package/esm/query-to-sparql.js +83 -0
- package/esm/query.js +620 -0
- package/esm/rdfaparser.js +1197 -0
- package/esm/rdfxmlparser.js +588 -0
- package/esm/serialize.js +95 -0
- package/esm/serializer.js +1162 -0
- package/esm/sparql-to-query.js +566 -0
- package/esm/statement.js +128 -0
- package/esm/store.js +1306 -0
- package/esm/tf-types.js +1 -0
- package/esm/types.js +25 -0
- package/esm/update-manager.js +1252 -0
- package/esm/updates-via.js +197 -0
- package/esm/uri.js +245 -0
- package/esm/utils/default-graph-uri.js +4 -0
- package/esm/utils/termValue.js +8 -0
- package/esm/utils/terms.js +72 -0
- package/esm/utils-js.js +348 -0
- package/esm/utils.js +103 -0
- package/esm/variable.js +101 -0
- package/esm/xsd-internal.js +10 -0
- package/esm/xsd.js +15 -0
- package/lib/blank-node.d.ts +44 -0
- package/lib/blank-node.js +0 -0
- package/lib/class-order.d.ts +7 -0
- package/lib/class-order.js +0 -0
- package/lib/collection.d.ts +65 -0
- package/lib/collection.js +0 -0
- package/lib/convert.d.ts +2 -0
- package/lib/convert.js +0 -0
- package/lib/default-graph.d.ts +13 -0
- package/lib/default-graph.js +0 -0
- package/lib/empty.d.ts +11 -0
- package/lib/empty.js +0 -0
- package/lib/factories/canonical-data-factory.d.ts +6 -0
- package/lib/factories/canonical-data-factory.js +0 -0
- package/lib/factories/extended-term-factory.d.ts +13 -0
- package/lib/factories/extended-term-factory.js +0 -0
- package/lib/factories/factory-types.d.ts +67 -0
- package/lib/factories/factory-types.js +0 -0
- package/lib/factories/rdflib-data-factory.d.ts +4 -0
- package/lib/factories/rdflib-data-factory.js +0 -0
- package/lib/fetcher.d.ts +443 -0
- package/lib/fetcher.js +3 -2
- package/lib/formula.d.ts +327 -0
- package/lib/formula.js +0 -0
- package/lib/index.d.ts +40 -0
- package/lib/index.js +0 -0
- package/lib/jsonldparser.d.ts +13 -0
- package/lib/jsonldparser.js +0 -0
- package/lib/jsonparser.d.ts +4 -0
- package/lib/jsonparser.js +0 -0
- package/lib/literal.d.ts +67 -0
- package/lib/literal.js +0 -0
- package/lib/log.d.ts +15 -0
- package/lib/log.js +0 -0
- package/lib/n3parser.d.ts +62 -0
- package/lib/n3parser.js +1334 -1289
- package/lib/named-node.d.ts +44 -0
- package/lib/named-node.js +0 -0
- package/lib/namespace.d.ts +7 -0
- package/lib/namespace.js +0 -0
- package/lib/node-internal.d.ts +63 -0
- package/lib/node-internal.js +0 -0
- package/lib/node.d.ts +2 -0
- package/lib/node.js +0 -0
- package/lib/parse.d.ts +16 -0
- package/lib/parse.js +0 -0
- package/lib/patch-parser.d.ts +3 -0
- package/lib/patch-parser.js +0 -0
- package/lib/query-to-sparql.d.ts +1 -0
- package/lib/query-to-sparql.js +0 -0
- package/lib/query.d.ts +27 -0
- package/lib/query.js +0 -0
- package/lib/rdfaparser.d.ts +78 -0
- package/lib/rdfaparser.js +0 -0
- package/lib/rdfxmlparser.d.ts +60 -0
- package/lib/rdfxmlparser.js +430 -413
- package/lib/serialize.d.ts +23 -0
- package/lib/serialize.js +1 -1
- package/lib/serializer.d.ts +54 -0
- package/lib/serializer.js +851 -824
- package/lib/sparql-to-query.d.ts +6 -0
- package/lib/sparql-to-query.js +0 -0
- package/lib/statement.d.ts +55 -0
- package/lib/statement.js +0 -0
- package/lib/store.d.ts +302 -0
- package/lib/store.js +0 -0
- package/lib/tf-types.d.ts +151 -0
- package/lib/tf-types.js +0 -0
- package/lib/types.d.ts +68 -0
- package/lib/types.js +0 -0
- package/lib/update-manager.d.ts +198 -0
- package/lib/update-manager.js +0 -0
- package/lib/updates-via.d.ts +26 -0
- package/lib/updates-via.js +0 -0
- package/lib/uri.d.ts +33 -0
- package/lib/uri.js +0 -0
- package/lib/utils/default-graph-uri.d.ts +3 -0
- package/lib/utils/default-graph-uri.js +0 -0
- package/lib/utils/termValue.d.ts +3 -0
- package/lib/utils/termValue.js +0 -0
- package/lib/utils/terms.d.ts +33 -0
- package/lib/utils/terms.js +0 -0
- package/lib/utils-js.d.ts +50 -0
- package/lib/utils-js.js +0 -0
- package/lib/utils.d.ts +20 -0
- package/lib/utils.js +0 -0
- package/lib/variable.d.ts +29 -0
- package/lib/variable.js +0 -0
- package/lib/xsd-internal.d.ts +11 -0
- package/lib/xsd-internal.js +0 -0
- package/lib/xsd.d.ts +19 -0
- package/lib/xsd.js +8 -14
- package/package.json +3 -3
- package/src/blank-node.ts +0 -0
- package/src/class-order.ts +0 -0
- package/src/collection.ts +0 -0
- package/src/convert.js +0 -0
- package/src/default-graph.ts +0 -0
- package/src/empty.ts +0 -0
- package/src/factories/canonical-data-factory.ts +0 -0
- package/src/factories/extended-term-factory.ts +0 -0
- package/src/factories/factory-types.ts +0 -0
- package/src/factories/rdflib-data-factory.ts +0 -0
- package/src/fetcher.ts +6 -3
- package/src/formula.ts +0 -0
- package/src/index.ts +0 -0
- package/src/jsonldparser.js +0 -0
- package/src/jsonparser.js +0 -0
- package/src/literal.ts +0 -0
- package/src/log.js +0 -0
- package/src/n3parser.js +1114 -1110
- package/src/named-node.ts +0 -0
- package/src/namespace.ts +0 -0
- package/src/node-internal.ts +0 -0
- package/src/node.ts +0 -0
- package/src/parse.ts +0 -0
- package/src/patch-parser.js +0 -0
- package/src/query-to-sparql.js +0 -0
- package/src/query.js +0 -0
- package/src/rdfaparser.js +0 -0
- package/src/rdfxmlparser.js +22 -21
- package/src/serialize.ts +3 -3
- package/src/serializer.js +74 -62
- package/src/sparql-to-query.js +0 -0
- package/src/statement.ts +0 -0
- package/src/store.ts +0 -0
- package/src/tf-types.ts +0 -0
- package/src/types.ts +0 -0
- package/src/update-manager.ts +0 -0
- package/src/updates-via.js +0 -0
- package/src/uri.ts +0 -0
- package/src/utils/default-graph-uri.ts +0 -0
- package/src/utils/termValue.ts +0 -0
- package/src/utils/terms.ts +0 -0
- package/src/utils-js.js +0 -0
- package/src/utils.ts +0 -0
- package/src/variable.ts +0 -0
- package/src/xsd-internal.js +0 -0
- package/src/xsd.js +16 -14
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["webpack://$rdf/webpack/universalModuleDefinition","webpack://$rdf/webpack/bootstrap","webpack://$rdf/./node_modules/@babel/runtime/helpers/defineProperty.js","webpack://$rdf/./src/types.ts","webpack://$rdf/./src/log.js","webpack://$rdf/./node_modules/@babel/runtime/helpers/assertThisInitialized.js","webpack://$rdf/./node_modules/@babel/runtime/helpers/classCallCheck.js","webpack://$rdf/./node_modules/@babel/runtime/helpers/createClass.js","webpack://$rdf/./src/uri.ts","webpack://$rdf/./src/utils/terms.ts","webpack://$rdf/./src/named-node.ts","webpack://$rdf/./node_modules/@babel/runtime/helpers/getPrototypeOf.js","webpack://$rdf/./src/utils-js.js","webpack://$rdf/./src/node-internal.ts","webpack://$rdf/./node_modules/@babel/runtime/helpers/inherits.js","webpack://$rdf/./src/namespace.ts","webpack://$rdf/./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js","webpack://$rdf/./src/utils.ts","webpack://$rdf/./src/class-order.ts","webpack://$rdf/./src/factories/canonical-data-factory.ts","webpack://$rdf/./src/xsd-internal.js","webpack://$rdf/./src/literal.ts","webpack://$rdf/./src/factories/factory-types.ts","webpack://$rdf/./src/blank-node.ts","webpack://$rdf/./node_modules/n3/src/IRIs.js","webpack://$rdf/./node_modules/@babel/runtime/helpers/typeof.js","webpack://$rdf/./src/variable.ts","webpack://$rdf/./node_modules/jsonld/lib/types.js","webpack://$rdf/./src/utils/termValue.ts","webpack://$rdf/./src/node.ts","webpack://$rdf/./node_modules/jsonld/lib/util.js","webpack://$rdf/./src/store.ts","webpack://$rdf/./node_modules/jsonld/lib/JsonLdError.js","webpack://$rdf/./node_modules/jsonld/lib/graphTypes.js","webpack://$rdf/./src/utils/default-graph-uri.ts","webpack://$rdf/./src/collection.ts","webpack://$rdf/./node_modules/jsonld/lib/url.js","webpack://$rdf/./src/n3parser.js","webpack://$rdf/./src/rdfaparser.js","webpack://$rdf/./src/query.js","webpack://$rdf/./src/default-graph.ts","webpack://$rdf/./node_modules/jsonld/lib/context.js","webpack://$rdf/./src/fetcher.ts","webpack://$rdf/./src/serialize.ts","webpack://$rdf/./node_modules/n3/src/N3DataFactory.js","webpack://$rdf/./src/rdfxmlparser.js","webpack://$rdf/./src/xsd.js","webpack://$rdf/./src/serializer.js","webpack://$rdf/(webpack)/buildin/global.js","webpack://$rdf/./src/statement.ts","webpack://$rdf/./src/parse.ts","webpack://$rdf/./src/formula.ts","webpack://$rdf/./src/factories/extended-term-factory.ts","webpack://$rdf/./node_modules/cross-fetch/dist/browser-ponyfill.js","webpack://$rdf/./node_modules/jsonld/lib/nodeMap.js","webpack://$rdf/./src/patch-parser.js","webpack://$rdf/./node_modules/async/dist/async.mjs","webpack://$rdf/./node_modules/n3/src/N3Writer.js","webpack://$rdf/./src/convert.js","webpack://$rdf/./src/jsonldparser.js","webpack://$rdf/./node_modules/jsonld/lib/jsonld.js","webpack://$rdf/./node_modules/n3/src/N3Util.js","webpack://$rdf/external \"window\"","webpack://$rdf/./node_modules/rdf-canonize/index.js","webpack://$rdf/./node_modules/rdf-canonize/lib/IdentifierIssuer.js","webpack://$rdf/./node_modules/rdf-canonize/lib/NQuads.js","webpack://$rdf/./node_modules/jsonld/lib/constants.js","webpack://$rdf/./src/empty.ts","webpack://$rdf/./src/jsonparser.js","webpack://$rdf/./src/query-to-sparql.js","webpack://$rdf/./src/sparql-to-query.js","webpack://$rdf/./src/update-manager.ts","webpack://$rdf/./src/factories/rdflib-data-factory.ts","webpack://$rdf/./src/updates-via.js","webpack://$rdf/./src/index.ts","webpack://$rdf/./node_modules/@babel/runtime/regenerator/index.js","webpack://$rdf/./node_modules/solid-namespace/index.js","webpack://$rdf/./node_modules/rdf-canonize/lib/URDNA2015.js","webpack://$rdf/./node_modules/setimmediate/setImmediate.js","webpack://$rdf/./node_modules/rdf-canonize/lib/MessageDigest-browser.js","webpack://$rdf/./node_modules/rdf-canonize/lib/Permuter.js","webpack://$rdf/./node_modules/rdf-canonize/lib/URDNA2015Sync.js","webpack://$rdf/./node_modules/jsonld/lib/RequestQueue.js","webpack://$rdf/./node_modules/lru-cache/index.js","webpack://$rdf/./node_modules/@babel/runtime/helpers/asyncToGenerator.js","webpack://$rdf/./node_modules/n3/src/N3Lexer.js","webpack://$rdf/./node_modules/queue-microtask/index.js","webpack://$rdf/./node_modules/@babel/runtime/helpers/setPrototypeOf.js","webpack://$rdf/./node_modules/regenerator-runtime/runtime.js","webpack://$rdf/(webpack)/buildin/harmony-module.js","webpack://$rdf/./node_modules/rdf-canonize/lib/index.js","webpack://$rdf/./node_modules/timers-browserify/main.js","webpack://$rdf/./node_modules/process/browser.js","webpack://$rdf/./node_modules/rdf-canonize/lib/URGNA2012.js","webpack://$rdf/./node_modules/rdf-canonize/lib/URGNA2012Sync.js","webpack://$rdf/./node_modules/jsonld/lib/platform-browser.js","webpack://$rdf/./node_modules/jsonld/lib/documentLoaders/xhr.js","webpack://$rdf/./node_modules/jsonld/lib/ContextResolver.js","webpack://$rdf/./node_modules/jsonld/lib/ResolvedContext.js","webpack://$rdf/./node_modules/yallist/yallist.js","webpack://$rdf/./node_modules/yallist/iterator.js","webpack://$rdf/./node_modules/jsonld/lib/NQuads.js","webpack://$rdf/./node_modules/jsonld/lib/expand.js","webpack://$rdf/./node_modules/jsonld/lib/flatten.js","webpack://$rdf/./node_modules/jsonld/lib/fromRdf.js","webpack://$rdf/./node_modules/jsonld/lib/toRdf.js","webpack://$rdf/./node_modules/canonicalize/lib/canonicalize.js","webpack://$rdf/./node_modules/jsonld/lib/frame.js","webpack://$rdf/./node_modules/jsonld/lib/compact.js","webpack://$rdf/./node_modules/jsonld/lib/JsonLdProcessor.js","webpack://$rdf/./node_modules/buffer/index.js","webpack://$rdf/./node_modules/base64-js/index.js","webpack://$rdf/./node_modules/ieee754/index.js","webpack://$rdf/./node_modules/buffer/node_modules/isarray/index.js","webpack://$rdf/./node_modules/n3/src/N3Parser.js"],"names":["root","factory","exports","module","require","define","amd","window","__WEBPACK_EXTERNAL_MODULE__56__","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","obj","configurable","writable","NamedNodeTermType","BlankNodeTermType","LiteralTermType","VariableTermType","DefaultGraphTermType","CollectionTermType","EmptyTermType","GraphTermType","HTMLContentType","JSONLDContentType","N3ContentType","N3LegacyContentType","NQuadsAltContentType","NQuadsContentType","NTriplesContentType","RDFXMLContentType","SPARQLUpdateContentType","SPARQLUpdateSingleMatchContentType","TurtleContentType","TurtleLegacyContentType","XHTMLContentType","log","debug","x","warn","info","error","success","msg","self","ReferenceError","instance","Constructor","TypeError","_defineProperties","target","props","length","descriptor","protoProps","staticProps","alert","console","docpart","uri","indexOf","slice","document","RDFlibNamedNode","hostpart","u","exec","join","given","base","baseColon","baseScheme","baseSingle","lastSlash","path","baseHash","lastIndexOf","match","replace","protocol","refTo","k","len","len1","q","ref","ref1","commonHost","RegExp","isStatement","isStore","isCollection","isTerm","termType","isRDFlibObject","isVariable","isLiteral","isQuad","isNamedNode","isBlankNode","isSubject","isPredicate","isRDFObject","isGraph","NamedNode","iri","termValue","ClassOrder","Error","includes","str","this","split","Node","_getPrototypeOf","setPrototypeOf","getPrototypeOf","__proto__","string","template","subs","baseA","result","mediaTypeClass","mediaType","trim","linkRelationProperty","relation","callbackify","callbacks","addHook","hook","addCallback","func","push","removeCallback","funcName","splice","insertCallback","unshift","fireCallbacks","args","callback","newCallbacks","replaceCallbacks","apply","DOMParserFactory","DOMParser","ActiveXObject","domToString","node","options","selfClosing","forEach","skipAttributes","dumpNode","out","noEsc","nodeType","hasAttribute","classWithChildText","matches","class","querySelector","element","textContent","skipNodeWithClass","ename","nodeName","toLowerCase","attrList","attributes","atn","test","replaceClassItemWith","source","re","skipClassWithValue","sortAttributes","sort","a","b","localeCompare","childNodes","pop","nodeValue","nl","dtstamp","now","Date","year","getYear","month","getMonth","day","getDate","hour","getUTCHours","minute","getUTCMinutes","second","getSeconds","heavyCompare","y","g","uriMap","nonBlank","signature","lis","statementsMatching","map","st","subject","predicate","concat","undefined","comparison","compareTerms","compareTerm","heavyCompareSPO","output","createElement","body","appendChild","parseXML","parseFromString","contentType","RDFArrayRemove","equals","why","string_startswith","pref","stackString","e","stack","lines","toString","toprint","line","charAt","chunks","bindings","other","classOrder","toCanonical","toNT","subClass","superClass","constructor","Namespace","nsuri","dataFactory","namedNode","ln","_typeof","assertThisInitialized","appliedFactoryMethods","rdf","arrayToStatements","rdfFactory","data","statements","reduce","id","_listObj","listData","nextNode","quad","blankNode","ArrayIndexOf","arr","item","defaultGraph","DefaultGraph","CanonicalDataFactory","supports","Feature","collections","defaultGraphType","equalsMethod","identity","reversibleId","variableType","BlankNode","graph","term","quadToNQ","Variable","nq","termToNQ","Statement","literal","languageOrDatatype","Literal","fromValue","strValue","triple","elements","toNQ","variable","boolean","dateTime","decimal","double","integer","langString","language","datatype","XSD","lang","d2","getUTCFullYear","getUTCMonth","getUTCDate","getUTCSeconds","Math","abs","Number","MAX_SAFE_INTEGER","isInteger","fromDate","fromBoolean","fromNumber","getId","formula","bnodeNew","copyTo","NTAnonymousNodePrefix","fragments","nextId","RDF","SWAP","xsd","type","nil","first","rest","owl","sameAs","forSome","forAll","implies","iterator","Uri","api","isArray","Array","isBoolean","v","isDouble","isNumber","String","isEmptyObject","isObject","keys","isNumeric","isNaN","parseFloat","isFinite","isString","isUndefined","toJS","graphTypes","types","IdentifierIssuer","JsonLdError","REGEX_LINK_HEADERS","REGEX_LINK_HEADER","REGEX_LINK_HEADER_PARAMS","DEFAULTS","accept","clone","rval","Map","set","Set","add","asArray","buildHeaders","headers","some","h","RangeError","assign","Accept","parseLinkHeader","header","entries","params","rel","validateTypeValue","isFrame","every","vv","code","hasProperty","hasValue","val","isList","compareValues","addValue","propertyIsArray","valueIsArray","allowDuplicate","prependValue","getValues","removeProperty","removeValue","values","filter","relabelBlankNodes","input","_labelBlankNodes","issuer","ki","v1","v2","isValue","compareShortestLeast","owlNamespaceURI","handleFP","subj","pred","o1","any","equate","handleIFP","s1","handleRDFType","typeCallback","classActions","done","IndexedFormula","features","opts","propertyActions","redirections","aliases","HTTPRedirects","subjectIndex","predicateIndex","objectIndex","whyIndex","index","namespaces","rdfArrayRemove","dataCallback","dataCallbacks","initPropertyActions","statementsCopy","ea","substitute","cb","patch","patchCallback","ds","targetKB","binding","doPatch","onDonePatch","bad","ds2","sts","remove","where","query","Query","pat","sync","bindingsFound","fetcher","_existentialVariables","addFn","newPropertyAction","proj","actions","arguments","appNode","objNode","predicateCallback","predHash","canon","holds","hash","ix","checkStatementList","from","origin","j","arrayContains","u1","u2","flags","statList","copy","u1in","u2in","replaceWith","bnode","sym","declareExistential","action","toBeFixed","_universalVariables","doc","mentionsURI","myQuery","onDone","indexedFormulaQuery","results","removeStatement","limit","removeStatements","big","small","oldhash","newhash","moveIndex","oldlist","newlist","nowKnownAs","x1","y1","prefix","justOne","list","pattern","wild","iBest","best","pBest","possibles","check","parts","cterm","terms","res","defaultGraphURI","Formula","message","details","super","isSubjectReference","isSimpleGraph","Collection","initial","RdflibBlankNode","closed","shift","collection","parsers","simple","regex","full","parse","parser","parsed","scheme","port","href","authority","normalizedPath","removeDotSegments","prependBase","isAbsolute","transform","substr","fragment","removeBase","baseSegments","iriSegments","last","next","isAbsoluteRegex","isRelative","Utf8","utftext","charCodeAt","fromCharCode","Logic_NS","pyjslib_Tuple","theList","pyjslib_List","pyjslib_Dict","listOfPairs","pyjslib_len","pyjslib_slice","StopIteration","pyjslib_Iterator","li","string_find","assertFudge","condition","desc","encode","encoding","decode","uripath_join","_notNameChars","_notQNameChars","number_syntax","datetime_syntax","interesting","langcode","createSinkParser","store","openFormula","thisDoc","baseURI","genPrefix","metaURI","SinkParser","_bindings","_flags","_store","setGenPrefix","_thisDoc","statementCount","startOfLine","previousLine","_genPrefix","keywords","keywordsSet","_anonymousNodes","_variables","_parentVariables","_reason","_reason2","_baseURI","RDFSink_uniqueURI","_formula","_context","_parentContext","stream","loadBuf","read","buf","startDoc","feed","endDoc","octets","skipSpace","directiveOrStatement","BadSyntax","directive","statement","checkDot","tok","commaSeparatedList","setKeywords","__x","newUniversal","uri_ref2","qname","encodeURI","hexify","qn","setPrefixForURI","property_list","prop","nodeOrLiteral","ch","ahead","here","makeStatement","subjectAlready","bnodeID","objs","objectList","__obj","mylist","first_run","newSet","oldParentContext","parentAnonymousNodes","grandParentVariables","reason2","close","thing_type","verb","pairFudge","dir","ofUris","bareWord","pfx","anonymousNode","symb","uref","delim","strconst","lastIndex","parseInt","dt","startline","res2","ustr","uEscape","UEscape","count","uch","uesc","__OLD_BadSyntax","_str","_i","_why","_uri","lineNo","SyntaxError","characterInFile","syntaxProblem","pre","post","ELEMENT_NODE","ATTRIBUTE_NODE","TEXT_NODE","CDATA_SECTION_NODE","ENTITY_REFERENCE_NODE","ENTITY_NODE","PROCESSING_INSTRUCTION_NODE","COMMENT_NODE","DOCUMENT_NODE","DOCUMENT_TYPE_NODE","DOCUMENT_FRAGMENT_NODE","NOTATION_NODE","RDFaProcessor","kb","subjects","prefixes","blankNodes","htmlOptions","theOne","getTime","vocabulary","blankCounter","langAttributes","namespaceURI","localName","inXHTMLMode","absURIRE","finishedHandlers","init","su","ob","pr","or","toRDFNodeObject","parentNode","mappings","newMappings","dateTimeTypes","matched","colon","substring","NCNAME","curie","parseCURIE","resolveAndNormalize","defaultVocabulary","ignoreTerms","parseTermOrCURIEOrAbsURI","tokenize","parseCURIEOrURI","documentElement","setContext","queue","removeHash","baseURIMap","current","context","parent","listMapping","bnodes","newBlankNode","addTriple","objectURI","skip","newSubject","currentObjectResource","typedResource","prefixesCopied","incomplete","listMappingDifferent","parseURI","vocabAtt","getAttributeNode","baseSubject","spec","att","copyMappings","prefixAtt","parsePrefixMappings","xmlLangAtt","getAttributeNodeNS","relAtt","revAtt","typeofAtt","propertyAtt","datatypeAtt","datetimeAtt","inHTMLMode","contentAtt","aboutAtt","srcAtt","resourceAtt","hrefAtt","inlistAtt","relAttPredicates","parsePredicate","revAttPredicates","parseSafeCURIEOrCURIEOrURI","parentObject","newSubjectOrigin","typeURI","forward","content","PlainLiteralURI","XMLLiteralURI","HTMLLiteralURI","deriveDateTimeType","childContext","listSubject","child","lastChild","previousSibling","copyProperties","getAttribute","setXHTMLContext","doctype","publicId","systemId","setHTMLContext","setXMLContext","setInitialContext","Util","dom","process","nameChar","nameStartChar","parseRDFaDOM","vars","bindingDebug","bindingsDebug","nbs","unifyContents","nbs2","actual","isVar","complexType","defaultDocumentURI","unifyTerm","nb","nb2","bindings2","union","OptionalBranchJunction","originalCallback","trunkBindings","branches","MandatoryBranch","checkAllDone","doCallBacks","reportMatch","reportDone","OptionalBranch","junction","prepare","f","termIndex","ind","nvars","easiestQuery","bindingsSoFar","level","localCallback","branch","pattern_debug","optional","br","matchIndex","fetchResource","requestedTerm","docuri","nowOrWhenFetched","ok","xhr","getState","match2","constraintsSatisfied","constraints","nk","newBindings1","nbs1","nc","onward","trunck","initBindings","setTimeout","isDefaultGraph","util","_isArray","_isObject","_isString","_isUndefined","_isAbsoluteIri","_isRelativeIri","_asArray","_compareShortestLeast","INITIAL_CONTEXT_CACHE","KEYWORD_PATTERN","_expandIri","activeCtx","relativeTo","localCtx","defined","isKeyword","createTermDefinition","vocab","mapping","suffix","_prefix","async","propagate","overrideProtected","cycles","resolved","contextResolver","resolve","documentLoader","previousContext","resolvedContext","ctx","protected","protectedMode","processed","getProcessed","oldActiveCtx","getInitialContext","_protected","setProcessed","processingMode","resolvedImport","processedImport","importCtx","keyCtx","url","has","validKeys","previousMapping","delete","simpleTerm","reverse","kw","_termHasColon","container","validContainers","isValid","hasSet","direction","nest","_deepCompare","x2","x1Array","k1s","k2s","k1","expandIri","JSON","stringify","cached","initialContext","inverse","getInverse","fastCurieMap","irisToTerms","defaultLanguage","defaultDirection","ids","entry","fastCurieEntry","_addPreferredTerm","_buildIriMap","revertToPreviousContext","size","clear","iriMap","idx","letter","typeOrLanguageValue","getContextValue","version","Parsable","CONTENT_TYPE_BY_EXT","getNS","link","http","httph","rdfs","dc","ldp","Handler","response","RDFXMLHandler","responseText","failFetch","resource","RDFParser","original","err","noMeta","doneFetch","mediatypes","XHTMLHandler","title","getElementsByTagName","links","linkData","scripts","rdfParse","noRDFa","XMLHandler","addStatus","req","html","xmlns","HTMLHandler","isXML","docTypeStart","docTypeEnd","isXHTML","isXMLNS","titleMatch","JsonLdHandler","Promise","reject","jsonldParser","TextHandler","N3Handler","N3Parser","defaultHandlers","Fetcher","timeout","_fetch","fetch","global","solidFetcher","solidFetch","crossFetch","requested","timeouts","redirectedTo","fetchQueue","fetchCallbacks","nonexistent","lookedUp","handlers","addHandler","all","load","uriIn","initFetchOptions","initialisedOptions","pendingFetchPromise","originalUri","pendingPromise","force","race","setRequestTimeout","fetchUri","cleanupFetchRequest","then","clearTimeout","_options","isPending","method","toUpperCase","Headers","cache","acceptString","requestedURI","offlineOverride","setCredentials","actualProxyURI","proxyIfNecessary","proxyUsed","unsupportedProtocol","state","status","statusText","dummyResponse","bodyUsed","saveRequestMetadata","handleResponse","errno","handleError","p2","userCallback","referringTerm","fetchResponse","oops","statusMessage","getHours","getMinutes","getMilliseconds","statusNode","the","append","errorMessage","statusCode","meth","encodeURIComponent","linkHeader","reqNode","paramexp","was","lookUpThing","uriSting","serialize","jsonString","webOperation","catch","there","unload","parentURI","folderName","invalidateCache","text","e2","rterm","uris","requests","each","request","anyValue","startsWith","timeNow","responseNode","refresh","clearPreviousData","exp","getHeader","removeMany","removeDocument","handler","register","retriedWithNoCredentials","newOptions","credentials","location","isCrossSite","retryNoCredentials","proxyUri","crossSiteProxy","redirectToProxy","rdfType","locURI","prev","reqURI","redirection","saveResponseMetadata","normalizedContentType","contentLocation","saveErrorResponse","diffLocation","absContentLocation","addType","isImage","handlerForContentType","find","forceContentType","guess","guessContentType","newURI","oldReq","acceptstring","crossSiteProxyTemplate","UI","panes","preferences","isExtension","$SolidTestEnvironment","localSiteMap","lookup","z","pcol","withCredentials","HANDLERS","sz","Serializer","setFlags","n3String","newSts","suggestNamespaces","setBase","executeCallback","statementsToXML","statementsToN3","statementsToNTriples","convert","DEFAULTGRAPH","_blankNodeCounter","DataFactory","languageOrDataType","Term","atPos","datatypeString","dtPos","char","Quad","_subject","_predicate","_object","_graph","toJSON","reify","uriUtil","rdfid","NODE","ARC","addSymbol","isTripleToLoad","loadTriple","listIndex","attributeNode","potentialNode","children","cleanParser","DOCUMENT","ELEMENT","frameFactory","parseDOM","buildFrame","frame","elementURI","el","dig","attrs","TEXT","CDATA_SECTION","addArc","addLiteral","addCollectionArc","removeAttributeNode","parsetype","nv","addBNode","addCollection","bnid2","addNode","about","bnid","rdftype","pframe","candidate","terminateFrame","removeAttribute","createXSD","localFactory","createSerializer","nsKeys","solidNs","suggestPrefix","namespacesUsed","prefixchars","incoming","formulas","fromNT","px","prefixs","canUse","pp","validPrefix","slash","allBnodes","checkMentions","ss","toStr","roots","xNT","fromStr","rootsHash","backslashUify","sorted","rdfns","termToNT","atomicTermToN3","defaultNamespace","predMap","spaces","treeToLine","tree","s2","statementListToTree","stats","rootSubjects","subjectTree","termToN3","propertyTree","objectTree","lastPred","objects","expr","prefixDirectives","explicitURI","treeToString","lastLength","eNotation","stringToN3","symbolToN3","forbidden","forbidden3","forbidden1","canSplit","localid","namesp","keyords","makeUpPrefix","write","session","sources","metaSources","metadata","namespaceCounts","liPrefix","XMLtreeToLine","statementListToXMLTree","subjectXMLTree","escapeForXML","relURI","propertyXMLTree","ap","bp","as","bs","an","bn","number","collectionXMLTree","tag","ns2","XMLtreeToString","Function","DefaultGraphNode","sparqlUpdateParser","n3Parser","N3jsParser","nquadCallback","executeErrorCallback","cause","nquads","tripleCallback","handled","Graph","factoryMethod","anyStatementMatching","bots","bottom","len2","len3","hashString","thisClass","len4","members","ref2","ref3","ref4","ref5","seeds","transitiveClosure","NTtoURI","findMembersNT","findTypesNT","excludePredicateURIs","todo","doneArcs","follow","_features","addAll","provenance","documentString","sups","agenda","tops","ExtendedTermFactory","__self__","F","DOMException","support","Blob","viewClasses","isArrayBufferView","ArrayBuffer","isView","normalizeName","normalizeValue","iteratorFor","items","getOwnPropertyNames","consumed","fileReaderReady","reader","onload","onerror","readBlobAsArrayBuffer","blob","FileReader","promise","readAsArrayBuffer","bufferClone","view","Uint8Array","byteLength","buffer","Body","_initBody","_bodyInit","_bodyText","isPrototypeOf","_bodyBlob","FormData","_bodyFormData","URLSearchParams","DataView","_bodyArrayBuffer","rejected","arrayBuffer","readAsText","chars","readArrayBufferAsText","formData","json","oldValue","thisArg","methods","Request","upcased","signal","referrer","form","bytes","decodeURIComponent","Response","bodyInit","redirectStatuses","redirect","aborted","XMLHttpRequest","abortXhr","abort","rawHeaders","getAllResponseHeaders","responseURL","ontimeout","onabort","open","responseType","setRequestHeader","addEventListener","onreadystatechange","readyState","removeEventListener","send","polyfill","ponyfill","default","createMergedNodeMap","graphs","createNodeMap","mergeNodeMaps","_list","properties","referencedNode","reverseMap","reverseProperty","itemName","mergeNodeMapGraphs","merged","mergedNode","graphNames","graphName","nodeMap","SQNS","clauses","badSyntax","found","initialParams","fn","hasQueueMicrotask","queueMicrotask","hasSetImmediate","setImmediate","hasNextTick","nextTick","fallback","wrap","defer","setImmediate$1","asyncify","isAsync","handlePromise","invokeCallback","wrapAsync","asyncFn","awaitify","arity","cbArgs","applyEach","eachfn","fns","callArgs","that","_asyncMap","iteratee","counter","_iteratee","_","iterCb","isArrayLike","breakLoop","once","wrapper","callFn","createIterator","coll","createArrayIterator","okeys","getIterator","createES2015Iterator","onlyOnce","asyncEachOfLimit","generator","canceled","awaiting","running","replenish","iterDone","iterateeCallback","eachOfLimit","asyncIterator","isAsyncIterable","nextElem","looping","elem","eachOfLimit$2","eachOfArrayLike","completed","iteratorCallback","eachOfGeneric","Infinity","eachOf$1","map$1","applyEach$1","eachOfSeries$1","mapSeries$1","applyEachSeries","PROMISE_SYMBOL","promiseCallback","rej","auto","tasks","concurrency","numTasks","runningTasks","hasError","listeners","readyTasks","readyToCheck","uncheckedDependencies","enqueueTask","task","taskCallback","safeResults","rkey","processQueue","taskFn","runTask","run","getDependents","taskName","dependencies","remainingDependencies","dependencyName","taskListeners","addListener","currentTask","dependent","checkForDeadlocks","FN_ARGS","ARROW_FN_ARGS","FN_ARG_SPLIT","FN_ARG","STRIP_COMMENTS","DLL","head","tail","newNode","insertBefore","setInitial","insertAfter","removeLink","cur","testFn","curr","dll","worker","payload","_worker","numRunning","workersList","events","drain","saturated","unsaturated","empty","off","event","ev","trigger","processingScheduled","_insert","insertAtFront","rejectOnError","started","_tasks","_createCB","idle","_maybeDrain","eventMethod","handleAndRemove","on","isProcessing","paused","datum","min","defineProperties","reduce$1","memo","seq","functions","_functions","newargs","nextargs","mapLimit$1","concatLimit$1","mapResults","concat$1","concatSeries$1","_createTester","getResult","testResult","testPassed","detect$1","bool","detectLimit$1","detectSeries$1","consoleFunc","resultArgs","doWhilst$1","_fn","_test","truth","_withoutIndex","eachLimit$2","eachSeries$1","ensureAsync","innerArgs","every$1","everyLimit$1","everySeries$1","filterArray","truthValues","filterGeneric","_filter","filter$1","filterLimit$1","filterSeries$1","forever$1","errback","groupByLimit$1","mapValuesLimit$1","newObj","_parallel","taskCb","queue$1","Heap","heap","pushCount","MIN_SAFE_INTEGER","smaller","percUp","top","percDown","priority","race$1","reduceRight","array","reversed","reflect","reflectCallback","retVal","reject$2","rejectLimit$1","rejectSeries$1","constant$1","retry","times","intervalFunc","parseTimes","_task","attempt","retryAttempt","errorFilter","acc","interval","some$1","Boolean","someLimit$1","someSeries$1","sortBy$1","criteria","comparator","left","right","timesLimit","range","tryEach$1","whilst$1","waterfall$1","taskIndex","nextTask","autoInject","newTasks","fnIsAsync","hasNoDeps","newTask","src","arg","parseParams","newArgs","cargo","cargoQueue","compose","concatLimit","concatSeries","constant","ignoredArgs","detect","detectLimit","detectSeries","doUntil","doWhilst","eachLimit","eachOf","eachOfSeries","eachSeries","everyLimit","everySeries","filterLimit","filterSeries","forever","groupBy","groupByLimit","groupBySeries","mapLimit","mapSeries","mapValues","mapValuesLimit","mapValuesSeries","memoize","hasher","queues","memoized","unmemoized","parallel","parallelLimit","priorityQueue","reflectAll","rejectLimit","rejectSeries","retryable","series","someLimit","someSeries","sortBy","milliseconds","timer","timedOut","timesSeries","accumulator","tryEach","unmemoize","until","waterfall","whilst","allLimit","allSeries","anyLimit","anySeries","findLimit","findSeries","flatMap","flatMapLimit","flatMapSeries","forEachSeries","forEachLimit","forEachOf","forEachOfSeries","forEachOfLimit","inject","foldl","foldr","select","selectLimit","selectSeries","wrapSync","during","doDuring","N3DataFactory","escapeAll","escapedCharacters","outputStream","_prefixRegex","_lists","lists","_outputStream","_endStream","end","chunk","format","_lineMode","_writeQuad","_writeQuadLine","_baseIRI","baseIRI","_prefixIRIs","addPrefixes","_write","_inDefaultGraph","_encodeIriOrBlank","_encodeObject","_encodePredicate","_encodeSubject","_prefixMatch","quadToString","quads","entity","_encodeQuad","characterReplacer","prefixMatch","_encodeLiteral","addQuad","hasPrefixes","IRIlist","prefixList","prefixIRI","contents","_blockedWrite","singleDone","character","convertToJson","jsonCallback","Parser","n3Writer","Writer","asyncLib","jsonld","fromRDF","convertToNQuads","nquadString","jsonldObjectToTerm","listToCollection","listId","listItem","listToStatements","baseString","flatten","flattened","flatResource","addStatement","createStatement","canonize","platform","ContextResolver","LRU","NQuads","expand","_expand","_flatten","_fromRDF","toRDF","_toRDF","frameMergedOrDefault","_frameMergedOrDefault","cleanupNull","_cleanupNull","_isSubjectReference","_getInitialContext","_processContext","_processingMode","compact","_compact","compactIri","_compactIri","_createNodeMap","_createMergedNodeMap","_mergeNodeMaps","_rdfParsers","_resolvedContextCache","max","_setDefaults","defaults","expanded","compactArrays","compactToRelative","skipExpansion","sharedCache","processContext","compacted","compactionMap","tmp","hasContext","graphAlias","keepFreeFloatingNodes","expansionMap","toResolve","contextsToProcess","expandContext","defaultBase","remoteDoc","documentUrl","contextUrl","remoteContext","embed","explicit","requireAll","omitDefault","bnodesToClear","frameContext","omitGraph","pruneBlankNodeIdentifiers","expandedFrame","frameKeys","is11","framed","framing","normalize","algorithm","inputFormat","parsedInput","produceGeneralizedRdf","dataset","rdfParser","parsedDataset","merge","docs","mergeNodes","_graphs","_nodeMap","_documentLoader","documentLoaders","useDocumentLoader","registerRDFParser","unregisterRDFParser","promises","RequestQueue","JsonLdProcessor","setupGlobals","setupDocumentLoaders","existing","_existing","old","identifier","RDF_LANGSTRING","XSD_STRING","REGEX","_compareTriples","t1","t2","eoln","lineNumber","_unescapeRegex","U","unique","legacyDatasetToQuads","serializeQuad","nquad","_escapeRegex","_escape","termTypeMap","IRI","componentName","oldComponent","newComponent","LINK_HEADER_REL","LINK_HEADER_CONTEXT","RDF_LIST","RDF_FIRST","RDF_REST","RDF_NIL","RDF_TYPE","RDF_PLAIN_LITERAL","RDF_XML_LITERAL","RDF_JSON_LITERAL","RDF_OBJECT","XSD_BOOLEAN","XSD_DOUBLE","XSD_INTEGER","Empty","parseJSON","preds","queryToSPARQL","indent","getPattern","addIndent","getConstraints","foo","describe","getWhere","getOptionals","getSelect","getSPARQL","SPARQLToQuery","SPARQL","testMode","variableHash","makeVar","newVar","isRealText","fixSymbolBrackets","isSymbol","isBnode","isPrefix","isPrefixedSymbol","getPrefix","getSuffix","removeBrackets","spaceDelimit","arrayIndexOf","arrayIndicesOf","getMatchingBracket","ConstraintEqualTo","varstr","ConstraintRegexp","rg","setConstraint","setOptional","opt","setWhere","toTerms","filt","arrayZero","per","stat","sem","stat2","com","stat3","extractStatements","sp","token1","parseLiterals","sin","doub","end2","token2","strarr","replaceKeywords","prefInd","symbol","getPrefixDeclarations","selectLoc","whereLoc","label","setVars","UpdateManager","updater","ifps","fps","patchControl","isHttpUri","definitive","wacAllow","lr","acceptPatch","authorVia","mentioned","stmt","anonymize","statementBnodes","bnodes2","depth","isBlank","bnodeContext2","con","connectedStatements","cacheIfps","bnodeContext1","bnodeContext","anonymizeNT","callbackFunction","statementContext","statementNT","contextWhere","set_object","fire","st0","stText","control","patchControlFor","pendingUpstream","downstreamAction","upstreamCount","linkHeaders","listener","downstreamChangeListeners","setRefreshHandler","reloadAndSync","reloading","outOfDate","retryTimeout","tryReload","reload","wssURI","getUpdatesVia","theHandler","retries","validWssURI","uriJoin","openWebsocket","socket","WebSocket","onopen","requestDownstreamAction","onclose","onmessage","deletions","insertions","thisUpdater","uniqueDocs","uniqueDoc","updates","update","secondTry","errorBody","is","startTime","editable","statementArrayBnodes","whereClause","elapsedTimeMs","updateDav","updateLocalFile","targetURI","candidateTarget","dot","ext","onErrorWasCalled","reloadTimeTotal","reloadTimeCount","RDFlibDataFactory","lit","UpdatesSocket","via","connected","pending","subscribed","onOpen","onClose","onMessage","onError","elt","_send","onUpdate","_decode","_subscribe","UpdatesVia","onHeaders","etag","subscribe","boundDataFactory","NextId","acl","cal","cert","contact","dct","doap","foaf","geo","gpx","icalTZ","meeting","mo","org","pad","prov","qu","trip","rss","sched","schema","sioc","solid","space","tab","tabont","ui","vcard","wf","cco","alias","expansion","MessageDigest","Permuter","_stringHashCompare","blankNodeInfo","canonicalIssuer","hashAlgorithm","_addBlankNodeQuadInfo","component","hashToBlankNodes","nonNormalized","_yield","_hashAndTrackBlankNode","hashes","nonUnique","idList","hashPathList","hasId","hashNDegreeQuads","oldIds","getOldIds","normalized","_useCanonicalId","modifyFirstDegreeComponent","md","digest","related","position","getRelatedPredicate","hashToRelated","createHashToRelated","chosenIssuer","chosenPath","permuter","hasNext","permutation","issuerCopy","recursionList","nextPermutation","_addRelatedBlankNodeHash","hashFirstDegreeQuads","hashRelatedBlankNode","registerImmediate","channel","messagePrefix","onGlobalMessage","nextHandle","tasksByHandle","currentlyRunningATask","attachTo","handle","runIfPresent","postMessage","importScripts","postMessageIsAsynchronous","oldOnMessage","canUsePostMessage","MessageChannel","port1","port2","script","removeChild","random","attachEvent","clearImmediate","crypto","msCrypto","subtle","_content","TextEncoder","hex","padStart","pos","swap","_requests","loader","_loader","Yallist","MAX","LENGTH","LENGTH_CALCULATOR","ALLOW_STALE","MAX_AGE","DISPOSE","NO_DISPOSE_ON_SET","LRU_LIST","CACHE","UPDATE_AGE_ON_GET","naiveLength","doUse","hit","isStale","del","unshiftNode","maxAge","diff","walker","removeNode","Entry","forEachStep","thisp","lc","stale","dispose","noDisposeOnSet","updateAgeOnGet","reset","mL","allowStale","mA","lC","toArray","expiresAt","asyncGeneratorStep","gen","_next","_throw","escapeSequence","escapeReplacements","illegalIriChars","lineModeRegExps","_iri","_unescapedIri","_simpleQuotedString","_langcode","_blank","_newline","_comment","_whitespace","_endOfFile","invalidRegExp","N3Lexer","_simpleApostropheString","_prefixed","_variable","_number","_boolean","_keyword","_sparqlKeyword","_shortPredicates","lineMode","_n3Mode","n3","_comments","comments","_literalClosingPos","inputFinished","_input","outputComments","whiteSpaceMatch","comment","_line","firstChar","matchLength","inconclusive","_previousMarker","_unescape","reportSyntaxError","_parseLiteral","token","previousToken","_syntaxError","invalid","replaced","sequence","unicode4","unicode8","escapedChar","charCode","opening","openingLength","closingPos","backslashCount","raw","issue","_readStartingBom","tokens","_tokenizeToEnd","_pendingBuffer","setEncoding","Buffer","_setPrototypeOf","runtime","Op","hasOwn","$Symbol","iteratorSymbol","asyncIteratorSymbol","toStringTagSymbol","innerFn","outerFn","tryLocsList","protoGenerator","Generator","Context","_invoke","doneResult","delegate","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","makeInvokeMethod","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","getProto","NativeIteratorPrototype","Gp","defineIteratorMethods","AsyncIterator","PromiseImpl","previousPromise","callInvokeWithMethodAndArg","invoke","__await","unwrapped","resultName","nextLoc","pushTryEntry","locs","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","iterable","iteratorMethod","displayName","isGeneratorFunction","genFun","ctor","mark","awrap","iter","skipTempReset","stop","rootRecord","exception","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","regeneratorRuntime","accidentalStrictMode","globalThis","originalModule","webpackPolyfill","URDNA2015","URGNA2012","URDNA2015Sync","URGNA2012Sync","rdfCanonizeNative","_rdfCanonizeNative","useNative","canonical","main","_canonizeSync","canonizeSync","Timeout","clearFn","_id","_clearFn","scope","setInterval","clearInterval","unref","enroll","msecs","_idleTimeoutId","_idleTimeout","unenroll","_unrefActive","active","_onTimeout","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","marker","runClearTimeout","Item","noop","browser","env","argv","versions","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","cwd","chdir","umask","xhrLoader","secure","wrapLoader","_get","httpStatusCode","alternate","getResponseHeader","linkedContext","ResolvedContext","_throwInvalidLocalContext","perOpCache","allResolved","_resolveRemoteContext","_cacheResolvedContext","tagMap","_fetchContext","_resolveContextUrls","processedCtx","insert","inserted","pushNode","forEachReverse","getReverse","mapReverse","reduceReverse","toArrayReverse","to","ret","sliceReverse","start","deleteCount","nodes","er","_isEmptyObject","_isList","_isValue","_isGraph","_isSubject","_getContextValue","_isKeyword","_addValue","_getValues","_validateTypeValue","REGEX_BCP47","_expandValue","activeProperty","expandedProperty","_expandLanguageMap","languageMap","expandedKey","_expandIndexMap","asGraph","indexKey","propertyIndex","isTypeIndex","insideList","insideIndex","typeScopedContext","mapped","unmappedValue","expandedParent","expandedActiveProperty","propertyScopedCtx","mustRevert","typeKey","_expandObject","nests","unexpandedValue","isJsonType","expandedValue","unmappedProperty","keyword","fromEntries","includedResult","ii","termCtx","nextActiveProperty","nestedValues","validCount","_RDFToObject","useNativeTypes","rdfDirection","endsWith","toFixed","useRdfType","graphMap","referencedOnce","objectIsNode","usages","graphObject","usage","listNodes","nodeKeyCount","listNode","graphSubjects","graphSubject","jsonCanonicalize","_graphToRDF","graphTerm","_objectToRDF","toExponential","_listToRDF","cv","ci","_mergeNodeMapGraphs","_createImplicitFrame","_createsCircularReference","subjectToEmbed","subjectStack","_getFrameFlag","flag","_validateFrame","_filterSubject","wildcard","matchesSome","matchThis","nodeValues","isEmpty","tt","thisFrame","hasDefault","listValue","nodeListValues","lv","_valueMatch","_nodeMatch","_removeEmbed","embeds","uniqueEmbeds","useArray","removeDependents","_addFrameOutput","nodeObject","l1","l2","embedded","bnodeMap","_cleanupPreserve","_filterSubjects","recurse","subframe","oo","preserve","reverseProp","_isSimpleGraph","_removeBase","_prependBase","_checkNestProperty","nestProperty","linked","compactValue","insideReverse","inputCtx","typeContext","compactedType","itemActiveProperty","nestResult","expandedItem","inner","compactedItem","mapObject","containerKey","others","idKey","compactedValue","compactedProperty","expandedIri","isPropertyTermScoped","inverseCtx","containers","typeOrLanguage","commonLanguage","commonType","itemLanguage","itemType","prefs","langDir","containerMap","typeOrLanguageValueMap","_selectTerm","choice","partialMatches","maxPartialLength","td","preserveIndex","keyCount","isValueOnlyKey","hasDefaultLanguage","isValueString","hasNullMapping","base64","ieee754","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","encodingOrOffset","allocUnsafe","byteOffset","fromArrayLike","fromArrayBuffer","isEncoding","fromString","isBuffer","checked","fromObject","assertSize","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","bidirectionalIndexOf","indexSize","arrLength","valLength","readUInt16BE","foundIndex","hexWrite","offset","remaining","strLen","utf8Write","blitBuffer","asciiWrite","byteArray","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","decodeCodePointsArray","SlowBuffer","alloc","INSPECT_MAX_BYTES","subarray","typedArraySupport","poolSize","_augment","species","fill","allocUnsafeSlow","_isBuffer","compare","swap16","swap32","swap64","inspect","thisStart","thisEnd","thisCopy","targetCopy","_arr","toHex","checkOffset","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","pow","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","floor","writeUInt16LE","writeUInt16BE","writeUInt32LE","writeUInt32BE","writeIntLE","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","INVALID_BASE64_RE","leadSurrogate","toByteArray","stringtrim","base64clean","dst","b64","lens","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","encodeChunk","num","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","LN2","blankNodePrefix","_contextStack","_setBase","initDataFactory","isTurtle","isTriG","isNTriples","isNQuads","isN3","isLineMode","_supportsNamedGraphs","_readPredicateOrNamedGraph","_readPredicate","_supportsQuads","_supportsRDFStar","_resolveRelativeIRI","_blankNodePrefix","_lexer","lexer","_explicitQuantifiers","explicitQuantifiers","fragmentPos","_base","_basePath","_baseRoot","_baseScheme","n3Mode","_inversePredicate","blankPrefix","_prefixes","quantified","_quantified","_error","_callback","_sparqlStyle","_readPrefix","_readBaseIRI","_readSubject","_readNamedGraphLabel","quantifier","_resolveIRI","_namedNode","_blankNode","_saveContext","_readBlankNodeHead","_readListItem","_readPunctuation","N3_FORSOME","_quantifier","_readQuantifierList","N3_FORALL","_literalValue","_completeSubjectLiteral","_literal","_readEntity","_getPathReader","ABBREVIATIONS","_readBlankNodeTail","_readObject","_readDataTypeOrLang","_getContextEndReader","_readGraph","_readBlankNodePunctuation","_emit","_restoreContext","_readPredicateAfterBlank","previousList","_readListItemDataTypeOrLang","_completeObjectLiteral","_completeLiteral","_readCallback","inversePredicate","_readFormulaTail","_readInTopContext","_readQuadPunctuation","_readPrefixIRI","prefixNode","_prefixCallback","_readDeclarationPunctuation","_readNamedGraphBlankLabel","QUANTIFIERS_GRAPH","_readQuantifierPunctuation","afterPath","_afterPath","_readPath","_readForwardPath","_readBackwardPath","_readRDFStarTail","_quad","contextStack","_readRDFStarTailOrGraph","_removeDotSegments","pathStart","segmentStart","quadCallback","prefixCallback"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,EAAQG,QAAQ,WACR,mBAAXC,QAAyBA,OAAOC,IAC9CD,OAAO,CAAC,UAAWJ,GACO,iBAAZC,QACdA,QAAc,KAAID,EAAQG,QAAQ,WAElCJ,EAAW,KAAIC,EAAQD,EAAa,Q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AKixF,cAAgBjxF,KAAKixF,cAAc/jB,OAMhD,SAAS8I,KAGT,SAAS8W,EAAgBlxE,EAAQ1kB,GAE/B,MAAM2R,EAAY3R,EAAQ2R,UAC1B+S,EAAOwzE,WAAevmF,EACtB+S,EAAOyzE,WAAen4F,EAAQ2S,UAC9B+R,EAAOo0E,SAAe94F,EAAQkU,QAC9BwQ,EAAO6vD,UAAev0E,EAAQ0U,SAC9BgQ,EAAOu2E,MAAej7F,EAAQ0S,KAC9BgS,EAAOmoB,aAAe7sC,EAAQ+S,eAG9B2R,EAAOg6C,UAAa/sD,EAAU,IAAWK,IAAI8E,OAC7C4N,EAAOi6C,SAAahtD,EAAU,IAAWK,IAAI+E,MAC7C2N,EAAOk6C,QAAajtD,EAAU,IAAWK,IAAI6E,KAC7C6N,EAAOi0E,UAAahnF,EAAU,IAAWlQ,EAAE0V,QAC3CuN,EAAO8zE,WAAa7mF,EAAU,IAAWlQ,EAAEyV,SAC3CwN,EAAOu0E,cAAgB,CACrB,EAAKtnF,EAAU,IAAWK,IAAI4E,MAC9B,IAAKjF,EAAU,IAAWqF,IAAIC,QAC9B,IAAKtF,EAAU,IAAWxN,IAAIiT,UAEhCsN,EAAO+1E,kBAAoB9oF,EAAU,sBAEvCikF,EAAgBhzD,EAASrgC,UAAW","file":"rdflib.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"window\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"window\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"$rdf\"] = factory(require(\"window\"));\n\telse\n\t\troot[\"$rdf\"] = factory(root[\"window\"]);\n})(window, function(__WEBPACK_EXTERNAL_MODULE__56__) {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 75);\n","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","import Node from './node-internal'\nimport RDFlibVariable from './variable'\nimport RDFlibBlankNode from './blank-node'\nimport Collection from './collection'\nimport RDFlibLiteral from './literal'\nimport RDFlibNamedNode from './named-node'\nimport RDFlibDefaultGraph from './default-graph'\nimport { DataFactory } from './factories/factory-types'\nimport IndexedFormula from './store'\nimport Fetcher from './fetcher'\nimport Statement from './statement'\nimport Empty from './empty'\nimport { NamedNode, Term, Quad_Subject, Quad_Predicate, Quad_Object, Quad_Graph } from './tf-types'\n\nexport const NamedNodeTermType = \"NamedNode\" as const\nexport const BlankNodeTermType = \"BlankNode\" as const\nexport const LiteralTermType = \"Literal\" as const\nexport const VariableTermType = \"Variable\" as const\nexport const DefaultGraphTermType = \"DefaultGraph\" as const\n// Non-RDF/JS types:\nexport const CollectionTermType = \"Collection\" as const\nexport const EmptyTermType = \"Empty\" as const\nexport const GraphTermType = \"Graph\" as const\n\nexport type TermType = typeof NamedNodeTermType\n | typeof BlankNodeTermType\n | typeof LiteralTermType\n | typeof VariableTermType\n | typeof DefaultGraphTermType\n | typeof CollectionTermType\n | typeof EmptyTermType\n | typeof GraphTermType\n\nexport const HTMLContentType = \"text/html\" as const\nexport const JSONLDContentType = \"application/ld+json\" as const\nexport const N3ContentType = \"text/n3\" as const\nexport const N3LegacyContentType = \"application/n3\" as const\nexport const NQuadsAltContentType = \"application/nquads\" as const\nexport const NQuadsContentType = \"application/n-quads\" as const\nexport const NTriplesContentType = \"application/n-triples\" as const\nexport const RDFXMLContentType = \"application/rdf+xml\" as const\nexport const SPARQLUpdateContentType = \"application/sparql-update\" as const\nexport const SPARQLUpdateSingleMatchContentType = \"application/sparql-update-single-match\" as const\nexport const TurtleContentType = \"text/turtle\" as const\nexport const TurtleLegacyContentType = \"application/x-turtle\" as const\nexport const XHTMLContentType = \"application/xhtml+xml\" as const\n\n/**\n * A valid mime type header\n */\nexport type ContentType = typeof RDFXMLContentType\n | typeof HTMLContentType\n | typeof JSONLDContentType\n | typeof N3ContentType\n | typeof N3LegacyContentType\n | typeof NQuadsAltContentType\n | typeof NQuadsContentType\n | typeof SPARQLUpdateContentType\n | typeof SPARQLUpdateSingleMatchContentType\n | typeof TurtleContentType\n | typeof TurtleLegacyContentType\n | typeof XHTMLContentType\n\n/** A type for values that serves as inputs */\nexport type ValueType = Term | Node | Date | string | number | boolean | undefined | null | Collection\n\n/**\n * In this project, there exist two types for the same kind of RDF concept.\n * We have RDF/JS spec types (standardized, generic), and RDFlib types (internal, specific).\n * When deciding which type to use in a function, it is preferable to accept generic inputs,\n * whenever possible, and provide strict outputs.\n * In some ways, the TF types in here are a bit more strict.\n * Variables are missing, and the statement requires specific types of terms (e.g. NamedNode instead of Term).\n */\n\n/** An RDF/JS Subject */\nexport type SubjectType = RDFlibBlankNode | RDFlibNamedNode | RDFlibVariable\n/** An RDF/JS Predicate */\nexport type PredicateType = RDFlibNamedNode | RDFlibVariable\n/** An RDF/JS Object */\nexport type ObjectType = RDFlibNamedNode | RDFlibLiteral | Collection | RDFlibBlankNode | RDFlibVariable | Empty\n/** An RDF/JS Graph */\nexport type GraphType = RDFlibDefaultGraph | RDFlibNamedNode | RDFlibVariable // | Formula\n\nexport interface Bindings {\n [id: string]: Term;\n}\n\n/** All the types that a .fromValue() method might return */\nexport type FromValueReturns<C extends Node = any> = Term | undefined | null | Collection<C>\n\nexport interface IRDFlibDataFactory extends DataFactory<\n RDFlibNamedNode | RDFlibBlankNode | RDFlibLiteral | Collection | Statement\n> {\n fetcher: (store: IndexedFormula, options: any) => Fetcher\n lit: (val: string, lang?: string, dt?: NamedNode) => RDFlibLiteral\n graph: (features?, opts?) => IndexedFormula\n st: (\n subject: Quad_Subject,\n predicate: Quad_Predicate,\n object: Quad_Object,\n graph?: Quad_Graph\n ) => Statement\n}\n","/**\n * A Dummy log\n * @module log\n */\nconst log = {\n debug (x) {},\n warn (x) {},\n info (x) {},\n error (x) {},\n success (x) {},\n msg (x) {},\n}\nexport default log\n","function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nmodule.exports = _assertThisInitialized;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nmodule.exports = _createClass;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","/*\n * Implements URI-specific functions\n *\n * See RFC 2386\n *\n * See also:\n * http://www.w3.org/2005/10/ajaw/uri.js\n * http://www.w3.org/2000/10/swap/uripath.py\n *\n */\nvar alert = alert || console.log\n\nimport RDFlibNamedNode from './named-node'\n\n/**\n * Gets the document part of an URI\n * @param uri The URI\n */\nexport function docpart(uri: string): string {\n var i: number\n i = uri.indexOf('#')\n if (i < 0) {\n return uri\n } else {\n return uri.slice(0, i)\n }\n}\n\n/**\n * Gets the document part of an URI as a named node\n * @param x - The URI\n */\nexport function document(x: string): RDFlibNamedNode {\n return new RDFlibNamedNode(docpart(x))\n}\n\n/**\n * Gets the hostname in an URI\n * @param u The URI\n */\nexport function hostpart(u: string): string {\n var m = /[^\\/]*\\/\\/([^\\/]*)\\//.exec(u)\n if (m) {\n return m[1]\n } else {\n return ''\n }\n}\n\n/**\n * Joins an URI with a base\n * @param given - The relative part\n * @param base - The base URI\n */\nexport function join(given: string, base: string): string {\n var baseColon, baseScheme, baseSingle\n var colon, lastSlash, path\n var baseHash = base.indexOf('#')\n if (baseHash > 0) {\n base = base.slice(0, baseHash)\n }\n if (given.length === 0) {\n return base\n }\n if (given.indexOf('#') === 0) {\n return base + given\n }\n colon = given.indexOf(':')\n if (colon >= 0) {\n return given\n }\n baseColon = base.indexOf(':')\n if (base.length === 0) {\n return given\n }\n if (baseColon < 0) {\n alert('Invalid base: ' + base + ' in join with given: ' + given)\n return given\n }\n baseScheme = base.slice(0, +baseColon + 1 || 9e9)\n if (given.indexOf('//') === 0) {\n return baseScheme + given\n }\n if (base.indexOf('//', baseColon) === baseColon + 1) {\n baseSingle = base.indexOf('/', baseColon + 3)\n if (baseSingle < 0) {\n if (base.length - baseColon - 3 > 0) {\n return base + '/' + given\n } else {\n return baseScheme + given\n }\n }\n } else {\n baseSingle = base.indexOf('/', baseColon + 1)\n if (baseSingle < 0) {\n if (base.length - baseColon - 1 > 0) {\n return base + '/' + given\n } else {\n return baseScheme + given\n }\n }\n }\n if (given.indexOf('/') === 0) {\n return base.slice(0, baseSingle) + given\n }\n path = base.slice(baseSingle)\n lastSlash = path.lastIndexOf('/')\n if (lastSlash < 0) {\n return baseScheme + given\n }\n if (lastSlash >= 0 && lastSlash < path.length - 1) {\n path = path.slice(0, +lastSlash + 1 || 9e9)\n }\n path += given\n while (path.match(/[^\\/]*\\/\\.\\.\\//)) {\n path = path.replace(/[^\\/]*\\/\\.\\.\\//, '')\n }\n path = path.replace(/\\.\\//g, '')\n path = path.replace(/\\/\\.$/, '/')\n return base.slice(0, baseSingle) + path\n}\n\n/**\n * Gets the protocol part of an URI\n * @param uri The URI\n */\nexport function protocol(uri: string): string | null {\n const i = uri.indexOf(':')\n if (i < 0) {\n return null\n } else {\n return uri.slice(0, i)\n }\n}\n\n/**\n * Gets a relative uri\n * @param base The base URI\n * @param uri The absolute URI\n */\nexport function refTo(base: string, uri: string): string {\n var c: string,\n i: number,\n k: number,\n l: number,\n len: number,\n len1: number,\n n: number,\n o: number,\n p: number,\n q: number,\n ref: string,\n ref1: number,\n s: string\n var commonHost = new RegExp('^[-_a-zA-Z0-9.]+:(//[^/]*)?/[^/]*$')\n if (!base) {\n return uri\n }\n if (base === uri) {\n return ''\n }\n for (i = o = 0, len = uri.length; o < len; i = ++o) {\n const c = uri[i]\n if (c !== base[i]) {\n break\n }\n }\n if (base.slice(0, i).match(commonHost)) {\n k = uri.indexOf('//')\n if (k < 0) {\n k = -2\n }\n l = uri.indexOf('/', k + 2)\n if (uri[l + 1] !== '/' && base[l + 1] !== '/' && uri.slice(0, l) === base.slice(0, l)) {\n return uri.slice(l)\n }\n }\n if (uri[i] === '#' && base.length === i) {\n return uri.slice(i)\n }\n while (i > 0 && uri[i - 1] !== '/') {\n i--\n }\n if (i < 3) {\n return uri\n }\n if (base.indexOf('//', i - 2) > 0 || uri.indexOf('//', i - 2) > 0) {\n return uri\n }\n if (base.indexOf(':', i) > 0) {\n return uri\n }\n n = 0\n ref = base.slice(i)\n for (p = 0, len1 = ref.length; p < len1; p++) {\n c = ref[p]\n if (c === '/') {\n n++\n }\n }\n if (n === 0 && i < uri.length && uri[i] === '#') {\n return './' + uri.slice(i)\n }\n if (n === 0 && i === uri.length) {\n return './'\n }\n s = ''\n if (n > 0) {\n for (q = 1, ref1 = n; ref1 >= 1 ? q <= ref1 : q >= ref1; ref1 >= 1 ? ++q : --q) {\n s += '../'\n }\n }\n return s + uri.slice(i)\n}\n","import {\n ObjectType, CollectionTermType, NamedNodeTermType, VariableTermType, BlankNodeTermType, LiteralTermType, GraphTermType, DefaultGraphTermType,\n} from '../types'\nimport Collection from '../collection'\nimport IndexedFormula from '../store'\nimport Statement from '../statement'\nimport {\n BlankNode,\n Quad_Graph,\n Literal,\n NamedNode,\n Quad_Object,\n Quad_Predicate,\n Quad,\n Quad_Subject,\n Term,\n Variable,\n} from '../tf-types'\n\n/** TypeGuard for RDFLib Statements */\nexport function isStatement(obj): obj is Statement {\n return typeof obj === 'object' && obj !== null && 'subject' in obj\n}\n\n/** TypeGuard for RDFlib Stores */\nexport function isStore(obj): obj is IndexedFormula {\n return typeof obj === 'object' && obj !== null && 'statements' in obj\n}\n\n/** TypeGuard for RDFLib Collections */\nexport function isCollection(obj: any): obj is Collection<any> {\n return isTerm(obj)\n && (obj as Term).termType === CollectionTermType\n}\n\n/** TypeGuard for valid RDFlib Object types, also allows Collections */\nexport function isRDFlibObject(obj: any): obj is ObjectType {\n return obj && Object.prototype.hasOwnProperty.call(obj, 'termType') && (\n obj.termType === NamedNodeTermType ||\n obj.termType === VariableTermType ||\n obj.termType === BlankNodeTermType ||\n obj.termType === CollectionTermType ||\n obj.termType === LiteralTermType ||\n obj.termType === GraphTermType\n )\n}\n\n/** TypeGuard for RDFLib Variables */\nexport function isVariable(obj: any): obj is Variable {\n return isTerm(obj)\n && (obj as Term).termType === VariableTermType\n}\n\n/** TypeGuard for RDF/JS spec Terms */\nexport function isTerm(obj: any): obj is Term {\n return typeof obj === 'object'\n && obj !== null\n && 'termType' in obj\n}\n\n/** TypeGuard for RDF/JS spec Literals */\nexport function isLiteral(value: any): value is Literal {\n return (value as Term).termType === LiteralTermType\n}\n\n/** TypeGuard for RDF/JS spec Quads */\nexport function isQuad(obj: any): obj is Quad<any, any, any, any> {\n return typeof obj === \"object\" && obj !== null && (\n 'subject' in obj\n && 'predicate' in obj\n && 'object' in obj\n )\n}\n\n/** TypeGuard for RDF/JS spec NamedNodes */\nexport function isNamedNode(obj: any): obj is NamedNode {\n return isTerm(obj) && obj.termType === 'NamedNode'\n}\n\n/** TypeGuard for RDF/JS spec BlankNodes */\nexport function isBlankNode(obj: any): obj is BlankNode {\n return isTerm(obj) && 'termType' in obj && obj.termType === 'BlankNode'\n}\n\n/** TypeGuard for valid RDF/JS spec Subject types */\nexport function isSubject(obj: any): obj is Quad_Subject {\n return isTerm(obj) && (\n obj.termType === NamedNodeTermType ||\n obj.termType === VariableTermType ||\n obj.termType === BlankNodeTermType\n )\n}\n\n/** TypeGuard for valid RDF/JS spec Predicate types */\nexport function isPredicate(obj: any): obj is Quad_Predicate {\n return isTerm(obj) && (\n obj.termType === NamedNodeTermType ||\n obj.termType === VariableTermType\n )\n}\n\n/** TypeGuard for valid RDF/JS spec Object types */\nexport function isRDFObject(obj: any): obj is Quad_Object {\n return isTerm(obj) && (\n obj.termType === NamedNodeTermType ||\n obj.termType === VariableTermType ||\n obj.termType === BlankNodeTermType ||\n obj.termType === LiteralTermType\n )\n}\n\n/** TypeGuard for valid RDF/JS Graph types */\nexport function isGraph(obj: any): obj is Quad_Graph {\n return isTerm(obj) && (\n obj.termType === NamedNodeTermType ||\n obj.termType === VariableTermType ||\n obj.termType === BlankNodeTermType ||\n obj.termType === DefaultGraphTermType\n )\n}\n","import ClassOrder from './class-order'\nimport Node from './node-internal'\nimport { NamedNodeTermType } from './types'\nimport { termValue } from './utils/termValue'\nimport { NamedNode as TFNamedNode } from './tf-types'\nimport { isTerm } from './utils/terms'\n\n/**\n * A named (IRI) RDF node\n */\nexport default class NamedNode extends Node implements TFNamedNode {\n termType: typeof NamedNodeTermType = NamedNodeTermType\n classOrder = ClassOrder.NamedNode\n\n /**\n * Create a named (IRI) RDF Node\n * @constructor\n * @param iri - The IRI for this node\n */\n constructor (iri: string) {\n super(termValue(iri))\n\n if (!this.value) {\n throw new Error('Missing IRI for NamedNode')\n }\n\n if (!this.value.includes(':')) {\n throw new Error('NamedNode IRI \"' + iri + '\" must be absolute.')\n }\n\n if (this.value.includes(' ')) {\n var message = 'Error: NamedNode IRI \"' + iri + '\" must not contain unencoded spaces.'\n throw new Error(message)\n }\n }\n\n /**\n * Returns an $rdf node for the containing directory, ending in slash.\n */\n dir (): NamedNode | null {\n var str = this.value.split('#')[0]\n var p = str.slice(0, -1).lastIndexOf('/')\n var q = str.indexOf('//')\n if ((q >= 0 && p < q + 2) || p < 0) return null\n return new NamedNode(str.slice(0, p + 1))\n }\n\n /**\n * Returns an NN for the whole web site, ending in slash.\n * Contrast with the \"origin\" which does NOT have a trailing slash\n */\n site (): NamedNode {\n var str = this.value.split('#')[0]\n var p = str.indexOf('//')\n if (p < 0) throw new Error('This URI does not have a web site part (origin)')\n var q = str.indexOf('/', p+2)\n if (q < 0) {\n return new NamedNode(str.slice(0) + '/') // Add slash to a bare origin\n } else {\n return new NamedNode(str.slice(0, q + 1))\n }\n }\n\n /**\n * Creates the fetchable named node for the document.\n * Removes everything from the # anchor tag.\n */\n doc (): NamedNode {\n if (this.value.indexOf('#') < 0) {\n return this\n } else {\n return new NamedNode(this.value.split('#')[0])\n }\n }\n\n /**\n * Returns the URI including <brackets>\n */\n toString (): string {\n return '<' + this.value + '>'\n }\n\n /** The local identifier with the document */\n id (): string {\n return this.value.split('#')[1]\n }\n\n /** Alias for value, favored by Tim */\n get uri (): string {\n return this.value\n }\n\n set uri (uri: string) {\n this.value = uri\n }\n\n /**\n * Creates a named node from the specified input value\n * @param value - An input value\n */\n static fromValue (value) {\n if (typeof value === 'undefined' || value === null) {\n return value\n }\n if (isTerm(value)) {\n return value\n }\n return new NamedNode(value)\n }\n}\n","function _getPrototypeOf(o) {\n module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n module.exports[\"default\"] = module.exports, module.exports.__esModule = true;\n return _getPrototypeOf(o);\n}\n\nmodule.exports = _getPrototypeOf;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","/**\n * Utility functions for $rdf\n * @module util\n */\nimport { docpart } from './uri'\nimport log from './log'\nimport * as uri from './uri'\nimport NamedNode from './named-node'\n\nconst string = { template: stringTemplate }\n\nexport { log, uri, string }\n\nexport function mediaTypeClass(mediaType){\n mediaType = mediaType.split(';')[0].trim() // remove media type parameters\n return new NamedNode('http://www.w3.org/ns/iana/media-types/' + mediaType + '#Resource')\n}\n\nexport function linkRelationProperty(relation){\n return new NamedNode('http://www.w3.org/ns/iana/link-relations/relation#' + relation.trim())\n}\n\n/**\n * Adds callback functionality to an object.\n * Callback functions are indexed by a 'hook' string.\n * They return true if they want to be called again.\n * @method callbackify\n * @param obj {Object}\n * @param callbacks {Array<string>}\n */\nexport function callbackify (obj, callbacks) {\n obj.callbacks = {}\n for (var x = callbacks.length - 1; x >= 0; x--) {\n obj.callbacks[callbacks[x]] = []\n }\n\n obj.addHook = function (hook) {\n if (!obj.callbacks[hook]) {\n obj.callbacks[hook] = []\n }\n }\n\n obj.addCallback = function (hook, func) {\n obj.callbacks[hook].push(func)\n }\n\n obj.removeCallback = function (hook, funcName) {\n for (var i = 0;i < obj.callbacks[hook].length;i++) {\n if (obj.callbacks[hook][i].name === funcName) {\n obj.callbacks[hook].splice(i, 1)\n return true\n }\n }\n return false\n }\n\n obj.insertCallback = function (hook, func) {\n obj.callbacks[hook].unshift(func)\n }\n\n obj.fireCallbacks = function fireCallbacks (hook, args) {\n var newCallbacks = []\n var replaceCallbacks = []\n var len = obj.callbacks[hook].length\n var x\n let callback\n\n // log.info('!@$ Firing '+hook+' call back with length'+len)\n for (x = len - 1; x >= 0; x--) {\n // log.info('@@ Firing '+hook+' callback '+ obj.callbacks[hook][x])\n callback = obj.callbacks[hook][x]\n if (callback && callback.apply(obj, args)) {\n newCallbacks.push(callback)\n }\n }\n\n for (x = newCallbacks.length - 1; x >= 0; x--) {\n replaceCallbacks.push(newCallbacks[x])\n }\n\n for (x = len; x < obj.callbacks[hook].length; x++) {\n replaceCallbacks.push(obj.callbacks[hook][x])\n }\n\n obj.callbacks[hook] = replaceCallbacks\n }\n}\n\n/**\n * Returns a DOM parser based on current runtime environment.\n */\nexport function DOMParserFactory () {\n if (window.DOMParser) {\n return new DOMParser()\n } else if (window.ActiveXObject) {\n return new ActiveXObject('Microsoft.XMLDOM')\n } else {\n return false\n }\n}\n\n// From https://github.com/linkeddata/dokieli\nexport function domToString (node, options) {\n options = options || {}\n var selfClosing = []\n if (options && options.selfClosing) {\n options.selfClosing.split(' ').forEach(function (n) {\n selfClosing[n] = true\n })\n }\n var skipAttributes = []\n if (options && options.skipAttributes) {\n options.skipAttributes.split(' ').forEach(function (n) {\n skipAttributes[n] = true\n })\n }\n return dumpNode(node, options, selfClosing, skipAttributes)\n}\n\nexport function dumpNode (node, options, selfClosing, skipAttributes) {\n var i\n var out = ''\n var noEsc = [ false ]\n if (typeof node.nodeType === 'undefined') return out\n if (node.nodeType === 1) {\n if (node.hasAttribute('class') && (options && options.classWithChildText) && node.matches(options.classWithChildText.class)) {\n out += node.querySelector(options.classWithChildText.element).textContent\n } else if (!((options && options.skipNodeWithClass) && node.matches('.' + options.skipNodeWithClass))) {\n var ename = node.nodeName.toLowerCase()\n out += '<' + ename\n\n var attrList = []\n for (i = node.attributes.length - 1; i >= 0; i--) {\n var atn = node.attributes[i]\n if (skipAttributes && skipAttributes.length > 0 && skipAttributes[atn.name]) continue\n if (/^\\d+$/.test(atn.name)) continue\n if (atn.name === 'class' && (options && options.replaceClassItemWith) && (atn.value.split(' ').indexOf(options.replaceClassItemWith.source) > -1)) {\n var re = new RegExp(options.replaceClassItemWith.source, 'g')\n atn.value = atn.value.replace(re, options.replaceClassItemWith.target).trim()\n }\n if (!(atn.name === 'class' && (options && options.skipClassWithValue) && options.skipClassWithValue === atn.value)) {\n attrList.push(atn.name + '=\\'' + atn.value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, '"') + '\\'')\n }\n }\n if (attrList.length > 0) {\n if (options && options.sortAttributes) {\n attrList.sort(function (a, b) {\n return a.toLowerCase().localeCompare(b.toLowerCase())\n })\n }\n out += ' ' + attrList.join(' ')\n }\n if (selfClosing && selfClosing.ename) {\n out += ' />'\n } else {\n out += '>'\n out += (ename === 'html') ? '\\n ' : ''\n noEsc.push(ename === 'style' || ename === 'script')\n for (i = 0; i < node.childNodes.length; i++) out += dumpNode(node.childNodes[i])\n noEsc.pop()\n out += (ename === 'body') ? '</' + ename + '>' + '\\n' : '</' + ename + '>'\n }\n }\n } else if (node.nodeType === 8) {\n // FIXME: If comments are not tabbed in source, a new line is not prepended\n out += '<!--' + node.nodeValue + '-->'\n } else if (node.nodeType === 3 || node.nodeType === 4) {\n // XXX: Remove new lines which were added after DOM ready\n var nl = node.nodeValue.replace(/\\n+$/, '')\n out += noEsc[noEsc.length - 1] ? nl : nl.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')\n } else {\n console.log('Warning; Cannot handle serialising nodes of type: ' + node.nodeType)\n console.log(node)\n }\n return out\n}\n\nexport function dtstamp () {\n var now = new Date()\n var year = now.getYear() + 1900\n var month = now.getMonth() + 1\n var day = now.getDate()\n var hour = now.getUTCHours()\n var minute = now.getUTCMinutes()\n var second = now.getSeconds()\n if (month < 10) month = '0' + month\n if (day < 10) day = '0' + day\n if (hour < 10) hour = '0' + hour\n if (minute < 10) minute = '0' + minute\n if (second < 10) second = '0' + second\n return year + '-' + month + '-' + day + 'T' +\n hour + ':' + minute + ':' + second + 'Z'\n}\n\n/**\n * Compares statements (heavy comparison for repeatable canonical ordering)\n */\nexport function heavyCompare (x, y, g, uriMap) {\n var nonBlank = function (x) {\n return (x.termType === 'BlankNode') ? null : x\n }\n var signature = function (x) {\n var lis = g.statementsMatching(x).map(function (st) {\n return ('' + nonBlank(st.subject) + ' ' + nonBlank(st.predicate) +\n ' ' + nonBlank(st.object))\n }).concat(g.statementsMatching(undefined, undefined, x).map(function (st) {\n return ('' + nonBlank(st.subject) + ' ' + nonBlank(st.predicate) +\n ' ' + nonBlank(st.object))\n }))\n lis.sort()\n return lis.join('\\n')\n }\n const comparison = Object.prototype.hasOwnProperty.call(g, \"compareTerms\")\n ? g.compareTerms(x, y)\n : x.compareTerm(y)\n\n if ((x.termType === 'BlankNode') && (y.termType === 'BlankNode')) {\n if (comparison === 0) return 0 // Same\n if (signature(x) > signature(y)) return +1\n if (signature(x) < signature(y)) return -1\n return comparison // Too bad -- this order not canonical.\n // throw \"different bnodes indistinquishable for sorting\"\n } else {\n if (uriMap && x.uri && y.uri){\n return (uriMap[x.uri] || x.uri).localeCompare(uriMap[y.uri] || y.uri)\n }\n return comparison\n }\n}\n\nexport function heavyCompareSPO (x, y, g, uriMap) {\n return heavyCompare(x.subject, y.subject, g, uriMap) ||\n heavyCompare(x.predicate, y.predicate, g, uriMap) ||\n heavyCompare(x.object, y.object, g, uriMap)\n}\n\n/**\n * Defines a simple debugging function\n * @method output\n * @param o {String}\n */\nexport function output (o) {\n var k = document.createElement('div')\n k.textContent = o\n document.body.appendChild(k)\n}\n\nimport { DOMParser } from 'xmldom'\n\n/**\n * Returns a DOM from parsex XML.\n */\nexport function parseXML (str, options) {\n var dparser\n options = options || {}\n if (typeof module !== 'undefined' && module && module.exports) { // Node.js\n var dom = new DOMParser().parseFromString(str, options.contentType || 'application/xhtml+xml')\n return dom\n } else {\n if (typeof window !== 'undefined' && window.DOMParser) {\n dparser = new window.DOMParser() // seems to actually work\n } else {\n dparser = new DOMParser() // Doc says this works\n }\n }\n return dparser.parseFromString(str, 'application/xml')\n}\n\n/**\n * Removes all statements equal to x from a\n */\nexport function RDFArrayRemove (a, x) {\n for (var i = 0; i < a.length; i++) {\n // TODO: This used to be the following, which didnt always work..why\n // if(a[i] === x)\n if (a[i].subject.equals(x.subject) &&\n a[i].predicate.equals(x.predicate) &&\n a[i].object.equals(x.object) &&\n a[i].why.equals(x.why)) {\n a.splice(i, 1)\n return\n }\n }\n throw new Error('RDFArrayRemove: Array did not contain ' + x + ' ' + x.why)\n}\n\nexport function string_startswith (str, pref) { // missing library routines\n return (str.slice(0, pref.length) === pref)\n}\n\n/**\n * C++, python style %s -> subs\n */\nfunction stringTemplate (base, subs) {\n var baseA = base.split('%s')\n var result = ''\n for (var i = 0;i < subs.length;i++) {\n subs[i] += ''\n result += baseA[i] + subs[i]\n }\n return result + baseA.slice(subs.length).join()\n}\n\n\n// Stack dump on errors - to pass errors back\n\nexport function stackString (e) {\n var str = '' + e + '\\n'\n if (!e.stack) {\n return str + 'No stack available.\\n'\n }\n var lines = e.stack.toString().split('\\n')\n var toprint = []\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i]\n if (line.indexOf('ecmaunit.js') > -1) {\n // remove useless bit of traceback\n break\n }\n if (line.charAt(0) == '(') {\n line = 'function' + line\n }\n var chunks = line.split('@')\n toprint.push(chunks)\n }\n // toprint.reverse(); No - I prefer the latest at the top by the error message -tbl\n\n for (var i = 0; i < toprint.length; i++) {\n str += ' ' + toprint[i][1] + '\\n ' + toprint[i][0]\n }\n return str\n}\n","import { ValueType, Bindings, FromValueReturns, TermType } from './types'\nimport { Term } from './tf-types'\n\n/**\n * The superclass of all RDF Statement objects, that is\n * NamedNode, Literal, BlankNode, etc.\n * Should not be instantiated directly.\n * Also called Term.\n * @link https://rdf.js.org/data-model-spec/#term-interface\n * @class Node\n */\nexport default abstract class Node {\n // Specified in './node.ts' to prevent circular dependency\n static fromValue: <T extends FromValueReturns>(value: ValueType) => T\n // Specified in './node.ts' to prevent circular dependency\n static toJS: (term: any) => Date | Number | string | boolean | object | Array<Date | Number | string | boolean | object>;\n\n /** The type of node */\n termType!: TermType;\n\n /** The class order for this node */\n classOrder!: number;\n\n /** The node's value */\n value: string;\n\n protected constructor(value: string) {\n this.value = value\n }\n\n /**\n * Creates the substituted node for this one, according to the specified bindings\n * @param bindings - Bindings of identifiers to nodes\n */\n substitute <T extends Node = Node>(bindings: Bindings): T {\n console.log('@@@ node substitute' + this)\n return this as unknown as T\n }\n\n /**\n * Compares this node with another\n * @see {equals} to check if two nodes are equal\n * @param other - The other node\n */\n compareTerm (other: Node): number {\n if (this.classOrder < other.classOrder) {\n return -1\n }\n if (this.classOrder > other.classOrder) {\n return +1\n }\n if (this.value < other.value) {\n return -1\n }\n if (this.value > other.value) {\n return +1\n }\n return 0\n }\n\n /**\n * Compares whether the two nodes are equal\n * @param other The other node\n */\n equals (other: Term): boolean {\n if (!other) {\n return false\n }\n return (this.termType === other.termType) &&\n (this.value === other.value)\n }\n\n /**\n * Creates a hash for this node\n * @deprecated use {rdfFactory.id} instead if possible\n */\n hashString (): string {\n return this.toCanonical()\n }\n\n /**\n * Compares whether this node is the same as the other one\n * @param other - Another node\n */\n sameTerm(other: Node): boolean {\n return this.equals(other)\n\n }\n\n /**\n * Creates a canonical string representation of this node\n */\n toCanonical (): string {\n return this.toNT()\n }\n\n /**\n * Creates a n-triples string representation of this node\n */\n toNT (): string {\n return this.toString()\n }\n\n /**\n * Creates a n-quads string representation of this node\n */\n toNQ (): string {\n return this.toNT();\n }\n\n /**\n * Creates a string representation of this node\n */\n toString (): string {\n throw new Error('Node.toString() is abstract - see the subclasses instead')\n }\n}\n","var setPrototypeOf = require(\"./setPrototypeOf.js\");\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}\n\nmodule.exports = _inherits;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","import RDFlibNamedNode from './named-node'\nimport { RdfJsDataFactory, NamedNode } from './tf-types'\n\n/**\n * Gets a namespace for the specified namespace's URI\n * @param nsuri - The URI for the namespace\n * @param [factory] - The factory for creating named nodes with\n */\nexport default function Namespace (nsuri: string, factory?: RdfJsDataFactory): (ln: string) => NamedNode {\n const dataFactory = factory || { namedNode: (value) => new RDFlibNamedNode(value) as NamedNode }\n\n return function (ln: string): NamedNode {\n return dataFactory.namedNode(nsuri + (ln || ''))\n }\n}\n","var _typeof = require(\"@babel/runtime/helpers/typeof\")[\"default\"];\n\nvar assertThisInitialized = require(\"./assertThisInitialized.js\");\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n\n return assertThisInitialized(self);\n}\n\nmodule.exports = _possibleConstructorReturn;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","import Fetcher from './fetcher'\nimport log from './log'\nimport { docpart } from './uri'\nimport { string_startswith } from './utils-js'\nimport { RdfJsDataFactory, Quad, Quad_Subject, Term } from './tf-types'\n\n/** RDF/JS spec Typeguards */\n\n/**\n * Loads ontologies of the data we load (this is the callback from the kb to\n * the fetcher).\n */\nexport function AJAR_handleNewTerm (kb: { fetcher: Fetcher }, p, requestedBy) {\n var sf: Fetcher | null = null\n if (typeof kb.fetcher !== 'undefined') {\n sf = kb.fetcher\n } else {\n return\n }\n if (p.termType !== 'NamedNode') return\n var docuri = docpart(p.uri)\n var fixuri\n if (p.uri.indexOf('#') < 0) { // No hash\n // @@ major hack for dbpedia Categories, which spread indefinitely\n if (string_startswith(p.uri, 'http://dbpedia.org/resource/Category:')) return\n\n /*\n if (string_startswith(p.uri, 'http://xmlns.com/foaf/0.1/')) {\n fixuri = \"http://dig.csail.mit.edu/2005/ajar/ajaw/test/foaf\"\n // should give HTTP 303 to ontology -- now is :-)\n } else\n */\n if (string_startswith(p.uri,\n 'http://purl.org/dc/elements/1.1/') ||\n string_startswith(p.uri, 'http://purl.org/dc/terms/')) {\n fixuri = 'http://dublincore.org/2005/06/13/dcq'\n // dc fetched multiple times\n } else if (string_startswith(p.uri, 'http://xmlns.com/wot/0.1/')) {\n fixuri = 'http://xmlns.com/wot/0.1/index.rdf'\n } else if (string_startswith(p.uri, 'http://web.resource.org/cc/')) {\n // log.warn(\"creative commons links to html instead of rdf. doesn't seem to content-negotiate.\")\n fixuri = 'http://web.resource.org/cc/schema.rdf'\n }\n }\n if (fixuri) {\n docuri = fixuri\n }\n if (sf && (sf as Fetcher).getState(docuri) !== 'unrequested') return\n\n if (fixuri) { // only give warning once: else happens too often\n log.warn('Assuming server still broken, faking redirect of <' + p.uri +\n '> to <' + docuri + '>')\n }\n\n return (sf as any).fetch(docuri, { referringTerm: requestedBy })\n}\n\nexport const appliedFactoryMethods = [\n 'blankNode',\n 'defaultGraph',\n 'literal',\n 'namedNode',\n 'quad',\n 'variable',\n 'supports',\n]\n\nconst rdf = {\n first: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first',\n rest: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest',\n nil: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'\n}\n\n/**\n * Expands an array of Terms to a set of statements representing the rdf:list.\n * @param rdfFactory - The factory to use\n * @param subject - The iri of the first list item.\n * @param data - The terms to expand into the list.\n * @return The {data} as a set of statements.\n */\nexport function arrayToStatements(\n rdfFactory: RdfJsDataFactory,\n subject: Quad_Subject,\n data: Term[]\n): Quad[] {\n const statements: Quad[] = []\n\n data.reduce<Quad_Subject>((id, _listObj, i, listData) => {\n statements.push(rdfFactory.quad(id, rdfFactory.namedNode(rdf.first), listData[i]))\n\n let nextNode\n if (i < listData.length - 1) {\n nextNode = rdfFactory.blankNode()\n statements.push(rdfFactory.quad(id, rdfFactory.namedNode(rdf.rest), nextNode))\n } else {\n statements.push(rdfFactory.quad(id, rdfFactory.namedNode(rdf.rest), rdfFactory.namedNode(rdf.nil)))\n }\n\n return nextNode\n }, subject)\n\n return statements\n}\n\nexport function ArrayIndexOf (arr, item, i: number = 0) {\n var length = arr.length\n if (i < 0) i = length + i\n for (; i < length; i++) {\n if (arr[i] === item) {\n return i\n }\n }\n return -1\n}\n","/**\n* Class orders\n*/\nconst ClassOrder: {\n [id: string]: number;\n} = {\n 'Literal': 1,\n 'Collection': 3,\n 'Graph': 4,\n 'NamedNode': 5,\n 'BlankNode': 6,\n 'Variable': 7\n}\n\nexport default ClassOrder\n","import BlankNode from '../blank-node'\nimport Literal from '../literal'\nimport NamedNode from '../named-node'\nimport Statement from '../statement'\nimport Variable from '../variable'\nimport {\n SubjectType,\n PredicateType,\n ObjectType,\n GraphType,\n EmptyTermType,\n DefaultGraphTermType,\n VariableTermType,\n BlankNodeTermType,\n LiteralTermType,\n NamedNodeTermType,\n CollectionTermType,\n GraphTermType,\n} from '../types'\nimport DefaultGraph from '../default-graph'\nimport {\n Comparable,\n DataFactory,\n DefaultFactoryTypes,\n Feature,\n} from './factory-types'\nimport { isQuad, isTerm } from '../utils/terms'\nimport { NamedNode as TFNamedNode, Quad, Term } from '../tf-types'\nimport Collection from \"../collection\";\n\nexport { defaultGraphURI } from '../utils/default-graph-uri'\n\n/**\n * Gets the default graph\n */\nconst defaultGraph = new DefaultGraph()\n\n/** A basic internal RDFlib datafactory, which does not support Collections */\nconst CanonicalDataFactory: DataFactory = {\n\n supports: {\n [Feature.collections]: false,\n [Feature.defaultGraphType]: false,\n [Feature.equalsMethod]: true,\n [Feature.identity]: false,\n [Feature.id]: true,\n [Feature.reversibleId]: false,\n [Feature.variableType]: true,\n },\n\n /**\n * Creates a new blank node\n * @param value - The blank node's identifier\n */\n blankNode(value?: string): BlankNode {\n return new BlankNode(value)\n },\n\n defaultGraph: () => defaultGraph,\n\n /**\n * Compares to (rdf) objects for equality.\n */\n equals(a: Comparable, b: Comparable): boolean {\n if (a === b || !a || !b) {\n return true\n }\n\n if (isQuad(a) || isQuad(b)) {\n if (isQuad(a) && isQuad(b)) {\n return (\n this.equals(a.subject, b.subject) &&\n this.equals(a.predicate, b.predicate) &&\n this.equals(a.object, b.object) &&\n this.equals(a.graph, b.graph)\n )\n }\n\n return false\n }\n\n if (isTerm(a) && isTerm(b)) {\n return this.id(a) === this.id(b)\n }\n\n return false\n },\n\n /**\n * Generates a uniquely identifiably *idempotent* string for the given {term}.\n *\n * Equivalent to [[Term.hashString]]\n *\n * @example Use this to associate data with a term in an object\n * { obj[id(term)] = \"myData\" }\n */\n id (term: Term | Statement | undefined): string {\n if (!term) {\n return 'undefined'\n }\n\n if (isQuad(term)) {\n return this.quadToNQ(term)\n }\n\n switch (term.termType) {\n case DefaultGraphTermType:\n return 'defaultGraph'\n case VariableTermType:\n return Variable.toString(term)\n default:\n const nq = this.termToNQ(term)\n if (nq) {\n return nq\n }\n\n throw new Error(`Can't id term with type '${term.termType}'`)\n }\n },\n\n isQuad (obj: any): obj is Statement {\n return obj instanceof Statement\n },\n\n /**\n * Creates a new literal node. Does some JS literal parsing for ease of use.\n * @param value - The lexical value\n * @param languageOrDatatype - Either the language or the datatype\n */\n literal(\n value: string | number | boolean | Date,\n languageOrDatatype?: string | TFNamedNode\n ): Literal {\n if (typeof value !== \"string\" && !languageOrDatatype) {\n return Literal.fromValue(value)\n }\n\n const strValue = typeof value === 'string' ? value : '' + value\n if (typeof languageOrDatatype === 'string') {\n if (languageOrDatatype.indexOf(':') === -1) {\n return new Literal(strValue, languageOrDatatype)\n } else {\n return new Literal(strValue, null, this.namedNode(languageOrDatatype))\n }\n } else {\n return new Literal(strValue, null, languageOrDatatype)\n }\n },\n\n /**\n * Creates a new named node\n * @param value - The new named node\n */\n namedNode(value: string): NamedNode {\n return new NamedNode(value)\n },\n\n /**\n * Creates a new statement\n * @param subject - The subject\n * @param predicate - The predicate\n * @param object - The object\n * @param graph - The containing graph\n */\n quad<\n S extends SubjectType = SubjectType,\n P extends PredicateType = PredicateType,\n O extends ObjectType = ObjectType,\n G extends GraphType = GraphType\n >(subject: S, predicate: P, object: O, graph?: G): Statement<S, P, O, G | DefaultGraph> {\n return new Statement(subject, predicate, object, graph || defaultGraph)\n },\n\n /**\n * Creates a new statement\n * @param subject - The subject\n * @param predicate - The predicate\n * @param object - The object\n * @param graph - The containing graph\n */\n triple(\n subject: Term | SubjectType,\n predicate: Term | PredicateType,\n object: Term | ObjectType,\n graph?: Term | GraphType\n ): Statement {\n return this.quad(subject, predicate, object, graph)\n },\n\n quadToNQ(q: Statement | Quad): string {\n return `${this.termToNQ(q.subject)} ${this.termToNQ(q.predicate)} ${this.termToNQ(q.object)} ${this.termToNQ(q.graph)} .`;\n },\n\n /** Stringify a {term} to n-quads serialization. */\n termToNQ(term: Term): string {\n switch (term.termType) {\n case BlankNodeTermType:\n return '_:' + term.value\n case DefaultGraphTermType:\n return ''\n case EmptyTermType:\n return '<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>'\n case LiteralTermType:\n return Literal.toNT(term as Literal)\n case GraphTermType:\n case NamedNodeTermType:\n return '<' + term.value + '>'\n case CollectionTermType:\n return '(' + (term as Collection).elements.map(t => this.termToNQ(t)).join(' ') + ')'\n default:\n throw new Error(`Can't serialize nonstandard term type (was '${term.termType}')`)\n }\n },\n\n /** Convert an rdf object (term or quad) to n-quads serialization. */\n toNQ (term: Term | (DefaultFactoryTypes & Variable)): string {\n if (this.isQuad(term)) {\n return this.quadToNQ(term);\n }\n\n return this.termToNQ(term);\n },\n\n /**\n * Creates a new variable\n * @param name - The name for the variable\n */\n variable(name?: string): Variable {\n return new Variable(name)\n },\n}\n\n/** Contains the factory methods as defined in the spec, plus id */\nexport default CanonicalDataFactory\n","import NamedNode from './named-node';\n\nexport default {\n boolean: new NamedNode('http://www.w3.org/2001/XMLSchema#boolean'),\n dateTime: new NamedNode('http://www.w3.org/2001/XMLSchema#dateTime'),\n decimal: new NamedNode('http://www.w3.org/2001/XMLSchema#decimal'),\n double: new NamedNode('http://www.w3.org/2001/XMLSchema#double'),\n integer: new NamedNode('http://www.w3.org/2001/XMLSchema#integer'),\n langString: new NamedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString'),\n string: new NamedNode('http://www.w3.org/2001/XMLSchema#string'),\n}\n","import ClassOrder from './class-order'\nimport RDFlibNamedNode from './named-node'\nimport Node from './node-internal'\nimport {\n FromValueReturns,\n LiteralTermType,\n ValueType\n} from './types'\nimport { isLiteral } from './utils/terms'\nimport XSD from './xsd-internal'\nimport { Literal as TFLiteral, Term } from './tf-types'\n\n/**\n * An RDF literal, containing some value which isn't expressed as an IRI.\n * @link https://rdf.js.org/data-model-spec/#literal-interface\n */\nexport default class Literal extends Node implements TFLiteral {\n termType: typeof LiteralTermType = LiteralTermType\n\n classOrder = ClassOrder.Literal\n\n /**\n * The literal's datatype as a named node\n */\n datatype: RDFlibNamedNode = XSD.string\n\n isVar = 0\n\n /**\n * The language for the literal\n */\n language: string = ''\n\n /**\n * Initializes a literal\n * @param value - The literal's lexical value\n * @param language - The language for the literal. Defaults to ''.\n * @param datatype - The literal's datatype as a named node. Defaults to xsd:string.\n */\n constructor (value: string, language?: string | null, datatype?) {\n super(value)\n\n if (language) {\n this.language = language\n this.datatype = XSD.langString\n } else if (datatype) {\n this.datatype = RDFlibNamedNode.fromValue(datatype)\n } else {\n this.datatype = XSD.string\n }\n }\n\n /**\n * Gets a copy of this literal\n */\n copy (): Literal {\n return new Literal(this.value, this.lang, this.datatype)\n }\n\n /**\n * Gets whether two literals are the same\n * @param other The other statement\n */\n equals (other: Term): boolean {\n if (!other) {\n return false\n }\n\n return (this.termType === other.termType) &&\n (this.value === other.value) &&\n (this.language === (other as Literal).language) &&\n ((!this.datatype && !(other as Literal).datatype) ||\n (this.datatype && this.datatype.equals((other as Literal).datatype)))\n }\n\n /**\n * The language for the literal\n * @deprecated use {language} instead\n */\n get lang (): string {\n return this.language\n }\n\n set lang (language: string) {\n this.language = language || ''\n }\n\n toNT(): string {\n return Literal.toNT(this)\n }\n\n /** Serializes a literal to an N-Triples string */\n static toNT (literal: Literal): string {\n if (typeof literal.value === 'number') {\n return '' + literal.value\n } else if (typeof literal.value !== 'string') {\n throw new Error('Value of RDF literal is not string or number: ' +\n literal.value)\n }\n var str = literal.value\n // #x22 (\"), #x5C (\\), #x0A (\\n) and #xD (\\r) are disallowed and need to be replaced\n // see https://www.w3.org/TR/n-triples/#grammar-production-STRING_LITERAL_QUOTE\n str = str.replace(/\\\\/g, '\\\\\\\\')\n str = str.replace(/\\\"/g, '\\\\\"')\n str = str.replace(/\\n/g, '\\\\n')\n str = str.replace(/\\r/g, '\\\\r')\n str = '\"' + str + '\"'\n\n if (literal.language) {\n str += '@' + literal.language\n } else if (!literal.datatype.equals(XSD.string)) {\n // Only add datatype if it's not a string\n str += '^^' + literal.datatype.toCanonical()\n }\n return str\n }\n\n toString () {\n return '' + this.value\n }\n\n /**\n * Builds a literal node from a boolean value\n * @param value - The value\n */\n static fromBoolean (value: boolean): Literal {\n let strValue = value ? '1' : '0'\n return new Literal(strValue, null, XSD.boolean)\n }\n\n /**\n * Builds a literal node from a date value\n * @param value The value\n */\n static fromDate(value: Date): Literal {\n if (!(value instanceof Date)) {\n throw new TypeError('Invalid argument to Literal.fromDate()')\n }\n let d2 = function (x) {\n return ('' + (100 + x)).slice(1, 3)\n }\n let date = '' + value.getUTCFullYear() + '-' + d2(value.getUTCMonth() + 1) +\n '-' + d2(value.getUTCDate()) + 'T' + d2(value.getUTCHours()) + ':' +\n d2(value.getUTCMinutes()) + ':' + d2(value.getUTCSeconds()) + 'Z'\n return new Literal(date, null, XSD.dateTime)\n }\n\n /**\n * Builds a literal node from a number value\n * @param value - The value\n */\n static fromNumber(value: number): Literal {\n if (typeof value !== 'number') {\n throw new TypeError('Invalid argument to Literal.fromNumber()')\n }\n let datatype: RDFlibNamedNode\n const strValue = value.toString()\n if (strValue.indexOf('e') < 0 && Math.abs(value) <= Number.MAX_SAFE_INTEGER) {\n datatype = Number.isInteger(value) ? XSD.integer : XSD.decimal\n } else {\n datatype = XSD.double\n }\n return new Literal(strValue, null, datatype)\n }\n\n /**\n * Builds a literal node from an input value\n * @param value - The input value\n */\n static fromValue<T extends FromValueReturns>(value: ValueType): T {\n if (isLiteral(value)) {\n return value as unknown as T\n }\n switch (typeof value) {\n case 'object':\n if (value instanceof Date) {\n return Literal.fromDate(value) as unknown as T\n }\n case 'boolean':\n return Literal.fromBoolean(value as boolean) as unknown as T\n case 'number':\n return Literal.fromNumber(value as number) as unknown as T\n case 'string':\n return new Literal(value) as unknown as T\n }\n\n throw new Error(\"Can't make literal from \" + value + ' of type ' +\n typeof value)\n }\n}\n","import Literal from '../literal'\nimport Statement from '../statement'\nimport NamedNode from '../named-node'\nimport BlankNode from '../blank-node'\nimport Variable from '../variable'\nimport DefaultGraph from '../default-graph'\nimport {\n BlankNode as TFBlankNode,\n RdfJsDataFactory,\n Literal as TFLiteral,\n NamedNode as TFNamedNode,\n Quad,\n Term,\n Variable as TFVariable,\n} from '../tf-types'\n\nexport type Comparable = Term | TFNamedNode | TFBlankNode | TFLiteral | Quad | undefined | null\n\nexport type DefaultFactoryTypes = NamedNode | BlankNode | Literal | Variable | Statement\n\nexport type Indexable = number | string\n\nexport type Namespace = (term:string) => TFNamedNode\n\n/** A set of features that may be supported by a Data Factory */\nexport type SupportTable = Record<Feature, boolean>\n\nexport type TFIDFactoryTypes = TFNamedNode | TFBlankNode | TFLiteral | Quad | TFVariable | Term\n\nexport enum Feature {\n /** Whether the factory supports termType:Collection terms */\n collections = \"COLLECTIONS\",\n /** Whether the factory supports termType:DefaultGraph terms */\n defaultGraphType = \"DEFAULT_GRAPH_TYPE\",\n /** Whether the factory supports equals on produced instances */\n equalsMethod = \"EQUALS_METHOD\",\n /** Whether the factory can create a unique idempotent identifier for the given term. */\n id = \"ID\",\n /**\n * Whether the factory will return the same instance for subsequent calls.\n * This implies `===`, which means methods like `indexOf` can be used.\n */\n identity = \"IDENTITY\",\n /** Whether the factory supports mapping ids back to instances (should adhere to the identity setting) */\n reversibleId = \"REVERSIBLE_ID\",\n /** Whether the factory supports termType:Variable terms */\n variableType = \"VARIABLE_TYPE\",\n}\n\n/**\n * Defines a DataFactory as used in rdflib, based on the RDF/JS: Data model specification,\n * but with additional extensions\n *\n * bnIndex is optional but useful.\n */\nexport interface DataFactory<\n FactoryTypes = DefaultFactoryTypes,\n IndexType = Indexable\n> extends RdfJsDataFactory {\n /**\n * BlankNode index\n * @private\n */\n bnIndex?: number\n\n supports: SupportTable\n\n namedNode(value: string): NamedNode\n\n blankNode(value?: string): BlankNode\n\n literal(value: string, languageOrDatatype?: string | TFNamedNode): Literal\n\n variable(value: string): Variable,\n\n defaultGraph(): DefaultGraph,\n\n isQuad(obj: any): obj is Statement\n\n equals(a: Comparable, b: Comparable): boolean\n\n toNQ(term: Term | FactoryTypes): string\n\n quad(\n subject: Term,\n predicate: Term,\n object: Term,\n graph?: Term,\n ): Statement;\n\n quadToNQ(term: Statement | Quad): string\n\n termToNQ(term: Term): string\n\n /**\n * Generates a unique session-idempotent identifier for the given object.\n *\n * @example NQ serialization (reversible from value)\n * @example MD5 hash of termType + value (irreversible from value, map needed)\n *\n * @return {Indexable} A unique value which must also be a valid JS object key type.\n */\n id(obj: Term | FactoryTypes): IndexType\n}\n","import ClassOrder from './class-order'\nimport Node from './node-internal'\nimport IndexedFormula from './store'\nimport { BlankNodeTermType } from './types'\nimport { BlankNode as TFBlankNode } from './tf-types'\n\n/**\n * An RDF blank node is a Node without a URI\n * @link https://rdf.js.org/data-model-spec/#blanknode-interface\n */\nexport default class BlankNode extends Node implements TFBlankNode {\n termType: typeof BlankNodeTermType = BlankNodeTermType;\n /**\n * The next unique identifier for blank nodes\n */\n static nextId: number = 0;\n static NTAnonymousNodePrefix: '_:' = '_:'\n\n private static getId (id: string | unknown): string {\n if (id) {\n if (typeof id !== 'string') {\n console.log('Bad blank id:', id)\n throw new Error('Bad id argument to new blank node: ' + id)\n }\n\n if (id.includes('#')) {\n // Is a URI with hash fragment\n let fragments = id.split('#')\n return fragments[fragments.length - 1]\n }\n\n return id\n }\n\n return 'n' + BlankNode.nextId++\n }\n\n classOrder = ClassOrder.BlankNode\n /** Whether this is a blank node */\n isBlank: number = 1\n /**\n * This type of node is a variable.\n *\n * Note that the existence of this property already indicates that it is a variable.\n */\n isVar = 1\n\n /**\n * Initializes this node\n * @param [id] The identifier for the blank node\n */\n constructor (id?: string | unknown) {\n super(BlankNode.getId(id))\n }\n\n /**\n * The identifier for the blank node\n */\n public get id (): string {\n return this.value\n }\n\n public set id (value: string) {\n this.value = value\n }\n\n compareTerm (other: BlankNode): number {\n if (this.classOrder < other.classOrder) {\n return -1\n }\n if (this.classOrder > other.classOrder) {\n return +1\n }\n if (this.id < other.id) {\n return -1\n }\n if (this.id > other.id) {\n return +1\n }\n return 0\n }\n\n /**\n * Gets a copy of this blank node in the specified formula\n * @param formula The formula\n */\n copy (formula: IndexedFormula): BlankNode { // depends on the formula\n var bnodeNew = new BlankNode()\n formula.copyTo(this, bnodeNew)\n return bnodeNew\n }\n\n toCanonical () {\n return BlankNode.NTAnonymousNodePrefix + this.value\n }\n\n toString () {\n return BlankNode.NTAnonymousNodePrefix + this.id\n }\n}\n","const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n XSD = 'http://www.w3.org/2001/XMLSchema#',\n SWAP = 'http://www.w3.org/2000/10/swap/';\n\nexport default {\n xsd: {\n decimal: `${XSD}decimal`,\n boolean: `${XSD}boolean`,\n double: `${XSD}double`,\n integer: `${XSD}integer`,\n string: `${XSD}string`,\n },\n rdf: {\n type: `${RDF}type`,\n nil: `${RDF}nil`,\n first: `${RDF}first`,\n rest: `${RDF}rest`,\n langString: `${RDF}langString`,\n },\n owl: {\n sameAs: 'http://www.w3.org/2002/07/owl#sameAs',\n },\n r: {\n forSome: `${SWAP}reify#forSome`,\n forAll: `${SWAP}reify#forAll`,\n },\n log: {\n implies: `${SWAP}log#implies`,\n },\n};\n","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n module.exports = _typeof = function _typeof(obj) {\n return typeof obj;\n };\n\n module.exports[\"default\"] = module.exports, module.exports.__esModule = true;\n } else {\n module.exports = _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n\n module.exports[\"default\"] = module.exports, module.exports.__esModule = true;\n }\n\n return _typeof(obj);\n}\n\nmodule.exports = _typeof;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","import ClassOrder from './class-order'\nimport Node from './node-internal'\nimport { VariableTermType } from './types'\nimport * as Uri from './uri'\nimport { Variable as TFVariable } from './tf-types'\n\n/**\n* Variables are placeholders used in patterns to be matched.\n* In cwm they are symbols which are the formula's list of quantified variables.\n* In sparql they are not visibly URIs. Here we compromise, by having\n* a common special base URI for variables. Their names are uris,\n* but the ? notation has an implicit base uri of 'varid:'\n*/\nexport default class Variable extends Node implements TFVariable {\n termType: typeof VariableTermType = VariableTermType\n\n /** The base string for a variable's name */\n base = 'varid:'\n classOrder = ClassOrder.Variable\n isVar = 1\n /** The unique identifier of this variable */\n uri: string\n\n /**\n * Initializes this variable\n * @param name The variable's name\n */\n constructor (name = '') {\n super(name)\n this.base = 'varid:'\n this.uri = Uri.join(name, this.base)\n }\n\n equals (other) {\n if (!other) {\n return false\n }\n\n return (this.termType === other.termType) && (this.value === other.value)\n }\n\n hashString () {\n return this.toString()\n }\n\n substitute (bindings) {\n var ref\n return (ref = bindings[this.toNT()]) != null ? ref : this\n }\n\n toString () {\n return Variable.toString(this)\n }\n\n static toString (variable) {\n if (variable.uri.slice(0, variable.base.length) === variable.base) {\n return `?${variable.uri.slice(variable.base.length)}`\n }\n\n return `?${variable.uri}`\n }\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Returns true if the given value is an Array.\n *\n * @param v the value to check.\n *\n * @return true if the value is an Array, false if not.\n */\napi.isArray = Array.isArray;\n\n/**\n * Returns true if the given value is a Boolean.\n *\n * @param v the value to check.\n *\n * @return true if the value is a Boolean, false if not.\n */\napi.isBoolean = v => (typeof v === 'boolean' ||\n Object.prototype.toString.call(v) === '[object Boolean]');\n\n/**\n * Returns true if the given value is a double.\n *\n * @param v the value to check.\n *\n * @return true if the value is a double, false if not.\n */\napi.isDouble = v => api.isNumber(v) &&\n (String(v).indexOf('.') !== -1 || Math.abs(v) >= 1e21);\n\n/**\n * Returns true if the given value is an empty Object.\n *\n * @param v the value to check.\n *\n * @return true if the value is an empty Object, false if not.\n */\napi.isEmptyObject = v => api.isObject(v) && Object.keys(v).length === 0;\n\n/**\n * Returns true if the given value is a Number.\n *\n * @param v the value to check.\n *\n * @return true if the value is a Number, false if not.\n */\napi.isNumber = v => (typeof v === 'number' ||\n Object.prototype.toString.call(v) === '[object Number]');\n\n/**\n * Returns true if the given value is numeric.\n *\n * @param v the value to check.\n *\n * @return true if the value is numeric, false if not.\n */\napi.isNumeric = v => !isNaN(parseFloat(v)) && isFinite(v);\n\n/**\n * Returns true if the given value is an Object.\n *\n * @param v the value to check.\n *\n * @return true if the value is an Object, false if not.\n */\napi.isObject = v => Object.prototype.toString.call(v) === '[object Object]';\n\n/**\n * Returns true if the given value is a String.\n *\n * @param v the value to check.\n *\n * @return true if the value is a String, false if not.\n */\napi.isString = v => (typeof v === 'string' ||\n Object.prototype.toString.call(v) === '[object String]');\n\n/**\n * Returns true if the given value is undefined.\n *\n * @param v the value to check.\n *\n * @return true if the value is undefined, false if not.\n */\napi.isUndefined = v => typeof v === 'undefined';\n","import { Term } from '../tf-types'\n\n/** Retrieve the value of a term, or self if already a string. */\nexport function termValue (node: Term | string): string {\n if (typeof node === 'string') {\n return node\n }\n\n return node.value\n}\n","// This file attaches all functionality to Node\n// that would otherwise require circular dependencies.\nimport { fromValue } from './collection'\nimport Node from './node-internal'\nimport Namespace from './namespace'\nimport { isCollection, isLiteral } from './utils/terms'\nimport { Term } from './tf-types'\n\n/**\n * Creates an RDF Node from a native javascript value.\n * RDF Nodes are returned unchanged, undefined returned as itself.\n * @method fromValue\n * @static\n * @param value {Node|Date|String|Number|Boolean|Undefined}\n * @return {Node|Collection}\n */\nNode.fromValue = fromValue;\n\nexport default Node\n\nconst ns = { xsd: Namespace('http://www.w3.org/2001/XMLSchema#') }\n\n/**\n * Gets the javascript object equivalent to a node\n * @param term The RDF node\n */\nNode.toJS = function (term: Term): Term | boolean | number | Date | string | any[] {\n if (isCollection(term)) {\n return term.elements.map(Node.toJS) // Array node (not standard RDFJS)\n }\n if (!isLiteral(term)) return term\n if (term.datatype.equals(ns.xsd('boolean'))) {\n return term.value === '1' || term.value === 'true'\n }\n if (term.datatype.equals(ns.xsd('dateTime')) ||\n term.datatype.equals(ns.xsd('date'))) {\n return new Date(term.value)\n }\n if (\n term.datatype.equals(ns.xsd('integer')) ||\n term.datatype.equals(ns.xsd('float')) ||\n term.datatype.equals(ns.xsd('decimal'))\n ) {\n return Number(term.value)\n }\n return term.value\n}\n","/*\n * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst graphTypes = require('./graphTypes');\nconst types = require('./types');\n// TODO: move `IdentifierIssuer` to its own package\nconst IdentifierIssuer = require('rdf-canonize').IdentifierIssuer;\nconst JsonLdError = require('./JsonLdError');\n\n// constants\nconst REGEX_LINK_HEADERS = /(?:<[^>]*?>|\"[^\"]*?\"|[^,])+/g;\nconst REGEX_LINK_HEADER = /\\s*<([^>]*?)>\\s*(?:;\\s*(.*))?/;\nconst REGEX_LINK_HEADER_PARAMS =\n /(.*?)=(?:(?:\"([^\"]*?)\")|([^\"]*?))\\s*(?:(?:;\\s*)|$)/g;\n\nconst DEFAULTS = {\n headers: {\n accept: 'application/ld+json, application/json'\n }\n};\n\nconst api = {};\nmodule.exports = api;\napi.IdentifierIssuer = IdentifierIssuer;\n\n/**\n * Clones an object, array, Map, Set, or string/number. If a typed JavaScript\n * object is given, such as a Date, it will be converted to a string.\n *\n * @param value the value to clone.\n *\n * @return the cloned value.\n */\napi.clone = function(value) {\n if(value && typeof value === 'object') {\n let rval;\n if(types.isArray(value)) {\n rval = [];\n for(let i = 0; i < value.length; ++i) {\n rval[i] = api.clone(value[i]);\n }\n } else if(value instanceof Map) {\n rval = new Map();\n for(const [k, v] of value) {\n rval.set(k, api.clone(v));\n }\n } else if(value instanceof Set) {\n rval = new Set();\n for(const v of value) {\n rval.add(api.clone(v));\n }\n } else if(types.isObject(value)) {\n rval = {};\n for(const key in value) {\n rval[key] = api.clone(value[key]);\n }\n } else {\n rval = value.toString();\n }\n return rval;\n }\n return value;\n};\n\n/**\n * Ensure a value is an array. If the value is an array, it is returned.\n * Otherwise, it is wrapped in an array.\n *\n * @param value the value to return as an array.\n *\n * @return the value as an array.\n */\napi.asArray = function(value) {\n return Array.isArray(value) ? value : [value];\n};\n\n/**\n * Builds an HTTP headers object for making a JSON-LD request from custom\n * headers and asserts the `accept` header isn't overridden.\n *\n * @param headers an object of headers with keys as header names and values\n * as header values.\n *\n * @return an object of headers with a valid `accept` header.\n */\napi.buildHeaders = (headers = {}) => {\n const hasAccept = Object.keys(headers).some(\n h => h.toLowerCase() === 'accept');\n\n if(hasAccept) {\n throw new RangeError(\n 'Accept header may not be specified; only \"' +\n DEFAULTS.headers.accept + '\" is supported.');\n }\n\n return Object.assign({Accept: DEFAULTS.headers.accept}, headers);\n};\n\n/**\n * Parses a link header. The results will be key'd by the value of \"rel\".\n *\n * Link: <http://json-ld.org/contexts/person.jsonld>;\n * rel=\"http://www.w3.org/ns/json-ld#context\"; type=\"application/ld+json\"\n *\n * Parses as: {\n * 'http://www.w3.org/ns/json-ld#context': {\n * target: http://json-ld.org/contexts/person.jsonld,\n * type: 'application/ld+json'\n * }\n * }\n *\n * If there is more than one \"rel\" with the same IRI, then entries in the\n * resulting map for that \"rel\" will be arrays.\n *\n * @param header the link header to parse.\n */\napi.parseLinkHeader = header => {\n const rval = {};\n // split on unbracketed/unquoted commas\n const entries = header.match(REGEX_LINK_HEADERS);\n for(let i = 0; i < entries.length; ++i) {\n let match = entries[i].match(REGEX_LINK_HEADER);\n if(!match) {\n continue;\n }\n const result = {target: match[1]};\n const params = match[2];\n while((match = REGEX_LINK_HEADER_PARAMS.exec(params))) {\n result[match[1]] = (match[2] === undefined) ? match[3] : match[2];\n }\n const rel = result['rel'] || '';\n if(Array.isArray(rval[rel])) {\n rval[rel].push(result);\n } else if(rval.hasOwnProperty(rel)) {\n rval[rel] = [rval[rel], result];\n } else {\n rval[rel] = result;\n }\n }\n return rval;\n};\n\n/**\n * Throws an exception if the given value is not a valid @type value.\n *\n * @param v the value to check.\n */\napi.validateTypeValue = (v, isFrame) => {\n if(types.isString(v)) {\n return;\n }\n\n if(types.isArray(v) && v.every(vv => types.isString(vv))) {\n return;\n }\n if(isFrame && types.isObject(v)) {\n switch(Object.keys(v).length) {\n case 0:\n // empty object is wildcard\n return;\n case 1:\n // default entry is all strings\n if('@default' in v &&\n api.asArray(v['@default']).every(vv => types.isString(vv))) {\n return;\n }\n }\n }\n\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@type\" value must a string, an array of ' +\n 'strings, an empty object, ' +\n 'or a default object.', 'jsonld.SyntaxError',\n {code: 'invalid type value', value: v});\n};\n\n/**\n * Returns true if the given subject has the given property.\n *\n * @param subject the subject to check.\n * @param property the property to look for.\n *\n * @return true if the subject has the given property, false if not.\n */\napi.hasProperty = (subject, property) => {\n if(subject.hasOwnProperty(property)) {\n const value = subject[property];\n return (!types.isArray(value) || value.length > 0);\n }\n return false;\n};\n\n/**\n * Determines if the given value is a property of the given subject.\n *\n * @param subject the subject to check.\n * @param property the property to check.\n * @param value the value to check.\n *\n * @return true if the value exists, false if not.\n */\napi.hasValue = (subject, property, value) => {\n if(api.hasProperty(subject, property)) {\n let val = subject[property];\n const isList = graphTypes.isList(val);\n if(types.isArray(val) || isList) {\n if(isList) {\n val = val['@list'];\n }\n for(let i = 0; i < val.length; ++i) {\n if(api.compareValues(value, val[i])) {\n return true;\n }\n }\n } else if(!types.isArray(value)) {\n // avoid matching the set of values with an array value parameter\n return api.compareValues(value, val);\n }\n }\n return false;\n};\n\n/**\n * Adds a value to a subject. If the value is an array, all values in the\n * array will be added.\n *\n * @param subject the subject to add the value to.\n * @param property the property that relates the value to the subject.\n * @param value the value to add.\n * @param [options] the options to use:\n * [propertyIsArray] true if the property is always an array, false\n * if not (default: false).\n * [valueIsArray] true if the value to be added should be preserved as\n * an array (lists) (default: false).\n * [allowDuplicate] true to allow duplicates, false not to (uses a\n * simple shallow comparison of subject ID or value) (default: true).\n * [prependValue] false to prepend value to any existing values.\n * (default: false)\n */\napi.addValue = (subject, property, value, options) => {\n options = options || {};\n if(!('propertyIsArray' in options)) {\n options.propertyIsArray = false;\n }\n if(!('valueIsArray' in options)) {\n options.valueIsArray = false;\n }\n if(!('allowDuplicate' in options)) {\n options.allowDuplicate = true;\n }\n if(!('prependValue' in options)) {\n options.prependValue = false;\n }\n\n if(options.valueIsArray) {\n subject[property] = value;\n } else if(types.isArray(value)) {\n if(value.length === 0 && options.propertyIsArray &&\n !subject.hasOwnProperty(property)) {\n subject[property] = [];\n }\n if(options.prependValue) {\n value = value.concat(subject[property]);\n subject[property] = [];\n }\n for(let i = 0; i < value.length; ++i) {\n api.addValue(subject, property, value[i], options);\n }\n } else if(subject.hasOwnProperty(property)) {\n // check if subject already has value if duplicates not allowed\n const hasValue = (!options.allowDuplicate &&\n api.hasValue(subject, property, value));\n\n // make property an array if value not present or always an array\n if(!types.isArray(subject[property]) &&\n (!hasValue || options.propertyIsArray)) {\n subject[property] = [subject[property]];\n }\n\n // add new value\n if(!hasValue) {\n if(options.prependValue) {\n subject[property].unshift(value);\n } else {\n subject[property].push(value);\n }\n }\n } else {\n // add new value as set or single value\n subject[property] = options.propertyIsArray ? [value] : value;\n }\n};\n\n/**\n * Gets all of the values for a subject's property as an array.\n *\n * @param subject the subject.\n * @param property the property.\n *\n * @return all of the values for a subject's property as an array.\n */\napi.getValues = (subject, property) => [].concat(subject[property] || []);\n\n/**\n * Removes a property from a subject.\n *\n * @param subject the subject.\n * @param property the property.\n */\napi.removeProperty = (subject, property) => {\n delete subject[property];\n};\n\n/**\n * Removes a value from a subject.\n *\n * @param subject the subject.\n * @param property the property that relates the value to the subject.\n * @param value the value to remove.\n * @param [options] the options to use:\n * [propertyIsArray] true if the property is always an array, false\n * if not (default: false).\n */\napi.removeValue = (subject, property, value, options) => {\n options = options || {};\n if(!('propertyIsArray' in options)) {\n options.propertyIsArray = false;\n }\n\n // filter out value\n const values = api.getValues(subject, property).filter(\n e => !api.compareValues(e, value));\n\n if(values.length === 0) {\n api.removeProperty(subject, property);\n } else if(values.length === 1 && !options.propertyIsArray) {\n subject[property] = values[0];\n } else {\n subject[property] = values;\n }\n};\n\n/**\n * Relabels all blank nodes in the given JSON-LD input.\n *\n * @param input the JSON-LD input.\n * @param [options] the options to use:\n * [issuer] an IdentifierIssuer to use to label blank nodes.\n */\napi.relabelBlankNodes = (input, options) => {\n options = options || {};\n const issuer = options.issuer || new IdentifierIssuer('_:b');\n return _labelBlankNodes(issuer, input);\n};\n\n/**\n * Compares two JSON-LD values for equality. Two JSON-LD values will be\n * considered equal if:\n *\n * 1. They are both primitives of the same type and value.\n * 2. They are both @values with the same @value, @type, @language,\n * and @index, OR\n * 3. They both have @ids they are the same.\n *\n * @param v1 the first value.\n * @param v2 the second value.\n *\n * @return true if v1 and v2 are considered equal, false if not.\n */\napi.compareValues = (v1, v2) => {\n // 1. equal primitives\n if(v1 === v2) {\n return true;\n }\n\n // 2. equal @values\n if(graphTypes.isValue(v1) && graphTypes.isValue(v2) &&\n v1['@value'] === v2['@value'] &&\n v1['@type'] === v2['@type'] &&\n v1['@language'] === v2['@language'] &&\n v1['@index'] === v2['@index']) {\n return true;\n }\n\n // 3. equal @ids\n if(types.isObject(v1) &&\n ('@id' in v1) &&\n types.isObject(v2) &&\n ('@id' in v2)) {\n return v1['@id'] === v2['@id'];\n }\n\n return false;\n};\n\n/**\n * Compares two strings first based on length and then lexicographically.\n *\n * @param a the first string.\n * @param b the second string.\n *\n * @return -1 if a < b, 1 if a > b, 0 if a === b.\n */\napi.compareShortestLeast = (a, b) => {\n if(a.length < b.length) {\n return -1;\n }\n if(b.length < a.length) {\n return 1;\n }\n if(a === b) {\n return 0;\n }\n return (a < b) ? -1 : 1;\n};\n\n/**\n * Labels the blank nodes in the given value using the given IdentifierIssuer.\n *\n * @param issuer the IdentifierIssuer to use.\n * @param element the element with blank nodes to rename.\n *\n * @return the element.\n */\nfunction _labelBlankNodes(issuer, element) {\n if(types.isArray(element)) {\n for(let i = 0; i < element.length; ++i) {\n element[i] = _labelBlankNodes(issuer, element[i]);\n }\n } else if(graphTypes.isList(element)) {\n element['@list'] = _labelBlankNodes(issuer, element['@list']);\n } else if(types.isObject(element)) {\n // relabel blank node\n if(graphTypes.isBlankNode(element)) {\n element['@id'] = issuer.getId(element['@id']);\n }\n\n // recursively apply to all keys\n const keys = Object.keys(element).sort();\n for(let ki = 0; ki < keys.length; ++ki) {\n const key = keys[ki];\n if(key !== '@id') {\n element[key] = _labelBlankNodes(issuer, element[key]);\n }\n }\n }\n\n return element;\n}\n","/* Identity management and indexing for RDF\n *\n * This file provides IndexedFormula a formula (set of triples) which\n * indexed by predicate, subject and object.\n *\n * It \"smushes\" (merges into a single node) things which are identical\n * according to owl:sameAs or an owl:InverseFunctionalProperty\n * or an owl:FunctionalProperty\n *\n *\n * 2005-10 Written Tim Berners-Lee\n * 2007 Changed so as not to munge statements from documents when smushing\n * 2019 Converted to typescript\n *\n *\n*/\n\n/** @module store */\n\nimport ClassOrder from './class-order'\nimport { defaultGraphURI } from './factories/canonical-data-factory'\nimport Formula, { FormulaOpts } from './formula'\nimport { ArrayIndexOf } from './utils'\nimport { RDFArrayRemove } from './utils-js'\nimport {\n isRDFlibObject,\n isStore,\n isGraph,\n isPredicate,\n isQuad,\n isSubject\n} from './utils/terms'\nimport Node from './node'\nimport Variable from './variable'\nimport { Query, indexedFormulaQuery } from './query'\nimport UpdateManager from './update-manager'\nimport {\n Bindings, BlankNodeTermType, CollectionTermType, DefaultGraphTermType, EmptyTermType, GraphTermType, LiteralTermType, NamedNodeTermType, VariableTermType\n} from './types'\nimport Statement from './statement'\nimport { Indexable } from './factories/factory-types'\nimport NamedNode from './named-node'\nimport Fetcher from './fetcher'\nimport {\n Quad_Graph,\n Literal as TFLiteral,\n NamedNode as TFNamedNode,\n Quad_Object,\n Quad_Predicate,\n Quad,\n Quad_Subject,\n Term,\n} from './tf-types'\nimport { namedNode } from './index'\nimport BlankNode from './blank-node'\nimport DefaultGraph from './default-graph'\nimport Empty from './empty'\nimport Literal from './literal'\nimport Collection from './collection'\n\nconst owlNamespaceURI = 'http://www.w3.org/2002/07/owl#'\n\ntype FeaturesType = Array<('sameAs' | 'InverseFunctionalProperty' | 'FunctionalProperty')> | undefined\n\nexport { defaultGraphURI }\n// var link_ns = 'http://www.w3.org/2007/ont/link#'\n\n// Handle Functional Property\nfunction handleFP (\n formula: IndexedFormula,\n subj: Quad_Subject,\n pred: Quad_Predicate,\n obj: Quad_Object\n): boolean {\n var o1 = formula.any(subj, pred, undefined)\n if (!o1) {\n return false // First time with this value\n }\n // log.warn(\"Equating \"+o1.uri+\" and \"+obj.uri + \" because FP \"+pred.uri); //@@\n formula.equate(o1, obj)\n return true\n} // handleFP\n\n// Handle Inverse Functional Property\nfunction handleIFP (\n formula: IndexedFormula,\n subj: Quad_Subject,\n pred: Quad_Predicate,\n obj: Quad_Object\n): boolean {\n var s1 = formula.any(undefined, pred, obj)\n if (!s1) {\n return false // First time with this value\n }\n // log.warn(\"Equating \"+s1.uri+\" and \"+subj.uri + \" because IFP \"+pred.uri); //@@\n formula.equate(s1, subj)\n return true\n} // handleIFP\n\nfunction handleRDFType (\n formula: IndexedFormula,\n subj: Quad_Subject,\n pred: Quad_Predicate,\n obj: Quad_Object,\n why: Quad_Graph\n) {\n //@ts-ignore this method does not seem to exist in this library\n if (formula.typeCallback) {\n (formula as any).typeCallback(formula, obj, why)\n }\n\n var x = formula.classActions[formula.id(obj)]\n var done = false\n if (x) {\n for (var i = 0; i < x.length; i++) {\n done = done || x[i](formula, subj, pred, obj, why)\n }\n }\n return done // statement given is not needed if true\n}\n\n/**\n * Indexed Formula aka Store\n */\nexport default class IndexedFormula extends Formula { // IN future - allow pass array of statements to constructor\n /**\n * An UpdateManager initialised to this store\n */\n updater?: UpdateManager\n\n /**\n * Dictionary of namespace prefixes\n */\n namespaces: {[key: string]: string}\n\n /** Map of iri predicates to functions to call when adding { s type X } */\n classActions: { [k: string]: Function[] }\n /** Map of iri predicates to functions to call when getting statement with {s X o} */\n propertyActions: { [k: string]: Function[] }\n /** Redirect to lexically smaller equivalent symbol */\n redirections: any[]\n /** Reverse mapping to redirection: aliases for this */\n aliases: any[]\n /** Redirections we got from HTTP */\n HTTPRedirects: Statement[]\n /** Array of statements with this X as subject */\n subjectIndex: Statement[]\n /** Array of statements with this X as predicate */\n predicateIndex: Statement[]\n /** Array of statements with this X as object */\n objectIndex: Statement[]\n /** Array of statements with X as provenance */\n whyIndex: Statement[]\n index: [\n Statement[],\n Statement[],\n Statement[],\n Statement[]\n ]\n features: FeaturesType\n static handleRDFType: Function\n _universalVariables?: NamedNode[]\n _existentialVariables?: BlankNode[]\n\n /** Function to remove quads from the store arrays with */\n private rdfArrayRemove: (arr: Quad[], q: Quad) => void\n /** Callbacks which are triggered after a statement has been added to the store */\n private dataCallbacks?: Array<(q: Quad) => void>\n\n /**\n * Creates a new formula\n * @param features - What sort of automatic processing to do? Array of string\n * @param features.sameAs - Smush together A and B nodes whenever { A sameAs B }\n * @param opts\n * @param [opts.rdfFactory] - The data factory that should be used by the store\n * @param [opts.rdfArrayRemove] - Function which removes statements from the store\n * @param [opts.dataCallback] - Callback when a statement is added to the store, will not trigger when adding duplicates\n */\n constructor (features?: FeaturesType, opts: FormulaOpts = {}) {\n super(undefined, undefined, undefined, undefined, opts)\n\n this.propertyActions = {}\n this.classActions = {}\n this.redirections = []\n this.aliases = []\n this.HTTPRedirects = []\n this.subjectIndex = []\n this.predicateIndex = []\n this.objectIndex = []\n this.whyIndex = []\n this.index = [\n this.subjectIndex,\n this.predicateIndex,\n this.objectIndex,\n this.whyIndex\n ]\n this.namespaces = {} // Dictionary of namespace prefixes\n this.features = features || [ // By default, devs do not expect these features.\n// See https://github.com/linkeddata/rdflib.js/issues/458\n// 'sameAs',\n// 'InverseFunctionalProperty',\n// 'FunctionalProperty',\n ]\n this.rdfArrayRemove = opts.rdfArrayRemove || RDFArrayRemove\n if (opts.dataCallback) {\n this.dataCallbacks = [opts.dataCallback]\n }\n\n this.initPropertyActions(this.features)\n }\n\n /**\n * Gets the URI of the default graph\n */\n static get defaultGraphURI(): string {\n return defaultGraphURI\n }\n\n /**\n * Gets this graph with the bindings substituted\n * @param bindings The bindings\n */\n substitute <T extends Node = IndexedFormula>(bindings: Bindings): T {\n var statementsCopy = this.statements.map(function (ea: Quad) {\n return (ea as Statement).substitute(bindings)\n })\n var y = new IndexedFormula()\n y.add(statementsCopy)\n return y as unknown as T\n }\n\n /**\n * Add a callback which will be triggered after a statement has been added to the store.\n * @param cb\n */\n addDataCallback(cb: (q: Quad) => void): void {\n if (!this.dataCallbacks) {\n this.dataCallbacks = []\n }\n this.dataCallbacks.push(cb)\n }\n\n /**\n * Apply a set of statements to be deleted and to be inserted\n *\n * @param patch - The set of statements to be deleted and to be inserted\n * @param target - The name of the document to patch\n * @param patchCallback - Callback to be called when patching is complete\n */\n applyPatch(\n patch: {\n delete?: ReadonlyArray<Statement>,\n patch?: ReadonlyArray<Statement>,\n where?: any\n },\n target: TFNamedNode,\n patchCallback: (errorString?: string) => void\n ): void {\n var targetKB = this\n var ds\n var binding: Bindings | null = null\n\n function doPatch (onDonePatch: (errorString?: string) => void) {\n if (patch['delete']) {\n ds = patch['delete']\n // console.log(bindingDebug(binding))\n // console.log('ds before substitute: ' + ds)\n if (binding) ds = ds.substitute(binding)\n // console.log('applyPatch: delete: ' + ds)\n ds = ds.statements as Statement[]\n var bad: Quad[] = []\n var ds2 = ds.map(function (st: Quad) { // Find the actual statements in the store\n var sts = targetKB.statementsMatching(st.subject, st.predicate, st.object, target)\n if (sts.length === 0) {\n // log.info(\"NOT FOUND deletable \" + st)\n bad.push(st)\n return null\n } else {\n // log.info(\"Found deletable \" + st)\n return sts[0]\n }\n })\n if (bad.length) {\n // console.log('Could not find to delete ' + bad.length + 'statements')\n // console.log('despite ' + targetKB.statementsMatching(bad[0].subject, bad[0].predicate)[0])\n return patchCallback('Could not find to delete: ' + bad.join('\\n or '))\n }\n ds2.map(function (st: Quad) {\n targetKB.remove(st)\n })\n }\n if (patch['insert']) {\n // log.info(\"doPatch insert \"+patch['insert'])\n ds = patch['insert']\n if (binding) ds = ds.substitute(binding)\n ds = ds.statements\n ds.map(function (st: Quad) {\n st.graph = target\n targetKB.add(st.subject, st.predicate, st.object, st.graph)\n })\n }\n onDonePatch()\n }\n if (patch.where) {\n // log.info(\"Processing WHERE: \" + patch.where + '\\n')\n var query = new Query('patch')\n query.pat = patch.where\n query.pat.statements.map(function (st) {\n st.graph = namedNode(target.value)\n })\n //@ts-ignore TODO: add sync property to Query when converting Query to typescript\n query.sync = true\n\n var bindingsFound: Bindings[] = []\n\n targetKB.query(\n query,\n function onBinding (binding) {\n bindingsFound.push(binding)\n // console.log(' got a binding: ' + bindingDebug(binding))\n },\n targetKB.fetcher,\n function onDone () {\n if (bindingsFound.length === 0) {\n return patchCallback('No match found to be patched:' + patch.where)\n }\n if (bindingsFound.length > 1) {\n return patchCallback('Patch ambiguous. No patch done.')\n }\n binding = bindingsFound[0]\n doPatch(patchCallback)\n })\n } else {\n doPatch(patchCallback)\n }\n }\n\n /**\n * N3 allows for declaring blank nodes, this function enables that support\n *\n * @param x The blank node to be declared, supported in N3\n */\n declareExistential(x: BlankNode): BlankNode {\n if (!this._existentialVariables) this._existentialVariables = []\n this._existentialVariables.push(x)\n return x\n }\n\n /**\n * @param features\n */\n initPropertyActions(features: FeaturesType) {\n // If the predicate is #type, use handleRDFType to create a typeCallback on the object\n this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'))] =\n [ handleRDFType ]\n\n // Assumption: these terms are not redirected @@fixme\n if (ArrayIndexOf(features, 'sameAs') >= 0) {\n this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${owlNamespaceURI}sameAs`))] = [\n function (formula, subj, pred, obj, why) {\n // log.warn(\"Equating \"+subj.uri+\" sameAs \"+obj.uri); //@@\n formula.equate(subj, obj)\n return true // true if statement given is NOT needed in the store\n }\n ] // sameAs -> equate & don't add to index\n }\n if (ArrayIndexOf(features, 'InverseFunctionalProperty') >= 0) {\n this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${owlNamespaceURI}InverseFunctionalProperty`))] = [\n function (formula, subj, pred, obj, addFn) {\n // yes subj not pred!\n return formula.newPropertyAction(subj, handleIFP)\n }\n ] // IFP -> handleIFP, do add to index\n }\n if (ArrayIndexOf(features, 'FunctionalProperty') >= 0) {\n this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${owlNamespaceURI}FunctionalProperty`))] = [\n function (formula, subj, proj, obj, addFn) {\n return formula.newPropertyAction(subj, handleFP)\n }\n ] // FP => handleFP, do add to index\n }\n }\n\n /** @deprecated Use {add} instead */\n addStatement (st: Quad): number {\n this.add(st.subject, st.predicate, st.object, st.graph)\n return this.statements.length\n }\n\n /**\n * Adds a triple (quad) to the store.\n *\n * @param subj - The thing about which the fact a relationship is asserted.\n * Also accepts a statement or an array of Statements.\n * @param pred - The relationship which is asserted\n * @param obj - The object of the relationship, e.g. another thing or a value. If passed a string, this will become a literal.\n * @param why - The document in which the triple (S,P,O) was or will be stored on the web\n * @returns The statement added to the store, or the store\n */\n add (\n subj: Quad_Subject | Quad | Quad[] | Statement | Statement[],\n pred?: Quad_Predicate,\n obj?: Term | string,\n why?: Quad_Graph\n ): Statement | null | this | number {\n var i: number\n if (arguments.length === 1) {\n if (subj instanceof Array) {\n for (i = 0; i < subj.length; i++) {\n this.add(subj[i])\n }\n } else if (isQuad(subj)) {\n this.add(subj.subject, subj.predicate, subj.object, subj.graph)\n } else if (isStore(subj)) {\n this.add((subj as any).statements)\n }\n return this\n }\n var actions: Function[]\n var st: Statement\n if (!why) {\n // system generated\n why = this.fetcher ? this.fetcher.appNode : this.rdfFactory.defaultGraph()\n }\n if (typeof subj == 'string') {\n subj = this.rdfFactory.namedNode(subj)\n }\n pred = Node.fromValue(pred)\n const objNode = Node.fromValue(obj) as Term\n why = Node.fromValue(why)\n if (!isSubject(subj)) {\n throw new Error('Subject is not a subject type')\n }\n if (!isPredicate(pred)) {\n throw new Error(`Predicate ${pred} is not a predicate type`)\n }\n if (!isRDFlibObject(objNode)) {\n throw new Error(`Object ${objNode} is not an object type`)\n }\n if (!isGraph(why)) {\n throw new Error(\"Why is not a graph type\")\n }\n //@ts-ignore This is not used internally\n if (this.predicateCallback) {\n //@ts-ignore This is not used internally\n this.predicateCallback(this, pred, why)\n }\n // Action return true if the statement does not need to be added\n var predHash = this.id(this.canon(pred!))\n actions = this.propertyActions[predHash] // Predicate hash\n var done = false\n if (actions) {\n // alert('type: '+typeof actions +' @@ actions='+actions)\n for (i = 0; i < actions.length; i++) {\n done = done || actions[i](this, subj, pred, objNode, why)\n }\n }\n if (this.holds(subj, pred, objNode, why)) { // Takes time but saves duplicates\n // console.log('rdflib: Ignoring dup! {' + subj + ' ' + pred + ' ' + obj + ' ' + why + '}')\n return null // @@better to return self in all cases?\n }\n // If we are tracking provenance, every thing should be loaded into the store\n // if (done) return this.rdfFactory.quad(subj, pred, obj, why)\n // Don't put it in the store\n // still return this statement for owl:sameAs input\n var hash = [\n this.id(this.canon(subj)),\n predHash,\n this.id(this.canon(objNode)),\n this.id(this.canon(why))\n ]\n // @ts-ignore this will fail if you pass a collection and the factory does not allow Collections\n st = this.rdfFactory.quad(subj, pred, objNode, why)\n for (i = 0; i < 4; i++) {\n var ix = this.index[i]\n var h = hash[i]\n if (!ix[h]) {\n ix[h] = []\n }\n ix[h].push(st) // Set of things with this as subject, etc\n }\n\n // log.debug(\"ADDING {\"+subj+\" \"+pred+\" \"+objNode+\"} \"+why)\n this.statements.push(st)\n\n if (this.dataCallbacks) {\n for (const callback of this.dataCallbacks) {\n callback(st)\n }\n }\n\n return st\n }\n\n /**\n * Returns the symbol with canonical URI as smushed\n * @param term - An RDF node\n */\n canon(term?: Term): Node {\n if (!term) {\n // @@ TODO Should improve this to return proper value - doing this to keep it backward compatible\n return term as unknown as Node\n }\n const y = this.redirections[this.id(term)]\n if (y) {\n return y\n }\n switch (term.termType) {\n case BlankNodeTermType:\n return new BlankNode(term.value)\n case CollectionTermType:\n return term as Collection // non-RDF/JS type, should just need to cast\n case DefaultGraphTermType:\n return new DefaultGraph()\n case EmptyTermType: // non-RDF/JS type, should just need to cast\n return term as Empty\n case GraphTermType: // non-RDF/JS type, should just need to cast\n return term as IndexedFormula\n case LiteralTermType:\n return new Literal(term.value, (term as TFLiteral).language, (term as TFLiteral).datatype)\n case NamedNodeTermType:\n return new NamedNode(term.value)\n case VariableTermType:\n return new Variable(term.value)\n default:\n throw new Error(`Term Type not recognized for canonization: ${term.termType}`)\n }\n }\n\n\n /**\n * Checks this formula for consistency\n */\n check(): void {\n this.checkStatementList(this.statements)\n for (var p = 0; p < 4; p++) {\n var ix = this.index[p]\n for (var key in ix) {\n if (ix.hasOwnProperty(key)) {\n // @ts-ignore should this pass an array or a single statement? checkStateMentsList expects an array.\n this.checkStatementList(ix[key], p)\n }\n }\n }\n }\n\n /**\n * Checks a list of statements for consistency\n * @param sts - The list of statements to check\n * @param from - An index with the array ['subject', 'predicate', 'object', 'why']\n */\n checkStatementList(\n sts: ReadonlyArray<Quad>,\n from?: number\n ): boolean | void {\n if (from === undefined) {\n from = 0\n }\n var names = ['subject', 'predicate', 'object', 'why']\n var origin = ' found in ' + names[from] + ' index.'\n var st: Quad\n for (var j = 0; j < sts.length; j++) {\n st = sts[j]\n var term = [ st.subject, st.predicate, st.object, st.graph ]\n var arrayContains = function (a: Array<any>, x: Quad) {\n for (var i = 0; i < a.length; i++) {\n if (a[i].subject.equals(x.subject) &&\n a[i].predicate.equals(x.predicate) &&\n a[i].object.equals(x.object) &&\n a[i].why.equals(x.graph)) {\n return true\n }\n }\n }\n for (var p = 0; p < 4; p++) {\n var c = this.canon(term[p])\n var h = this.id(c)\n if (!this.index[p][h]) {\n // throw new Error('No ' + name[p] + ' index for statement ' + st + '@' + st.why + origin)\n } else {\n if (!arrayContains(this.index[p][h], st)) {\n // throw new Error('Index for ' + name[p] + ' does not have statement ' + st + '@' + st.why + origin)\n }\n }\n }\n if (!arrayContains(this.statements, st)) {\n throw new Error('Statement list does not statement ' + st + '@' + st.graph + origin)\n }\n }\n }\n\n /**\n * Closes this formula (and return it)\n */\n close(): IndexedFormula {\n return this\n }\n\n compareTerms(u1: Term, u2: Term): number {\n // Keep compatibility with downstream classOrder changes\n if (Object.prototype.hasOwnProperty.call(u1, \"compareTerm\")) {\n return (u1 as Node).compareTerm(u2 as Node)\n }\n if (ClassOrder[u1.termType] < ClassOrder[u2.termType]) {\n return -1\n }\n if (ClassOrder[u1.termType] > ClassOrder[u2.termType]) {\n return +1\n }\n if (u1.value < u2.value) {\n return -1\n }\n if (u1.value > u2.value) {\n return +1\n }\n return 0\n }\n\n\n /**\n * replaces @template with @target and add appropriate triples\n * removes no triples by default and is a one-direction replication\n * @param template node to copy\n * @param target node to copy to\n * @param flags Whether or not to do a two-directional copy and/or delete triples\n */\n copyTo(\n template: Quad_Subject,\n target: Quad_Subject,\n flags?: Array<('two-direction' | 'delete')>\n ): void {\n if (!flags) flags = []\n var statList = this.statementsMatching(template)\n if (ArrayIndexOf(flags, 'two-direction') !== -1) {\n statList.concat(this.statementsMatching(undefined, undefined, template))\n }\n for (var i = 0; i < statList.length; i++) {\n var st = statList[i]\n switch (st.object.termType) {\n case 'NamedNode':\n this.add(target, st.predicate, st.object)\n break\n case 'Literal':\n case 'BlankNode':\n // @ts-ignore Collections can appear here\n case 'Collection':\n // @ts-ignore Possible bug: copy is not available on Collections\n this.add(target, st.predicate, st.object.copy(this))\n }\n if (ArrayIndexOf(flags, 'delete') !== -1) {\n this.remove(st)\n }\n }\n }\n\n /**\n * Simplify graph in store when we realize two identifiers are equivalent\n * We replace the bigger with the smaller.\n * @param u1in The first node\n * @param u2in The second node\n */\n equate(u1in: Term, u2in : Term): boolean {\n // log.warn(\"Equating \"+u1+\" and \"+u2); // @@\n // @@JAMBO Must canonicalize the uris to prevent errors from a=b=c\n // 03-21-2010\n const u1 = this.canon(u1in) as Quad_Subject\n const u2 = this.canon(u2in) as Quad_Subject\n var d = this.compareTerms(u1, u2)\n if (!d) {\n return true // No information in {a = a}\n }\n // var big\n // var small\n if (d < 0) { // u1 less than u2\n return this.replaceWith(u2, u1)\n } else {\n return this.replaceWith(u1, u2)\n }\n }\n\n /**\n * Creates a new empty indexed formula\n * Only applicable for IndexedFormula, but TypeScript won't allow a subclass to override a property\n * @param features The list of features\n */\n formula(features: FeaturesType): IndexedFormula {\n return new IndexedFormula(features)\n }\n\n /**\n * Returns the number of statements contained in this IndexedFormula.\n * (Getter proxy to this.statements).\n * Usage:\n * ```\n * var kb = rdf.graph()\n * kb.length // -> 0\n * ```\n * @returns {Number}\n */\n get length (): number {\n return this.statements.length\n }\n\n /**\n * Returns any quads matching the given arguments.\n * Standard RDFJS spec method for Source objects, implemented as an\n * alias to `statementsMatching()`\n * @param subject The subject\n * @param predicate The predicate\n * @param object The object\n * @param graph The graph that contains the statement\n */\n match(\n subject?: Quad_Subject | null,\n predicate?: Quad_Predicate | null,\n object?: Quad_Object | null,\n graph?: Quad_Graph | null\n ): Quad[] {\n return this.statementsMatching(\n Node.fromValue(subject),\n Node.fromValue(predicate),\n Node.fromValue(object),\n Node.fromValue(graph)\n )\n }\n\n /**\n * Find out whether a given URI is used as symbol in the formula\n * @param uri The URI to look for\n */\n mentionsURI(uri: string): boolean {\n var hash = '<' + uri + '>'\n return (!!this.subjectIndex[hash] ||\n !!this.objectIndex[hash] ||\n !!this.predicateIndex[hash])\n }\n\n /**\n * Existentials are BNodes - something exists without naming\n * @param uri An URI\n */\n newExistential(uri: string): Term {\n if (!uri) return this.bnode()\n var x = this.sym(uri)\n // @ts-ignore x should be blanknode, but is namedNode.\n return this.declareExistential(x)\n }\n\n /**\n * Adds a new property action\n * @param pred the predicate that the function should be triggered on\n * @param action the function that should trigger\n */\n newPropertyAction(\n pred: Quad_Predicate,\n action: (\n store: IndexedFormula,\n subject: Quad_Subject,\n predicate: Quad_Predicate,\n object: Quad_Object\n ) => boolean\n ): boolean {\n // log.debug(\"newPropertyAction: \"+pred)\n var hash = this.id(pred)\n if (!this.propertyActions[hash]) {\n this.propertyActions[hash] = []\n }\n this.propertyActions[hash].push(action)\n // Now apply the function to to statements already in the store\n var toBeFixed = this.statementsMatching(undefined, pred, undefined)\n var done = false\n for (var i = 0; i < toBeFixed.length; i++) { // NOT optimized - sort toBeFixed etc\n done = done || action(this, toBeFixed[i].subject, pred, toBeFixed[i].object)\n }\n return done\n }\n\n /**\n * Creates a new universal node\n * Universals are Variables\n * @param uri An URI\n */\n newUniversal(uri: string): TFNamedNode {\n var x = this.sym(uri)\n if (!this._universalVariables) this._universalVariables = []\n this._universalVariables.push(x)\n return x\n }\n\n // convenience function used by N3 parser\n variable (name: string) {\n return new Variable(name)\n }\n\n /**\n * Find an unused id for a file being edited: return a symbol\n * (Note: Slow iff a lot of them -- could be O(log(k)) )\n * @param doc A document named node\n */\n nextSymbol(doc: TFNamedNode): TFNamedNode {\n for (var i = 0; ;i++) {\n var uri = doc.value + '#n' + i\n if (!this.mentionsURI(uri)) return this.sym(uri)\n }\n }\n\n /**\n * Query this store asynchronously, return bindings in callback\n *\n * @param myQuery The query to be run\n * @param callback Function to call when bindings\n * @param Fetcher | null If you want the query to do link following\n * @param onDone OBSOLETE - do not use this // @@ Why not ?? Called when query complete\n */\n query(\n myQuery: Query,\n callback: (bindings: Bindings) => void,\n fetcher?: Fetcher | null,\n onDone?: () => void\n ): void {\n return indexedFormulaQuery.call(this, myQuery, callback, fetcher, onDone)\n }\n\n /**\n * Query this store synchronously and return bindings\n *\n * @param myQuery The query to be run\n */\n querySync(myQuery: Query): any[] {\n var results: Bindings[] = []\n function saveBinginds (bindings: Bindings) {\n results.push(bindings)\n }\n function onDone () {\n done = true\n }\n var done = false\n // @ts-ignore TODO: Add .sync to Query\n myQuery.sync = true\n\n indexedFormulaQuery.call(this, myQuery, saveBinginds, null, onDone)\n if (!done) {\n throw new Error('Sync query should have called done function')\n }\n return results\n }\n\n /**\n * Removes one or multiple statement(s) from this formula\n * @param st - A Statement or array of Statements to remove\n */\n remove(st: Quad | Quad[]): IndexedFormula {\n if (st instanceof Array) {\n for (var i = 0; i < st.length; i++) {\n this.remove(st[i])\n }\n return this\n }\n if (isStore(st)) {\n return this.remove(st.statements)\n }\n var sts = this.statementsMatching(st.subject, st.predicate, st.object, st.graph)\n if (!sts.length) {\n throw new Error('Statement to be removed is not on store: ' + st)\n }\n this.removeStatement(sts[0])\n return this\n }\n\n /**\n * Removes all statements in a doc\n * @param doc - The document / graph\n */\n removeDocument(doc: Quad_Graph): IndexedFormula {\n var sts: Quad[] = this.statementsMatching(undefined, undefined, undefined, doc).slice() // Take a copy as this is the actual index\n for (var i = 0; i < sts.length; i++) {\n this.removeStatement(sts[i])\n }\n return this\n }\n\n /**\n * Remove all statements matching args (within limit) *\n * @param subj The subject\n * @param pred The predicate\n * @param obj The object\n * @param why The graph that contains the statement\n * @param limit The number of statements to remove\n */\n removeMany(\n subj?: Quad_Subject | null,\n pred?: Quad_Predicate | null,\n obj?: Quad_Object | null,\n why?: Quad_Graph | null,\n limit?: number\n ): void {\n // log.debug(\"entering removeMany w/ subj,pred,obj,why,limit = \" + subj +\", \"+ pred+\", \" + obj+\", \" + why+\", \" + limit)\n var sts = this.statementsMatching(subj, pred, obj, why, false)\n // This is a subtle bug that occurred in updateCenter.js too.\n // The fact is, this.statementsMatching returns this.whyIndex instead of a copy of it\n // but for perfromance consideration, it's better to just do that\n // so make a copy here.\n var statements: Quad[] = []\n for (var i = 0; i < sts.length; i++) statements.push(sts[i])\n if (limit) statements = statements.slice(0, limit)\n for (i = 0; i < statements.length; i++) this.remove(statements[i])\n }\n\n /**\n * Remove all matching statements\n * @param subject The subject\n * @param predicate The predicate\n * @param object The object\n * @param graph The graph that contains the statement\n */\n removeMatches(\n subject?: Quad_Subject | null,\n predicate?: Quad_Predicate | null,\n object?: Quad_Object | null,\n graph?: Quad_Graph | null\n ): IndexedFormula {\n this.removeStatements(\n this.statementsMatching(subject, predicate, object, graph)\n )\n return this\n }\n\n /**\n * Remove a particular statement object from the store\n *\n * @param st - a statement which is already in the store and indexed.\n * Make sure you only use this for these.\n * Otherwise, you should use remove() above.\n */\n removeStatement(st: Quad): IndexedFormula {\n // log.debug(\"entering remove w/ st=\" + st)\n var term = [ st.subject, st.predicate, st.object, st.graph ]\n for (var p = 0; p < 4; p++) {\n var c = this.canon(term[p])\n var h = this.id(c)\n if (!this.index[p][h]) {\n // log.warn (\"Statement removal: no index '+p+': \"+st)\n } else {\n this.rdfArrayRemove(this.index[p][h], st)\n }\n }\n this.rdfArrayRemove(this.statements, st)\n return this\n }\n\n /**\n * Removes statements\n * @param sts The statements to remove\n */\n removeStatements(sts: ReadonlyArray<Quad>): IndexedFormula {\n for (var i = 0; i < sts.length; i++) {\n this.remove(sts[i])\n }\n return this\n }\n\n /**\n * Replace big with small, obsoleted with obsoleting.\n */\n replaceWith (big: Quad_Subject, small: Quad_Subject): boolean {\n // log.debug(\"Replacing \"+big+\" with \"+small) // this.id(@@\n var oldhash = this.id(big)\n var newhash = this.id(small)\n var moveIndex = function (ix) {\n var oldlist = ix[oldhash]\n if (!oldlist) {\n return // none to move\n }\n var newlist = ix[newhash]\n if (!newlist) {\n ix[newhash] = oldlist\n } else {\n ix[newhash] = oldlist.concat(newlist)\n }\n delete ix[oldhash]\n }\n // the canonical one carries all the indexes\n for (var i = 0; i < 4; i++) {\n moveIndex(this.index[i])\n }\n this.redirections[oldhash] = small\n if (big.value) {\n // @@JAMBO: must update redirections,aliases from sub-items, too.\n if (!this.aliases[newhash]) {\n this.aliases[newhash] = []\n }\n this.aliases[newhash].push(big) // Back link\n if (this.aliases[oldhash]) {\n for (i = 0; i < this.aliases[oldhash].length; i++) {\n this.redirections[this.id(this.aliases[oldhash][i])] = small\n this.aliases[newhash].push(this.aliases[oldhash][i])\n }\n }\n this.add(small, this.sym('http://www.w3.org/2007/ont/link#uri'), big)\n // If two things are equal, and one is requested, we should request the other.\n if (this.fetcher) {\n this.fetcher.nowKnownAs(big, small)\n }\n }\n moveIndex(this.classActions)\n moveIndex(this.propertyActions)\n // log.debug(\"Equate done. \"+big+\" to be known as \"+small)\n return true // true means the statement does not need to be put in\n }\n\n /**\n * Return all equivalent URIs by which this is known\n * @param x A named node\n */\n allAliases(x: NamedNode): NamedNode[] {\n var a = this.aliases[this.id(this.canon(x))] || []\n a.push(this.canon(x))\n return a\n }\n\n /**\n * Compare by canonical URI as smushed\n * @param x A named node\n * @param y Another named node\n */\n sameThings(x: NamedNode, y: NamedNode): boolean {\n if (x.equals(y)) {\n return true\n }\n var x1 = this.canon(x)\n // alert('x1='+x1)\n if (!x1) return false\n var y1 = this.canon(y)\n // alert('y1='+y1); //@@\n if (!y1) return false\n return (x1.value === y1.value)\n }\n\n setPrefixForURI (prefix: string, nsuri: string): void {\n // TODO: This is a hack for our own issues, which ought to be fixed\n // post-release\n // See http://dig.csail.mit.edu/cgi-bin/roundup.cgi/$rdf/issue227\n if (prefix === 'tab' && this.namespaces['tab']) {\n return\n } // There are files around with long badly generated prefixes like this\n if (prefix.slice(0, 2) === 'ns' || prefix.slice(0, 7) === 'default') {\n return\n }\n this.namespaces[prefix] = nsuri\n }\n\n /** Search the Store\n *\n * ALL CONVENIENCE LOOKUP FUNCTIONS RELY ON THIS!\n * @param subj - A node to search for as subject, or if null, a wildcard\n * @param pred - A node to search for as predicate, or if null, a wildcard\n * @param obj - A node to search for as object, or if null, a wildcard\n * @param why - A node to search for as graph, or if null, a wildcard\n * @param justOne - flag - stop when found one rather than get all of them?\n * @returns An array of nodes which match the wildcard position\n */\n statementsMatching (\n subj?: Quad_Subject | null,\n pred?: Quad_Predicate | null,\n obj?: Quad_Object | null,\n why?: Quad_Graph | null,\n justOne?: boolean\n ): Statement[] {\n // log.debug(\"Matching {\"+subj+\" \"+pred+\" \"+obj+\"}\")\n var pat = [ subj, pred, obj, why ]\n var pattern: Term[] = []\n var hash: Indexable[] = []\n var wild: number[] = [] // wildcards\n var given: number[] = [] // Not wild\n var p: number\n var list\n for (p = 0; p < 4; p++) {\n pattern[p] = this.canon(Node.fromValue(pat[p]))\n if (!pattern[p]) {\n wild.push(p)\n } else {\n given.push(p)\n hash[p] = this.id(pattern[p])\n }\n }\n if (given.length === 0) {\n return this.statements\n }\n if (given.length === 1) { // Easy too, we have an index for that\n p = given[0]\n list = this.index[p][hash[p]]\n if (list && justOne) {\n if (list.length > 1) {\n list = list.slice(0, 1)\n }\n }\n list = list || []\n return list\n }\n // Now given.length is 2, 3 or 4.\n // We hope that the scale-free nature of the data will mean we tend to get\n // a short index in there somewhere!\n var best = 1e10 // really bad\n var iBest\n var i\n for (i = 0; i < given.length; i++) {\n p = given[i] // Which part we are dealing with\n list = this.index[p][hash[p]]\n if (!list) {\n return [] // No occurrences\n }\n if (list.length < best) {\n best = list.length\n iBest = i // (not p!)\n }\n }\n // Ok, we have picked the shortest index but now we have to filter it\n var pBest = given[iBest]\n var possibles: Statement[] = this.index[pBest][hash[pBest]]\n var check = given.slice(0, iBest).concat(given.slice(iBest + 1)) // remove iBest\n var results: Statement[] = []\n var parts = [ 'subject', 'predicate', 'object', 'why' ]\n for (var j = 0; j < possibles.length; j++) {\n var st: Statement | null = possibles[j]\n\n for (i = 0; i < check.length; i++) { // for each position to be checked\n p = check[i]\n if (!this.canon(st[parts[p]]).equals(pattern[p])) {\n st = null\n break\n }\n }\n if (st != null) {\n results.push(st)\n if (justOne) break\n }\n }\n return results\n }\n\n /**\n * A list of all the URIs by which this thing is known\n * @param term\n */\n uris(term: Quad_Subject): string[] {\n var cterm = this.canon(term)\n var terms = this.aliases[this.id(cterm)]\n if (!cterm.value) return []\n var res = [ cterm.value ]\n if (terms) {\n for (var i = 0; i < terms.length; i++) {\n res.push(terms[i].uri)\n }\n }\n return res\n }\n}\nIndexedFormula.handleRDFType = handleRDFType\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nmodule.exports = class JsonLdError extends Error {\n /**\n * Creates a JSON-LD Error.\n *\n * @param msg the error message.\n * @param type the error type.\n * @param details the error details.\n */\n constructor(\n message = 'An unspecified JSON-LD error occurred.',\n name = 'jsonld.Error',\n details = {}) {\n super(message);\n this.name = name;\n this.message = message;\n this.details = details;\n }\n};\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst types = require('./types');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Returns true if the given value is a subject with properties.\n *\n * @param v the value to check.\n *\n * @return true if the value is a subject with properties, false if not.\n */\napi.isSubject = v => {\n // Note: A value is a subject if all of these hold true:\n // 1. It is an Object.\n // 2. It is not a @value, @set, or @list.\n // 3. It has more than 1 key OR any existing key is not @id.\n if(types.isObject(v) &&\n !(('@value' in v) || ('@set' in v) || ('@list' in v))) {\n const keyCount = Object.keys(v).length;\n return (keyCount > 1 || !('@id' in v));\n }\n return false;\n};\n\n/**\n * Returns true if the given value is a subject reference.\n *\n * @param v the value to check.\n *\n * @return true if the value is a subject reference, false if not.\n */\napi.isSubjectReference = v =>\n // Note: A value is a subject reference if all of these hold true:\n // 1. It is an Object.\n // 2. It has a single key: @id.\n (types.isObject(v) && Object.keys(v).length === 1 && ('@id' in v));\n\n/**\n * Returns true if the given value is a @value.\n *\n * @param v the value to check.\n *\n * @return true if the value is a @value, false if not.\n */\napi.isValue = v =>\n // Note: A value is a @value if all of these hold true:\n // 1. It is an Object.\n // 2. It has the @value property.\n types.isObject(v) && ('@value' in v);\n\n/**\n * Returns true if the given value is a @list.\n *\n * @param v the value to check.\n *\n * @return true if the value is a @list, false if not.\n */\napi.isList = v =>\n // Note: A value is a @list if all of these hold true:\n // 1. It is an Object.\n // 2. It has the @list property.\n types.isObject(v) && ('@list' in v);\n\n/**\n * Returns true if the given value is a @graph.\n *\n * @return true if the value is a @graph, false if not.\n */\napi.isGraph = v => {\n // Note: A value is a graph if all of these hold true:\n // 1. It is an object.\n // 2. It has an `@graph` key.\n // 3. It may have '@id' or '@index'\n return types.isObject(v) &&\n '@graph' in v &&\n Object.keys(v)\n .filter(key => key !== '@id' && key !== '@index').length === 1;\n};\n\n/**\n * Returns true if the given value is a simple @graph.\n *\n * @return true if the value is a simple @graph, false if not.\n */\napi.isSimpleGraph = v => {\n // Note: A value is a simple graph if all of these hold true:\n // 1. It is an object.\n // 2. It has an `@graph` key.\n // 3. It has only 1 key or 2 keys where one of them is `@index`.\n return api.isGraph(v) && !('@id' in v);\n};\n\n/**\n * Returns true if the given value is a blank node.\n *\n * @param v the value to check.\n *\n * @return true if the value is a blank node, false if not.\n */\napi.isBlankNode = v => {\n // Note: A value is a blank node if all of these hold true:\n // 1. It is an Object.\n // 2. If it has an @id key its value begins with '_:'.\n // 3. It has no keys OR is not a @value, @set, or @list.\n if(types.isObject(v)) {\n if('@id' in v) {\n return (v['@id'].indexOf('_:') === 0);\n }\n return (Object.keys(v).length === 0 ||\n !(('@value' in v) || ('@set' in v) || ('@list' in v)));\n }\n return false;\n};\n","// Prevents circular dependencies between data-factory-internal and statement\n\nimport NamedNode from '../named-node'\n\nexport const defaultGraphURI = 'chrome:theSession'\nexport const defaultGraphNode = new NamedNode(defaultGraphURI)\n","import RdflibBlankNode from './blank-node'\nimport ClassOrder from './class-order'\nimport Literal from './literal'\nimport Node from './node-internal'\nimport {\n Bindings,\n CollectionTermType,\n FromValueReturns,\n ValueType\n} from './types'\nimport Variable from './variable'\nimport { isTerm } from './utils/terms'\nimport { Term } from './tf-types'\n\n/**\n * Creates an RDF Node from a native javascript value.\n * RDF Nodes are returned unchanged, undefined returned as itself.\n * Arrays return Collections.\n * Strings, numbers and booleans return Literals.\n * @param value {Node|Date|String|Number|Boolean|Undefined}\n * @return {Node|Collection}\n */\nexport function fromValue <T extends FromValueReturns<C> = any, C extends Node = any>(value: ValueType): T {\n if (typeof value === 'undefined' || value === null) {\n return value as T\n }\n\n if (isTerm(value)) { // a Node subclass or a Collection\n return value as T\n }\n\n if (Array.isArray(value)) {\n return new Collection<C>(value) as T\n }\n\n return Literal.fromValue<any>(value)\n}\n\n/**\n * A collection of other RDF nodes\n *\n * Use generic T to control the contents of the array.\n */\nexport default class Collection<\n T extends Node = Node | RdflibBlankNode | Collection<any> | Literal | Variable\n> extends Node implements Term {\n static termType: typeof CollectionTermType = CollectionTermType\n termType: typeof CollectionTermType = CollectionTermType\n\n classOrder = ClassOrder.Collection\n closed: boolean = false\n compareTerm = RdflibBlankNode.prototype.compareTerm\n /**\n * The nodes in this collection\n */\n elements: T[] = []\n isVar = 0\n\n constructor (initial?: ReadonlyArray<ValueType>) {\n super((RdflibBlankNode.nextId++).toString())\n\n if (initial && initial.length > 0) {\n initial.forEach(element => {\n this.elements.push(fromValue<T>(element))\n })\n }\n }\n\n public get id (): string {\n return this.value\n }\n\n public set id (value) {\n this.value = value\n }\n\n /**\n * Appends an element to this collection\n * @param element - The new element\n */\n append (element: T): number {\n return this.elements.push(element)\n }\n\n /**\n * Closes this collection\n */\n close (): boolean {\n this.closed = true\n return this.closed\n }\n\n /**\n * Removes the first element from the collection (and return it)\n */\n shift (): T | undefined {\n return this.elements.shift()\n }\n\n /**\n * Creates a new Collection with the substituting bindings applied\n * @param bindings - The bindings to substitute\n */\n substitute (bindings: Bindings) {\n const elementsCopy = this.elements.map((ea) => ea.substitute(bindings))\n\n return new Collection(elementsCopy) as Collection<Node | Collection<any> | Literal | Variable>\n }\n\n toNT () {\n return Collection.toNT(this)\n }\n\n static toNT (collection) {\n return RdflibBlankNode.NTAnonymousNodePrefix + collection.id\n }\n\n /**\n * Serializes the collection to a string.\n * Surrounded by (parentheses) and separated by spaces.\n */\n toString () {\n return '(' + this.elements.join(' ') + ')'\n }\n\n /**\n * Prepends the specified element to the collection's front\n * @param element - The element to prepend\n */\n unshift (element: T): number {\n return this.elements.unshift(element)\n }\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst types = require('./types');\n\nconst api = {};\nmodule.exports = api;\n\n// define URL parser\n// parseUri 1.2.2\n// (c) Steven Levithan <stevenlevithan.com>\n// MIT License\n// with local jsonld.js modifications\napi.parsers = {\n simple: {\n // RFC 3986 basic parts\n keys: [\n 'href', 'scheme', 'authority', 'path', 'query', 'fragment'\n ],\n /* eslint-disable-next-line max-len */\n regex: /^(?:([^:\\/?#]+):)?(?:\\/\\/([^\\/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?/\n },\n full: {\n keys: [\n 'href', 'protocol', 'scheme', 'authority', 'auth', 'user', 'password',\n 'hostname', 'port', 'path', 'directory', 'file', 'query', 'fragment'\n ],\n /* eslint-disable-next-line max-len */\n regex: /^(([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?(?:(((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/\n }\n};\napi.parse = (str, parser) => {\n const parsed = {};\n const o = api.parsers[parser || 'full'];\n const m = o.regex.exec(str);\n let i = o.keys.length;\n while(i--) {\n parsed[o.keys[i]] = (m[i] === undefined) ? null : m[i];\n }\n\n // remove default ports in found in URLs\n if((parsed.scheme === 'https' && parsed.port === '443') ||\n (parsed.scheme === 'http' && parsed.port === '80')) {\n parsed.href = parsed.href.replace(':' + parsed.port, '');\n parsed.authority = parsed.authority.replace(':' + parsed.port, '');\n parsed.port = null;\n }\n\n parsed.normalizedPath = api.removeDotSegments(parsed.path);\n return parsed;\n};\n\n/**\n * Prepends a base IRI to the given relative IRI.\n *\n * @param base the base IRI.\n * @param iri the relative IRI.\n *\n * @return the absolute IRI.\n */\napi.prependBase = (base, iri) => {\n // skip IRI processing\n if(base === null) {\n return iri;\n }\n // already an absolute IRI\n if(api.isAbsolute(iri)) {\n return iri;\n }\n\n // parse base if it is a string\n if(!base || types.isString(base)) {\n base = api.parse(base || '');\n }\n\n // parse given IRI\n const rel = api.parse(iri);\n\n // per RFC3986 5.2.2\n const transform = {\n protocol: base.protocol || ''\n };\n\n if(rel.authority !== null) {\n transform.authority = rel.authority;\n transform.path = rel.path;\n transform.query = rel.query;\n } else {\n transform.authority = base.authority;\n\n if(rel.path === '') {\n transform.path = base.path;\n if(rel.query !== null) {\n transform.query = rel.query;\n } else {\n transform.query = base.query;\n }\n } else {\n if(rel.path.indexOf('/') === 0) {\n // IRI represents an absolute path\n transform.path = rel.path;\n } else {\n // merge paths\n let path = base.path;\n\n // append relative path to the end of the last directory from base\n path = path.substr(0, path.lastIndexOf('/') + 1);\n if((path.length > 0 || base.authority) && path.substr(-1) !== '/') {\n path += '/';\n }\n path += rel.path;\n\n transform.path = path;\n }\n transform.query = rel.query;\n }\n }\n\n if(rel.path !== '') {\n // remove slashes and dots in path\n transform.path = api.removeDotSegments(transform.path);\n }\n\n // construct URL\n let rval = transform.protocol;\n if(transform.authority !== null) {\n rval += '//' + transform.authority;\n }\n rval += transform.path;\n if(transform.query !== null) {\n rval += '?' + transform.query;\n }\n if(rel.fragment !== null) {\n rval += '#' + rel.fragment;\n }\n\n // handle empty base\n if(rval === '') {\n rval = './';\n }\n\n return rval;\n};\n\n/**\n * Removes a base IRI from the given absolute IRI.\n *\n * @param base the base IRI.\n * @param iri the absolute IRI.\n *\n * @return the relative IRI if relative to base, otherwise the absolute IRI.\n */\napi.removeBase = (base, iri) => {\n // skip IRI processing\n if(base === null) {\n return iri;\n }\n\n if(!base || types.isString(base)) {\n base = api.parse(base || '');\n }\n\n // establish base root\n let root = '';\n if(base.href !== '') {\n root += (base.protocol || '') + '//' + (base.authority || '');\n } else if(iri.indexOf('//')) {\n // support network-path reference with empty base\n root += '//';\n }\n\n // IRI not relative to base\n if(iri.indexOf(root) !== 0) {\n return iri;\n }\n\n // remove root from IRI and parse remainder\n const rel = api.parse(iri.substr(root.length));\n\n // remove path segments that match (do not remove last segment unless there\n // is a hash or query)\n const baseSegments = base.normalizedPath.split('/');\n const iriSegments = rel.normalizedPath.split('/');\n const last = (rel.fragment || rel.query) ? 0 : 1;\n while(baseSegments.length > 0 && iriSegments.length > last) {\n if(baseSegments[0] !== iriSegments[0]) {\n break;\n }\n baseSegments.shift();\n iriSegments.shift();\n }\n\n // use '../' for each non-matching base segment\n let rval = '';\n if(baseSegments.length > 0) {\n // don't count the last segment (if it ends with '/' last path doesn't\n // count and if it doesn't end with '/' it isn't a path)\n baseSegments.pop();\n for(let i = 0; i < baseSegments.length; ++i) {\n rval += '../';\n }\n }\n\n // prepend remaining segments\n rval += iriSegments.join('/');\n\n // add query and hash\n if(rel.query !== null) {\n rval += '?' + rel.query;\n }\n if(rel.fragment !== null) {\n rval += '#' + rel.fragment;\n }\n\n // handle empty base\n if(rval === '') {\n rval = './';\n }\n\n return rval;\n};\n\n/**\n * Removes dot segments from a URL path.\n *\n * @param path the path to remove dot segments from.\n */\napi.removeDotSegments = path => {\n // RFC 3986 5.2.4 (reworked)\n\n // empty path shortcut\n if(path.length === 0) {\n return '';\n }\n\n const input = path.split('/');\n const output = [];\n\n while(input.length > 0) {\n const next = input.shift();\n const done = input.length === 0;\n\n if(next === '.') {\n if(done) {\n // ensure output has trailing /\n output.push('');\n }\n continue;\n }\n\n if(next === '..') {\n output.pop();\n if(done) {\n // ensure output has trailing /\n output.push('');\n }\n continue;\n }\n\n output.push(next);\n }\n\n // if path was absolute, ensure output has leading /\n if(path[0] === '/' && output.length > 0 && output[0] !== '') {\n output.unshift('');\n }\n if(output.length === 1 && output[0] === '') {\n return '/';\n }\n\n return output.join('/');\n};\n\n// TODO: time better isAbsolute/isRelative checks using full regexes:\n// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html\n\n// regex to check for absolute IRI (starting scheme and ':') or blank node IRI\nconst isAbsoluteRegex = /^([A-Za-z][A-Za-z0-9+-.]*|_):[^\\s]*$/;\n\n/**\n * Returns true if the given value is an absolute IRI or blank node IRI, false\n * if not.\n * Note: This weak check only checks for a correct starting scheme.\n *\n * @param v the value to check.\n *\n * @return true if the value is an absolute IRI, false if not.\n */\napi.isAbsolute = v => types.isString(v) && isAbsoluteRegex.test(v);\n\n/**\n * Returns true if the given value is a relative IRI, false if not.\n * Note: this is a weak check.\n *\n * @param v the value to check.\n *\n * @return true if the value is a relative IRI, false if not.\n */\napi.isRelative = v => types.isString(v);\n","/**\n*\n* UTF-8 data encode / decode\n* http://www.webtoolkit.info/\n*\n**/\nimport * as Uri from './uri'\nimport { ArrayIndexOf } from './utils'\n\nfunction hexify (str) { // also used in parser\n return encodeURI(str);\n}\n\nvar Utf8 = {\n // public method for url encoding\n encode : function (string) {\n string = string.replace(/\\r\\n/g,\"\\n\");\n var utftext = \"\";\n\n for (var n = 0; n < string.length; n++) {\n\n var c = string.charCodeAt(n);\n\n if (c < 128) {\n utftext += String.fromCharCode(c);\n }\n else if((c > 127) && (c < 2048)) {\n utftext += String.fromCharCode((c >> 6) | 192);\n utftext += String.fromCharCode((c & 63) | 128);\n }\n else {\n utftext += String.fromCharCode((c >> 12) | 224);\n utftext += String.fromCharCode(((c >> 6) & 63) | 128);\n utftext += String.fromCharCode((c & 63) | 128);\n }\n\n }\n\n return utftext;\n },\n // public method for url decoding\n decode : function (utftext) {\n var string = \"\";\n var i = 0;\n\n while ( i < utftext.length ) {\n\n var c = utftext.charCodeAt(i);\n if (c < 128) {\n string += String.fromCharCode(c);\n i++;\n }\n else if((c > 191) && (c < 224)) {\n string += String.fromCharCode(((c & 31) << 6)\n | (utftext.charCodeAt(i+1) & 63));\n i += 2;\n }\n else {\n string += String.fromCharCode(((c & 15) << 12)\n | ((utftext.charCodeAt(i+1) & 63) << 6)\n | (utftext.charCodeAt(i+2) & 63));\n i += 3;\n }\n }\n return string;\n }\n}// Things we need to define to make converted pythn code work in js\n// environment of $rdf\n\nvar RDFSink_forSomeSym = \"http://www.w3.org/2000/10/swap/log#forSome\";\nvar RDFSink_forAllSym = \"http://www.w3.org/2000/10/swap/log#forAll\";\nvar Logic_NS = \"http://www.w3.org/2000/10/swap/log#\";\n\n// pyjs seems to reference runtime library which I didn't find\n\nvar pyjslib_Tuple = function(theList) { return theList };\n\nvar pyjslib_List = function(theList) { return theList };\n\nvar pyjslib_Dict = function(listOfPairs) {\n if (listOfPairs.length > 0)\n\tthrow \"missing.js: oops nnonempty dict not imp\";\n return [];\n}\n\nvar pyjslib_len = function(s) { return s.length }\n\nvar pyjslib_slice = function(str, i, j) {\n if (typeof str.slice == 'undefined')\n throw '@@ mising.js: No .slice function for '+str+' of type '+(typeof str)\n if ((typeof j == 'undefined') || (j ==null)) return str.slice(i);\n return str.slice(i, j) // @ exactly the same spec?\n}\nvar StopIteration = Error('dummy error stop iteration');\n\nvar pyjslib_Iterator = function(theList) {\n this.last = 0;\n this.li = theList;\n this.next = function() {\n\tif (this.last == this.li.length) throw StopIteration;\n\treturn this.li[this.last++];\n }\n return this;\n};\n\nvar ord = function(str) {\n return str.charCodeAt(0)\n}\n\nvar string_find = function(str, s) {\n return str.indexOf(s)\n}\n\nvar assertFudge = function(condition, desc) {\n if (condition) return;\n if (desc) throw \"python Assertion failed: \"+desc;\n throw \"(python) Assertion failed.\";\n}\n\n\nvar stringFromCharCode = function(uesc) {\n return String.fromCharCode(uesc);\n}\n\n\nString.prototype.encode = function(encoding) {\n if (encoding != 'utf-8') throw \"UTF8_converter: can only do utf-8\"\n return Utf8.encode(this);\n}\nString.prototype.decode = function(encoding) {\n if (encoding != 'utf-8') throw \"UTF8_converter: can only do utf-8\"\n //return Utf8.decode(this);\n return this;\n}\n\n\n\nvar uripath_join = function(base, given) {\n return Uri.join(given, base) // sad but true\n}\n\nvar becauseSubexpression = null; // No reason needed\nvar diag_tracking = 0;\nvar diag_chatty_flag = 0;\nvar diag_progress = function(str) { /*$rdf.log.debug(str);*/ }\n\n// why_BecauseOfData = function(doc, reason) { return doc };\n\n\nvar RDF_type_URI = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\";\nvar DAML_sameAs_URI = \"http://www.w3.org/2002/07/owl#sameAs\";\n\n/*\nfunction SyntaxError(details) {\n return new __SyntaxError(details);\n}\n*/\n\nfunction __SyntaxError(details) {\n this.details = details\n}\n\n/*\n\n$Id: n3parser.js 14561 2008-02-23 06:37:26Z kennyluck $\n\nHAND EDITED FOR CONVERSION TO JAVASCRIPT\n\nThis module implements a Nptation3 parser, and the final\npart of a notation3 serializer.\n\nSee also:\n\nNotation 3\nhttp://www.w3.org/DesignIssues/Notation3\n\nClosed World Machine - and RDF Processor\nhttp://www.w3.org/2000/10/swap/cwm\n\nTo DO: See also \"@@\" in comments\n\n- Clean up interfaces\n______________________________________________\n\nModule originally by Dan Connolly, includeing notation3\nparser and RDF generator. TimBL added RDF stream model\nand N3 generation, replaced stream model with use\nof common store/formula API. Yosi Scharf developped\nthe module, including tests and test harness.\n\n*/\n\nvar ADDED_HASH = \"#\";\nvar LOG_implies_URI = \"http://www.w3.org/2000/10/swap/log#implies\";\nvar INTEGER_DATATYPE = \"http://www.w3.org/2001/XMLSchema#integer\";\nvar FLOAT_DATATYPE = \"http://www.w3.org/2001/XMLSchema#double\";\nvar DECIMAL_DATATYPE = \"http://www.w3.org/2001/XMLSchema#decimal\";\nvar DATE_DATATYPE = \"http://www.w3.org/2001/XMLSchema#date\";\nvar DATETIME_DATATYPE = \"http://www.w3.org/2001/XMLSchema#dateTime\";\nvar BOOLEAN_DATATYPE = \"http://www.w3.org/2001/XMLSchema#boolean\";\nvar option_noregen = 0;\nvar _notQNameChars = \"\\t\\r\\n !\\\"#$%&'()*.,+/;<=>?@[\\\\]^`{|}~\";\nvar _notNameChars = ( _notQNameChars + \":\" ) ;\nvar _rdfns = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\";\nvar N3CommentCharacter = \"#\";\nvar eol = new RegExp(\"^[ \\\\t]*(#[^\\\\n]*)?\\\\r?\\\\n\", 'g');\nvar eof = new RegExp(\"^[ \\\\t]*(#[^\\\\n]*)?$\", 'g');\nvar ws = new RegExp(\"^[ \\\\t]*\", 'g');\nvar signed_integer = new RegExp(\"^[-+]?[0-9]+\", 'g');\nvar number_syntax = new RegExp(\"^([-+]?[0-9]+)(\\\\.[0-9]+)?(e[-+]?[0-9]+)?\", 'g');\nvar datetime_syntax = new RegExp('^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9](T[0-9][0-9]:[0-9][0-9](:[0-9][0-9](\\\\.[0-9]*)?)?)?Z?');\n\nvar digitstring = new RegExp(\"^[0-9]+\", 'g');\nvar interesting = new RegExp(\"[\\\\\\\\\\\\r\\\\n\\\\\\\"]\", 'g');\nvar langcode = new RegExp(\"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\", 'g');\n\nfunction createSinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) {\n return new SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why);\n}\n\nexport default createSinkParser;\n\nexport class SinkParser {\n constructor(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) {\n if (typeof openFormula == 'undefined') openFormula=null;\n if (typeof thisDoc == 'undefined') thisDoc=\"\";\n if (typeof baseURI == 'undefined') baseURI=null;\n if (typeof genPrefix == 'undefined') genPrefix=\"\";\n if (typeof metaURI == 'undefined') metaURI=null;\n if (typeof flags == 'undefined') flags=\"\";\n if (typeof why == 'undefined') why=null;\n /*\n note: namespace names should *not* end in #;\n the # will get added during qname processing */\n\n this._bindings = new pyjslib_Dict([]);\n this._flags = flags;\n if ((thisDoc != \"\")) {\n assertFudge((thisDoc.indexOf(\":\") >= 0), ( \"Document URI not absolute: \" + thisDoc ) );\n this._bindings[\"\"] = ( ( thisDoc + \"#\" ) );\n }\n this._store = store;\n if (genPrefix) {\n store.setGenPrefix(genPrefix);\n }\n this._thisDoc = thisDoc;\n this.source = store.sym(thisDoc);\n this.lines = 0;\n this.statementCount = 0;\n this.startOfLine = 0;\n this.previousLine = 0;\n this._genPrefix = genPrefix;\n this.keywords = new pyjslib_List([\"a\", \"this\", \"bind\", \"has\", \"is\", \"of\", \"true\", \"false\"]);\n this.keywordsSet = 0;\n this._anonymousNodes = new pyjslib_Dict([]);\n this._variables = new pyjslib_Dict([]);\n this._parentVariables = new pyjslib_Dict([]);\n this._reason = why;\n this._reason2 = null;\n if (diag_tracking) {\n this._reason2 = why_BecauseOfData(store.sym(thisDoc), this._reason);\n }\n if (baseURI) {\n this._baseURI = baseURI;\n }\n else {\n if (thisDoc) {\n this._baseURI = thisDoc;\n }\n else {\n this._baseURI = null;\n }\n }\n assertFudge(!(this._baseURI) || (this._baseURI.indexOf(\":\") >= 0));\n if (!(this._genPrefix)) {\n if (this._thisDoc) {\n this._genPrefix = ( this._thisDoc + \"#_g\" ) ;\n }\n else {\n this._genPrefix = RDFSink_uniqueURI();\n }\n }\n if ((openFormula == null)) {\n if (this._thisDoc) {\n this._formula = store.formula( ( thisDoc + \"#_formula\" ) );\n }\n else {\n this._formula = store.formula();\n }\n }\n else {\n this._formula = openFormula;\n }\n this._context = this._formula;\n this._parentContext = null;\n }\n\n\n here(i) {\n return ( ( ( ( this._genPrefix + \"_L\" ) + this.lines ) + \"C\" ) + ( ( i - this.startOfLine ) + 1 ) ) ;\n };\n formula() {\n return this._formula;\n };\n loadStream(stream) {\n return this.loadBuf(stream.read());\n };\n loadBuf(buf) {\n /*\n Parses a buffer and returns its top level formula*/\n\n this.startDoc();\n this.feed(buf);\n return this.endDoc();\n };\n feed(octets) {\n /*\n Feed an octet stream tothe parser\n\n if BadSyntax is raised, the string\n passed in the exception object is the\n remainder after any statements have been parsed.\n So if there is more data to feed to the\n parser, it should be straightforward to recover.*/\n\n var str = octets.decode(\"utf-8\");\n var i = 0;\n while ((i >= 0)) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return;\n }\n var i = this.directiveOrStatement(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected directive or statement\");\n }\n }\n };\n directiveOrStatement(str, h) {\n var i = this.skipSpace(str, h);\n if ((i < 0)) {\n return i;\n }\n var j = this.directive(str, i);\n if ((j >= 0)) {\n return this.checkDot(str, j);\n }\n var j = this.statement(str, i);\n if ((j >= 0)) {\n return this.checkDot(str, j);\n }\n return j;\n };\n tok(tok, str, i) {\n /*\n Check for keyword. Space must have been stripped on entry and\n we must not be at end of file.*/\n var whitespace = \"\\t\\n\\v\\f\\r \";\n if ((str.slice( i, ( i + 1 ) ) == \"@\")) {\n var i = ( i + 1 ) ;\n }\n else {\n if ((ArrayIndexOf(this.keywords,tok) < 0)) {\n return -1;\n }\n }\n var k = ( i + pyjslib_len(tok) ) ;\n if ((str.slice( i, k) == tok) && (_notQNameChars.indexOf(str.charAt(k)) >= 0)) {\n return k;\n }\n else {\n return -1;\n }\n };\n directive(str, i) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n var res = new pyjslib_List([]);\n var j = this.tok(\"bind\", str, i);\n if ((j > 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"keyword bind is obsolete: use @prefix\");\n }\n var j = this.tok(\"keywords\", str, i);\n if ((j > 0)) {\n var i = this.commaSeparatedList(str, j, res, false);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"'@keywords' needs comma separated list of words\");\n }\n this.setKeywords(pyjslib_slice(res, null, null));\n if ((diag_chatty_flag > 80)) {\n diag_progress(\"Keywords \", this.keywords);\n }\n return i;\n }\n var j = this.tok(\"forAll\", str, i);\n if ((j > 0)) {\n var i = this.commaSeparatedList(str, j, res, true);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"Bad variable list after @forAll\");\n }\n\n var __x = new pyjslib_Iterator(res);\n try {\n while (true) {\n var x = __x.next();\n\n\n if (ArrayIndexOf(this._variables,x) < 0 || (ArrayIndexOf(this._parentVariables,x) >= 0)) {\n this._variables[x] = ( this._context.newUniversal(x));\n }\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n return i;\n }\n var j = this.tok(\"forSome\", str, i);\n if ((j > 0)) {\n var i = this.commaSeparatedList(str, j, res, this.uri_ref2);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"Bad variable list after @forSome\");\n }\n\n var __x = new pyjslib_Iterator(res);\n try {\n while (true) {\n var x = __x.next();\n\n\n this._context.declareExistential(x);\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n return i;\n }\n var j = this.tok(\"prefix\", str, i);\n if ((j >= 0)) {\n var t = new pyjslib_List([]);\n var i = this.qname(str, j, t);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected qname after @prefix\");\n }\n var j = this.uri_ref2(str, i, t);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected <uriref> after @prefix _qname_\");\n }\n var ns = t[1].uri;\n if (this._baseURI) {\n var ns = uripath_join(this._baseURI, ns);\n }\n else {\n assertFudge((ns.indexOf(\":\") >= 0), \"With no base URI, cannot handle relative URI for NS\");\n }\n assertFudge((ns.indexOf(\":\") >= 0));\n this._bindings[t[0][0]] = ( ns);\n\n this.bind(t[0][0], hexify(ns));\n return j;\n }\n var j = this.tok(\"base\", str, i);\n if ((j >= 0)) {\n var t = new pyjslib_List([]);\n var i = this.uri_ref2(str, j, t);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected <uri> after @base \");\n }\n var ns = t[0].uri;\n if (this._baseURI) {\n var ns = uripath_join(this._baseURI, ns);\n }\n else {\n throw BadSyntax(this._thisDoc, this.lines, str, j, ( ( \"With no previous base URI, cannot use relative URI in @base <\" + ns ) + \">\" ) );\n }\n assertFudge((ns.indexOf(\":\") >= 0));\n this._baseURI = ns;\n return i;\n }\n return -1;\n };\n bind(qn, uri) {\n if ((qn == \"\")) {\n }\n else {\n this._store.setPrefixForURI(qn, uri);\n }\n };\n setKeywords(k) {\n /*\n Takes a list of strings*/\n\n if ((k == null)) {\n this.keywordsSet = 0;\n }\n else {\n this.keywords = k;\n this.keywordsSet = 1;\n }\n };\n startDoc() {\n };\n endDoc() {\n /*\n Signal end of document and stop parsing. returns formula*/\n\n return this._formula;\n };\n makeStatement(quad) {\n quad[0].add(quad[2], quad[1], quad[3], this.source);\n this.statementCount += 1;\n };\n statement(str, i) {\n var r = new pyjslib_List([]);\n var i = this.object(str, i, r);\n if ((i < 0)) {\n return i;\n }\n var j = this.property_list(str, i, r[0]);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected propertylist\");\n }\n return j;\n };\n subject(str, i, res) {\n return this.item(str, i, res);\n };\n verb(str, i, res) {\n /*\n has _prop_\n is _prop_ of\n a\n =\n _prop_\n >- prop ->\n <- prop -<\n _operator_*/\n\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n var r = new pyjslib_List([]);\n var j = this.tok(\"has\", str, i);\n if ((j >= 0)) {\n var i = this.prop(str, j, r);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected property after 'has'\");\n }\n res.push(new pyjslib_Tuple([\"->\", r[0]]));\n return i;\n }\n var j = this.tok(\"is\", str, i);\n if ((j >= 0)) {\n var i = this.prop(str, j, r);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected <property> after 'is'\");\n }\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"End of file found, expected property after 'is'\");\n return j;\n }\n var i = j;\n var j = this.tok(\"of\", str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected 'of' after 'is' <prop>\");\n }\n res.push(new pyjslib_Tuple([\"<-\", r[0]]));\n return j;\n }\n var j = this.tok(\"a\", str, i);\n if ((j >= 0)) {\n res.push(new pyjslib_Tuple([\"->\", this._store.sym(RDF_type_URI)]));\n return j;\n }\n if ((str.slice( i, ( i + 2 ) ) == \"<=\")) {\n res.push(new pyjslib_Tuple([\"<-\", this._store.sym( ( Logic_NS + \"implies\" ) )]));\n return ( i + 2 ) ;\n }\n if ((str.slice( i, ( i + 1 ) ) == \"=\")) {\n if ((str.slice( ( i + 1 ) , ( i + 2 ) ) == \">\")) {\n res.push(new pyjslib_Tuple([\"->\", this._store.sym( ( Logic_NS + \"implies\" ) )]));\n return ( i + 2 ) ;\n }\n res.push(new pyjslib_Tuple([\"->\", this._store.sym(DAML_sameAs_URI)]));\n return ( i + 1 ) ;\n }\n if ((str.slice( i, ( i + 2 ) ) == \":=\")) {\n res.push(new pyjslib_Tuple([\"->\", ( Logic_NS + \"becomes\" ) ]));\n return ( i + 2 ) ;\n }\n var j = this.prop(str, i, r);\n if ((j >= 0)) {\n res.push(new pyjslib_Tuple([\"->\", r[0]]));\n return j;\n }\n if ((str.slice( i, ( i + 2 ) ) == \">-\") || (str.slice( i, ( i + 2 ) ) == \"<-\")) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \">- ... -> syntax is obsolete.\");\n }\n return -1;\n };\n prop(str, i, res) {\n return this.item(str, i, res);\n };\n item(str, i, res) {\n return this.path(str, i, res);\n };\n blankNode(uri) {\n return this._context.bnode(uri, this._reason2);\n };\n path(str, i, res) {\n /*\n Parse the path production.\n */\n\n var j = this.nodeOrLiteral(str, i, res);\n if ((j < 0)) {\n return j;\n }\n while ((\"!^.\".indexOf(str.slice( j, ( j + 1 ) )) >= 0)) {\n var ch = str.slice( j, ( j + 1 ) );\n if ((ch == \".\")) {\n var ahead = str.slice( ( j + 1 ) , ( j + 2 ) );\n if (!(ahead) || (_notNameChars.indexOf(ahead) >= 0) && (\":?<[{(\".indexOf(ahead) < 0)) {\n break;\n }\n }\n var subj = res.pop();\n var obj = this.blankNode(this.here(j));\n var j = this.node(str, ( j + 1 ) , res);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"EOF found in middle of path syntax\");\n }\n var pred = res.pop();\n if ((ch == \"^\")) {\n this.makeStatement(new pyjslib_Tuple([this._context, pred, obj, subj]));\n }\n else {\n this.makeStatement(new pyjslib_Tuple([this._context, pred, subj, obj]));\n }\n res.push(obj);\n }\n return j;\n };\n anonymousNode(ln) {\n /*\n Remember or generate a term for one of these _: anonymous nodes*/\n\n var term = this._anonymousNodes[ln];\n if (term) {\n return term;\n }\n var term = this._store.bnode(ln);\n // var term = this._store.bnode(this._context, this._reason2); eh?\n this._anonymousNodes[ln] = ( term);\n return term;\n };\n node(str, i, res, subjectAlready) {\n if (typeof subjectAlready == 'undefined') subjectAlready=null;\n /*\n Parse the <node> production.\n Space is now skipped once at the beginning\n instead of in multipe calls to self.skipSpace().\n */\n\n var subj = subjectAlready;\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n var i = j;\n var ch = str.slice( i, ( i + 1 ) );\n if ((ch == \"[\")) {\n var bnodeID = this.here(i);\n var j = this.skipSpace(str, ( i + 1 ) );\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF after '['\");\n }\n if ((str.slice( j, ( j + 1 ) ) == \"=\")) {\n var i = ( j + 1 ) ;\n var objs = new pyjslib_List([]);\n var j = this.objectList(str, i, objs);\n\n if ((j >= 0)) {\n var subj = objs[0];\n if ((pyjslib_len(objs) > 1)) {\n\n var __obj = new pyjslib_Iterator(objs);\n try {\n while (true) {\n var obj = __obj.next();\n\n\n this.makeStatement(new pyjslib_Tuple([this._context, this._store.sym(DAML_sameAs_URI), subj, obj]));\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n }\n var j = this.skipSpace(str, j);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF when objectList expected after [ = \");\n }\n if ((str.slice( j, ( j + 1 ) ) == \";\")) {\n var j = ( j + 1 ) ;\n }\n }\n else {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"objectList expected after [= \");\n }\n }\n if ((subj == null)) {\n var subj = this.blankNode(bnodeID);\n }\n var i = this.property_list(str, j, subj);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"property_list expected\");\n }\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF when ']' expected after [ <propertyList>\");\n }\n if ((str.slice( j, ( j + 1 ) ) != \"]\")) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"']' expected\");\n }\n res.push(subj);\n return ( j + 1 ) ;\n }\n if ((ch == \"{\")) {\n var ch2 = str.slice( ( i + 1 ) , ( i + 2 ) );\n if ((ch2 == \"$\")) {\n i += 1;\n var j = ( i + 1 ) ;\n var mylist = new pyjslib_List([]);\n var first_run = true;\n while (1) {\n var i = this.skipSpace(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"needed '$}', found end.\");\n }\n if ((str.slice( i, ( i + 2 ) ) == \"$}\")) {\n var j = ( i + 2 ) ;\n break;\n }\n if (!(first_run)) {\n if ((str.slice( i, ( i + 1 ) ) == \",\")) {\n i += 1;\n }\n else {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected: ','\");\n }\n }\n else {\n var first_run = false;\n }\n var item = new pyjslib_List([]);\n var j = this.item(str, i, item);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected item in set or '$}'\");\n }\n mylist.push(item[0]);\n }\n res.push(this._store.newSet(mylist, this._context));\n return j;\n }\n else {\n var j = ( i + 1 ) ;\n var oldParentContext = this._parentContext;\n this._parentContext = this._context;\n var parentAnonymousNodes = this._anonymousNodes;\n var grandParentVariables = this._parentVariables;\n this._parentVariables = this._variables;\n this._anonymousNodes = new pyjslib_Dict([]);\n this._variables = this._variables.slice();\n var reason2 = this._reason2;\n this._reason2 = becauseSubexpression;\n if ((subj == null)) {\n var subj = this._store.formula();\n }\n this._context = subj;\n while (1) {\n var i = this.skipSpace(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"needed '}', found end.\");\n }\n if ((str.slice( i, ( i + 1 ) ) == \"}\")) {\n var j = ( i + 1 ) ;\n break;\n }\n var j = this.directiveOrStatement(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected statement or '}'\");\n }\n }\n this._anonymousNodes = parentAnonymousNodes;\n this._variables = this._parentVariables;\n this._parentVariables = grandParentVariables;\n this._context = this._parentContext;\n this._reason2 = reason2;\n this._parentContext = oldParentContext;\n res.push(subj.close());\n return j;\n }\n }\n if ((ch == \"(\")) {\n var thing_type = this._store.list;\n var ch2 = str.slice( ( i + 1 ) , ( i + 2 ) );\n if ((ch2 == \"$\")) {\n var thing_type = this._store.newSet;\n i += 1;\n }\n var j = ( i + 1 ) ;\n var mylist = new pyjslib_List([]);\n while (1) {\n var i = this.skipSpace(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"needed ')', found end.\");\n }\n if ((str.slice( i, ( i + 1 ) ) == \")\")) {\n var j = ( i + 1 ) ;\n break;\n }\n var item = new pyjslib_List([]);\n var j = this.item(str, i, item);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected item in list or ')'\");\n }\n mylist.push(item[0]);\n }\n res.push(thing_type(mylist, this._context));\n return j;\n }\n var j = this.tok(\"this\", str, i);\n if ((j >= 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords.\");\n res.push(this._context);\n return j;\n }\n var j = this.tok(\"true\", str, i);\n if ((j >= 0)) {\n res.push(true);\n return j;\n }\n var j = this.tok(\"false\", str, i);\n if ((j >= 0)) {\n res.push(false);\n return j;\n }\n if ((subj == null)) {\n var j = this.uri_ref2(str, i, res);\n if ((j >= 0)) {\n return j;\n }\n }\n return -1;\n };\n property_list(str, i, subj) {\n /*\n Parse property list\n Leaves the terminating punctuation in the buffer\n */\n\n while (1) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF found when expected verb in property list\");\n return j;\n }\n if ((str.slice( j, ( j + 2 ) ) == \":-\")) {\n var i = ( j + 2 ) ;\n var res = new pyjslib_List([]);\n var j = this.node(str, i, res, subj);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"bad {} or () or [] node after :- \");\n }\n var i = j;\n continue;\n }\n var i = j;\n var v = new pyjslib_List([]);\n var j = this.verb(str, i, v);\n if ((j <= 0)) {\n return i;\n }\n var objs = new pyjslib_List([]);\n var i = this.objectList(str, j, objs);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"objectList expected\");\n }\n\n var __obj = new pyjslib_Iterator(objs);\n try {\n while (true) {\n var obj = __obj.next();\n\n\n var pairFudge = v[0];\n var dir = pairFudge[0];\n var sym = pairFudge[1];\n if ((dir == \"->\")) {\n this.makeStatement(new pyjslib_Tuple([this._context, sym, subj, obj]));\n }\n else {\n this.makeStatement(new pyjslib_Tuple([this._context, sym, obj, subj]));\n }\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"EOF found in list of objects\");\n return j;\n }\n if ((str.slice( i, ( i + 1 ) ) != \";\")) {\n return i;\n }\n var i = ( i + 1 ) ;\n }\n };\n commaSeparatedList(str, j, res, ofUris) {\n /*\n return value: -1 bad syntax; >1 new position in str\n res has things found appended\n\n Used to use a final value of the function to be called, e.g. this.bareWord\n but passing the function didn't work fo js converion pyjs\n */\n\n var i = this.skipSpace(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF found expecting comma sep list\");\n return i;\n }\n if ((str.charAt(i) == \".\")) {\n return j;\n }\n if (ofUris) {\n var i = this.uri_ref2(str, i, res);\n }\n else {\n var i = this.bareWord(str, i, res);\n }\n if ((i < 0)) {\n return -1;\n }\n while (1) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n var ch = str.slice( j, ( j + 1 ) );\n if ((ch != \",\")) {\n if ((ch != \".\")) {\n return -1;\n }\n return j;\n }\n if (ofUris) {\n var i = this.uri_ref2(str, ( j + 1 ) , res);\n }\n else {\n var i = this.bareWord(str, ( j + 1 ) , res);\n }\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"bad list content\");\n return i;\n }\n }\n };\n objectList(str, i, res) {\n var i = this.object(str, i, res);\n if ((i < 0)) {\n return -1;\n }\n while (1) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"EOF found after object\");\n return j;\n }\n if ((str.slice( j, ( j + 1 ) ) != \",\")) {\n return j;\n }\n var i = this.object(str, ( j + 1 ) , res);\n if ((i < 0)) {\n return i;\n }\n }\n };\n checkDot(str, i) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n if ((str.slice( j, ( j + 1 ) ) == \".\")) {\n return ( j + 1 ) ;\n }\n if ((str.slice( j, ( j + 1 ) ) == \"}\")) {\n return j;\n }\n if ((str.slice( j, ( j + 1 ) ) == \"]\")) {\n return j;\n }\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected '.' or '}' or ']' at end of statement\");\n return i;\n };\n uri_ref2(str, i, res) {\n /*\n Generate uri from n3 representation.\n\n Note that the RDF convention of directly concatenating\n NS and local name is now used though I prefer inserting a '#'\n to make the namesapces look more like what XML folks expect.\n */\n\n var qn = new pyjslib_List([]);\n var j = this.qname(str, i, qn);\n if ((j >= 0)) {\n var pairFudge = qn[0];\n var pfx = pairFudge[0];\n var ln = pairFudge[1];\n if ((pfx == null)) {\n assertFudge(0, \"not used?\");\n var ns = ( this._baseURI + ADDED_HASH ) ;\n }\n else {\n var ns = this._bindings[pfx];\n if (!(ns)) {\n if ((pfx == \"_\")) {\n res.push(this.anonymousNode(ln));\n return j;\n }\n throw BadSyntax(this._thisDoc, this.lines, str, i, ( ( \"Prefix \" + pfx ) + \" not bound.\" ) );\n }\n }\n var symb = this._store.sym( ( ns + ln ) );\n if ((ArrayIndexOf(this._variables, symb) >= 0)) {\n res.push(this._variables[symb]);\n }\n else {\n res.push(symb);\n }\n return j;\n }\n var i = this.skipSpace(str, i);\n if ((i < 0)) {\n return -1;\n }\n if ((str.charAt(i) == \"?\")) {\n var v = new pyjslib_List([]);\n var j = this.variable(str, i, v);\n if ((j > 0)) {\n res.push(v[0]);\n return j;\n }\n return -1;\n }\n else if ((str.charAt(i) == \"<\")) {\n var i = ( i + 1 ) ;\n var st = i;\n while ((i < pyjslib_len(str))) {\n if ((str.charAt(i) == \">\")) {\n var uref = str.slice( st, i);\n if (this._baseURI) {\n var uref = uripath_join(this._baseURI, uref);\n }\n else {\n assertFudge((uref.indexOf(\":\") >= 0), \"With no base URI, cannot deal with relative URIs\");\n }\n if ((str.slice( ( i - 1 ) , i) == \"#\") && !((pyjslib_slice(uref, -1, null) == \"#\"))) {\n var uref = ( uref + \"#\" ) ;\n }\n var symb = this._store.sym(uref);\n if ((ArrayIndexOf(this._variables,symb) >= 0)) {\n res.push(this._variables[symb]);\n }\n else {\n res.push(symb);\n }\n return ( i + 1 ) ;\n }\n var i = ( i + 1 ) ;\n }\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"unterminated URI reference\");\n }\n else if (this.keywordsSet) {\n var v = new pyjslib_List([]);\n var j = this.bareWord(str, i, v);\n if ((j < 0)) {\n return -1;\n }\n if ((ArrayIndexOf(this.keywords, v[0]) >= 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, ( ( \"Keyword \\\"\" + v[0] ) + \"\\\" not allowed here.\" ) );\n }\n res.push(this._store.sym( ( this._bindings[\"\"] + v[0] ) ));\n return j;\n }\n else {\n return -1;\n }\n };\n skipSpace(str, i) {\n /*\n Skip white space, newlines and comments.\n return -1 if EOF, else position of first non-ws character*/\n\n var whitespace = ' \\n\\r\\t\\f\\x0b\\xa0\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u200b\\u2028\\u2029\\u3000';\n for (var j = (i ? i : 0); j < str.length; j++) {\n var ch = str.charAt(j);\n // console.log(\" skipspace j= \"+j + \" i= \" + i + \" n= \" + str.length);\n // console.log(\" skipspace ch <\" + ch + \">\");\n if (whitespace.indexOf(ch) < 0 ) { //not ws\n // console.log(\" skipspace 2 ch <\" + ch + \">\");\n if( str.charAt(j)==='#' ) {\n for (;; j++) {\n // console.log(\" skipspace2 j= \"+j + \" i= \" + i + \" n= \" + str.length);\n if (j === str.length) {\n return -1; // EOF\n }\n if (str.charAt(j) === '\\n') {\n this.lines = this.lines + 1;\n break;\n }\n };\n } else { // Not hash - something interesting\n // console.log(\" skipspace 3 ch <\" + ch + \">\");\n return j\n }\n } else { // Whitespace\n // console.log(\" skipspace 5 ch <\" + ch + \">\");\n if (str.charAt(j) === '\\n') {\n this.lines = this.lines + 1;\n }\n }\n } // next j\n return -1; // EOF\n };\n\n variable(str, i, res) {\n /*\n ?abc -> variable(:abc)\n */\n\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return -1;\n }\n if ((str.slice( j, ( j + 1 ) ) != \"?\")) {\n return -1;\n }\n var j = ( j + 1 ) ;\n var i = j;\n if ((\"0123456789-\".indexOf(str.charAt(j)) >= 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, ( ( \"Varible name can't start with '\" + str.charAt(j) ) + \"s'\" ) );\n return -1;\n }\n while ((i < pyjslib_len(str)) && (_notNameChars.indexOf(str.charAt(i)) < 0)) {\n var i = ( i + 1 ) ;\n }\n if ((this._parentContext == null)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, ( \"Can't use ?xxx syntax for variable in outermost level: \" + str.slice( ( j - 1 ) , i) ) );\n }\n res.push(this._store.variable(str.slice( j, i)));\n return i;\n };\n bareWord(str, i, res) {\n /*\n abc -> :abc\n */\n\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return -1;\n }\n var ch = str.charAt(j);\n if ((\"0123456789-\".indexOf(ch) >= 0)) {\n return -1;\n }\n if ((_notNameChars.indexOf(ch) >= 0)) {\n return -1;\n }\n var i = j;\n while ((i < pyjslib_len(str)) && (_notNameChars.indexOf(str.charAt(i)) < 0)) {\n var i = ( i + 1 ) ;\n }\n res.push(str.slice( j, i));\n return i;\n };\n qname(str, i, res) {\n /*\n\n xyz:def -> ('xyz', 'def')\n If not in keywords and keywordsSet: def -> ('', 'def')\n :def -> ('', 'def')\n */\n\n var i = this.skipSpace(str, i);\n if ((i < 0)) {\n return -1;\n }\n var c = str.charAt(i);\n if ((\"0123456789-+\".indexOf(c) >= 0)) {\n return -1;\n }\n if ((_notNameChars.indexOf(c) < 0)) {\n var ln = c;\n var i = ( i + 1 ) ;\n while ((i < pyjslib_len(str))) {\n var c = str.charAt(i);\n if ((_notNameChars.indexOf(c) < 0)) {\n var ln = ( ln + c ) ;\n var i = ( i + 1 ) ;\n }\n else {\n break;\n }\n }\n }\n else {\n var ln = \"\";\n }\n if ((i < pyjslib_len(str)) && (str.charAt(i) == \":\")) {\n var pfx = ln;\n var i = ( i + 1 ) ;\n var ln = \"\";\n while ((i < pyjslib_len(str))) {\n var c = str.charAt(i);\n if ((_notNameChars.indexOf(c) < 0)) {\n var ln = ( ln + c ) ;\n var i = ( i + 1 ) ;\n }\n else {\n break;\n }\n }\n res.push(new pyjslib_Tuple([pfx, ln]));\n return i;\n }\n else {\n if (ln && this.keywordsSet && (ArrayIndexOf(this.keywords, ln) < 0)) {\n res.push(new pyjslib_Tuple([\"\", ln]));\n return i;\n }\n return -1;\n }\n };\n object(str, i, res) {\n var j = this.subject(str, i, res);\n if ((j >= 0)) {\n return j;\n }\n else {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return -1;\n }\n else {\n var i = j;\n }\n var delim = null\n let ch = str.charAt(i)\n if ((ch == \"\\\"\" || ch == \"'\")) {\n if (str.slice(i, ( i + 3 ) == ch + ch)) {\n delim = ch + ch + ch;\n }\n else {\n delim = ch;\n }\n var i = ( i + pyjslib_len(delim) ) ;\n var pairFudge = this.strconst(str, i, delim);\n var j = pairFudge[0];\n var s = pairFudge[1];\n res.push(this._store.literal(s));\n diag_progress(\"New string const \", s, j);\n return j;\n }\n else {\n return -1;\n }\n }\n };\n nodeOrLiteral(str, i, res) {\n var j = this.node(str, i, res);\n if ((j >= 0)) {\n return j;\n }\n else {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return -1;\n }\n else {\n var i = j;\n }\n var ch = str.charAt(i);\n if ((\"-+0987654321\".indexOf(ch) >= 0)) {\n\n datetime_syntax.lastIndex = 0;\n var m = datetime_syntax.exec(str.slice(i));\n if ((m != null)) {\n // j = ( i + datetime_syntax.lastIndex ) ;\n var val = m[0];\n j = i + val.length;\n if ((val.indexOf(\"T\") >= 0)) {\n res.push(this._store.literal(val, this._store.sym(DATETIME_DATATYPE)));\n } else {\n res.push(this._store.literal(val, this._store.sym(DATE_DATATYPE)));\n }\n\n } else {\n number_syntax.lastIndex = 0;\n var m = number_syntax.exec(str.slice(i));\n if ((m == null)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"Bad number or date syntax\");\n }\n j = ( i + number_syntax.lastIndex ) ;\n var val = str.slice( i, j);\n if ((val.indexOf(\"e\") >= 0)) {\n res.push(this._store.literal(parseFloat(val), this._store.sym(FLOAT_DATATYPE)));\n }\n else if ((str.slice( i, j).indexOf(\".\") >= 0)) {\n res.push(this._store.literal(parseFloat(val), this._store.sym(DECIMAL_DATATYPE)));\n }\n else {\n res.push(this._store.literal(parseInt(val), this._store.sym(INTEGER_DATATYPE)));\n }\n };\n return j; // Where we have got up to\n }\n if ((str.charAt(i) == \"\\\"\")) {\n if ((str.slice( i, ( i + 3 ) ) == \"\\\"\\\"\\\"\")) {\n var delim = \"\\\"\\\"\\\"\";\n }\n else {\n var delim = \"\\\"\";\n }\n var i = ( i + pyjslib_len(delim) ) ;\n var dt = null;\n var pairFudge = this.strconst(str, i, delim);\n var j = pairFudge[0];\n var s = pairFudge[1];\n var lang = null;\n if ((str.slice( j, ( j + 1 ) ) == \"@\")) {\n langcode.lastIndex = 0;\n\n var m = langcode.exec(str.slice( ( j + 1 ) ));\n if ((m == null)) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"Bad language code syntax on string literal, after @\");\n }\n var i = ( ( langcode.lastIndex + j ) + 1 ) ;\n\n var lang = str.slice( ( j + 1 ) , i);\n var j = i;\n }\n if ((str.slice( j, ( j + 2 ) ) == \"^^\")) {\n var res2 = new pyjslib_List([]);\n var j = this.uri_ref2(str, ( j + 2 ) , res2);\n var dt = res2[0];\n }\n res.push(this._store.literal(s, lang || dt));\n return j;\n }\n else {\n return -1;\n }\n }\n };\n strconst(str, i, delim) {\n /*\n parse an N3 string constant delimited by delim.\n return index, val\n */\n\n var j = i;\n var ustr = \"\";\n var startline = this.lines;\n while ((j < pyjslib_len(str))) {\n var i = ( j + pyjslib_len(delim) ) ;\n if ((str.slice( j, i) == delim)) {\n return new pyjslib_Tuple([i, ustr]);\n }\n if ((str.charAt(j) == \"\\\"\")) {\n var ustr = ( ustr + \"\\\"\" ) ;\n var j = ( j + 1 ) ;\n continue;\n }\n interesting.lastIndex = 0;\n var m = interesting.exec(str.slice(j));\n if (!(m)) {\n throw BadSyntax(this._thisDoc, startline, str, j, ( ( ( \"Closing quote missing in string at ^ in \" + str.slice( ( j - 20 ) , j) ) + \"^\" ) + str.slice( j, ( j + 20 ) ) ) );\n }\n var i = ( ( j + interesting.lastIndex ) - 1 ) ;\n var ustr = ( ustr + str.slice( j, i) ) ;\n var ch = str.charAt(i);\n if ((ch == \"\\\"\")) {\n var j = i;\n continue;\n }\n else if ((ch == \"\\r\")) {\n var j = ( i + 1 ) ;\n continue;\n }\n else if ((ch == \"\\n\")) {\n if ((delim == \"\\\"\")) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"newline found in string literal\");\n }\n this.lines = ( this.lines + 1 ) ;\n var ustr = ( ustr + ch ) ;\n var j = ( i + 1 ) ;\n this.previousLine = this.startOfLine;\n this.startOfLine = j;\n }\n else if ((ch == \"\\\\\")) {\n var j = ( i + 1 ) ;\n var ch = str.slice( j, ( j + 1 ) );\n if (!(ch)) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"unterminated string literal (2)\");\n }\n var k = string_find(\"abfrtvn\\\\\\\"\", ch);\n if ((k >= 0)) {\n var uch = \"\\a\\b\\f\\r\\t\\v\\n\\\\\\\"\".charAt(k);\n var ustr = ( ustr + uch ) ;\n var j = ( j + 1 ) ;\n }\n else if ((ch == \"u\")) {\n var pairFudge = this.uEscape(str, ( j + 1 ) , startline);\n var j = pairFudge[0];\n var ch = pairFudge[1];\n var ustr = ( ustr + ch ) ;\n }\n else if ((ch == \"U\")) {\n var pairFudge = this.UEscape(str, ( j + 1 ) , startline);\n var j = pairFudge[0];\n var ch = pairFudge[1];\n var ustr = ( ustr + ch ) ;\n }\n else {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"bad escape\");\n }\n }\n }\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"unterminated string literal\");\n };\n uEscape(str, i, startline) {\n var j = i;\n var count = 0;\n var value = 0;\n while ((count < 4)) {\n var chFudge = str.slice( j, ( j + 1 ) );\n var ch = chFudge.toLowerCase();\n var j = ( j + 1 ) ;\n if ((ch == \"\")) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"unterminated string literal(3)\");\n }\n var k = string_find(\"0123456789abcdef\", ch);\n if ((k < 0)) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"bad string literal hex escape\");\n }\n var value = ( ( value * 16 ) + k ) ;\n var count = ( count + 1 ) ;\n }\n var uch = String.fromCharCode(value);\n return new pyjslib_Tuple([j, uch]);\n };\n UEscape(str, i, startline) {\n var j = i;\n var count = 0;\n var value = \"\\\\U\";\n while ((count < 8)) {\n var chFudge = str.slice( j, ( j + 1 ) );\n var ch = chFudge.toLowerCase();\n var j = ( j + 1 ) ;\n if ((ch == \"\")) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"unterminated string literal(3)\");\n }\n var k = string_find(\"0123456789abcdef\", ch);\n if ((k < 0)) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"bad string literal hex escape\");\n }\n var value = ( value + ch ) ;\n var count = ( count + 1 ) ;\n }\n var uch = stringFromCharCode( ( ( \"0x\" + pyjslib_slice(value, 2, 10) ) - 0 ) );\n return new pyjslib_Tuple([j, uch]);\n };\n}\n\nfunction OLD_BadSyntax(uri, lines, str, i, why) {\n return new __OLD_BadSyntax(uri, lines, str, i, why);\n}\nfunction __OLD_BadSyntax(uri, lines, str, i, why) {\n this._str = str.encode(\"utf-8\");\n this._str = str;\n this._i = i;\n this._why = why;\n this.lines = lines;\n this._uri = uri;\n}\n__OLD_BadSyntax.prototype.toString = function() {\n var str = this._str;\n var i = this._i;\n var st = 0;\n if ((i > 60)) {\n var pre = \"...\";\n var st = ( i - 60 ) ;\n }\n else {\n var pre = \"\";\n }\n if (( ( pyjslib_len(str) - i ) > 60)) {\n var post = \"...\";\n }\n else {\n var post = \"\";\n }\n return \"Line %i of <%s>: Bad syntax (%s) at ^ in:\\n\\\"%s%s^%s%s\\\"\" % new pyjslib_Tuple([ ( this.lines + 1 ) , this._uri, this._why, pre, str.slice( st, i), str.slice( i, ( i + 60 ) ), post]);\n}\n\nfunction BadSyntax(uri, lines, str, i, why) {\n let lineNo = lines + 1\n let msg = ( ( ( ( ( ( ( ( \"Line \" + ( lineNo ) ) + \" of <\" ) + uri ) + \">: Bad syntax: \" ) + why ) + \"\\nat: \\\"\" ) + str.slice( i, ( i + 30 ) ) ) + \"\\\"\" ) ;\n let e = new SyntaxError(msg, uri , lineNo)\n e.lineNo = lineNo\n e.characterInFile = i\n e.syntaxProblem = why\n return e\n}\n\nfunction stripCR(str) {\n var res = \"\";\n\n var __ch = new pyjslib_Iterator(str);\n try {\n while (true) {\n var ch = __ch.next();\n\n\n if ((ch != \"\\r\")) {\n var res = ( res + ch ) ;\n }\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n return res;\n}\n\n\nfunction dummyWrite(x) {\n}\n\n","// RDFa Parser for rdflib.js\n\n// Originally by: Alex Milowski\n// From https://github.com/alexmilowski/green-turtle\n// Converted: timbl 2015-08-25 not yet working\n// Added wrapper: csarven 2016-05-09 working\n\n// RDFaProcessor.prototype = new Object() // Was URIResolver\n\n// RDFaProcessor.prototype.constructor=RDFaProcessor\n\n// options.base = base URI not really an option, shopuld always be set.\n//\n\nimport BlankNode from './blank-node'\nimport Literal from './literal'\nimport NamedNode from './named-node'\nimport * as Uri from './uri'\nimport * as Util from './utils-js'\nimport rdf from './factories/canonical-data-factory'\n\nif (typeof Node === 'undefined') { // @@@@@@ Global. Interface to xmldom.\n var Node = {\n ELEMENT_NODE: 1,\n ATTRIBUTE_NODE: 2,\n TEXT_NODE: 3,\n CDATA_SECTION_NODE: 4,\n ENTITY_REFERENCE_NODE: 5,\n ENTITY_NODE: 6,\n PROCESSING_INSTRUCTION_NODE: 7,\n COMMENT_NODE: 8,\n DOCUMENT_NODE: 9,\n DOCUMENT_TYPE_NODE: 10,\n DOCUMENT_FRAGMENT_NODE: 11,\n NOTATION_NODE: 12\n }\n}\n\nexport default class RDFaProcessor {\n constructor (kb, options) {\n this.options = options || {}\n this.kb = kb\n this.target = options.target || {\n graph: {\n subjects: {},\n prefixes: {},\n terms: {}\n }\n }\n // XXX: Added to track bnodes\n this.blankNodes = []\n // XXX: Added for normalisation\n this.htmlOptions = {\n 'selfClosing': 'br img input area base basefont col colgroup source wbr isindex link meta param hr'\n }\n this.theOne = '_:' + (new Date()).getTime()\n this.language = null\n this.vocabulary = null\n this.blankCounter = 0\n this.langAttributes = [ { namespaceURI: 'http://www.w3.org/XML/1998/namespace', localName: 'lang' } ]\n this.inXHTMLMode = false\n this.absURIRE = /[\\w\\_\\-]+:\\S+/\n this.finishedHandlers = []\n this.init()\n }\n\n addTriple (origin, subject, predicate, object) {\n var su, ob, pr, or\n if (typeof subject === 'undefined') {\n su = rdf.namedNode(this.options.base)\n } else {\n su = this.toRDFNodeObject(subject)\n }\n pr = this.toRDFNodeObject(predicate)\n ob = this.toRDFNodeObject(object)\n or = rdf.namedNode(this.options.base)\n // console.log('Adding { ' + su + ' ' + pr + ' ' + ob + ' ' + or + ' }')\n this.kb.add(su, pr, ob, or)\n }\n\n ancestorPath (node) {\n var path = ''\n while (node && node.nodeType !== Node.DOCUMENT_NODE) {\n path = '/' + node.localName + path\n node = node.parentNode\n }\n return path\n }\n\n copyMappings (mappings) {\n var newMappings = {}\n for (var k in mappings) {\n newMappings[k] = mappings[k]\n }\n return newMappings\n }\n\n copyProperties () {\n }\n\n deriveDateTimeType (value) {\n for (var i = 0; i < RDFaProcessor.dateTimeTypes.length; i++) {\n // console.log(\"Checking \"+value+\" against \"+RDFaProcessor.dateTimeTypes[i].type)\n var matched = RDFaProcessor.dateTimeTypes[i].pattern.exec(value)\n if (matched && matched[0].length === value.length) {\n // console.log(\"Matched!\")\n return RDFaProcessor.dateTimeTypes[i].type\n }\n }\n return null\n }\n\n init () {\n }\n\n newBlankNode () {\n this.blankCounter++\n return '_:' + this.blankCounter\n }\n\n newSubjectOrigin (origin, subject) {\n }\n\n parseCURIE (value, prefixes, base) {\n var colon = value.indexOf(':')\n var uri\n if (colon >= 0) {\n var prefix = value.substring(0, colon)\n if (prefix === '') {\n // default prefix\n uri = prefixes['']\n return uri ? uri + value.substring(colon + 1) : null\n } else if (prefix === '_') {\n // blank node\n return '_:' + value.substring(colon + 1)\n } else if (RDFaProcessor.NCNAME.test(prefix)) {\n uri = prefixes[prefix]\n if (uri) {\n return uri + value.substring(colon + 1)\n }\n }\n }\n return null\n }\n\n parseCURIEOrURI (value, prefixes, base) {\n var curie = this.parseCURIE(value, prefixes, base)\n if (curie) {\n return curie\n }\n return this.resolveAndNormalize(base, value)\n }\n\n parsePredicate (value, defaultVocabulary, terms, prefixes, base,\n ignoreTerms) {\n if (value === '') {\n return null\n }\n var predicate = this.parseTermOrCURIEOrAbsURI(value, defaultVocabulary, ignoreTerms ? null : terms, prefixes, base)\n if (predicate && predicate.indexOf('_:') === 0) {\n return null\n }\n return predicate\n }\n\n parsePrefixMappings (str, target) {\n var values = this.tokenize(str)\n var prefix = null\n // var uri = null\n for (var i = 0; i < values.length; i++) {\n if (values[i][values[i].length - 1] === ':') {\n prefix = values[i].substring(0, values[i].length - 1)\n } else if (prefix) {\n target[prefix] = this.options.base ? Uri.join(values[i], this.options.base) : values[i]\n prefix = null\n }\n }\n }\n\n static parseRDFaDOM (dom, kb, base) {\n var p = new RDFaProcessor(kb, { 'base': base })\n // Cannot assign to read only property 'baseURI' of object '#<XMLDocument>':\n if (!dom.baseURI) { // Note this became a read-only attribute some time before 2018\n dom.baseURI = base // oinly set if not already set\n }\n p.process(dom, { baseURI: base})\n }\n\n parseSafeCURIEOrCURIEOrURI (value, prefixes, base) {\n value = this.trim(value)\n if (value.charAt(0) === '[' && value.charAt(value.length - 1) === ']') {\n value = value.substring(1, value.length - 1)\n value = value.trim(value)\n if (value.length === 0) {\n return null\n }\n if (value === '_:') {\n // the one node\n return this.theOne\n }\n return this.parseCURIE(value, prefixes, base)\n } else {\n return this.parseCURIEOrURI(value, prefixes, base)\n }\n }\n\n parseTermOrCURIEOrAbsURI (value, defaultVocabulary, terms, prefixes, base) {\n // alert(\"Parsing \"+value+\" with default vocab \"+defaultVocabulary)\n value = this.trim(value)\n var curie = this.parseCURIE(value, prefixes, base)\n if (curie) {\n return curie\n } else if (terms) {\n if (defaultVocabulary && !this.absURIRE.exec(value)) {\n return defaultVocabulary + value\n }\n var term = terms[value]\n if (term) {\n return term\n }\n var lcvalue = value.toLowerCase()\n term = terms[lcvalue]\n if (term) {\n return term\n }\n }\n if (this.absURIRE.exec(value)) {\n return this.resolveAndNormalize(base, value)\n }\n return null\n }\n\n parseTermOrCURIEOrURI (value, defaultVocabulary, terms, prefixes, base) {\n // alert(\"Parsing \"+value+\" with default vocab \"+defaultVocabulary)\n value = this.trim(value)\n var curie = this.parseCURIE(value, prefixes, base)\n if (curie) {\n return curie\n } else {\n var term = terms[value]\n if (term) {\n return term\n }\n var lcvalue = value.toLowerCase()\n term = terms[lcvalue]\n if (term) {\n return term\n }\n if (defaultVocabulary && !this.absURIRE.exec(value)) {\n return defaultVocabulary + value\n }\n }\n return this.resolveAndNormalize(base, value)\n }\n\n parseURI (uri) {\n return uri // We just use strings as URIs, not objects now.\n }\n\n process (node, options) {\n /*\n if (!window.console) {\n window.console = { log: function() {} }\n } */\n options = options || {}\n var base\n if (node.nodeType === Node.DOCUMENT_NODE) {\n if (node.baseURI && !options.baseURI) {\n options.baseURI = node.baseURI // be defensive as DOM implementations vary\n }\n base = node.baseURI\n node = node.documentElement\n if (!node.baseURI) {\n node.baseURI = base\n }\n this.setContext(node)\n } else if (node.parentNode.nodeType === Node.DOCUMENT_NODE) {\n this.setContext(node)\n }\n var queue = []\n // Fix for Firefox that includes the hash in the base URI\n var removeHash = function (baseURI) {\n // Fix for undefined baseURI property\n if (!baseURI && options && options.baseURI) {\n return options.baseURI\n }\n\n var hash = baseURI.indexOf('#')\n if (hash >= 0) {\n baseURI = baseURI.substring(0, hash)\n }\n if (options && options.baseURIMap) {\n baseURI = options.baseURIMap(baseURI)\n }\n return baseURI\n }\n queue.push({ current: node,\n context: this.push(null, removeHash(node.baseURI))\n })\n while (queue.length > 0) {\n var item = queue.shift()\n if (item.parent) {\n // Sequence Step 14: list triple generation\n if (item.context.parent && item.context.parent.listMapping === item.listMapping) {\n // Skip a child context with exactly the same mapping\n continue\n }\n // console.log(\"Generating lists for \"+item.subject+\", tag \"+item.parent.localName)\n for (let predicate in item.listMapping) {\n var list = item.listMapping[predicate]\n if (list.length === 0) {\n this.addTriple(item.parent, item.subject, predicate, { type: RDFaProcessor.objectURI, value: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' })\n continue\n }\n var bnodes = []\n for (let i = 0; i < list.length; i++) {\n bnodes.push(this.newBlankNode())\n // this.newSubject(item.parent,bnodes[i])\n }\n for (let i = 0; i < bnodes.length; i++) {\n this.addTriple(item.parent, bnodes[i], 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first', list[i])\n this.addTriple(item.parent, bnodes[i], 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest', { type: RDFaProcessor.objectURI, value: (i + 1) < bnodes.length ? bnodes[i + 1] : 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' })\n }\n this.addTriple(item.parent, item.subject, predicate, { type: RDFaProcessor.objectURI, value: bnodes[0] })\n }\n continue\n }\n var current = item.current\n var context = item.context\n // console.log(\"Tag: \"+current.localName+\", listMapping=\"+JSON.stringify(context.listMapping))\n // Sequence Step 1\n var skip = false\n var newSubject = null\n var currentObjectResource = null\n var typedResource = null\n var prefixes = context.prefixes\n var prefixesCopied = false\n var incomplete = []\n var listMapping = context.listMapping\n var listMappingDifferent = !context.parent\n var language = context.language\n var vocabulary = context.vocabulary\n // TODO: the \"base\" element may be used for HTML+RDFa 1.1\n base = this.parseURI(removeHash(current.baseURI))\n current.item = null\n // Sequence Step 2: set the default vocabulary\n var vocabAtt = current.getAttributeNode('vocab')\n if (vocabAtt) {\n let value = this.trim(vocabAtt.value)\n if (value.length > 0) {\n vocabulary = value\n var baseSubject = base.spec\n // this.newSubject(current,baseSubject)\n this.addTriple(current, baseSubject, 'http://www.w3.org/ns/rdfa#usesVocabulary', { type: RDFaProcessor.objectURI, value: vocabulary })\n } else {\n vocabulary = this.vocabulary\n }\n }\n // Sequence Step 3: IRI mappings\n // handle xmlns attributes\n for (var i = 0; i < current.attributes.length; i++) {\n var att = current.attributes[i]\n // if (att.namespaceURI==\"http://www.w3.org/2000/xmlns/\") {\n if (att.nodeName.charAt(0) === 'x' && att.nodeName.indexOf('xmlns:') === 0) {\n if (!prefixesCopied) {\n prefixes = this.copyMappings(prefixes)\n prefixesCopied = true\n }\n var prefix = att.nodeName.substring(6)\n // TODO: resolve relative?\n var ref = RDFaProcessor.trim(att.value)\n prefixes[prefix] = this.options.base ? Uri.join(ref, this.options.base) : ref\n }\n }\n // Handle prefix mappings (@prefix)\n var prefixAtt = current.getAttributeNode('prefix')\n if (prefixAtt) {\n if (!prefixesCopied) {\n prefixes = this.copyMappings(prefixes)\n prefixesCopied = true\n }\n this.parsePrefixMappings(prefixAtt.value, prefixes)\n }\n // Sequence Step 4: language\n var xmlLangAtt = null\n for (let i = 0; !xmlLangAtt && i < this.langAttributes.length; i++) {\n xmlLangAtt = current.getAttributeNodeNS(this.langAttributes[i].namespaceURI, this.langAttributes[i].localName)\n }\n if (xmlLangAtt) {\n let value = RDFaProcessor.trim(xmlLangAtt.value)\n if (value.length > 0) {\n language = value\n } else {\n language = null\n }\n }\n var relAtt = current.getAttributeNode('rel')\n var revAtt = current.getAttributeNode('rev')\n var typeofAtt = current.getAttributeNode('typeof')\n var propertyAtt = current.getAttributeNode('property')\n var datatypeAtt = current.getAttributeNode('datatype')\n var datetimeAtt = this.inHTMLMode\n ? current.getAttributeNode('datetime')\n : null\n var contentAtt = current.getAttributeNode('content')\n var aboutAtt = current.getAttributeNode('about')\n var srcAtt = current.getAttributeNode('src')\n var resourceAtt = current.getAttributeNode('resource')\n var hrefAtt = current.getAttributeNode('href')\n var inlistAtt = current.getAttributeNode('inlist')\n var relAttPredicates = []\n var predicate, values\n if (relAtt) {\n values = this.tokenize(relAtt.value)\n for (let i = 0; i < values.length; i++) {\n predicate = this.parsePredicate(values[i], vocabulary, context.terms, prefixes, base, this.inHTMLMode && propertyAtt !== null)\n if (predicate) {\n relAttPredicates.push(predicate)\n }\n }\n }\n var revAttPredicates = []\n if (revAtt) {\n values = this.tokenize(revAtt.value)\n for (let i = 0; i < values.length; i++) {\n predicate = this.parsePredicate(values[i], vocabulary, context.terms, prefixes, base, this.inHTMLMode && propertyAtt)\n if (predicate) {\n revAttPredicates.push(predicate)\n }\n }\n }\n // Section 3.1, bullet 7\n if (this.inHTMLMode && (relAtt || revAtt) && propertyAtt) {\n if (relAttPredicates.length === 0) {\n relAtt = null\n }\n if (revAttPredicates.length === 0) {\n revAtt = null\n }\n }\n if (relAtt || revAtt) {\n // Sequence Step 6: establish new subject and value\n if (aboutAtt) {\n newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base)\n }\n if (typeofAtt) {\n typedResource = newSubject\n }\n if (!newSubject) {\n if (current.parentNode.nodeType === Node.DOCUMENT_NODE) {\n newSubject = removeHash(current.baseURI)\n } else if (context.parentObject) {\n // TODO: Verify: If the xml:base has been set and the parentObject is the baseURI of the parent, then the subject needs to be the new base URI\n newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n }\n }\n if (resourceAtt) {\n currentObjectResource = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base)\n }\n if (!currentObjectResource) {\n if (hrefAtt) {\n currentObjectResource = this.resolveAndNormalize(base, encodeURI(hrefAtt.value))\n } else if (srcAtt) {\n currentObjectResource = this.resolveAndNormalize(base, encodeURI(srcAtt.value))\n } else if (typeofAtt && !aboutAtt && !(this.inXHTMLMode && (current.localName === 'head' || current.localName === 'body'))) {\n currentObjectResource = this.newBlankNode()\n }\n }\n if (typeofAtt && !aboutAtt && this.inXHTMLMode && (current.localName === 'head' || current.localName === 'body')) {\n typedResource = newSubject\n } else if (typeofAtt && !aboutAtt) {\n typedResource = currentObjectResource\n }\n } else if (propertyAtt && !contentAtt && !datatypeAtt) {\n // Sequence Step 5.1: establish a new subject\n if (aboutAtt) {\n newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base)\n if (typeofAtt) {\n typedResource = newSubject\n }\n }\n if (!newSubject && current.parentNode.nodeType === Node.DOCUMENT_NODE) {\n newSubject = removeHash(current.baseURI)\n if (typeofAtt) {\n typedResource = newSubject\n }\n } else if (!newSubject && context.parentObject) {\n // TODO: Verify: If the xml:base has been set and the parentObject is the baseURI of the parent, then the subject needs to be the new base URI\n newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n }\n if (typeofAtt && !typedResource) {\n if (resourceAtt) {\n typedResource = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base)\n }\n if (!typedResource && hrefAtt) {\n typedResource = this.resolveAndNormalize(base, encodeURI(hrefAtt.value))\n }\n if (!typedResource && srcAtt) {\n typedResource = this.resolveAndNormalize(base, encodeURI(srcAtt.value))\n }\n if (!typedResource && (this.inXHTMLMode || this.inHTMLMode) && (current.localName === 'head' || current.localName === 'body')) {\n typedResource = newSubject\n }\n if (!typedResource) {\n typedResource = this.newBlankNode()\n }\n currentObjectResource = typedResource\n }\n // console.log(current.localName+\", newSubject=\"+newSubject+\", typedResource=\"+typedResource+\", currentObjectResource=\"+currentObjectResource)\n } else {\n // Sequence Step 5.2: establish a new subject\n if (aboutAtt) {\n newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base)\n }\n if (!newSubject && resourceAtt) {\n newSubject = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base)\n }\n if (!newSubject && hrefAtt) {\n newSubject = this.resolveAndNormalize(base, encodeURI(hrefAtt.value))\n }\n if (!newSubject && srcAtt) {\n newSubject = this.resolveAndNormalize(base, encodeURI(srcAtt.value))\n }\n if (!newSubject) {\n if (current.parentNode.nodeType === Node.DOCUMENT_NODE) {\n newSubject = removeHash(current.baseURI)\n } else if ((this.inXHTMLMode || this.inHTMLMode) && (current.localName === 'head' || current.localName === 'body')) {\n newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n } else if (typeofAtt) {\n newSubject = this.newBlankNode()\n } else if (context.parentObject) {\n // TODO: Verify: If the xml:base has been set and the parentObject is the baseURI of the parent, then the subject needs to be the new base URI\n newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n if (!propertyAtt) {\n skip = true\n }\n }\n }\n if (typeofAtt) {\n typedResource = newSubject\n }\n }\n // console.log(current.tagName+\": newSubject=\"+newSubject+\", currentObjectResource=\"+currentObjectResource+\", typedResource=\"+typedResource+\", skip=\"+skip)\n // var rdfaData = null\n if (newSubject) {\n // this.newSubject(current,newSubject)\n if (aboutAtt || resourceAtt || typedResource) {\n var id = newSubject\n if (typeofAtt && !aboutAtt && !resourceAtt && currentObjectResource) {\n id = currentObjectResource\n }\n // console.log(\"Setting data attribute for \"+current.localName+\" for subject \"+id)\n this.newSubjectOrigin(current, id)\n }\n }\n // Sequence Step 7: generate type triple\n if (typedResource) {\n values = this.tokenize(typeofAtt.value)\n for (let i = 0; i < values.length; i++) {\n var object = this.parseTermOrCURIEOrAbsURI(values[i], vocabulary, context.terms, prefixes, base)\n if (object) {\n this.addTriple(current, typedResource, RDFaProcessor.typeURI, { type: RDFaProcessor.objectURI, value: object })\n }\n }\n }\n // Sequence Step 8: new list mappings if there is a new subject\n // console.log(\"Step 8: newSubject=\"+newSubject+\", context.parentObject=\"+context.parentObject)\n if (newSubject && newSubject !== context.parentObject) {\n // console.log(\"Generating new list mapping for \"+newSubject)\n listMapping = {}\n listMappingDifferent = true\n }\n // Sequence Step 9: generate object triple\n if (currentObjectResource) {\n if (relAtt && inlistAtt) {\n for (let i = 0; i < relAttPredicates.length; i++) {\n let list = listMapping[relAttPredicates[i]]\n if (!list) {\n list = []\n listMapping[relAttPredicates[i]] = list\n }\n list.push({ type: RDFaProcessor.objectURI, value: currentObjectResource })\n }\n } else if (relAtt) {\n for (let i = 0; i < relAttPredicates.length; i++) {\n this.addTriple(current, newSubject, relAttPredicates[i], { type: RDFaProcessor.objectURI, value: currentObjectResource })\n }\n }\n if (revAtt) {\n for (let i = 0; i < revAttPredicates.length; i++) {\n this.addTriple(current, currentObjectResource, revAttPredicates[i], { type: RDFaProcessor.objectURI, value: newSubject })\n }\n }\n } else {\n // Sequence Step 10: incomplete triples\n if (newSubject && !currentObjectResource && (relAtt || revAtt)) {\n currentObjectResource = this.newBlankNode()\n // alert(current.tagName+\": generated blank node, newSubject=\"+newSubject+\" currentObjectResource=\"+currentObjectResource)\n }\n if (relAtt && inlistAtt) {\n for (let i = 0; i < relAttPredicates.length; i++) {\n let list = listMapping[relAttPredicates[i]]\n if (!list) {\n list = []\n listMapping[predicate] = list\n }\n // console.log(\"Adding incomplete list for \"+predicate)\n incomplete.push({ predicate: relAttPredicates[i], list: list })\n }\n } else if (relAtt) {\n for (let i = 0; i < relAttPredicates.length; i++) {\n incomplete.push({ predicate: relAttPredicates[i], forward: true })\n }\n }\n if (revAtt) {\n for (let i = 0; i < revAttPredicates.length; i++) {\n incomplete.push({ predicate: revAttPredicates[i], forward: false })\n }\n }\n }\n // Step 11: Current property values\n if (propertyAtt) {\n var datatype = null\n var content = null\n if (datatypeAtt) {\n datatype = datatypeAtt.value === '' ? RDFaProcessor.PlainLiteralURI : this.parseTermOrCURIEOrAbsURI(datatypeAtt.value, vocabulary, context.terms, prefixes, base)\n if (datetimeAtt && !contentAtt) {\n content = datetimeAtt.value\n } else {\n content = datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI ? null : (contentAtt ? contentAtt.value : current.textContent)\n }\n } else if (contentAtt) {\n datatype = RDFaProcessor.PlainLiteralURI\n content = contentAtt.value\n } else if (datetimeAtt) {\n content = datetimeAtt.value\n datatype = RDFaProcessor.deriveDateTimeType(content)\n if (!datatype) {\n datatype = RDFaProcessor.PlainLiteralURI\n }\n } else if (!relAtt && !revAtt) {\n if (resourceAtt) {\n content = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base)\n }\n if (!content && hrefAtt) {\n content = this.resolveAndNormalize(base, encodeURI(hrefAtt.value))\n } else if (!content && srcAtt) {\n content = this.resolveAndNormalize(base, encodeURI(srcAtt.value))\n }\n if (content) {\n datatype = RDFaProcessor.objectURI\n }\n }\n if (!datatype) {\n if (typeofAtt && !aboutAtt) {\n datatype = RDFaProcessor.objectURI\n content = typedResource\n } else {\n content = current.textContent\n if (this.inHTMLMode && current.localName === 'time') {\n datatype = RDFaProcessor.deriveDateTimeType(content)\n }\n if (!datatype) {\n datatype = RDFaProcessor.PlainLiteralURI\n }\n }\n }\n values = this.tokenize(propertyAtt.value)\n for (let i = 0; i < values.length; i++) {\n let predicate = this.parsePredicate(values[i], vocabulary, context.terms, prefixes, base)\n if (predicate) {\n if (inlistAtt) {\n let list = listMapping[predicate]\n if (!list) {\n list = []\n listMapping[predicate] = list\n }\n list.push((datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI) ? { type: datatype, value: current.childNodes } : { type: datatype || RDFaProcessor.PlainLiteralURI, value: content, language: language })\n } else {\n if (datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI) {\n this.addTriple(current, newSubject, predicate, { type: datatype, value: current.childNodes })\n } else {\n this.addTriple(current, newSubject, predicate, { type: datatype || RDFaProcessor.PlainLiteralURI, value: content, language: language })\n // console.log(newSubject+\" \"+predicate+\"=\"+content)\n }\n }\n }\n }\n }\n // Sequence Step 12: complete incomplete triples with new subject\n if (newSubject && !skip) {\n for (let i = 0; i < context.incomplete.length; i++) {\n if (context.incomplete[i].list) {\n // console.log(\"Adding subject \"+newSubject+\" to list for \"+context.incomplete[i].predicate)\n // TODO: it is unclear what to do here\n context.incomplete[i].list.push({ type: RDFaProcessor.objectURI, value: newSubject })\n } else if (context.incomplete[i].forward) {\n // console.log(current.tagName+\": completing forward triple \"+context.incomplete[i].predicate+\" with object=\"+newSubject)\n this.addTriple(current, context.subject, context.incomplete[i].predicate, { type: RDFaProcessor.objectURI, value: newSubject })\n } else {\n // console.log(current.tagName+\": completing reverse triple with object=\"+context.subject)\n this.addTriple(current, newSubject, context.incomplete[i].predicate, { type: RDFaProcessor.objectURI, value: context.subject })\n }\n }\n }\n var childContext = null\n var listSubject = newSubject\n if (skip) {\n // TODO: should subject be null?\n childContext = this.push(context, context.subject)\n // TODO: should the entObject be passed along? If not, then intermediary children will keep properties from being associated with incomplete triples.\n // TODO: Verify: if the current baseURI has changed and the parentObject is the parent's base URI, then the baseURI should change\n childContext.parentObject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n childContext.incomplete = context.incomplete\n childContext.language = language\n childContext.prefixes = prefixes\n childContext.vocabulary = vocabulary\n } else {\n childContext = this.push(context, newSubject)\n childContext.parentObject = currentObjectResource || (newSubject || context.subject)\n childContext.prefixes = prefixes\n childContext.incomplete = incomplete\n if (currentObjectResource) {\n // console.log(\"Generating new list mapping for \"+currentObjectResource)\n listSubject = currentObjectResource\n listMapping = {}\n listMappingDifferent = true\n }\n childContext.listMapping = listMapping\n childContext.language = language\n childContext.vocabulary = vocabulary\n }\n if (listMappingDifferent) {\n // console.log(\"Pushing list parent \"+current.localName)\n queue.unshift({ parent: current, context: context, subject: listSubject, listMapping: listMapping })\n }\n for (var child = current.lastChild; child; child = child.previousSibling) {\n if (child.nodeType === Node.ELEMENT_NODE) {\n // console.log(\"Pushing child \"+child.localName)\n // child.baseURI = current.baseURI\n queue.unshift({ current: child, context: childContext })\n }\n }\n }\n if (this.inHTMLMode) {\n this.copyProperties()\n }\n for (let i = 0; i < this.finishedHandlers.length; i++) {\n this.finishedHandlers[i](node)\n }\n }\n\n push (parent, subject) {\n return {\n parent: parent,\n subject: subject || (parent ? parent.subject : null),\n parentObject: null,\n incomplete: [],\n listMapping: parent ? parent.listMapping : {},\n language: parent ? parent.language : this.language,\n prefixes: parent ? parent.prefixes : this.target.graph.prefixes,\n terms: parent ? parent.terms : this.target.graph.terms,\n vocabulary: parent ? parent.vocabulary : this.vocabulary\n }\n }\n\n resolveAndNormalize (base, uri) {\n // console.log(\"Joining \" + uri + \" to \" + base + \" making \" + Uri.join(uri, base))\n return Uri.join(uri, base) // @@ normalize?\n }\n\n setContext (node) {\n // We only recognized XHTML+RDFa 1.1 if the version is set propertyly\n if (node.localName === 'html' && node.getAttribute('version') === 'XHTML+RDFa 1.1') {\n this.setXHTMLContext()\n } else if (node.localName === 'html' || node.namespaceURI === 'http://www.w3.org/1999/xhtml') {\n if (typeof document !== 'undefined' && document.doctype) {\n if (document.doctype.publicId === '-//W3C//DTD XHTML+RDFa 1.0//EN' && document.doctype.systemId === 'http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd') {\n console.log('WARNING: RDF 1.0 is not supported. Defaulting to HTML5 mode.')\n this.setHTMLContext()\n } else if (document.doctype.publicId === '-//W3C//DTD XHTML+RDFa 1.1//EN' && document.doctype.systemId === 'http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd') {\n this.setXHTMLContext()\n } else {\n this.setHTMLContext()\n }\n } else {\n this.setHTMLContext()\n }\n } else {\n this.setXMLContext()\n }\n }\n\n setHTMLContext () {\n this.setInitialContext()\n this.langAttributes = [\n {\n namespaceURI: 'http://www.w3.org/XML/1998/namespace',\n localName: 'lang'\n },\n { namespaceURI: null, localName: 'lang' }\n ]\n this.inXHTMLMode = false\n this.inHTMLMode = true\n }\n\n setInitialContext () {\n this.vocabulary = null\n // By default, the prefixes are terms are loaded to the RDFa 1.1. standard within the graph constructor\n this.langAttributes = [\n {\n namespaceURI: 'http://www.w3.org/XML/1998/namespace',\n localName: 'lang'\n }\n ]\n }\n\n setXHTMLContext () {\n this.setInitialContext()\n this.inXHTMLMode = true\n this.inHTMLMode = false\n this.langAttributes = [\n {\n namespaceURI: 'http://www.w3.org/XML/1998/namespace',\n localName: 'lang' },\n { namespaceURI: null, localName: 'lang' }\n ]\n // From http://www.w3.org/2011/rdfa-context/xhtml-rdfa-1.1\n this.target.graph.terms['alternate'] = 'http://www.w3.org/1999/xhtml/vocab#alternate'\n this.target.graph.terms['appendix'] = 'http://www.w3.org/1999/xhtml/vocab#appendix'\n this.target.graph.terms['bookmark'] = 'http://www.w3.org/1999/xhtml/vocab#bookmark'\n this.target.graph.terms['cite'] = 'http://www.w3.org/1999/xhtml/vocab#cite'\n this.target.graph.terms['chapter'] = 'http://www.w3.org/1999/xhtml/vocab#chapter'\n this.target.graph.terms['contents'] = 'http://www.w3.org/1999/xhtml/vocab#contents'\n this.target.graph.terms['copyright'] = 'http://www.w3.org/1999/xhtml/vocab#copyright'\n this.target.graph.terms['first'] = 'http://www.w3.org/1999/xhtml/vocab#first'\n this.target.graph.terms['glossary'] = 'http://www.w3.org/1999/xhtml/vocab#glossary'\n this.target.graph.terms['help'] = 'http://www.w3.org/1999/xhtml/vocab#help'\n this.target.graph.terms['icon'] = 'http://www.w3.org/1999/xhtml/vocab#icon'\n this.target.graph.terms['index'] = 'http://www.w3.org/1999/xhtml/vocab#index'\n this.target.graph.terms['last'] = 'http://www.w3.org/1999/xhtml/vocab#last'\n this.target.graph.terms['license'] = 'http://www.w3.org/1999/xhtml/vocab#license'\n this.target.graph.terms['meta'] = 'http://www.w3.org/1999/xhtml/vocab#meta'\n this.target.graph.terms['next'] = 'http://www.w3.org/1999/xhtml/vocab#next'\n this.target.graph.terms['prev'] = 'http://www.w3.org/1999/xhtml/vocab#prev'\n this.target.graph.terms['previous'] = 'http://www.w3.org/1999/xhtml/vocab#previous'\n this.target.graph.terms['section'] = 'http://www.w3.org/1999/xhtml/vocab#section'\n this.target.graph.terms['stylesheet'] = 'http://www.w3.org/1999/xhtml/vocab#stylesheet'\n this.target.graph.terms['subsection'] = 'http://www.w3.org/1999/xhtml/vocab#subsection'\n this.target.graph.terms['start'] = 'http://www.w3.org/1999/xhtml/vocab#start'\n this.target.graph.terms['top'] = 'http://www.w3.org/1999/xhtml/vocab#top'\n this.target.graph.terms['up'] = 'http://www.w3.org/1999/xhtml/vocab#up'\n this.target.graph.terms['p3pv1'] = 'http://www.w3.org/1999/xhtml/vocab#p3pv1'\n // other\n this.target.graph.terms['related'] = 'http://www.w3.org/1999/xhtml/vocab#related'\n this.target.graph.terms['role'] = 'http://www.w3.org/1999/xhtml/vocab#role'\n this.target.graph.terms['transformation'] = 'http://www.w3.org/1999/xhtml/vocab#transformation'\n }\n\n setXMLContext () {\n this.setInitialContext()\n this.inXHTMLMode = false\n this.inHTMLMode = false\n }\n\n tokenize (str) {\n return this.trim(str).split(/\\s+/)\n }\n static tokenize (str) {\n return this.trim(str).split(/\\s+/)\n }\n\n toRDFNodeObject (x) {\n if (typeof x === 'undefined') return undefined\n if (typeof x === 'string') {\n if (x.substring(0, 2) === '_:') {\n if (typeof this.blankNodes[x.substring(2)] === 'undefined') {\n this.blankNodes[x.substring(2)] = new BlankNode(x.substring(2))\n }\n return this.blankNodes[x.substring(2)]\n }\n return rdf.namedNode(x)\n }\n switch (x.type) {\n case RDFaProcessor.objectURI:\n if (x.value.substring(0, 2) === '_:') {\n if (typeof this.blankNodes[x.value.substring(2)] === 'undefined') {\n this.blankNodes[x.value.substring(2)] = new BlankNode(x.value.substring(2))\n }\n return this.blankNodes[x.value.substring(2)]\n }\n return rdf.namedNode(x.value)\n case RDFaProcessor.PlainLiteralURI:\n return new Literal(x.value, x.language || '')\n case RDFaProcessor.XMLLiteralURI:\n case RDFaProcessor.HTMLLiteralURI:\n var string = ''\n Object.keys(x.value).forEach(i => {\n string += Util.domToString(x.value[i], this.htmlOptions)\n })\n return new Literal(string, '', new NamedNode(x.type))\n default:\n return new Literal(x.value, '', new NamedNode(x.type))\n }\n }\n\n trim (str) {\n return str.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '')\n }\n static trim (str) {\n return str.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '')\n }\n}\n\nRDFaProcessor.XMLLiteralURI =\n 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral'\nRDFaProcessor.HTMLLiteralURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML'\nRDFaProcessor.PlainLiteralURI =\n 'http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral'\nRDFaProcessor.objectURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'\nRDFaProcessor.typeURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'\nRDFaProcessor.nameChar =\n '[-A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u10000-\\uEFFFF\\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]'\nRDFaProcessor.nameStartChar =\n '[\\u0041-\\u005A\\u0061-\\u007A\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u00FF\\u0100-\\u0131\\u0134-\\u013E\\u0141-\\u0148\\u014A-\\u017E\\u0180-\\u01C3\\u01CD-\\u01F0\\u01F4-\\u01F5\\u01FA-\\u0217\\u0250-\\u02A8\\u02BB-\\u02C1\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03CE\\u03D0-\\u03D6\\u03DA\\u03DC\\u03DE\\u03E0\\u03E2-\\u03F3\\u0401-\\u040C\\u040E-\\u044F\\u0451-\\u045C\\u045E-\\u0481\\u0490-\\u04C4\\u04C7-\\u04C8\\u04CB-\\u04CC\\u04D0-\\u04EB\\u04EE-\\u04F5\\u04F8-\\u04F9\\u0531-\\u0556\\u0559\\u0561-\\u0586\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u063A\\u0641-\\u064A\\u0671-\\u06B7\\u06BA-\\u06BE\\u06C0-\\u06CE\\u06D0-\\u06D3\\u06D5\\u06E5-\\u06E6\\u0905-\\u0939\\u093D\\u0958-\\u0961\\u0985-\\u098C\\u098F-\\u0990\\u0993-\\u09A8\\u09A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0F40-\\u0F47\\u0F49-\\u0F69\\u10A0-\\u10C5\\u10D0-\\u10F6\\u1100\\u1102-\\u1103\\u1105-\\u1107\\u1109\\u110B-\\u110C\\u110E-\\u1112\\u113C\\u113E\\u1140\\u114C\\u114E\\u1150\\u1154-\\u1155\\u1159\\u115F-\\u1161\\u1163\\u1165\\u1167\\u1169\\u116D-\\u116E\\u1172-\\u1173\\u1175\\u119E\\u11A8\\u11AB\\u11AE-\\u11AF\\u11B7-\\u11B8\\u11BA\\u11BC-\\u11C2\\u11EB\\u11F0\\u11F9\\u1E00-\\u1E9B\\u1EA0-\\u1EF9\\u1F00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2126\\u212A-\\u212B\\u212E\\u2180-\\u2182\\u3041-\\u3094\\u30A1-\\u30FA\\u3105-\\u312C\\uAC00-\\uD7A3\\u4E00-\\u9FA5\\u3007\\u3021-\\u3029_]'\nRDFaProcessor.NCNAME = new RegExp('^' + RDFaProcessor.nameStartChar +\n RDFaProcessor.nameChar + '*$')\n\n/*\nRDFaProcessor.prototype.resolveAndNormalize = function(base,href) {\n var u = base.resolve(href)\n var parsed = this.parseURI(u)\n parsed.normalize()\n return parsed.spec\n}\n*/\n\nRDFaProcessor.dateTimeTypes = [\n { pattern: /-?P(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+(?:\\.[0-9]+)?S)?)?/,\n type: 'http://www.w3.org/2001/XMLSchema#duration' },\n { pattern: /-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9]T(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\\.[0-9]+)?(?:Z|[+\\-][0-9][0-9]:[0-9][0-9])?/,\n type: 'http://www.w3.org/2001/XMLSchema#dateTime' },\n { pattern: /-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9](?:Z|[+\\-][0-9][0-9]:[0-9][0-9])?/,\n type: 'http://www.w3.org/2001/XMLSchema#date' },\n { pattern: /(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\\.[0-9]+)?(?:Z|[+\\-][0-9][0-9]:[0-9][0-9])?/,\n type: 'http://www.w3.org/2001/XMLSchema#time' },\n { pattern: /-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]/,\n type: 'http://www.w3.org/2001/XMLSchema#gYearMonth' },\n { pattern: /-?[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9]/,\n type: 'http://www.w3.org/2001/XMLSchema#gYear' }\n]\n\nconst parseRDFaDOM = RDFaProcessor.parseRDFaDOM\nexport { parseRDFaDOM }\n","// Matching a formula against another formula\n// Assync as well as Synchronously\n//\n// W3C open source licence 2005.\n//\n// This builds on term.js, match.js (and identity.js?)\n// to allow a query of a formula.\n//\n// Here we introduce for the first time a subclass of term: variable.\n//\n// SVN ID: $Id: query.js 25116 2008-11-15 16:13:48Z timbl $\n\n// Variable\n//\n// Compare with BlankNode. They are similar, but a variable\n// stands for something whose value is to be returned.\n// Also, users name variables and want the same name back when stuff is printed\n/* jsl:option explicit */ // Turn on JavaScriptLint variable declaration checking\n\nimport IndexedFormula from './store'\nimport { defaultGraphURI as defaultDocumentURI } from './utils/default-graph-uri'\nimport log from './log'\nimport { docpart } from './uri'\n\n/**\n * Query class, for tracking queries the user has in the UI.\n */\nexport class Query {\n constructor (name, id) {\n this.pat = new IndexedFormula() // The pattern to search for\n this.vars = [] // Used by UI code but not in query.js\n // this.orderBy = [] // Not used yet\n this.name = name\n this.id = id\n }\n}\n\n/**\n * This function will match a pattern to the current Store\n *\n * The callback function is called whenever a match is found\n * When fetcher is supplied this will be called to load from the web\n * any new nodes as they are discovered. This will cause the query to traverse the\n * graph of linked data, sometimes called \"Link Following Query\"\n *\n * @param myQuery - a knowledgebase containing a pattern to use as query\n * @param callback - whenever the pattern in myQuery is met this is called with\n * the new bindings as parameter\n * @param fetcher? - If and only if, you want link following, give a fetcher\n * which has been created for the quadstore being queried.\n * @param onDone - callback when query finished\n */\nexport function indexedFormulaQuery (myQuery, callback, fetcher, onDone) {\n /** Debug strings\n */\n function bindingDebug (b) {\n var str = ''\n var v\n for (v in b) {\n if (b.hasOwnProperty(v)) {\n str += ' ' + v + ' -> ' + b[v]\n }\n }\n return str\n }\n\n function bindingsDebug (nbs) {\n var str = 'Bindings: '\n var i\n var n = nbs.length\n for (i = 0; i < n; i++) {\n str += bindingDebug(nbs[i][0]) + ';\\n\\t'\n }\n return str\n } // bindingsDebug\n\n /** Unification\n *\n * Unification finds all bindings such that when the binding is applied\n * to one term it is equal to the other.\n * @returns {Arrray}- a list of bindings, where a binding is an associative array\n * mapping variuable to value.\n */\n function unifyTerm (self, other, bindings, formula) {\n var actual = bindings[self]\n if (actual === undefined) { // Not mapped\n if (self.isVar) {\n var b = []\n b[self] = other\n return [[ b, null ]] // Match\n }\n actual = self\n }\n if (!actual.complexType) {\n if (formula.redirections[actual]) {\n actual = formula.redirections[actual]\n }\n if (formula.redirections[other]) {\n other = formula.redirections[other]\n }\n if (actual.equals(other) || (actual.uri && actual.uri === defaultDocumentURI)) { // Used to mean 'any graph' in a query\n return [[ [], null ]]\n }\n return []\n }\n if (self instanceof Array) {\n if (!(other instanceof Array)) {\n return []\n }\n return unifyContents(self, other, bindings)\n }\n throw new Error('query.js: oops - code not written yet')\n // return undefined; // for lint - no jslint objects to unreachables\n // return actual.unifyContents(other, bindings)\n } // unifyTerm\n\n function unifyContents (self, other, bindings, formula) {\n var nbs2\n if (self.length !== other.length) {\n return [] // no way\n }\n if (!self.length) {\n return [[ [], null ]] // Success\n }\n var nbs = unifyTerm(self[0], other[0], bindings, formula)\n if (nbs.length === 0) {\n return nbs\n }\n var res = []\n var i\n var n = nbs.length\n var nb\n var j\n var m\n var v\n var nb2\n var bindings2\n for (i = 0; i < n; i++) { // for each possibility from the first term\n nb = nbs[i][0] // new bindings\n bindings2 = []\n for (v in nb) {\n if (nb.hasOwnProperty(v)) {\n bindings2[v] = nb[v] // copy\n }\n }\n for (v in bindings) {\n if (bindings.hasOwnProperty(v)) {\n bindings2[v] = bindings[v] // copy\n }\n }\n nbs2 = unifyContents(self.slice(1), other.slice(1), bindings2, formula)\n m = nbs2.length\n for (j = 0; j < m; j++) {\n nb2 = nbs2[j][0] // @@@@ no idea whether this is used or right\n for (v in nb) {\n if (nb.hasOwnProperty(v)) {\n nb2[v] = nb[v]\n }\n }\n res.push([nb2, null])\n }\n }\n return res\n } // unifyContents\n\n // Matching\n //\n // Matching finds all bindings such that when the binding is applied\n // to one term it is equal to the other term. We only match formulae.\n\n /** if x is not in the bindings array, return the var; otherwise, return the bindings **/\n function bind (x, binding) {\n var y = binding[x]\n if (y === undefined) {\n return x\n }\n return y\n }\n\n // When there are OPTIONAL clauses, we must return bindings without them if none of them\n // succeed. However, if any of them do succeed, we should not. (This is what branchCount()\n // tracked. The problem currently is (2011/7) that when several optionals exist, and they\n // all match, multiple sets of bindings are returned, each with one optional filled in.)\n\n function union (a, b) {\n var c = {}\n var x\n for (x in a) {\n if (a.hasOwnProperty(x)) {\n c[x] = a[x]\n }\n }\n for (x in b) {\n if (b.hasOwnProperty(x)) {\n c[x] = b[x]\n }\n }\n return c\n }\n\n function OptionalBranchJunction (originalCallback, trunkBindings) {\n this.trunkBindings = trunkBindings\n this.originalCallback = originalCallback\n this.branches = []\n // this.results = []; // result[i] is an array of bindings for branch i\n // this.done = {}; // done[i] means all/any results are in for branch i\n // this.count = {}\n return this\n }\n\n OptionalBranchJunction.prototype.checkAllDone = function () {\n var i\n for (i = 0; i < this.branches.length; i++) {\n if (!this.branches[i].done) {\n return\n }\n }\n log.debug('OPTIONAL BIDNINGS ALL DONE:')\n this.doCallBacks(this.branches.length - 1, this.trunkBindings)\n }\n // Recrursively generate the cross product of the bindings\n OptionalBranchJunction.prototype.doCallBacks = function (b, bindings) {\n var j\n if (b < 0) {\n return this.originalCallback(bindings)\n }\n for (j = 0; j < this.branches[b].results.length; j++) {\n this.doCallBacks(b - 1, union(bindings, this.branches[b].results[j]))\n }\n }\n\n // A mandatory branch is the normal one, where callbacks\n // are made immediately and no junction is needed.\n // Might be useful for onFinsihed callback for query API.\n function MandatoryBranch (callback, onDone) {\n this.count = 0\n this.success = false\n this.done = false\n // this.results = []\n this.callback = callback\n this.onDone = onDone\n // this.junction = junction\n // junction.branches.push(this)\n return this\n }\n\n MandatoryBranch.prototype.reportMatch = function (bindings) {\n // log.error(\"@@@@ query.js 1\"); // @@\n this.callback(bindings)\n this.success = true\n }\n\n MandatoryBranch.prototype.reportDone = function () {\n this.done = true\n log.info('Mandatory query branch finished.***')\n if (this.onDone !== undefined) {\n this.onDone()\n }\n }\n\n // An optional branch hoards its results.\n var OptionalBranch = function (junction) {\n this.count = 0\n this.done = false\n this.results = []\n this.junction = junction\n junction.branches.push(this)\n return this\n }\n\n OptionalBranch.prototype.reportMatch = function (bindings) {\n this.results.push(bindings)\n }\n\n OptionalBranch.prototype.reportDone = function () {\n log.debug('Optional branch finished - results.length = ' + this.results.length)\n if (this.results.length === 0) { // This is what optional means: if no hits,\n this.results.push({}) // mimic success, but with no bindings\n log.debug(\"Optional branch FAILED - that's OK.\")\n }\n this.done = true\n this.junction.checkAllDone()\n }\n\n /** prepare -- sets the index of the item to the possible matches\n * @param f - formula\n * @param item - an Statement, possibly w/ vars in it\n * @param bindings - Bindings so far\n * @returns false if the query fails -- there are no items that match\n */\n function prepare (f, item, bindings) {\n var terms, termIndex, i, ind\n item.nvars = 0\n item.index = null\n // if (!f.statements) log.warn(\"@@@ prepare: f is \"+f)\n // log.debug(\"Prepare: f has \"+ f.statements.length)\n // log.debug(\"Prepare: Kb size \"+f.statements.length+\" Preparing \"+item)\n\n terms = [item.subject, item.predicate, item.object, item.why]\n ind = [f.subjectIndex, f.predicateIndex, f.objectIndex, f.whyIndex]\n for (i = 0; i < 4; i++) {\n let t = terms[i]\n // console.log(\" Prepare (\" + t + \") \"+(t in bindings))\n if (t.uri && t.uri === defaultDocumentURI) { // chrome:session\n // console.log(' query: Ignoring slot ' + i)\n } else if (t.isVar && !(bindings[t] !== undefined)) {\n item.nvars++\n } else {\n t = bind(terms[i], bindings) // returns the RDF binding if bound, otherwise itself\n // if (terms[i]!=bind(terms[i],bindings) alert(\"Term: \"+terms[i]+\"Binding: \"+bind(terms[i], bindings))\n if (f.redirections[f.id(t)]) {\n t = f.redirections[f.id(t)] // redirect\n }\n termIndex = ind[i][f.id(t)]\n\n if (!termIndex) {\n item.index = []\n return false // Query line cannot match\n }\n if ((item.index === null) || (item.index.length > termIndex.length)) { // Find smallest index\n item.index = termIndex\n }\n }\n }\n\n if (item.index === null) { // All 4 are variables?\n item.index = f.statements\n }\n return true\n } // prepare\n\n /** sorting function -- negative if self is easier **/\n // We always prefer to start with a URI to be able to browse a graph\n // this is why we put off items with more variables till later.\n function easiestQuery (self, other) {\n if (self.nvars !== other.nvars) {\n return self.nvars - other.nvars\n }\n return self.index.length - other.index.length\n }\n\n var matchIndex = 0 // index\n /** matches a pattern formula against the knowledge base, e.g. to find matches for table-view\n *\n * @param f - knowledge base formula\n * @param g - pattern formula (may have vars)\n * @param bindingsSoFar - bindings accumulated in matching to date\n * @param level - spaces to indent stuff also lets you know what level of recursion you're at\n * @param fetcher - function (term, requestedBy) If you want link following\n * @param localCallback - function(bindings, pattern, branch) called on sucess\n * @returns nothing\n *\n * Will fetch linked data from the web iff the knowledge base an associated source fetcher (f.fetcher)\n ***/\n var match = function (f, g, bindingsSoFar, level, fetcher, localCallback, branch) {\n log.debug('Match begins, Branch count now: ' + branch.count + ' for ' + branch.pattern_debug)\n\n // log.debug(\"match: f has \"+f.statements.length+\", g has \"+g.statements.length)\n var pattern = g.statements\n if (pattern.length === 0) { // when it's satisfied all the pattern triples\n log.debug('FOUND MATCH WITH BINDINGS:' + bindingDebug(bindingsSoFar))\n if (g.optional.length === 0) {\n branch.reportMatch(bindingsSoFar)\n } else {\n log.debug('OPTIONAL: ' + g.optional)\n var junction = new OptionalBranchJunction(callback, bindingsSoFar) // @@ won't work with nested optionals? nest callbacks\n var br = []\n var b\n for (b = 0; b < g.optional.length; b++) {\n br[b] = new OptionalBranch(junction) // Allocate branches to prevent premature ending\n br[b].pattern_debug = g.optional[b] // for diagnotics only\n }\n for (b = 0; b < g.optional.length; b++) {\n br[b].count = br[b].count + 1 // Count how many matches we have yet to complete\n match(f, g.optional[b], bindingsSoFar, '', fetcher, callback, br[b])\n }\n }\n branch.count--\n log.debug('Match ends -- success , Branch count now: ' + branch.count + ' for ' + branch.pattern_debug)\n return // Success\n }\n\n var item\n var i\n var n = pattern.length\n // log.debug(level + \"Match \"+n+\" left, bs so far:\"+bindingDebug(bindingsSoFar))\n\n // Follow links from variables in query\n if (fetcher) { // Fetcher is used to fetch URIs, function first term is a URI term, second is the requester\n var id = 'match' + matchIndex++\n var fetchResource = function (requestedTerm, id) {\n var docuri = requestedTerm.uri.split('#')[0]\n fetcher.nowOrWhenFetched(docuri, undefined, function (ok, body, xhr) {\n if (!ok) {\n console.log('Error following link to <' + requestedTerm.uri + '> in query: ' + body)\n }\n match(f, g, bindingsSoFar, level, fetcher, // match not match2 to look up any others necessary.\n localCallback, branch)\n })\n }\n for (i = 0; i < n; i++) {\n item = pattern[i] // for each of the triples in the query\n if (bindingsSoFar[item.subject] !== undefined &&\n bindingsSoFar[item.subject].uri && fetcher &&\n fetcher.getState(docpart(bindingsSoFar[item.subject].uri)) === 'unrequested') {\n // fetch the subject info and return to id\n fetchResource(bindingsSoFar[item.subject], id)\n return // only look up one per line this time, but we will come back again though match\n }\n if (bindingsSoFar[item.object] !== undefined &&\n bindingsSoFar[item.object].uri && fetcher &&\n fetcher.getState(docpart(bindingsSoFar[item.object].uri)) === 'unrequested') {\n fetchResource(bindingsSoFar[item.object], id)\n return\n }\n }\n } // if fetcher\n match2(f, g, bindingsSoFar, level, fetcher, localCallback, branch)\n } // match\n\n var constraintsSatisfied = function (bindings, constraints) {\n var res = true\n var x\n var test\n for (x in bindings) {\n if (bindings.hasOwnProperty(x)) {\n if (constraints[x]) {\n test = constraints[x].test\n if (test && !test(bindings[x])) {\n res = false\n }\n }\n }\n }\n return res\n }\n\n /** match2 -- stuff after the fetch **/\n var match2 = function (f, g, bindingsSoFar, level, fetcher, callback, branch) { // post fetch\n var pattern = g.statements\n var n = pattern.length\n var i\n var k\n var nk\n var v\n var bindings2\n var newBindings1\n var item\n for (i = 0; i < n; i++) { // For each statement left in the query, run prepare\n item = pattern[i]\n // log.info('match2: item=' + item + ', bindingsSoFar=' + bindingDebug(bindingsSoFar))\n prepare(f, item, bindingsSoFar)\n // if (item.index) console.log(' item.index.length ' + item.index.length)\n }\n pattern.sort(easiestQuery)\n item = pattern[0]\n // log.debug(\"Sorted pattern:\\n\"+pattern)\n var rest = f.formula()\n rest.optional = g.optional\n rest.constraints = g.constraints\n rest.statements = pattern.slice(1) // No indexes: we will not query g.\n log.debug(level + 'match2 searching ' + item.index.length + ' for ' + item +\n '; bindings so far=' + bindingDebug(bindingsSoFar))\n // var results = []\n var c\n var nc = item.index.length\n var nbs1\n var st\n var onward = 0\n // var x\n for (c = 0; c < nc; c++) { // For each candidate statement\n st = item.index[c] // for each statement in the item's index, spawn a new match with that binding\n nbs1 = unifyContents(\n [item.subject, item.predicate, item.object, item.why],\n [st.subject, st.predicate, st.object, st.why], bindingsSoFar, f)\n log.info(level + ' From first: ' + nbs1.length + ': ' + bindingsDebug(nbs1))\n nk = nbs1.length\n // branch.count += nk\n // log.debug(\"Branch count bumped \"+nk+\" to: \"+branch.count)\n for (k = 0; k < nk; k++) { // For each way that statement binds\n bindings2 = []\n newBindings1 = nbs1[k][0]\n if (!constraintsSatisfied(newBindings1, g.constraints)) {\n // branch.count--\n log.debug('Branch count CS: ' + branch.count)\n } else {\n for (v in newBindings1) {\n if (newBindings1.hasOwnProperty(v)) {\n bindings2[v] = newBindings1[v] // copy\n }\n }\n for (v in bindingsSoFar) {\n if (bindingsSoFar.hasOwnProperty(v)) {\n bindings2[v] = bindingsSoFar[v] // copy\n }\n }\n\n branch.count++ // Count how many matches we have yet to complete\n onward++\n match(f, rest, bindings2, level + ' ', fetcher, callback, branch) // call match\n }\n }\n }\n branch.count--\n if (onward === 0) {\n log.debug('Match2 fails completely on ' + item)\n }\n log.debug('Match2 ends, Branch count: ' + branch.count + ' for ' + branch.pattern_debug)\n if (branch.count === 0) {\n log.debug('Branch finished.')\n branch.reportDone()\n }\n } // match2\n // ////////////////////////// Body of query() ///////////////////////\n var f = this\n log.debug('Query on ' + this.statements.length)\n var trunck = new MandatoryBranch(callback, onDone)\n trunck.count++ // count one branch to complete at the moment\n if (myQuery.sync) {\n match(f, myQuery.pat, myQuery.pat.initBindings, '', fetcher, callback, trunck)\n } else { // Give up thread: Allow other activities to run\n setTimeout(function () {\n match(f, myQuery.pat, myQuery.pat.initBindings, '', fetcher, callback, trunck)\n }, 0)\n }\n\n // returns nothing; callback does the work\n} // query\n","import Node from './node-internal'\nimport { DefaultGraphTermType } from './types'\nimport { DefaultGraph as TFDefaultGraph } from './tf-types'\nimport { defaultGraphURI } from './utils/default-graph-uri'\n\n/** The RDF default graph */\nexport default class DefaultGraph extends Node implements TFDefaultGraph {\n value: '' = '';\n termType: typeof DefaultGraphTermType = DefaultGraphTermType;\n uri = defaultGraphURI\n\n constructor () {\n super('')\n }\n\n toCanonical () {\n return this.value\n }\n\n toString () {\n return 'DefaultGraph';\n }\n}\n\nexport function isDefaultGraph(object: any): object is DefaultGraph {\n return !!object && object.termType === DefaultGraphTermType;\n}\n","/*\n * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst util = require('./util');\nconst JsonLdError = require('./JsonLdError');\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isString: _isString,\n isUndefined: _isUndefined\n} = require('./types');\n\nconst {\n isAbsolute: _isAbsoluteIri,\n isRelative: _isRelativeIri,\n prependBase\n} = require('./url');\n\nconst {\n asArray: _asArray,\n compareShortestLeast: _compareShortestLeast\n} = require('./util');\n\nconst INITIAL_CONTEXT_CACHE = new Map();\nconst INITIAL_CONTEXT_CACHE_MAX_SIZE = 10000;\nconst KEYWORD_PATTERN = /^@[a-zA-Z]+$/;\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Processes a local context and returns a new active context.\n *\n * @param activeCtx the current active context.\n * @param localCtx the local context to process.\n * @param options the context processing options.\n * @param propagate `true` if `false`, retains any previously defined term,\n * which can be rolled back when the descending into a new node object.\n * @param overrideProtected `false` allows protected terms to be modified.\n *\n * @return a Promise that resolves to the new active context.\n */\napi.process = async ({\n activeCtx, localCtx, options,\n propagate = true,\n overrideProtected = false,\n cycles = new Set()\n}) => {\n // normalize local context to an array of @context objects\n if(_isObject(localCtx) && '@context' in localCtx &&\n _isArray(localCtx['@context'])) {\n localCtx = localCtx['@context'];\n }\n const ctxs = _asArray(localCtx);\n\n // no contexts in array, return current active context w/o changes\n if(ctxs.length === 0) {\n return activeCtx;\n }\n\n // resolve contexts\n const resolved = await options.contextResolver.resolve({\n activeCtx,\n context: localCtx,\n documentLoader: options.documentLoader,\n base: options.base\n });\n\n // override propagate if first resolved context has `@propagate`\n if(_isObject(resolved[0].document) &&\n typeof resolved[0].document['@propagate'] === 'boolean') {\n // retrieve early, error checking done later\n propagate = resolved[0].document['@propagate'];\n }\n\n // process each context in order, update active context\n // on each iteration to ensure proper caching\n let rval = activeCtx;\n\n // track the previous context\n // if not propagating, make sure rval has a previous context\n if(!propagate && !rval.previousContext) {\n // clone `rval` context before updating\n rval = rval.clone();\n rval.previousContext = activeCtx;\n }\n\n for(const resolvedContext of resolved) {\n let {document: ctx} = resolvedContext;\n\n // update active context to one computed from last iteration\n activeCtx = rval;\n\n // reset to initial context\n if(ctx === null) {\n // We can't nullify if there are protected terms and we're\n // not allowing overrides (e.g. processing a property term scoped context)\n if(!overrideProtected &&\n Object.keys(activeCtx.protected).length !== 0) {\n const protectedMode = (options && options.protectedMode) || 'error';\n if(protectedMode === 'error') {\n throw new JsonLdError(\n 'Tried to nullify a context with protected terms outside of ' +\n 'a term definition.',\n 'jsonld.SyntaxError',\n {code: 'invalid context nullification'});\n } else if(protectedMode === 'warn') {\n // FIXME: remove logging and use a handler\n console.warn('WARNING: invalid context nullification');\n\n // get processed context from cache if available\n const processed = resolvedContext.getProcessed(activeCtx);\n if(processed) {\n rval = activeCtx = processed;\n continue;\n }\n\n const oldActiveCtx = activeCtx;\n // copy all protected term definitions to fresh initial context\n rval = activeCtx = api.getInitialContext(options).clone();\n for(const [term, _protected] of\n Object.entries(oldActiveCtx.protected)) {\n if(_protected) {\n activeCtx.mappings[term] =\n util.clone(oldActiveCtx.mappings[term]);\n }\n }\n activeCtx.protected = util.clone(oldActiveCtx.protected);\n\n // cache processed result\n resolvedContext.setProcessed(oldActiveCtx, rval);\n continue;\n }\n throw new JsonLdError(\n 'Invalid protectedMode.',\n 'jsonld.SyntaxError',\n {code: 'invalid protected mode', context: localCtx, protectedMode});\n }\n rval = activeCtx = api.getInitialContext(options).clone();\n continue;\n }\n\n // get processed context from cache if available\n const processed = resolvedContext.getProcessed(activeCtx);\n if(processed) {\n rval = activeCtx = processed;\n continue;\n }\n\n // dereference @context key if present\n if(_isObject(ctx) && '@context' in ctx) {\n ctx = ctx['@context'];\n }\n\n // context must be an object by now, all URLs retrieved before this call\n if(!_isObject(ctx)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context must be an object.',\n 'jsonld.SyntaxError', {code: 'invalid local context', context: ctx});\n }\n\n // TODO: there is likely a `previousContext` cloning optimization that\n // could be applied here (no need to copy it under certain conditions)\n\n // clone context before updating it\n rval = rval.clone();\n\n // define context mappings for keys in local context\n const defined = new Map();\n\n // handle @version\n if('@version' in ctx) {\n if(ctx['@version'] !== 1.1) {\n throw new JsonLdError(\n 'Unsupported JSON-LD version: ' + ctx['@version'],\n 'jsonld.UnsupportedVersion',\n {code: 'invalid @version value', context: ctx});\n }\n if(activeCtx.processingMode &&\n activeCtx.processingMode === 'json-ld-1.0') {\n throw new JsonLdError(\n '@version: ' + ctx['@version'] + ' not compatible with ' +\n activeCtx.processingMode,\n 'jsonld.ProcessingModeConflict',\n {code: 'processing mode conflict', context: ctx});\n }\n rval.processingMode = 'json-ld-1.1';\n rval['@version'] = ctx['@version'];\n defined.set('@version', true);\n }\n\n // if not set explicitly, set processingMode to \"json-ld-1.1\"\n rval.processingMode =\n rval.processingMode || activeCtx.processingMode;\n\n // handle @base\n if('@base' in ctx) {\n let base = ctx['@base'];\n\n if(base === null || _isAbsoluteIri(base)) {\n // no action\n } else if(_isRelativeIri(base)) {\n base = prependBase(rval['@base'], base);\n } else {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@base\" in a ' +\n '@context must be an absolute IRI, a relative IRI, or null.',\n 'jsonld.SyntaxError', {code: 'invalid base IRI', context: ctx});\n }\n\n rval['@base'] = base;\n defined.set('@base', true);\n }\n\n // handle @vocab\n if('@vocab' in ctx) {\n const value = ctx['@vocab'];\n if(value === null) {\n delete rval['@vocab'];\n } else if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@vocab\" in a ' +\n '@context must be a string or null.',\n 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx});\n } else if(!_isAbsoluteIri(value) && api.processingMode(rval, 1.0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@vocab\" in a ' +\n '@context must be an absolute IRI.',\n 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx});\n } else {\n rval['@vocab'] = _expandIri(rval, value, {vocab: true, base: true},\n undefined, undefined, options);\n }\n defined.set('@vocab', true);\n }\n\n // handle @language\n if('@language' in ctx) {\n const value = ctx['@language'];\n if(value === null) {\n delete rval['@language'];\n } else if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@language\" in a ' +\n '@context must be a string or null.',\n 'jsonld.SyntaxError',\n {code: 'invalid default language', context: ctx});\n } else {\n rval['@language'] = value.toLowerCase();\n }\n defined.set('@language', true);\n }\n\n // handle @direction\n if('@direction' in ctx) {\n const value = ctx['@direction'];\n if(activeCtx.processingMode === 'json-ld-1.0') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @direction not compatible with ' +\n activeCtx.processingMode,\n 'jsonld.SyntaxError',\n {code: 'invalid context member', context: ctx});\n }\n if(value === null) {\n delete rval['@direction'];\n } else if(value !== 'ltr' && value !== 'rtl') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@direction\" in a ' +\n '@context must be null, \"ltr\", or \"rtl\".',\n 'jsonld.SyntaxError',\n {code: 'invalid base direction', context: ctx});\n } else {\n rval['@direction'] = value;\n }\n defined.set('@direction', true);\n }\n\n // handle @propagate\n // note: we've already extracted it, here we just do error checking\n if('@propagate' in ctx) {\n const value = ctx['@propagate'];\n if(activeCtx.processingMode === 'json-ld-1.0') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @propagate not compatible with ' +\n activeCtx.processingMode,\n 'jsonld.SyntaxError',\n {code: 'invalid context entry', context: ctx});\n }\n if(typeof value !== 'boolean') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @propagate value must be a boolean.',\n 'jsonld.SyntaxError',\n {code: 'invalid @propagate value', context: localCtx});\n }\n defined.set('@propagate', true);\n }\n\n // handle @import\n if('@import' in ctx) {\n const value = ctx['@import'];\n if(activeCtx.processingMode === 'json-ld-1.0') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @import not compatible with ' +\n activeCtx.processingMode,\n 'jsonld.SyntaxError',\n {code: 'invalid context entry', context: ctx});\n }\n if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @import must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid @import value', context: localCtx});\n }\n\n // resolve contexts\n const resolvedImport = await options.contextResolver.resolve({\n activeCtx,\n context: value,\n documentLoader: options.documentLoader,\n base: options.base\n });\n if(resolvedImport.length !== 1) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @import must reference a single context.',\n 'jsonld.SyntaxError',\n {code: 'invalid remote context', context: localCtx});\n }\n const processedImport = resolvedImport[0].getProcessed(activeCtx);\n if(processedImport) {\n // Note: if the same context were used in this active context\n // as a reference context, then processed_input might not\n // be a dict.\n ctx = processedImport;\n } else {\n const importCtx = resolvedImport[0].document;\n if('@import' in importCtx) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax: ' +\n 'imported context must not include @import.',\n 'jsonld.SyntaxError',\n {code: 'invalid context entry', context: localCtx});\n }\n\n // merge ctx into importCtx and replace rval with the result\n for(const key in importCtx) {\n if(!ctx.hasOwnProperty(key)) {\n ctx[key] = importCtx[key];\n }\n }\n\n // Note: this could potenially conflict if the import\n // were used in the same active context as a referenced\n // context and an import. In this case, we\n // could override the cached result, but seems unlikely.\n resolvedImport[0].setProcessed(activeCtx, ctx);\n }\n\n defined.set('@import', true);\n }\n\n // handle @protected; determine whether this sub-context is declaring\n // all its terms to be \"protected\" (exceptions can be made on a\n // per-definition basis)\n defined.set('@protected', ctx['@protected'] || false);\n\n // process all other keys\n for(const key in ctx) {\n api.createTermDefinition({\n activeCtx: rval,\n localCtx: ctx,\n term: key,\n defined,\n options,\n overrideProtected\n });\n\n if(_isObject(ctx[key]) && '@context' in ctx[key]) {\n const keyCtx = ctx[key]['@context'];\n let process = true;\n if(_isString(keyCtx)) {\n const url = prependBase(options.base, keyCtx);\n // track processed contexts to avoid scoped context recursion\n if(cycles.has(url)) {\n process = false;\n } else {\n cycles.add(url);\n }\n }\n // parse context to validate\n if(process) {\n try {\n await api.process({\n activeCtx: rval.clone(),\n localCtx: ctx[key]['@context'],\n overrideProtected: true,\n options,\n cycles\n });\n } catch(e) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid scoped context.',\n 'jsonld.SyntaxError',\n {\n code: 'invalid scoped context',\n context: ctx[key]['@context'],\n term: key\n });\n }\n }\n }\n }\n\n // cache processed result\n resolvedContext.setProcessed(activeCtx, rval);\n }\n\n return rval;\n};\n\n/**\n * Creates a term definition during context processing.\n *\n * @param activeCtx the current active context.\n * @param localCtx the local context being processed.\n * @param term the term in the local context to define the mapping for.\n * @param defined a map of defining/defined keys to detect cycles and prevent\n * double definitions.\n * @param {Object} [options] - creation options.\n * @param {string} [options.protectedMode=\"error\"] - \"error\" to throw error\n * on `@protected` constraint violation, \"warn\" to allow violations and\n * signal a warning.\n * @param overrideProtected `false` allows protected terms to be modified.\n */\napi.createTermDefinition = ({\n activeCtx,\n localCtx,\n term,\n defined,\n options,\n overrideProtected = false,\n}) => {\n if(defined.has(term)) {\n // term already defined\n if(defined.get(term)) {\n return;\n }\n // cycle detected\n throw new JsonLdError(\n 'Cyclical context definition detected.',\n 'jsonld.CyclicalContext',\n {code: 'cyclic IRI mapping', context: localCtx, term});\n }\n\n // now defining term\n defined.set(term, false);\n\n // get context term value\n let value;\n if(localCtx.hasOwnProperty(term)) {\n value = localCtx[term];\n }\n\n if(term === '@type' &&\n _isObject(value) &&\n (value['@container'] || '@set') === '@set' &&\n api.processingMode(activeCtx, 1.1)) {\n\n const validKeys = ['@container', '@id', '@protected'];\n const keys = Object.keys(value);\n if(keys.length === 0 || keys.some(k => !validKeys.includes(k))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; keywords cannot be overridden.',\n 'jsonld.SyntaxError',\n {code: 'keyword redefinition', context: localCtx, term});\n }\n } else if(api.isKeyword(term)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; keywords cannot be overridden.',\n 'jsonld.SyntaxError',\n {code: 'keyword redefinition', context: localCtx, term});\n } else if(term.match(KEYWORD_PATTERN)) {\n // FIXME: remove logging and use a handler\n console.warn('WARNING: terms beginning with \"@\" are reserved' +\n ' for future use and ignored', {term});\n return;\n } else if(term === '') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a term cannot be an empty string.',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n\n // keep reference to previous mapping for potential `@protected` check\n const previousMapping = activeCtx.mappings.get(term);\n\n // remove old mapping\n if(activeCtx.mappings.has(term)) {\n activeCtx.mappings.delete(term);\n }\n\n // convert short-hand value to object w/@id\n let simpleTerm = false;\n if(_isString(value) || value === null) {\n simpleTerm = true;\n value = {'@id': value};\n }\n\n if(!_isObject(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context term values must be ' +\n 'strings or objects.',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n\n // create new mapping\n const mapping = {};\n activeCtx.mappings.set(term, mapping);\n mapping.reverse = false;\n\n // make sure term definition only has expected keywords\n const validKeys = ['@container', '@id', '@language', '@reverse', '@type'];\n\n // JSON-LD 1.1 support\n if(api.processingMode(activeCtx, 1.1)) {\n validKeys.push(\n '@context', '@direction', '@index', '@nest', '@prefix', '@protected');\n }\n\n for(const kw in value) {\n if(!validKeys.includes(kw)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a term definition must not contain ' + kw,\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n }\n\n // always compute whether term has a colon as an optimization for\n // _compactIri\n const colon = term.indexOf(':');\n mapping._termHasColon = (colon > 0);\n\n if('@reverse' in value) {\n if('@id' in value) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @reverse term definition must not ' +\n 'contain @id.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property', context: localCtx});\n }\n if('@nest' in value) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @reverse term definition must not ' +\n 'contain @nest.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property', context: localCtx});\n }\n const reverse = value['@reverse'];\n if(!_isString(reverse)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @reverse value must be a string.',\n 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});\n }\n\n if(!api.isKeyword(reverse) && reverse.match(KEYWORD_PATTERN)) {\n // FIXME: remove logging and use a handler\n console.warn('WARNING: values beginning with \"@\" are reserved' +\n ' for future use and ignored', {reverse});\n if(previousMapping) {\n activeCtx.mappings.set(term, previousMapping);\n } else {\n activeCtx.mappings.delete(term);\n }\n return;\n }\n\n // expand and add @id mapping\n const id = _expandIri(\n activeCtx, reverse, {vocab: true, base: false}, localCtx, defined,\n options);\n if(!_isAbsoluteIri(id)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @reverse value must be an ' +\n 'absolute IRI or a blank node identifier.',\n 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});\n }\n\n mapping['@id'] = id;\n mapping.reverse = true;\n } else if('@id' in value) {\n let id = value['@id'];\n if(id && !_isString(id)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @id value must be an array ' +\n 'of strings or a string.',\n 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});\n }\n if(id === null) {\n // reserve a null term, which may be protected\n mapping['@id'] = null;\n } else if(!api.isKeyword(id) && id.match(KEYWORD_PATTERN)) {\n // FIXME: remove logging and use a handler\n console.warn('WARNING: values beginning with \"@\" are reserved' +\n ' for future use and ignored', {id});\n if(previousMapping) {\n activeCtx.mappings.set(term, previousMapping);\n } else {\n activeCtx.mappings.delete(term);\n }\n return;\n } else if(id !== term) {\n // expand and add @id mapping\n id = _expandIri(\n activeCtx, id, {vocab: true, base: false}, localCtx, defined, options);\n if(!_isAbsoluteIri(id) && !api.isKeyword(id)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @id value must be an ' +\n 'absolute IRI, a blank node identifier, or a keyword.',\n 'jsonld.SyntaxError',\n {code: 'invalid IRI mapping', context: localCtx});\n }\n\n // if term has the form of an IRI it must map the same\n if(term.match(/(?::[^:])|\\//)) {\n const termDefined = new Map(defined).set(term, true);\n const termIri = _expandIri(\n activeCtx, term, {vocab: true, base: false},\n localCtx, termDefined, options);\n if(termIri !== id) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; term in form of IRI must ' +\n 'expand to definition.',\n 'jsonld.SyntaxError',\n {code: 'invalid IRI mapping', context: localCtx});\n }\n }\n\n mapping['@id'] = id;\n // indicate if this term may be used as a compact IRI prefix\n mapping._prefix = (simpleTerm &&\n !mapping._termHasColon &&\n id.match(/[:\\/\\?#\\[\\]@]$/));\n }\n }\n\n if(!('@id' in mapping)) {\n // see if the term has a prefix\n if(mapping._termHasColon) {\n const prefix = term.substr(0, colon);\n if(localCtx.hasOwnProperty(prefix)) {\n // define parent prefix\n api.createTermDefinition({\n activeCtx, localCtx, term: prefix, defined, options\n });\n }\n\n if(activeCtx.mappings.has(prefix)) {\n // set @id based on prefix parent\n const suffix = term.substr(colon + 1);\n mapping['@id'] = activeCtx.mappings.get(prefix)['@id'] + suffix;\n } else {\n // term is an absolute IRI\n mapping['@id'] = term;\n }\n } else if(term === '@type') {\n // Special case, were we've previously determined that container is @set\n mapping['@id'] = term;\n } else {\n // non-IRIs *must* define @ids if @vocab is not available\n if(!('@vocab' in activeCtx)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context terms must define an @id.',\n 'jsonld.SyntaxError',\n {code: 'invalid IRI mapping', context: localCtx, term});\n }\n // prepend vocab to term\n mapping['@id'] = activeCtx['@vocab'] + term;\n }\n }\n\n // Handle term protection\n if(value['@protected'] === true ||\n (defined.get('@protected') === true && value['@protected'] !== false)) {\n activeCtx.protected[term] = true;\n mapping.protected = true;\n }\n\n // IRI mapping now defined\n defined.set(term, true);\n\n if('@type' in value) {\n let type = value['@type'];\n if(!_isString(type)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n\n if((type === '@json' || type === '@none')) {\n if(api.processingMode(activeCtx, 1.0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type value must not be ' +\n `\"${type}\" in JSON-LD 1.0 mode.`,\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n } else if(type !== '@id' && type !== '@vocab') {\n // expand @type to full IRI\n type = _expandIri(\n activeCtx, type, {vocab: true, base: false}, localCtx, defined,\n options);\n if(!_isAbsoluteIri(type)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type value must be an ' +\n 'absolute IRI.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n if(type.indexOf('_:') === 0) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type value must be an IRI, ' +\n 'not a blank node identifier.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n }\n\n // add @type to mapping\n mapping['@type'] = type;\n }\n\n if('@container' in value) {\n // normalize container to an array form\n const container = _isString(value['@container']) ?\n [value['@container']] : (value['@container'] || []);\n const validContainers = ['@list', '@set', '@index', '@language'];\n let isValid = true;\n const hasSet = container.includes('@set');\n\n // JSON-LD 1.1 support\n if(api.processingMode(activeCtx, 1.1)) {\n validContainers.push('@graph', '@id', '@type');\n\n // check container length\n if(container.includes('@list')) {\n if(container.length !== 1) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container with @list must ' +\n 'have no other values',\n 'jsonld.SyntaxError',\n {code: 'invalid container mapping', context: localCtx});\n }\n } else if(container.includes('@graph')) {\n if(container.some(key =>\n key !== '@graph' && key !== '@id' && key !== '@index' &&\n key !== '@set')) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container with @graph must ' +\n 'have no other values other than @id, @index, and @set',\n 'jsonld.SyntaxError',\n {code: 'invalid container mapping', context: localCtx});\n }\n } else {\n // otherwise, container may also include @set\n isValid &= container.length <= (hasSet ? 2 : 1);\n }\n\n if(container.includes('@type')) {\n // If mapping does not have an @type,\n // set it to @id\n mapping['@type'] = mapping['@type'] || '@id';\n\n // type mapping must be either @id or @vocab\n if(!['@id', '@vocab'].includes(mapping['@type'])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; container: @type requires @type to be ' +\n '@id or @vocab.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n }\n } else {\n // in JSON-LD 1.0, container must not be an array (it must be a string,\n // which is one of the validContainers)\n isValid &= !_isArray(value['@container']);\n\n // check container length\n isValid &= container.length <= 1;\n }\n\n // check against valid containers\n isValid &= container.every(c => validContainers.includes(c));\n\n // @set not allowed with @list\n isValid &= !(hasSet && container.includes('@list'));\n\n if(!isValid) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container value must be ' +\n 'one of the following: ' + validContainers.join(', '),\n 'jsonld.SyntaxError',\n {code: 'invalid container mapping', context: localCtx});\n }\n\n if(mapping.reverse &&\n !container.every(c => ['@index', '@set'].includes(c))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container value for a @reverse ' +\n 'type definition must be @index or @set.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property', context: localCtx});\n }\n\n // add @container to mapping\n mapping['@container'] = container;\n }\n\n // property indexing\n if('@index' in value) {\n if(!('@container' in value) || !mapping['@container'].includes('@index')) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @index without @index in @container: ' +\n `\"${value['@index']}\" on term \"${term}\".`, 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n if(!_isString(value['@index']) || value['@index'].indexOf('@') === 0) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @index must expand to an IRI: ' +\n `\"${value['@index']}\" on term \"${term}\".`, 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n mapping['@index'] = value['@index'];\n }\n\n // scoped contexts\n if('@context' in value) {\n mapping['@context'] = value['@context'];\n }\n\n if('@language' in value && !('@type' in value)) {\n let language = value['@language'];\n if(language !== null && !_isString(language)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @language value must be ' +\n 'a string or null.', 'jsonld.SyntaxError',\n {code: 'invalid language mapping', context: localCtx});\n }\n\n // add @language to mapping\n if(language !== null) {\n language = language.toLowerCase();\n }\n mapping['@language'] = language;\n }\n\n // term may be used as a prefix\n if('@prefix' in value) {\n if(term.match(/:|\\//)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @prefix used on a compact IRI term',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n if(api.isKeyword(mapping['@id'])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; keywords may not be used as prefixes',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n if(typeof value['@prefix'] === 'boolean') {\n mapping._prefix = value['@prefix'] === true;\n } else {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context value for @prefix must be boolean',\n 'jsonld.SyntaxError',\n {code: 'invalid @prefix value', context: localCtx});\n }\n }\n\n if('@direction' in value) {\n const direction = value['@direction'];\n if(direction !== null && direction !== 'ltr' && direction !== 'rtl') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @direction value must be ' +\n 'null, \"ltr\", or \"rtl\".',\n 'jsonld.SyntaxError',\n {code: 'invalid base direction', context: localCtx});\n }\n mapping['@direction'] = direction;\n }\n\n if('@nest' in value) {\n const nest = value['@nest'];\n if(!_isString(nest) || (nest !== '@nest' && nest.indexOf('@') === 0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @nest value must be ' +\n 'a string which is not a keyword other than @nest.',\n 'jsonld.SyntaxError',\n {code: 'invalid @nest value', context: localCtx});\n }\n mapping['@nest'] = nest;\n }\n\n // disallow aliasing @context and @preserve\n const id = mapping['@id'];\n if(id === '@context' || id === '@preserve') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context and @preserve cannot be aliased.',\n 'jsonld.SyntaxError', {code: 'invalid keyword alias', context: localCtx});\n }\n\n // Check for overriding protected terms\n if(previousMapping && previousMapping.protected && !overrideProtected) {\n // force new term to continue to be protected and see if the mappings would\n // be equal\n activeCtx.protected[term] = true;\n mapping.protected = true;\n if(!_deepCompare(previousMapping, mapping)) {\n const protectedMode = (options && options.protectedMode) || 'error';\n if(protectedMode === 'error') {\n throw new JsonLdError(\n `Invalid JSON-LD syntax; tried to redefine \"${term}\" which is a ` +\n 'protected term.',\n 'jsonld.SyntaxError',\n {code: 'protected term redefinition', context: localCtx, term});\n } else if(protectedMode === 'warn') {\n // FIXME: remove logging and use a handler\n console.warn('WARNING: protected term redefinition', {term});\n return;\n }\n throw new JsonLdError(\n 'Invalid protectedMode.',\n 'jsonld.SyntaxError',\n {code: 'invalid protected mode', context: localCtx, term,\n protectedMode});\n }\n }\n};\n\n/**\n * Expands a string to a full IRI. The string may be a term, a prefix, a\n * relative IRI, or an absolute IRI. The associated absolute IRI will be\n * returned.\n *\n * @param activeCtx the current active context.\n * @param value the string to expand.\n * @param relativeTo options for how to resolve relative IRIs:\n * base: true to resolve against the base IRI, false not to.\n * vocab: true to concatenate after @vocab, false not to.\n * @param {Object} [options] - processing options.\n *\n * @return the expanded value.\n */\napi.expandIri = (activeCtx, value, relativeTo, options) => {\n return _expandIri(activeCtx, value, relativeTo, undefined, undefined,\n options);\n};\n\n/**\n * Expands a string to a full IRI. The string may be a term, a prefix, a\n * relative IRI, or an absolute IRI. The associated absolute IRI will be\n * returned.\n *\n * @param activeCtx the current active context.\n * @param value the string to expand.\n * @param relativeTo options for how to resolve relative IRIs:\n * base: true to resolve against the base IRI, false not to.\n * vocab: true to concatenate after @vocab, false not to.\n * @param localCtx the local context being processed (only given if called\n * during context processing).\n * @param defined a map for tracking cycles in context definitions (only given\n * if called during context processing).\n * @param {Object} [options] - processing options.\n *\n * @return the expanded value.\n */\nfunction _expandIri(activeCtx, value, relativeTo, localCtx, defined, options) {\n // already expanded\n if(value === null || !_isString(value) || api.isKeyword(value)) {\n return value;\n }\n\n // ignore non-keyword things that look like a keyword\n if(value.match(KEYWORD_PATTERN)) {\n return null;\n }\n\n // define term dependency if not defined\n if(localCtx && localCtx.hasOwnProperty(value) &&\n defined.get(value) !== true) {\n api.createTermDefinition({\n activeCtx, localCtx, term: value, defined, options\n });\n }\n\n relativeTo = relativeTo || {};\n if(relativeTo.vocab) {\n const mapping = activeCtx.mappings.get(value);\n\n // value is explicitly ignored with a null mapping\n if(mapping === null) {\n return null;\n }\n\n if(_isObject(mapping) && '@id' in mapping) {\n // value is a term\n return mapping['@id'];\n }\n }\n\n // split value into prefix:suffix\n const colon = value.indexOf(':');\n if(colon > 0) {\n const prefix = value.substr(0, colon);\n const suffix = value.substr(colon + 1);\n\n // do not expand blank nodes (prefix of '_') or already-absolute\n // IRIs (suffix of '//')\n if(prefix === '_' || suffix.indexOf('//') === 0) {\n return value;\n }\n\n // prefix dependency not defined, define it\n if(localCtx && localCtx.hasOwnProperty(prefix)) {\n api.createTermDefinition({\n activeCtx, localCtx, term: prefix, defined, options\n });\n }\n\n // use mapping if prefix is defined\n const mapping = activeCtx.mappings.get(prefix);\n if(mapping && mapping._prefix) {\n return mapping['@id'] + suffix;\n }\n\n // already absolute IRI\n if(_isAbsoluteIri(value)) {\n return value;\n }\n }\n\n // prepend vocab\n if(relativeTo.vocab && '@vocab' in activeCtx) {\n return activeCtx['@vocab'] + value;\n }\n\n // prepend base\n if(relativeTo.base && '@base' in activeCtx) {\n if(activeCtx['@base']) {\n // The null case preserves value as potentially relative\n return prependBase(prependBase(options.base, activeCtx['@base']), value);\n }\n } else if(relativeTo.base) {\n return prependBase(options.base, value);\n }\n\n return value;\n}\n\n/**\n * Gets the initial context.\n *\n * @param options the options to use:\n * [base] the document base IRI.\n *\n * @return the initial context.\n */\napi.getInitialContext = options => {\n const key = JSON.stringify({processingMode: options.processingMode});\n const cached = INITIAL_CONTEXT_CACHE.get(key);\n if(cached) {\n return cached;\n }\n\n const initialContext = {\n processingMode: options.processingMode,\n mappings: new Map(),\n inverse: null,\n getInverse: _createInverseContext,\n clone: _cloneActiveContext,\n revertToPreviousContext: _revertToPreviousContext,\n protected: {}\n };\n // TODO: consider using LRU cache instead\n if(INITIAL_CONTEXT_CACHE.size === INITIAL_CONTEXT_CACHE_MAX_SIZE) {\n // clear whole cache -- assumes scenario where the cache fills means\n // the cache isn't being used very efficiently anyway\n INITIAL_CONTEXT_CACHE.clear();\n }\n INITIAL_CONTEXT_CACHE.set(key, initialContext);\n return initialContext;\n\n /**\n * Generates an inverse context for use in the compaction algorithm, if\n * not already generated for the given active context.\n *\n * @return the inverse context.\n */\n function _createInverseContext() {\n const activeCtx = this;\n\n // lazily create inverse\n if(activeCtx.inverse) {\n return activeCtx.inverse;\n }\n const inverse = activeCtx.inverse = {};\n\n // variables for building fast CURIE map\n const fastCurieMap = activeCtx.fastCurieMap = {};\n const irisToTerms = {};\n\n // handle default language\n const defaultLanguage = (activeCtx['@language'] || '@none').toLowerCase();\n\n // handle default direction\n const defaultDirection = activeCtx['@direction'];\n\n // create term selections for each mapping in the context, ordered by\n // shortest and then lexicographically least\n const mappings = activeCtx.mappings;\n const terms = [...mappings.keys()].sort(_compareShortestLeast);\n for(const term of terms) {\n const mapping = mappings.get(term);\n if(mapping === null) {\n continue;\n }\n\n let container = mapping['@container'] || '@none';\n container = [].concat(container).sort().join('');\n\n if(mapping['@id'] === null) {\n continue;\n }\n // iterate over every IRI in the mapping\n const ids = _asArray(mapping['@id']);\n for(const iri of ids) {\n let entry = inverse[iri];\n const isKeyword = api.isKeyword(iri);\n\n if(!entry) {\n // initialize entry\n inverse[iri] = entry = {};\n\n if(!isKeyword && !mapping._termHasColon) {\n // init IRI to term map and fast CURIE prefixes\n irisToTerms[iri] = [term];\n const fastCurieEntry = {iri, terms: irisToTerms[iri]};\n if(iri[0] in fastCurieMap) {\n fastCurieMap[iri[0]].push(fastCurieEntry);\n } else {\n fastCurieMap[iri[0]] = [fastCurieEntry];\n }\n }\n } else if(!isKeyword && !mapping._termHasColon) {\n // add IRI to term match\n irisToTerms[iri].push(term);\n }\n\n // add new entry\n if(!entry[container]) {\n entry[container] = {\n '@language': {},\n '@type': {},\n '@any': {}\n };\n }\n entry = entry[container];\n _addPreferredTerm(term, entry['@any'], '@none');\n\n if(mapping.reverse) {\n // term is preferred for values using @reverse\n _addPreferredTerm(term, entry['@type'], '@reverse');\n } else if(mapping['@type'] === '@none') {\n _addPreferredTerm(term, entry['@any'], '@none');\n _addPreferredTerm(term, entry['@language'], '@none');\n _addPreferredTerm(term, entry['@type'], '@none');\n } else if('@type' in mapping) {\n // term is preferred for values using specific type\n _addPreferredTerm(term, entry['@type'], mapping['@type']);\n } else if('@language' in mapping && '@direction' in mapping) {\n // term is preferred for values using specific language and direction\n const language = mapping['@language'];\n const direction = mapping['@direction'];\n if(language && direction) {\n _addPreferredTerm(term, entry['@language'],\n `${language}_${direction}`.toLowerCase());\n } else if(language) {\n _addPreferredTerm(term, entry['@language'], language.toLowerCase());\n } else if(direction) {\n _addPreferredTerm(term, entry['@language'], `_${direction}`);\n } else {\n _addPreferredTerm(term, entry['@language'], '@null');\n }\n } else if('@language' in mapping) {\n _addPreferredTerm(term, entry['@language'],\n (mapping['@language'] || '@null').toLowerCase());\n } else if('@direction' in mapping) {\n if(mapping['@direction']) {\n _addPreferredTerm(term, entry['@language'],\n `_${mapping['@direction']}`);\n } else {\n _addPreferredTerm(term, entry['@language'], '@none');\n }\n } else if(defaultDirection) {\n _addPreferredTerm(term, entry['@language'], `_${defaultDirection}`);\n _addPreferredTerm(term, entry['@language'], '@none');\n _addPreferredTerm(term, entry['@type'], '@none');\n } else {\n // add entries for no type and no language\n _addPreferredTerm(term, entry['@language'], defaultLanguage);\n _addPreferredTerm(term, entry['@language'], '@none');\n _addPreferredTerm(term, entry['@type'], '@none');\n }\n }\n }\n\n // build fast CURIE map\n for(const key in fastCurieMap) {\n _buildIriMap(fastCurieMap, key, 1);\n }\n\n return inverse;\n }\n\n /**\n * Runs a recursive algorithm to build a lookup map for quickly finding\n * potential CURIEs.\n *\n * @param iriMap the map to build.\n * @param key the current key in the map to work on.\n * @param idx the index into the IRI to compare.\n */\n function _buildIriMap(iriMap, key, idx) {\n const entries = iriMap[key];\n const next = iriMap[key] = {};\n\n let iri;\n let letter;\n for(const entry of entries) {\n iri = entry.iri;\n if(idx >= iri.length) {\n letter = '';\n } else {\n letter = iri[idx];\n }\n if(letter in next) {\n next[letter].push(entry);\n } else {\n next[letter] = [entry];\n }\n }\n\n for(const key in next) {\n if(key === '') {\n continue;\n }\n _buildIriMap(next, key, idx + 1);\n }\n }\n\n /**\n * Adds the term for the given entry if not already added.\n *\n * @param term the term to add.\n * @param entry the inverse context typeOrLanguage entry to add to.\n * @param typeOrLanguageValue the key in the entry to add to.\n */\n function _addPreferredTerm(term, entry, typeOrLanguageValue) {\n if(!entry.hasOwnProperty(typeOrLanguageValue)) {\n entry[typeOrLanguageValue] = term;\n }\n }\n\n /**\n * Clones an active context, creating a child active context.\n *\n * @return a clone (child) of the active context.\n */\n function _cloneActiveContext() {\n const child = {};\n child.mappings = util.clone(this.mappings);\n child.clone = this.clone;\n child.inverse = null;\n child.getInverse = this.getInverse;\n child.protected = util.clone(this.protected);\n if(this.previousContext) {\n child.previousContext = this.previousContext.clone();\n }\n child.revertToPreviousContext = this.revertToPreviousContext;\n if('@base' in this) {\n child['@base'] = this['@base'];\n }\n if('@language' in this) {\n child['@language'] = this['@language'];\n }\n if('@vocab' in this) {\n child['@vocab'] = this['@vocab'];\n }\n return child;\n }\n\n /**\n * Reverts any type-scoped context in this active context to the previous\n * context.\n */\n function _revertToPreviousContext() {\n if(!this.previousContext) {\n return this;\n }\n return this.previousContext.clone();\n }\n};\n\n/**\n * Gets the value for the given active context key and type, null if none is\n * set or undefined if none is set and type is '@context'.\n *\n * @param ctx the active context.\n * @param key the context key.\n * @param [type] the type of value to get (eg: '@id', '@type'), if not\n * specified gets the entire entry for a key, null if not found.\n *\n * @return the value, null, or undefined.\n */\napi.getContextValue = (ctx, key, type) => {\n // invalid key\n if(key === null) {\n if(type === '@context') {\n return undefined;\n }\n return null;\n }\n\n // get specific entry information\n if(ctx.mappings.has(key)) {\n const entry = ctx.mappings.get(key);\n\n if(_isUndefined(type)) {\n // return whole entry\n return entry;\n }\n if(entry.hasOwnProperty(type)) {\n // return entry value for type\n return entry[type];\n }\n }\n\n // get default language\n if(type === '@language' && type in ctx) {\n return ctx[type];\n }\n\n // get default direction\n if(type === '@direction' && type in ctx) {\n return ctx[type];\n }\n\n if(type === '@context') {\n return undefined;\n }\n return null;\n};\n\n/**\n * Processing Mode check.\n *\n * @param activeCtx the current active context.\n * @param version the string or numeric version to check.\n *\n * @return boolean.\n */\napi.processingMode = (activeCtx, version) => {\n if(version.toString() >= '1.1') {\n return !activeCtx.processingMode ||\n activeCtx.processingMode >= 'json-ld-' + version.toString();\n } else {\n return activeCtx.processingMode === 'json-ld-1.0';\n }\n};\n\n/**\n * Returns whether or not the given value is a keyword.\n *\n * @param v the value to check.\n *\n * @return true if the value is a keyword, false if not.\n */\napi.isKeyword = v => {\n if(!_isString(v) || v[0] !== '@') {\n return false;\n }\n switch(v) {\n case '@base':\n case '@container':\n case '@context':\n case '@default':\n case '@direction':\n case '@embed':\n case '@explicit':\n case '@graph':\n case '@id':\n case '@included':\n case '@index':\n case '@json':\n case '@language':\n case '@list':\n case '@nest':\n case '@none':\n case '@omitDefault':\n case '@prefix':\n case '@preserve':\n case '@protected':\n case '@requireAll':\n case '@reverse':\n case '@set':\n case '@type':\n case '@value':\n case '@version':\n case '@vocab':\n return true;\n }\n return false;\n};\n\nfunction _deepCompare(x1, x2) {\n // compare `null` or primitive types directly\n if((!(x1 && typeof x1 === 'object')) ||\n (!(x2 && typeof x2 === 'object'))) {\n return x1 === x2;\n }\n // x1 and x2 are objects (also potentially arrays)\n const x1Array = Array.isArray(x1);\n if(x1Array !== Array.isArray(x2)) {\n return false;\n }\n if(x1Array) {\n if(x1.length !== x2.length) {\n return false;\n }\n for(let i = 0; i < x1.length; ++i) {\n if(!_deepCompare(x1[i], x2[i])) {\n return false;\n }\n }\n return true;\n }\n // x1 and x2 are non-array objects\n const k1s = Object.keys(x1);\n const k2s = Object.keys(x2);\n if(k1s.length !== k2s.length) {\n return false;\n }\n for(const k1 in x1) {\n let v1 = x1[k1];\n let v2 = x2[k1];\n // special case: `@container` can be in any order\n if(k1 === '@container') {\n if(Array.isArray(v1) && Array.isArray(v2)) {\n v1 = v1.slice().sort();\n v2 = v2.slice().sort();\n }\n }\n if(!_deepCompare(v1, v2)) {\n return false;\n }\n }\n return true;\n}\n","/* global $SolidTestEnvironment */\n/**\n *\n * Project: rdflib.js\n *\n * @file: fetcher.js\n *\n * Description: contains functions for requesting/fetching/retracting\n * This implements quite a lot of the web architecture.\n * A fetcher is bound to a specific quad store, into which\n * it loads stuff and into which it writes its metadata\n * @@ The metadata could be optionally a separate graph\n *\n * - implements semantics of HTTP headers, Internet Content Types\n * - selects parsers for rdf/xml, n3, rdfa, grddl\n *\n * TO do:\n * - Implement a runtime registry for parsers and serializers\n * -\n */\n\n/**\n * Things to test: callbacks on request, refresh, retract\n * loading from HTTP, HTTPS, FTP, FILE, others?\n * To do:\n * Firing up a mail client for mid: (message:) URLs\n */\nimport IndexedFormula from './store'\nimport log from './log'\nimport N3Parser from './n3parser'\nimport RDFlibNamedNode from './named-node'\nimport Namespace from './namespace'\nimport rdfParse from './parse'\nimport { parseRDFaDOM } from './rdfaparser'\nimport RDFParser from './rdfxmlparser'\nimport * as Uri from './uri'\nimport { isCollection, isNamedNode} from './utils/terms'\nimport * as Util from './utils-js'\nimport serialize from './serialize'\nimport crossFetch, { Headers } from 'cross-fetch'\n\nimport {\n ContentType, TurtleContentType, RDFXMLContentType, XHTMLContentType\n} from './types'\nimport { termValue } from './utils/termValue'\nimport {\n BlankNode,\n RdfJsDataFactory,\n Quad_Graph,\n NamedNode,\n Quad_Predicate,\n Quad_Subject\n} from './tf-types'\nimport jsonldParser from './jsonldparser'\n\nconst Parsable = {\n 'text/n3': true,\n 'text/turtle': true,\n 'application/rdf+xml': true,\n 'application/xhtml+xml': true,\n 'text/html': true,\n 'application/ld+json': true\n}\n\n// This is a minimal set to allow the use of damaged servers if necessary\nconst CONTENT_TYPE_BY_EXT = {\n 'rdf': RDFXMLContentType,\n 'owl': RDFXMLContentType,\n 'n3': 'text/n3',\n 'ttl': 'text/turtle',\n 'nt': 'text/n3',\n 'acl': 'text/n3',\n 'html': 'text/html',\n 'xml': 'text/xml'\n}\n\n// Convenience namespaces needed in this module.\n// These are deliberately not exported as the user application should\n// make its own list and not rely on the prefixes used here,\n// and not be tempted to add to them, and them clash with those of another\n// application.\nconst getNS = (factory?: RdfJsDataFactory) => {\n return {\n link: Namespace('http://www.w3.org/2007/ont/link#', factory),\n http: Namespace('http://www.w3.org/2007/ont/http#', factory),\n httph: Namespace('http://www.w3.org/2007/ont/httph#', factory), // headers\n rdf: Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#', factory),\n rdfs: Namespace('http://www.w3.org/2000/01/rdf-schema#', factory),\n dc: Namespace('http://purl.org/dc/elements/1.1/', factory),\n ldp: Namespace('http://www.w3.org/ns/ldp#', factory)\n }\n}\nconst ns = getNS()\n\nexport interface FetchError extends Error {\n statusText?: string\n status?: StatusValues\n response?: ExtendedResponse\n}\n\n/** An extended interface of Response, since RDFlib.js adds some properties. */\nexport interface ExtendedResponse extends Response {\n /** String representation of the Body */\n responseText?: string\n /** Identifier of the reqest */\n req?: Quad_Subject\n size?: number\n timeout?: number\n /** Used in UpdateManager.updateDav */\n error?: string\n}\n\n/** tell typescript that a 'panes' child may exist on Window */\ndeclare global {\n interface Window {\n panes?: any\n solidFetcher?: any\n solidFetch?: any\n }\n var solidFetcher: Function\n var solidFetch: Function\n}\ndeclare var $SolidTestEnvironment: {\n localSiteMap?: any\n}\n\ntype UserCallback = (\n ok: boolean,\n message: string,\n response?: any\n) => void\n\ntype HTTPMethods = 'GET' | 'PUT' | 'POST' | 'PATCH' | 'HEAD' | 'DELETE' | 'CONNECT' | 'TRACE' | 'OPTIONS'\n\n/** All valid inputs for initFetchOptions */\ntype Options = Partial<AutoInitOptions>\n\n/** Initiated by initFetchOptions, which runs on load */\nexport interface AutoInitOptions extends RequestInit{\n /** The used Fetch function */\n fetch?: Fetch\n /**\n * Referring term, the resource which\n * referred to this (for tracking bad links).\n * The document in which this link was found.\n */\n referringTerm?: NamedNode\n /** Provided content type (for writes) */\n contentType?: string\n /**\n * Override the incoming header to\n * force the data to be treated as this content-type (for reads)\n */\n forceContentType?: ContentType\n /**\n * Load the data even if loaded before.\n * Also sets the `Cache-Control:` header to `no-cache`\n */\n force?: boolean\n /**\n * Original uri to preserve\n * through proxying etc (`xhr.original`).\n */\n baseURI: string\n /**\n * Whether this request is a retry via\n * a proxy (generally done from an error handler)\n */\n proxyUsed?: boolean\n actualProxyURI?: string\n /** flag for XHR/CORS etc */\n withCredentials?: boolean\n /** Before we parse new data, clear old, but only on status 200 responses */\n clearPreviousData?: boolean\n /** Prevents the addition of various metadata triples (about the fetch request) to the store*/\n noMeta?: boolean\n noRDFa?: boolean\n handlers?: Handler[]\n timeout?: number\n method?: HTTPMethods\n retriedWithNoCredentials?: boolean\n requestedURI?: string\n // Seems to be required in some functions, such as XHTML parse and RedirectToProxy\n resource: Quad_Subject\n /** The serialized resource in the body*/\n // Used for storing metadata of requests\n original: NamedNode\n // Like requeststatus? Can contain text with error.\n data?: string\n // Probably an identifier for request?s\n req: BlankNode\n // Might be the same as Options.data\n body?: string\n headers: HeadersInit\n credentials?: 'include' | 'omit'\n}\n\nclass Handler {\n // TODO: Document, type\n response: ExtendedResponse\n // TODO: Document, type\n dom: Document\n static pattern: RegExp\n\n constructor (response: ExtendedResponse, dom?: Document) {\n this.response = response\n // The type assertion operator here might need to be removed.\n this.dom = dom!\n }\n}\n\nclass RDFXMLHandler extends Handler {\n static toString () {\n return 'RDFXMLHandler'\n }\n\n static register (fetcher: Fetcher) {\n fetcher.mediatypes[RDFXMLContentType] = {\n 'q': 0.9\n }\n }\n\n parse (\n fetcher: Fetcher,\n /** An XML String */\n responseText: String,\n /** Requires .original */\n options: {\n original: Quad_Subject\n req: Quad_Subject\n } & Options,\n ) {\n let kb = fetcher.store\n if (!this.dom) {\n this.dom = Util.parseXML(responseText)\n }\n let root = this.dom.documentElement\n if (root.nodeName === 'parsererror') { // Mozilla only See issue/issue110\n // have to fail the request\n return fetcher.failFetch(options, 'Badly formed XML in ' +\n options.resource!.value, 'parse_error')\n }\n let parser = new RDFParser(kb)\n try {\n parser.parse(this.dom, options.original.value, options.original)\n } catch (err) {\n return fetcher.failFetch(options, 'Syntax error parsing RDF/XML! ' + err,\n 'parse_error')\n }\n if (!options.noMeta) {\n kb.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode)\n }\n\n return fetcher.doneFetch(options, this.response)\n }\n}\nRDFXMLHandler.pattern = new RegExp('application/rdf\\\\+xml')\n\nclass XHTMLHandler extends Handler {\n static toString () {\n return 'XHTMLHandler'\n }\n\n static register (fetcher: Fetcher) {\n fetcher.mediatypes[XHTMLContentType] = {}\n }\n\n parse (\n fetcher: Fetcher,\n responseText: string,\n options: {\n resource: Quad_Subject\n original: Quad_Subject\n } & Options,\n ): Promise<FetchError> | ExtendedResponse {\n let relation, reverse: boolean\n if (!this.dom) {\n this.dom = Util.parseXML(responseText)\n }\n let kb = fetcher.store\n\n // dc:title\n let title = this.dom.getElementsByTagName('title')\n if (title.length > 0) {\n kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(title[0].textContent as string),\n options.resource)\n // log.info(\"Inferring title of \" + xhr.resource)\n }\n\n // link rel\n let links = this.dom.getElementsByTagName('link')\n for (let x = links.length - 1; x >= 0; x--) { // @@ rev\n relation = links[x].getAttribute('rel')\n reverse = false\n if (!relation) {\n relation = links[x].getAttribute('rev')\n reverse = true\n }\n if (relation) {\n fetcher.linkData(options.original, relation,\n links[x].getAttribute('href') as string, options.resource, reverse)\n }\n }\n\n // Data Islands\n let scripts = this.dom.getElementsByTagName('script')\n for (let i = 0; i < scripts.length; i++) {\n let contentType = scripts[i].getAttribute('type')\n if (Parsable[contentType!]) {\n // @ts-ignore incompatibility between Store.add and Formula.add\n rdfParse(scripts[i].textContent as string, kb, options.original.value, contentType)\n // @ts-ignore incompatibility between Store.add and Formula.add\n rdfParse(scripts[i].textContent as string, kb, options.original.value, contentType)\n }\n }\n\n if (!options.noMeta) {\n kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode)\n }\n\n if (!options.noRDFa && parseRDFaDOM) { // enable by default\n try {\n parseRDFaDOM(this.dom, kb, options.original.value)\n } catch (err) {\n // @ts-ignore\n let msg = 'Error trying to parse ' + options.resource + ' as RDFa:\\n' + err + ':\\n' + err.stack\n return fetcher.failFetch(options as AutoInitOptions, msg, 'parse_error')\n }\n }\n\n return fetcher.doneFetch(options as AutoInitOptions, this.response)\n }\n}\nXHTMLHandler.pattern = new RegExp('application/xhtml')\n\nclass XMLHandler extends Handler {\n static toString () {\n return 'XMLHandler'\n }\n\n static register (fetcher: Fetcher) {\n fetcher.mediatypes['text/xml'] = { 'q': 0.5 }\n fetcher.mediatypes['application/xml'] = { 'q': 0.5 }\n }\n\n parse (\n fetcher: Fetcher,\n responseText: string,\n options: {\n original: Quad_Subject\n req: BlankNode\n resource: Quad_Subject\n } & Options,\n ): ExtendedResponse | Promise<FetchError> {\n let dom = Util.parseXML(responseText)\n\n // XML Semantics defined by root element namespace\n // figure out the root element\n for (let c = 0; c < dom.childNodes.length; c++) {\n // is this node an element?\n if (dom.childNodes[c].nodeType === 1) {\n // We've found the first element, it's the root\n let ns = dom.childNodes[c].namespaceURI\n\n // Is it RDF/XML?\n if (ns && ns === ns['rdf']) {\n fetcher.addStatus(options.req,\n 'Has XML root element in the RDF namespace, so assume RDF/XML.')\n\n let rdfHandler = new RDFXMLHandler(this.response, dom)\n return rdfHandler.parse(fetcher, responseText, options)\n }\n\n break\n }\n }\n\n // Or it could be XHTML?\n // Maybe it has an XHTML DOCTYPE?\n if (dom.doctype) {\n // log.info(\"We found a DOCTYPE in \" + xhr.resource)\n if (dom.doctype.name === 'html' &&\n dom.doctype.publicId.match(/^-\\/\\/W3C\\/\\/DTD XHTML/) &&\n dom.doctype.systemId.match(/http:\\/\\/www.w3.org\\/TR\\/xhtml/)) {\n fetcher.addStatus(options.req,\n 'Has XHTML DOCTYPE. Switching to XHTML Handler.\\n')\n\n let xhtmlHandler = new XHTMLHandler(this.response, dom)\n return xhtmlHandler.parse(fetcher, responseText, options)\n }\n }\n\n // Or what about an XHTML namespace?\n let html = dom.getElementsByTagName('html')[0]\n if (html) {\n let xmlns = html.getAttribute('xmlns')\n if (xmlns && xmlns.match(/^http:\\/\\/www.w3.org\\/1999\\/xhtml/)) {\n fetcher.addStatus(options.req,\n 'Has a default namespace for ' + 'XHTML. Switching to XHTMLHandler.\\n')\n\n let xhtmlHandler = new XHTMLHandler(this.response, dom)\n return xhtmlHandler.parse(fetcher, responseText, options)\n }\n }\n\n // At this point we should check the namespace document (cache it!) and\n // look for a GRDDL transform\n // @@ Get namespace document <n>, parse it, look for <n> grddl:namespaceTransform ?y\n // Apply ?y to dom\n // We give up. What dialect is this?\n return fetcher.failFetch(options,\n 'Unsupported dialect of XML: not RDF or XHTML namespace, etc.\\n' +\n responseText.slice(0, 80), 901)\n }\n}\nXMLHandler.pattern = new RegExp('(text|application)/(.*)xml')\n\nclass HTMLHandler extends Handler {\n static toString () {\n return 'HTMLHandler'\n }\n\n static register (fetcher: Fetcher) {\n fetcher.mediatypes['text/html'] = {\n 'q': 0.9\n }\n }\n\n parse (\n fetcher: Fetcher,\n responseText: string,\n options: {\n req: BlankNode,\n resource: Quad_Subject,\n original: Quad_Subject,\n } & Options\n ): Promise<FetchError> | ExtendedResponse {\n let kb = fetcher.store\n\n // We only handle XHTML so we have to figure out if this is XML\n // log.info(\"Sniffing HTML \" + xhr.resource + \" for XHTML.\")\n if (isXML(responseText)) {\n fetcher.addStatus(options.req, \"Has an XML declaration. We'll assume \" +\n \"it's XHTML as the content-type was text/html.\\n\")\n\n let xhtmlHandler = new XHTMLHandler(this.response)\n return xhtmlHandler.parse(fetcher, responseText, options)\n }\n\n // DOCTYPE html\n if (isXHTML(responseText)) {\n fetcher.addStatus(options.req,\n 'Has XHTML DOCTYPE. Switching to XHTMLHandler.\\n')\n\n let xhtmlHandler = new XHTMLHandler(this.response)\n return xhtmlHandler.parse(fetcher, responseText, options)\n }\n\n // xmlns\n if (isXMLNS(responseText)) {\n fetcher.addStatus(options.req,\n 'Has default namespace for XHTML, so switching to XHTMLHandler.\\n')\n\n let xhtmlHandler = new XHTMLHandler(this.response)\n return xhtmlHandler.parse(fetcher, responseText, options)\n }\n\n // dc:title\n // no need to escape '/' here\n let titleMatch = (new RegExp('<title>([\\\\s\\\\S]+?)</title>', 'im')).exec(responseText)\n if (titleMatch) {\n kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(titleMatch[1]),\n options.resource) // think about xml:lang later\n }\n kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode)\n fetcher.addStatus(options.req, 'non-XML HTML document, not parsed for data.')\n\n return fetcher.doneFetch(options, this.response)\n }\n}\nHTMLHandler.pattern = new RegExp('text/html')\n\nclass JsonLdHandler extends Handler {\n static toString () {\n return 'JsonLdHandler'\n }\n static register (fetcher: Fetcher) {\n fetcher.mediatypes['application/ld+json'] = {\n 'q': 0.9\n }\n }\n parse (\n fetcher: Fetcher,\n responseText: string,\n options: {\n req: Quad_Subject\n original: Quad_Subject\n resource: Quad_Subject\n } & Options,\n response: ExtendedResponse\n ): Promise<ExtendedResponse | FetchError> {\n const kb = fetcher.store\n return new Promise((resolve, reject) => {\n try {\n jsonldParser (responseText, kb, options.original.value, () => {\n resolve(fetcher.doneFetch(options, response))\n })\n } catch (err) {\n const msg = 'Error trying to parse ' + options.resource +\n ' as JSON-LD:\\n' + err // not err.stack -- irrelevant\n resolve(fetcher.failFetch(options, msg, 'parse_error', response))\n }\n })\n }\n}\nJsonLdHandler.pattern = /application\\/ld\\+json/\n\nclass TextHandler extends Handler {\n static toString () {\n return 'TextHandler'\n }\n\n static register (fetcher: Fetcher) {\n fetcher.mediatypes['text/plain'] = {\n 'q': 0.5\n }\n }\n\n parse (\n fetcher: Fetcher,\n responseText: string,\n options: {\n req: Quad_Subject\n original: Quad_Subject\n resource: Quad_Subject\n } & Options\n ): ExtendedResponse | Promise<FetchError> {\n // We only speak dialects of XML right now. Is this XML?\n\n // Look for an XML declaration\n if (isXML(responseText)) {\n fetcher.addStatus(options.req, 'Warning: ' + options.resource +\n \" has an XML declaration. We'll assume \" +\n \"it's XML but its content-type wasn't XML.\\n\")\n\n let xmlHandler = new XMLHandler(this.response)\n return xmlHandler.parse(fetcher, responseText, options)\n }\n\n // Look for an XML declaration\n if (responseText.slice(0, 500).match(/xmlns:/)) {\n fetcher.addStatus(options.req, \"May have an XML namespace. We'll assume \" +\n \"it's XML but its content-type wasn't XML.\\n\")\n\n let xmlHandler = new XMLHandler(this.response)\n return xmlHandler.parse(fetcher, responseText, options)\n }\n\n // We give up finding semantics - this is not an error, just no data\n fetcher.addStatus(options.req, 'Plain text document, no known RDF semantics.')\n\n return fetcher.doneFetch(options, this.response)\n }\n}\nTextHandler.pattern = new RegExp('text/plain')\n\nclass N3Handler extends Handler {\n static toString () {\n return 'N3Handler'\n }\n\n static register (fetcher: Fetcher) {\n fetcher.mediatypes['text/n3'] = {\n 'q': '1.0'\n } // as per 2008 spec\n /*\n fetcher.mediatypes['application/x-turtle'] = {\n 'q': 1.0\n } // pre 2008\n */\n fetcher.mediatypes['text/turtle'] = {\n 'q': 1.0\n } // post 2008\n }\n\n parse (\n fetcher: Fetcher,\n responseText: string,\n options: {\n original: NamedNode\n req: Quad_Subject\n } & Options,\n response: ExtendedResponse\n ): ExtendedResponse | Promise<FetchError> {\n // Parse the text of this N3 file\n let kb = fetcher.store\n let p = N3Parser(kb, kb, options.original.value, options.original.value,\n null, null, '', null)\n // p.loadBuf(xhr.responseText)\n try {\n p.loadBuf(responseText)\n } catch (err) {\n let msg = 'Error trying to parse ' + options.resource +\n ' as Notation3:\\n' + err // not err.stack -- irrelevant\n return fetcher.failFetch(options, msg, 'parse_error', response)\n }\n\n fetcher.addStatus(options.req, 'N3 parsed: ' + p.statementCount + ' triples in ' + p.lines + ' lines.')\n fetcher.store.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode)\n\n return fetcher.doneFetch(options, this.response)\n }\n}\nN3Handler.pattern = new RegExp('(application|text)/(x-)?(rdf\\\\+)?(n3|turtle)')\n\nconst defaultHandlers = {\n RDFXMLHandler, XHTMLHandler, XMLHandler, HTMLHandler, TextHandler, N3Handler, JsonLdHandler\n}\n\nfunction isXHTML (responseText) {\n const docTypeStart = responseText.indexOf('<!DOCTYPE html')\n const docTypeEnd = responseText.indexOf('>')\n if (docTypeStart === -1 || docTypeEnd === -1 || docTypeStart > docTypeEnd) {\n return false\n }\n return responseText.substr(docTypeStart, docTypeEnd - docTypeStart).indexOf('XHTML') !== -1\n}\n\nfunction isXML (responseText: string): boolean {\n const match = responseText.match(/\\s*<\\?xml\\s+version\\s*=[^<>]+\\?>/)\n return !!match\n}\n\nfunction isXMLNS (responseText: string): boolean {\n const match = responseText.match(/[^(<html)]*<html\\s+[^<]*xmlns=['\"]http:\\/\\/www.w3.org\\/1999\\/xhtml[\"'][^<]*>/)\n return !!match\n}\n\ntype StatusValues =\n /** No record of web access or record reset */\n undefined |\n /** Has been requested, fetch in progress */\n true |\n /** Received, OK */\n 'done' |\n /** Not logged in */\n 401 |\n /** HTTP status unauthorized */\n 403 |\n /** Not found, resource does not exist */\n 404 |\n /** In attempt to counter CORS problems retried */\n 'redirected' |\n /** If it did fail */\n 'failed' |\n 'parse_error' |\n /**\n * URI is not a protocol Fetcher can deal with\n * other strings mean various other errors.\n */\n 'unsupported_protocol' |\n 'timeout' |\n /** Any other HTTP status code */\n number\n\ninterface MediatypesMap {\n [id: string]: {\n // Either string '1.0' or number 1.0 is allowed\n 'q'?: number | string\n };\n}\n\ninterface RequestedMap {\n [uri: string]: StatusValues\n}\n\ninterface TimeOutsMap {\n [uri: string]: number[]\n}\n\ninterface FetchQueue {\n [uri: string]: Promise<ExtendedResponse>\n}\n\ninterface FetchCallbacks {\n [uri: string]: UserCallback[]\n}\n\ninterface BooleanMap {\n [uri: string]: boolean\n}\n\n// Not sure about the shapes of this. Response? FetchError?\ntype Result = Response\n\n/** Differs from normal Fetch, has an extended Response type */\ntype Fetch = (input: RequestInfo, init?: RequestInit) => Promise<ExtendedResponse>;\n\ninterface CallbackifyInterface {\n fireCallbacks: Function\n}\n\n/** Fetcher\n *\n * The Fetcher object is a helper object for a quadstore\n * which turns it from an offline store to an online store.\n * The fetcher deals with loading data files rom the web,\n * figuring how to parse them. It will also refresh, remove, the data\n * and put back the data to the web.\n */\nexport default class Fetcher implements CallbackifyInterface {\n store: IndexedFormula\n timeout: number\n _fetch: Fetch\n mediatypes: MediatypesMap\n /** Denoting this session */\n appNode: BlankNode\n /**\n * this.requested[uri] states:\n * undefined no record of web access or records reset\n * true has been requested, fetch in progress\n * 'done' received, Ok\n * 401 Not logged in\n * 403 HTTP status unauthorized\n * 404 Resource does not exist. Can be created etc.\n * 'redirected' In attempt to counter CORS problems retried.\n * 'parse_error' Parse error\n * 'unsupported_protocol' URI is not a protocol Fetcher can deal with\n * other strings mean various other errors.\n */\n requested: RequestedMap\n /** List of timeouts associated with a requested URL */\n timeouts: TimeOutsMap\n /** Redirected from *key uri* to *value uri* */\n redirectedTo: Record<string, string>\n fetchQueue: FetchQueue\n /** fetchCallbacks[uri].push(callback) */\n fetchCallbacks: FetchCallbacks\n /** Keep track of explicit 404s -> we can overwrite etc */\n nonexistent: BooleanMap\n lookedUp: BooleanMap\n handlers: Array<typeof Handler>\n ns: { [k: string]: (ln: string) => Quad_Predicate }\n static HANDLERS: {\n [handlerName: number]: Handler\n }\n static CONTENT_TYPE_BY_EXT: Record<string, string>\n // TODO: Document this\n static crossSiteProxyTemplate: any\n\n /** Methods added by calling Util.callbackify in the constructor*/\n fireCallbacks!: Function\n\n constructor (store: IndexedFormula, options: Options = {}) {\n this.store = store || new IndexedFormula()\n this.ns = getNS(this.store.rdfFactory)\n this.timeout = options.timeout || 30000\n\n // solidFetcher is deprecated\n this._fetch = options.fetch\n || (typeof global !== 'undefined' && (global.solidFetcher || global.solidFetch))\n || (typeof window !== 'undefined' && (window.solidFetcher || window.solidFetch))\n || crossFetch\n if (!this._fetch) {\n throw new Error('No _fetch function available for Fetcher')\n }\n\n this.appNode = this.store.rdfFactory.blankNode()\n this.store.fetcher = this // Bi-linked\n this.requested = {}\n this.timeouts = {}\n this.redirectedTo = {}\n this.fetchQueue = {}\n this.fetchCallbacks = {}\n this.nonexistent = {}\n this.lookedUp = {}\n this.handlers = []\n this.mediatypes = {\n 'image/*': { 'q': 0.9 },\n '*/*': { 'q': 0.1 } // Must allow access to random content\n }\n\n // Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail',\n // 'refresh', 'retract', 'done'])\n // In switching to fetch(), 'recv', 'headers' and 'load' do not make sense\n Util.callbackify(this, ['request', 'fail', 'refresh', 'retract', 'done'])\n\n Object.keys(options.handlers || defaultHandlers).map(key => this.addHandler(defaultHandlers[key]))\n }\n\n static crossSiteProxy (uri: string): undefined | any {\n if (Fetcher.crossSiteProxyTemplate) {\n return Fetcher.crossSiteProxyTemplate\n .replace('{uri}', encodeURIComponent(uri))\n } else {\n return undefined\n }\n }\n\n static offlineOverride (uri: string): string {\n // Map the URI to a localhost proxy if we are running on localhost\n // This is used for working offline, e.g. on planes.\n // Is the script itself is running in localhost, then access all\n // data in a localhost mirror.\n // Do not remove without checking with TimBL\n let requestedURI = uri\n\n var UI\n if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) &&\n UI.preferences && UI.preferences.get('offlineModeUsingLocalhost')) {\n if (requestedURI.slice(0, 7) === 'http://' && requestedURI.slice(7, 17) !== 'localhost/') {\n requestedURI = 'http://localhost/' + requestedURI.slice(7)\n log.warn('Localhost kludge for offline use: actually getting <' +\n requestedURI + '>')\n } else {\n // log.warn(\"Localhost kludge NOT USED <\" + requestedURI + \">\")\n }\n } else {\n // log.warn(\"Localhost kludge OFF offline use: actually getting <\" +\n // requestedURI + \">\")\n }\n\n return requestedURI\n }\n\n static proxyIfNecessary (uri: string) {\n var UI\n if (\n typeof window !== 'undefined' &&\n (window as any).panes &&\n (UI = (window as any).panes.UI) &&\n UI.isExtension\n ) {\n return uri\n } // Extension does not need proxy\n\n if (typeof $SolidTestEnvironment !== 'undefined' &&\n $SolidTestEnvironment.localSiteMap) {\n // nested dictionaries of URI parts from origin down\n let hostpath = uri.split('/').slice(2) // the bit after the //\n\n const lookup = (parts, index) => {\n let z = index[parts.shift()]\n\n if (!z) { return null }\n\n if (typeof z === 'string') {\n return z + parts.join('/')\n }\n\n if (!parts) { return null }\n\n return lookup(parts, z)\n }\n\n const y = lookup(hostpath, $SolidTestEnvironment.localSiteMap)\n\n if (y) {\n return y\n }\n }\n\n // browser does 2014 on as https browser script not trusted\n // If the web app origin is https: then the mixed content rules\n // prevent it loading insecure http: stuff so we need proxy.\n if (Fetcher.crossSiteProxyTemplate &&\n typeof document !== 'undefined' && document.location &&\n ('' + document.location).slice(0, 6) === 'https:' && // origin is secure\n uri.slice(0, 5) === 'http:') { // requested data is not\n return Fetcher.crossSiteProxyTemplate\n .replace('{uri}', encodeURIComponent(uri))\n }\n\n return uri\n }\n\n /**\n * Tests whether the uri's protocol is supported by the Fetcher.\n * @param uri\n */\n static unsupportedProtocol (uri: string): boolean {\n let pcol = Uri.protocol(uri)\n\n return (pcol === 'tel' || pcol === 'mailto' || pcol === 'urn')\n }\n\n /** Decide on credentials using old XXHR api or new fetch() one\n * @param requestedURI\n * @param options\n */\n static setCredentials (requestedURI: string, options: Options = {}) {\n // 2014 CORS problem:\n // XMLHttpRequest cannot load http://www.w3.org/People/Berners-Lee/card.\n // A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin'\n // header when the credentials flag is true.\n // @ Many ontology files under http: and need CORS wildcard ->\n // can't have credentials\n if (options.credentials === undefined) { // Caller using new fetch convention\n if (options.withCredentials !== undefined) { // XHR style is what Fetcher specified before\n options.credentials = options.withCredentials ? 'include' : 'omit'\n } else {\n options.credentials = 'include' // default is to be logged on\n }\n }\n }\n\n /**\n * Promise-based load function\n *\n * Loads a web resource or resources into the store.\n *\n * A resource may be given as NamedNode object, or as a plain URI.\n * an array of resources will be given, in which they will be fetched in parallel.\n * By default, the HTTP headers are recorded also, in the same store, in a separate graph.\n * This allows code like editable() for example to test things about the resource.\n *\n * @param uri {Array<RDFlibNamedNode>|Array<string>|RDFlibNamedNode|string}\n *\n * @param [options={}] {Object}\n *\n * @param [options.fetch] {Function}\n *\n * @param [options.referringTerm] {RDFlibNamedNode} Referring term, the resource which\n * referred to this (for tracking bad links)\n *\n * @param [options.contentType] {string} Provided content type (for writes)\n *\n * @param [options.forceContentType] {string} Override the incoming header to\n * force the data to be treated as this content-type (for reads)\n *\n * @param [options.force] {boolean} Load the data even if loaded before.\n * Also sets the `Cache-Control:` header to `no-cache`\n *\n * @param [options.baseURI=docuri] {Node|string} Original uri to preserve\n * through proxying etc (`xhr.original`).\n *\n * @param [options.proxyUsed] {boolean} Whether this request is a retry via\n * a proxy (generally done from an error handler)\n *\n * @param [options.withCredentials] {boolean} flag for XHR/CORS etc\n *\n * @param [options.clearPreviousData] {boolean} Before we parse new data,\n * clear old, but only on status 200 responses\n *\n * @param [options.noMeta] {boolean} Prevents the addition of various metadata\n * triples (about the fetch request) to the store\n *\n * @param [options.noRDFa] {boolean}\n *\n * @returns {Promise<Result>}\n */\n load <T extends NamedNode | string | Array<string | NamedNode>>(\n uri: T,\n options: Options = {}\n ): T extends Array<string | NamedNode> ? Promise<Result[]> : Promise<Result> {\n options = Object.assign({}, options) // Take a copy as we add stuff to the options!!\n if (uri instanceof Array) {\n return Promise.all(uri.map((x) => {\n return this.load(x, Object.assign({}, options)) as unknown as Promise<Result>\n })) as T extends Array<string | NamedNode> ? Promise<Result[]> : Promise<Result>\n }\n\n const uriIn: NamedNode | string = uri as NamedNode\n\n let docuri = termValue(uriIn)\n docuri = docuri.split('#')[0]\n\n options = this.initFetchOptions(docuri, options)\n\n const initialisedOptions = this.initFetchOptions(docuri, options)\n\n return this.pendingFetchPromise(docuri, initialisedOptions.baseURI, initialisedOptions) as any\n }\n\n pendingFetchPromise (\n uri: string,\n originalUri: string,\n options: AutoInitOptions\n ): Promise<Result> {\n let pendingPromise\n\n // Check to see if some request is already dealing with this uri\n if (!options.force && this.fetchQueue[originalUri]) {\n pendingPromise = this.fetchQueue[originalUri]\n } else {\n pendingPromise = Promise\n .race([\n this.setRequestTimeout(uri, options),\n this.fetchUri(uri, options)\n ])\n this.fetchQueue[originalUri] = pendingPromise\n\n // Clean up the queued promise after a time, if it's resolved\n this.cleanupFetchRequest(originalUri, undefined, this.timeout)\n }\n\n return pendingPromise.then(x => {\n if (uri in this.timeouts) {\n this.timeouts[uri].forEach(clearTimeout)\n delete this.timeouts[uri]\n }\n return x\n })\n }\n\n /**\n * @param _options - DEPRECATED\n */\n cleanupFetchRequest (\n originalUri: string,\n _options,\n timeout: number\n ) {\n if (_options !== undefined) {\n console.warn(\"_options is deprecated\")\n }\n this.timeouts[originalUri] = (this.timeouts[originalUri] || []).concat(setTimeout(() => {\n if (!this.isPending(originalUri)) {\n delete this.fetchQueue[originalUri]\n }\n }, timeout) as unknown as number)\n }\n\n initFetchOptions (\n uri: string,\n options: Options\n ): AutoInitOptions {\n let kb = this.store\n\n let isGet = !options.method || options.method.toUpperCase() === 'GET'\n if (!isGet) {\n options.force = true\n }\n\n options.resource = kb.rdfFactory.namedNode(uri) // This might be proxified\n options.baseURI = options.baseURI || uri // Preserve though proxying etc\n options.original = kb.rdfFactory.namedNode(options.baseURI)\n options.req = kb.bnode()\n options.headers = options.headers || new Headers()\n\n if (options.contentType) {\n // @ts-ignore\n options.headers['content-type'] = options.contentType\n }\n\n if (options.force) {\n options.cache = 'no-cache'\n }\n\n let acceptString = this.acceptString()\n // @ts-ignore\n options.headers['accept'] = acceptString\n\n let requestedURI = Fetcher.offlineOverride(uri)\n options.requestedURI = requestedURI\n\n Fetcher.setCredentials(requestedURI, options)\n\n let actualProxyURI = Fetcher.proxyIfNecessary(requestedURI)\n if (requestedURI !== actualProxyURI) {\n options.proxyUsed = true\n }\n options.actualProxyURI = actualProxyURI\n\n return options as AutoInitOptions\n }\n\n /**\n * (The promise chain ends in either a `failFetch()` or a `doneFetch()`)\n *\n * @param docuri {string}\n * @param options {Object}\n *\n * @returns {Promise<Object>} fetch() result or an { error, status } object\n */\n fetchUri (docuri: string, options: AutoInitOptions): Promise<ExtendedResponse | FetchError> {\n if (!docuri) {\n return Promise.reject(new Error('Cannot fetch an empty uri'))\n }\n\n if (Fetcher.unsupportedProtocol(docuri)) {\n return this.failFetch(options, 'fetcher: Unsupported protocol', 'unsupported_protocol')\n }\n\n let state = this.getState(docuri)\n\n if (!options.force) {\n if (state === 'fetched') { // URI already fetched and added to store\n return Promise.resolve(\n // @ts-ignore This is not a valid response object\n this.doneFetch(options, {\n status: 200,\n ok: true,\n statusText: 'Already loaded into quadstore.'\n })\n )\n }\n if (state === 'failed' && this.requested[docuri] === 404) { // Remember nonexistence\n let message = 'Previously failed: ' + this.requested[docuri]\n // @ts-ignore This is not a valid response object\n let dummyResponse: ExtendedResponse = {\n url: docuri,\n // This does not comply to Fetch spec, it can be a string value in rdflib\n status: this.requested[docuri] as number,\n statusText: message,\n responseText: message,\n headers: new Headers, // Headers() ???\n ok: false,\n body: null,\n bodyUsed: false,\n size: 0,\n timeout: 0\n }\n return this.failFetch(options, message,\n this.requested[docuri], dummyResponse)\n }\n } else {\n // options.force == true\n delete this.nonexistent[docuri]\n }\n\n this.fireCallbacks('request', [docuri])\n\n this.requested[docuri] = true // mark this uri as 'requested'\n\n if (!options.noMeta) {\n this.saveRequestMetadata(docuri, options)\n }\n\n let { actualProxyURI } = options\n\n // Map might get mistakenly added into headers\n // error TS2339: Property 'map' does not exist on type 'Headers'.\n /* let map\n if (options.headers && map in options.headers) {\n delete options.headers.map\n } */\n\n return this._fetch((actualProxyURI as string), options)\n .then(response => this.handleResponse(response, docuri, options),\n error => { // @@ handleError?\n // @ts-ignore Invalid response object\n let dummyResponse: ExtendedResponse = {\n url: actualProxyURI as string,\n status: 999, // @@ what number/string should fetch failures report?\n statusText: (error.name || 'network failure') + ': ' +\n (error.errno || error.code || error.type),\n responseText: error.message,\n headers: new Headers(), // Headers() ???\n ok: false,\n body: null,\n bodyUsed: false,\n size: 0,\n timeout: 0\n }\n console.log('Fetcher: <' + actualProxyURI + '> Non-HTTP fetch exception: ' + error)\n return this.handleError(dummyResponse, docuri, options) // possible credentials retry\n // return this.failFetch(options, 'fetch failed: ' + error, 999, dummyResponse) // Fake status code: fetch exception\n\n // handleError expects a response so we fake some important bits.\n /*\n this.handleError(, docuri, options)\n */\n }\n )\n }\n\n /**\n * Asks for a doc to be loaded if necessary then calls back\n *\n * Calling methods:\n * nowOrWhenFetched (uri, userCallback)\n * nowOrWhenFetched (uri, options, userCallback)\n * nowOrWhenFetched (uri, referringTerm, userCallback, options) <-- old\n * nowOrWhenFetched (uri, referringTerm, userCallback) <-- old\n *\n * Options include:\n * referringTerm The document in which this link was found.\n * this is valuable when finding the source of bad URIs\n * force boolean. Never mind whether you have tried before,\n * load this from scratch.\n * forceContentType Override the incoming header to force the data to be\n * treated as this content-type.\n *\n * Callback function takes:\n *\n * ok True if the fetch worked, and got a 200 response.\n * False if any error happened\n *\n * errmessage Text error message if not OK.\n *\n * response The fetch Response object (was: XHR) if there was was one\n * includes response.status as the HTTP status if any.\n */\n nowOrWhenFetched (\n uriIn: string | NamedNode,\n p2?: UserCallback | Options,\n userCallback?: UserCallback,\n options: Options = {}\n ): void {\n const uri = termValue(uriIn)\n\n if (typeof p2 === 'function') {\n // nowOrWhenFetched (uri, userCallback)\n userCallback = p2\n } else if (typeof p2 === 'undefined') { // original calling signature\n // referringTerm = undefined\n } else if (isNamedNode(p2)) {\n // referringTerm = p2\n options.referringTerm = p2\n } else {\n // nowOrWhenFetched (uri, options, userCallback)\n options = p2\n }\n\n (this.load(uri, options) as Promise<Response>)\n .then((fetchResponse: ExtendedResponse) => {\n if (userCallback) {\n if (fetchResponse) {\n if ((fetchResponse as Response).ok) {\n userCallback(true, 'OK', fetchResponse)\n } else {\n // console.log('@@@ fetcher.js Should not take this path !!!!!!!!!!!!')\n let oops = 'HTTP error: Status ' + fetchResponse.status + ' (' + fetchResponse.statusText + ')'\n if (fetchResponse.responseText) {\n oops += ' ' + fetchResponse.responseText // not in 404, dns error, nock failure\n }\n console.log(oops + ' fetching ' + uri)\n userCallback(false, oops, fetchResponse)\n }\n } else {\n let oops = ('@@ nowOrWhenFetched: no response object!')\n console.log(oops)\n userCallback(false, oops)\n }\n }\n }, function (err: FetchError) {\n var message = err.message || err.statusText\n message = 'Failed to load <' + uri + '> ' + message\n console.log(message)\n if (err.response && err.response.status) {\n message += ' status: ' + err.response.status\n }\n (userCallback as any)(false, message, err.response)\n })\n }\n\n /**\n * Records a status message (as a literal node) by appending it to the\n * request's metadata status collection.\n *\n */\n addStatus (req: BlankNode, statusMessage: string) {\n // <Debug about=\"parsePerformance\">\n let now = new Date()\n statusMessage = '[' + now.getHours() + ':' + now.getMinutes() + ':' +\n now.getSeconds() + '.' + now.getMilliseconds() + '] ' + statusMessage\n // </Debug>\n let kb = this.store\n\n const statusNode = kb.the(req, this.ns.link('status'))\n if (isCollection(statusNode)) {\n statusNode.append(kb.rdfFactory.literal(statusMessage))\n } else {\n log.warn('web.js: No list to add to: ' + statusNode + ',' + statusMessage)\n }\n }\n\n /**\n * Records errors in the system on failure:\n *\n * - Adds an entry to the request status collection\n * - Adds an error triple with the fail message to the metadata\n * - Fires the 'fail' callback\n * - Rejects with an error result object, which has a response object if any\n */\n failFetch (\n options: {\n req: BlankNode\n original: Quad_Subject\n } & Options,\n errorMessage: string,\n statusCode: StatusValues,\n response?: ExtendedResponse\n ): Promise<FetchError> {\n this.addStatus(options.req, errorMessage)\n\n if (!options.noMeta) {\n this.store.add(\n options.original,\n this.ns.link('error'),\n this.store.rdfFactory.literal(errorMessage)\n )\n }\n\n let meth = (options.method || 'GET').toUpperCase()\n let isGet = meth === 'GET' || meth === 'HEAD'\n\n if (isGet) { // only cache the status code on GET or HEAD\n if (!(options as any).resource.equals(options.original)) {\n // console.log('@@ Recording failure ' + meth + ' original ' + options.original +option '( as ' + options.resource + ') : ' + statusCode)\n } else {\n // console.log('@@ Recording ' + meth + ' failure for ' + options.original + ': ' + statusCode)\n }\n this.requested[Uri.docpart(options.original.value)] = statusCode\n this.fireCallbacks('fail', [options.original.value, errorMessage])\n }\n\n var err: FetchError = new Error('Fetcher: ' + errorMessage)\n\n // err.ok = false // Is taken as a response, will work too @@ phase out?\n err.status = statusCode\n err.statusText = errorMessage\n err.response = response\n\n return Promise.reject(err)\n }\n\n // in the why part of the quad distinguish between HTML and HTTP header\n // Reverse is set iif the link was rev= as opposed to rel=\n linkData (\n originalUri: NamedNode,\n rel: string,\n uri: string,\n why: Quad_Graph,\n reverse?: boolean\n ) {\n if (!uri) return\n let kb = this.store\n let predicate\n // See http://www.w3.org/TR/powder-dr/#httplink for describedby 2008-12-10\n let obj = kb.rdfFactory.namedNode(Uri.join(uri, originalUri.value))\n\n if (rel === 'alternate' || rel === 'seeAlso' || rel === 'meta' ||\n rel === 'describedby') {\n if (obj.value === originalUri.value) { return }\n predicate = this.ns.rdfs('seeAlso')\n } else if (rel === 'type') {\n predicate = kb.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type')\n } else {\n // See https://www.iana.org/assignments/link-relations/link-relations.xml\n // Alas not yet in RDF yet for each predicate\n // encode space in e.g. rel=\"shortcut icon\"\n predicate = kb.rdfFactory.namedNode(\n Uri.join(encodeURIComponent(rel),\n 'http://www.iana.org/assignments/link-relations/')\n )\n }\n if (reverse) {\n kb.add(obj, predicate, originalUri, why)\n } else {\n kb.add(originalUri, predicate, obj, why)\n }\n }\n\n parseLinkHeader (\n linkHeader: string,\n originalUri: NamedNode,\n reqNode: Quad_Graph\n ): void {\n if (!linkHeader) { return }\n\n // const linkexp = /<[^>]*>\\s*(\\s*;\\s*[^()<>@,;:\"/[\\]?={} \\t]+=(([^()<>@,;:\"/[]?={} \\t]+)|(\"[^\"]*\")))*(,|$)/g\n // const paramexp = /[^()<>@,;:\"/[]?={} \\t]+=(([^()<>@,;:\"/[]?={} \\t]+)|(\"[^\"]*\"))/g\n\n // From https://www.dcode.fr/regular-expression-simplificator:\n // const linkexp = /<[^>]*>\\s*(\\s*;\\s*[^()<>@,;:\"/[\\]?={} t]+=[\"]))*[,$]/g\n // const paramexp = /[^\\\\<>@,;:\"\\/\\[\\]?={} \\t]+=[\"])/g\n // Original:\n const linkexp = /<[^>]*>\\s*(\\s*;\\s*[^()<>@,;:\"/[\\]?={} \\t]+=(([^\\(\\)<>@,;:\"\\/\\[\\]\\?={} \\t]+)|(\"[^\"]*\")))*(,|$)/g\n const paramexp = /[^\\(\\)<>@,;:\"\\/\\[\\]\\?={} \\t]+=(([^\\(\\)<>@,;:\"\\/\\[\\]\\?={} \\t]+)|(\"[^\"]*\"))/g\n\n const matches = linkHeader.match(linkexp)\n\n if (matches == null) return;\n\n for (let i = 0; i < matches.length; i++) {\n let split = matches[i].split('>')\n let href = split[0].substring(1)\n let ps = split[1]\n let s = ps.match(paramexp)\n if (s == null) return\n for (let j = 0; j < s.length; j++) {\n let p = s[j]\n let paramsplit = p.split('=')\n // var name = paramsplit[0]\n let rel = paramsplit[1].replace(/[\"']/g, '') // '\"\n this.linkData(originalUri, rel, href, reqNode)\n }\n }\n }\n\n doneFetch (\n options: {\n req: Quad_Subject,\n original: Quad_Subject\n } & Options,\n response: ExtendedResponse\n ): Response {\n this.addStatus(options.req, 'Done.')\n this.requested[options.original.value] = 'done'\n\n this.fireCallbacks('done', [options.original.value])\n\n response.req = options.req // Set the request meta blank node\n\n return response\n }\n\n /**\n * Note two nodes are now smushed\n * If only one was flagged as looked up, then the new node is looked up again,\n * which will make sure all the URIs are dereferenced\n */\n nowKnownAs (was: Quad_Subject, now: Quad_Subject): void {\n if (this.lookedUp[was.value]) {\n // Transfer userCallback\n if (!this.lookedUp[now.value]) {\n this.lookUpThing(now, was)\n }\n } else if (this.lookedUp[now.value]) {\n if (!this.lookedUp[was.value]) {\n this.lookUpThing(was, now)\n }\n }\n }\n\n /**\n * Writes back to the web what we have in the store for this uri\n */\n putBack (\n uri: NamedNode | string,\n options: Options = {}\n ): Promise<Response> {\n const uriSting = termValue(uri)\n let doc = new RDFlibNamedNode(uriSting).doc() // strip off #\n options.contentType = options[\"content-type\"] || options[\"Content-Type\"] || options.contentType || TurtleContentType\n if (options.contentType === 'application/ld+json') {\n return new Promise((resolve, reject) => {\n serialize(doc, this.store, doc.uri, options.contentType, (err, jsonString) => {\n if (err) {\n reject(err)\n } else {\n // @ts-ignore\n options.data = jsonString\n this.webOperation('PUT', uri, options)\n .then((res) => resolve(res))\n .catch((error) => reject(error))\n }\n })\n })\n }\n options.data = serialize(doc, this.store, doc.value, options.contentType) as string\n return this.webOperation('PUT', uriSting, options)\n }\n\n webCopy (here: string, there: string, contentType): Promise<ExtendedResponse> {\n return this.webOperation('GET', here)\n .then((result) => {\n return this.webOperation(\n 'PUT', // change to binary from text\n there, { data: result.responseText, contentType })\n })\n }\n\n delete (uri: string, options?: Options): Promise<ExtendedResponse> {\n return this.webOperation('DELETE', uri, options)\n .then(response => {\n this.requested[uri] = 404\n this.nonexistent[uri] = true\n this.unload(this.store.rdfFactory.namedNode(uri))\n\n return response\n })\n }\n\n /** Create an empty resource if it really does not exist\n * Be absolutely sure something does not exist before creating a new empty file\n * as otherwise existing could be deleted.\n * @param doc - The resource\n */\n async createIfNotExists (\n doc: RDFlibNamedNode,\n contentType = TurtleContentType,\n data = ''\n ): Promise<ExtendedResponse> {\n const fetcher = this\n try {\n var response = await fetcher.load(doc as NamedNode)\n } catch (err) {\n // @ts-ignore\n if (err.response.status === 404) {\n console.log('createIfNotExists: doc does NOT exist, will create... ' + doc)\n try {\n response = await fetcher.webOperation('PUT', doc.value, {data, contentType})\n } catch (err) {\n console.log('createIfNotExists doc FAILED: ' + doc + ': ' + err)\n throw err\n }\n delete fetcher.requested[doc.value] // delete cached 404 error\n // console.log('createIfNotExists doc created ok ' + doc)\n return response\n } else {\n console.log('createIfNotExists doc load error NOT 404: ' + doc + ': ' + err)\n throw err\n }\n }\n // console.log('createIfNotExists: doc exists, all good: ' + doc)\n return response as Response\n }\n\n /**\n * @param parentURI URI of parent container\n * @param folderName - Optional folder name (slug)\n * @param data - Optional folder metadata\n */\n createContainer (\n parentURI: string,\n folderName: string,\n data: string\n ): Promise<Response> {\n let headers = {\n // Force the right mime type for containers\n 'content-type': TurtleContentType,\n 'link': this.ns.ldp('BasicContainer') + '; rel=\"type\"'\n }\n\n if (folderName) {\n headers['slug'] = folderName\n }\n\n // @ts-ignore These headers lack some of the required operators.\n let options: Options = { headers }\n\n if (data) {\n options.body = data\n }\n\n return this.webOperation('POST', parentURI, options)\n }\n\n invalidateCache (iri: string | NamedNode): void {\n const uri = termValue(iri)\n const fetcher = this\n // @ts-ignore\n if (fetcher.fetchQueue && fetcher.fetchQueue[uri]) {\n console.log('Internal error - fetchQueue exists ' + uri)\n var promise = fetcher.fetchQueue[uri]\n if (promise['PromiseStatus'] === 'resolved') {\n delete fetcher.fetchQueue[uri]\n } else { // pending\n delete fetcher.fetchQueue[uri]\n console.log('*** Fetcher: pending fetchQueue deleted ' + uri)\n }\n } if (fetcher.requested[uri] && fetcher.requested[uri] !== 'done' &&\n fetcher.requested[uri] !== 'failed' && fetcher.requested[uri] !== 404) {\n let msg = `Rdflib: fetcher: Destructive operation on <${fetcher.requested[uri]}> file being fetched! ` + uri\n console.error(msg)\n // alert(msg)\n } else {\n delete fetcher.requested[uri] // invalidate read cache -- @@ messes up logic if request in progress ??\n delete fetcher.nonexistent[uri]\n }\n }\n\n /**\n * A generic web opeation, at the fetch() level.\n * does not invole the quadstore.\n *\n * Returns promise of Response\n * If data is returned, copies it to response.responseText before returning\n */\n webOperation (\n method: HTTPMethods,\n uriIn: string | NamedNode,\n // Not sure about this type. Maybe this Options is different?\n options: Options = {}\n ): Promise<ExtendedResponse> {\n const uri = termValue(uriIn)\n options.method = method\n options.body = options.data || options.body\n options.force = true\n const fetcher = this\n\n if (options.body && !options.contentType) {\n throw new Error('Web operation sending data must have a defined contentType.')\n }\n if (options.contentType) {\n (options as any).headers = options.headers || {};\n (options as any).headers['content-type'] = options.contentType\n }\n Fetcher.setCredentials(uri, options)\n\n return new Promise(function (resolve, reject) {\n fetcher._fetch(uri, options).then(response => {\n if (response.ok) {\n if (method === 'PUT' || method === 'PATCH' || method === 'POST' || method === 'DELETE') {\n fetcher.invalidateCache (uri)\n } // response.body with Chrome can't be relied on\n if (response.text) { // Was: response.body https://github.com/linkeddata/rdflib.js/issues/506\n response.text().then(data => {\n response.responseText = data\n resolve(response)\n })\n } else {\n resolve(response)\n }\n } else {\n let msg = 'Web error: ' + response.status\n if (response.statusText) msg += ' (' + response.statusText + ')'\n msg += ' on ' + method + ' of <' + uri + '>'\n if (response.responseText) msg += ': ' + response.responseText\n let e2: FetchError = new Error(msg)\n e2.response = response\n reject(e2)\n }\n }, (err: Error) => {\n let msg = 'Fetch error for ' + method + ' of <' + uri + '>:' + err\n reject(new Error(msg))\n })\n })\n }\n\n /**\n * Looks up something.\n * Looks up all the URIs a things has.\n *\n * @param term - canonical term for the thing whose URI is\n * to be dereferenced\n * @param rterm - the resource which referred to this\n * (for tracking bad links)\n */\n lookUpThing (\n term: Quad_Subject,\n rterm: Quad_Subject\n ): Promise<Response> | Promise<Response>[] {\n let uris = this.store.uris(term) // Get all URIs\n uris = uris.map(u => Uri.docpart(u)) // Drop hash fragments\n\n uris.forEach(u => {\n this.lookedUp[u] = true\n })\n\n // @ts-ignore Recursive type\n return this.load(uris, { referringTerm: rterm })\n }\n\n /**\n * Looks up response header.\n *\n * @returns {Array|undefined} a list of header values found in a stored HTTP\n * response, or [] if response was found but no header found,\n * or undefined if no response is available.\n * Looks for { [] link:requestedURI ?uri; link:response [ httph:header-name ?value ] }\n */\n getHeader (\n doc: NamedNode,\n header: string\n ): undefined | string[] {\n const kb = this.store // look for the URI (AS A STRING NOT A NODE) for a stored request\n const docuri: string = doc.value\n const requests = kb.each(undefined, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri)) as Quad_Subject[]\n\n for (let r = 0; r < requests.length; r++) {\n let request = requests[r]\n if (request !== undefined) {\n let response = kb.any(request, this.ns.link('response')) as Quad_Subject\n if (response !== undefined && kb.anyValue(response, this.ns.http('status')) && (kb.anyValue(response, this.ns.http('status')) as string).startsWith('2')) {\n // Only look at success returns - not 401 error messagess etc\n let results = kb.each(response, this.ns.httph(header.toLowerCase()))\n\n if (results.length) {\n return results.map(v => { return v.value })\n }\n\n return []\n }\n }\n }\n return undefined\n }\n\n saveRequestMetadata (\n docuri: string,\n options: AutoInitOptions\n ) {\n let req = options.req\n let kb = this.store\n let rterm = options.referringTerm\n\n this.addStatus(options.req, 'Accept: ' + options.headers['accept'])\n\n if (isNamedNode(rterm)) {\n kb.add(kb.rdfFactory.namedNode(docuri), this.ns.link('requestedBy'), rterm, this.appNode)\n }\n\n if (options.original && options.original.value !== docuri) {\n kb.add(req, this.ns.link('orginalURI'), kb.rdfFactory.literal(options.original.value),\n this.appNode)\n }\n\n const now = new Date()\n const timeNow = '[' + now.getHours() + ':' + now.getMinutes() + ':' +\n now.getSeconds() + '] '\n\n kb.add(req, this.ns.rdfs('label'),\n kb.rdfFactory.literal(timeNow + ' Request for ' + docuri), this.appNode)\n // We store the docuri as a string, not as a node,\n // see https://github.com/linkeddata/rdflib.js/pull/427#pullrequestreview-447910061\n kb.add(req, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri), this.appNode)\n kb.add(req, this.ns.link('status'), kb.collection(), this.appNode)\n }\n\n saveResponseMetadata (\n response: Response,\n options: {\n req: BlankNode,\n resource: Quad_Subject\n } & Options\n ): BlankNode {\n const kb = this.store\n\n let responseNode = kb.bnode()\n\n kb.add(options.req, this.ns.link('response'), responseNode, responseNode)\n kb.add(responseNode, this.ns.http('status'),\n kb.rdfFactory.literal(response.status as any), responseNode)\n kb.add(responseNode, this.ns.http('statusText'),\n kb.rdfFactory.literal(response.statusText), responseNode)\n\n // Save the response headers\n response.headers.forEach((value, header) => {\n kb.add(responseNode, this.ns.httph(header), this.store.rdfFactory.literal(value), responseNode)\n\n if (header === 'content-type') {\n kb.add(\n options.resource,\n this.ns.rdf('type'),\n kb.rdfFactory.namedNode(Util.mediaTypeClass(value).value),\n responseNode\n )\n }\n })\n\n return responseNode\n }\n\n objectRefresh (term: NamedNode): void {\n let uris = this.store.uris(term) // Get all URIs\n if (typeof uris !== 'undefined') {\n for (let i = 0; i < uris.length; i++) {\n this.refresh(this.store.rdfFactory.namedNode(Uri.docpart(uris[i])))\n // what about rterm?\n }\n }\n }\n\n /* refresh Reload data from a given document\n **\n ** @param term - An RDF Named Node for the eodcument in question\n ** @param userCallback - A function userCallback(ok, message, response)\n */\n refresh (\n term: NamedNode,\n userCallback?: UserCallback\n ): void { // sources_refresh\n this.fireCallbacks('refresh', arguments)\n\n this.nowOrWhenFetched(term, { force: true, clearPreviousData: true },\n userCallback)\n }\n\n /* refreshIfExpired Conditional refresh if Expired\n **\n ** @param term - An RDF Named Node for the eodcument in question\n ** @param userCallback - A function userCallback(ok, message, response)\n */\n refreshIfExpired (\n term: NamedNode,\n userCallback: UserCallback\n ): void {\n let exp = this.getHeader(term, 'Expires')\n if (!exp || (new Date(exp[0]).getTime()) <= (new Date().getTime())) {\n this.refresh(term, userCallback)\n } else {\n userCallback(true, 'Not expired', {})\n }\n }\n\n retract (term: Quad_Graph) { // sources_retract\n this.store.removeMany(undefined, undefined, undefined, term)\n if (term.value) {\n delete this.requested[Uri.docpart(term.value)]\n }\n this.fireCallbacks('retract', arguments)\n }\n\n getState (docuri: string) {\n if (typeof this.requested[docuri] === 'undefined') {\n return 'unrequested'\n } else if (this.requested[docuri] === true) {\n return 'requested'\n } else if (this.requested[docuri] === 'done') {\n return 'fetched'\n } else if (this.requested[docuri] === 'redirected') {\n return this.getState(this.redirectedTo[docuri])\n } else { // An non-200 HTTP error status\n return 'failed'\n }\n }\n\n isPending (docuri: string) { // sources_pending\n // doing anyStatementMatching is wasting time\n // if it's not pending: false -> flailed\n // 'done' -> done 'redirected' -> redirected\n return this.requested[docuri] === true\n }\n\n unload (term: NamedNode) {\n this.store.removeDocument(term)\n delete this.requested[term.value] // So it can be load2ed again\n }\n\n addHandler (handler: typeof Handler) {\n this.handlers.push(handler);\n (handler as any).register(this)\n }\n\n retryNoCredentials (\n docuri: string,\n options\n ): Promise<Result> {\n console.log('Fetcher: CORS: RETRYING with NO CREDENTIALS for ' + options.resource)\n\n options.retriedWithNoCredentials = true // protect against being called twice\n\n delete this.requested[docuri] // forget the original request happened\n delete this.fetchQueue[docuri]\n // Note: XHR property was withCredentials, but fetch property is just credentials\n let newOptions = Object.assign({}, options, { credentials: 'omit' })\n\n this.addStatus(options.req,\n 'Abort: Will retry with credentials SUPPRESSED to see if that helps')\n\n return this.load(docuri, newOptions) as Promise<Result>\n }\n\n /**\n * Tests whether a request is being made to a cross-site URI (for purposes\n * of retrying with a proxy)\n */\n isCrossSite (uri: string): boolean {\n // Mashup situation, not node etc\n if (typeof document === 'undefined' || !document.location) {\n return false\n }\n\n const hostpart = Uri.hostpart\n const here = '' + document.location\n return (hostpart(here) && hostpart(uri) && hostpart(here)) !== hostpart(uri)\n }\n\n /**\n * Called when there's a network error in fetch(), or a response\n * with status of 0.\n */\n handleError (\n response: ExtendedResponse | Error,\n docuri: string,\n options: AutoInitOptions\n ): Promise<ExtendedResponse | FetchError> {\n if (this.isCrossSite(docuri)) {\n // Make sure we haven't retried already\n if (options.credentials && options.credentials === 'include' && !options.retriedWithNoCredentials) {\n return this.retryNoCredentials(docuri, options)\n }\n\n // Now attempt retry via proxy\n let proxyUri = Fetcher.crossSiteProxy(docuri)\n\n if (proxyUri && !options.proxyUsed) {\n console.log('web: Direct failed so trying proxy ' + proxyUri)\n\n return this.redirectToProxy(proxyUri, options)\n }\n }\n\n var message\n if (response instanceof Error) {\n message = 'Fetch error: ' + response.message\n } else {\n message = response.statusText\n if (response.responseText) {\n message += ` ${response.responseText}`\n }\n }\n\n // This is either not a CORS error, or retries have been made\n return this.failFetch(options, message, (response as Response).status || 998, (response as Response))\n }\n\n // deduce some things from the HTTP transaction\n addType (\n rdfType: NamedNode,\n req: Quad_Subject,\n kb: IndexedFormula,\n locURI: string\n ): void { // add type to all redirected resources too\n let prev = req\n if (locURI) {\n var reqURI = kb.any(prev, this.ns.link('requestedURI'))\n if (reqURI && reqURI.value !== locURI) {\n kb.add(kb.rdfFactory.namedNode(locURI), this.ns.rdf('type'), rdfType, this.appNode)\n }\n }\n for (;;) {\n const doc = kb.any(prev, this.ns.link('requestedURI'))\n if (doc && doc.value) {\n kb.add(kb.rdfFactory.namedNode(doc.value), this.ns.rdf('type'), rdfType, this.appNode)\n } // convert Literal\n prev = kb.any(undefined, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#redirectedRequest'), prev) as Quad_Subject\n if (!prev) { break }\n var response = kb.any(prev, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#response'))\n if (!response) { break }\n var redirection = kb.any((response as NamedNode), kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/http#status'))\n if (!redirection) { break }\n // @ts-ignore always true?\n if ((redirection !== '301') && (redirection !== '302')) { break }\n }\n }\n\n /**\n * Handle fetch() response\n */\n handleResponse (\n response: ExtendedResponse,\n docuri: string,\n options: AutoInitOptions\n ): Promise<FetchError | ExtendedResponse> | ExtendedResponse {\n\n const kb = this.store\n const headers = (response as Response).headers\n\n const reqNode = options.req\n\n const responseNode = this.saveResponseMetadata(response, options)\n\n const contentType = this.normalizedContentType(options, headers) || ''\n let contentLocation = headers.get('content-location')\n\n // this.fireCallbacks('recv', xhr.args)\n // this.fireCallbacks('headers', [{uri: docuri, headers: xhr.headers}])\n\n // Check for masked errors (CORS, etc)\n if (response.status === 0) {\n console.log('Masked error - status 0 for ' + docuri)\n return this.handleError(response, docuri, options)\n }\n\n if (response.status >= 400) {\n if (response.status === 404) {\n this.nonexistent[options.original.value] = true\n this.nonexistent[docuri] = true\n }\n\n return this.saveErrorResponse(response, responseNode)\n .then(() => {\n let errorMessage = options.resource + ' ' + response.statusText\n\n return this.failFetch(options, errorMessage, response.status, response)\n })\n }\n\n var diffLocation: null | string = null\n var absContentLocation: null | string = null\n if (contentLocation) {\n absContentLocation = Uri.join(contentLocation, docuri)\n if (absContentLocation !== docuri) {\n diffLocation = absContentLocation\n }\n }\n if (response.status === 200) {\n this.addType(this.ns.link('Document') as NamedNode, reqNode, kb, docuri)\n if (diffLocation) {\n this.addType(this.ns.link('Document') as NamedNode, reqNode, kb,\n diffLocation)\n }\n\n // Before we parse new data clear old but only on 200\n if (options.clearPreviousData) {\n kb.removeDocument(options.resource)\n }\n\n let isImage = contentType.includes('image/') ||\n contentType.includes('application/pdf')\n\n if (contentType && isImage) {\n this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb,\n docuri)\n if (diffLocation) {\n this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb,\n diffLocation)\n }\n }\n }\n\n // If we have already got the thing at this location, abort\n if (contentLocation) {\n if (!options.force && diffLocation && this.requested[absContentLocation as string] === 'done') {\n // we have already fetched this\n // should we smush too?\n // log.info(\"HTTP headers indicate we have already\" + \" retrieved \" +\n // xhr.resource + \" as \" + absContentLocation + \". Aborting.\")\n return this.doneFetch(options, response)\n }\n\n this.requested[absContentLocation as string] = true\n }\n\n this.parseLinkHeader(headers.get('link') as string, options.original, reqNode)\n\n let handler = this.handlerForContentType(contentType, response) as Handler\n\n if (!handler) {\n // Not a problem, we just don't extract data\n this.addStatus(reqNode, 'Fetch over. No data handled.')\n return this.doneFetch(options, response)\n }\n\n return response\n .text()\n // @ts-ignore Types seem right\n .then(responseText => {\n response.responseText = responseText\n return (handler as N3Handler).parse(this, responseText, options, response)\n })\n }\n\n saveErrorResponse (\n response: ExtendedResponse,\n responseNode: Quad_Subject\n ): Promise<void> {\n let kb = this.store\n\n return response.text()\n .then(content => {\n if (content.length > 10) {\n kb.add(responseNode, this.ns.http('content'), kb.rdfFactory.literal(content), responseNode)\n }\n })\n }\n\n handlerForContentType (contentType: string, response: ExtendedResponse): Handler | null {\n if (!contentType) {\n return null\n }\n\n let Handler = this.handlers.find(handler => {\n return contentType.match(handler.pattern)\n })\n\n // @ts-ignore in practice all Handlers have constructors.\n return Handler ? new Handler(response) : null\n }\n\n guessContentType (uri: string): ContentType | undefined {\n return CONTENT_TYPE_BY_EXT[uri.split('.').pop() as string]\n }\n\n normalizedContentType (\n options: AutoInitOptions,\n headers: Headers\n ): ContentType | string | null {\n if (options.forceContentType) {\n return options.forceContentType\n }\n\n let contentType = headers.get('content-type')\n if (!contentType || contentType.includes('application/octet-stream')) {\n let guess = this.guessContentType(options.resource.value)\n\n if (guess) {\n return guess\n }\n }\n\n let protocol = Uri.protocol(options.resource.value) as string\n\n if (!contentType && ['file', 'chrome'].includes(protocol)) {\n return 'text/xml'\n }\n\n return contentType\n }\n\n /**\n * Sends a new request to the specified uri. (Extracted from `onerrorFactory()`)\n */\n redirectToProxy (\n newURI: string,\n options: AutoInitOptions\n ): Promise<ExtendedResponse | FetchError> {\n this.addStatus(options.req, 'BLOCKED -> Cross-site Proxy to <' + newURI + '>')\n\n options.proxyUsed = true\n\n const kb = this.store\n const oldReq = options.req // request metadata blank node\n\n if (!options.noMeta) {\n kb.add(oldReq, this.ns.link('redirectedTo'), kb.rdfFactory.namedNode(newURI), oldReq)\n this.addStatus(oldReq, 'redirected to new request') // why\n }\n\n this.requested[options.resource.value] = 'redirected'\n this.redirectedTo[options.resource.value] = newURI\n\n let newOptions = Object.assign({}, options)\n newOptions.baseURI = options.resource.value\n\n return this.fetchUri(newURI, newOptions)\n .then(response => {\n if (!newOptions.noMeta) {\n kb.add(oldReq, this.ns.link('redirectedRequest'), newOptions.req, this.appNode)\n }\n\n return response\n })\n }\n\n setRequestTimeout (\n uri: string,\n options: {\n req: Quad_Subject\n original: Quad_Subject\n } & Options\n ): Promise<number | FetchError> {\n return new Promise((resolve) => {\n this.timeouts[uri] = (this.timeouts[uri] || []).concat(setTimeout(() => {\n if (this.isPending(uri) &&\n !options.retriedWithNoCredentials &&\n !options.proxyUsed) {\n resolve(this.failFetch(options, `Request to ${uri} timed out`, 'timeout'))\n }\n }, this.timeout) as unknown as number)\n })\n }\n\n addFetchCallback (\n uri: string,\n callback: UserCallback\n ): void {\n if (!this.fetchCallbacks[uri]) {\n this.fetchCallbacks[uri] = [callback]\n } else {\n this.fetchCallbacks[uri].push(callback)\n }\n }\n\n acceptString () {\n let acceptstring = ''\n\n for (let mediaType in this.mediatypes) {\n if (acceptstring !== '') {\n acceptstring += ', '\n }\n\n acceptstring += mediaType\n\n for (let property in this.mediatypes[mediaType]) {\n acceptstring += ';' + property + '=' + this.mediatypes[mediaType][property]\n }\n }\n\n return acceptstring\n }\n // var updatesVia = new $rdf.UpdatesVia(this) // Subscribe to headers\n// @@@@@@@@ This is turned off because it causes a websocket to be set up for ANY fetch\n// whether we want to track it ot not. including ontologies loaed though the XSSproxy\n}\n\nFetcher.HANDLERS = defaultHandlers\nFetcher.CONTENT_TYPE_BY_EXT = CONTENT_TYPE_BY_EXT\n","import * as convert from './convert'\nimport Formula from './formula'\nimport Serializer from './serializer'\nimport {\n ContentType,\n JSONLDContentType,\n N3ContentType,\n N3LegacyContentType,\n NQuadsAltContentType,\n NQuadsContentType,\n NTriplesContentType,\n RDFXMLContentType,\n TurtleContentType,\n TurtleLegacyContentType,\n} from './types'\nimport IndexedFormula from './store'\nimport { BlankNode, NamedNode } from './tf-types'\n\n/**\n * Serialize to the appropriate format\n */\nexport default function serialize (\n /** The graph or nodes that should be serialized */\n target: Formula | NamedNode | BlankNode,\n /** The store */\n kb?: IndexedFormula,\n base?: unknown,\n /**\n * The mime type.\n * Defaults to Turtle.\n */\n contentType?: string | ContentType,\n callback?: (err: Error | undefined | null, result?: string) => any,\n options?: {\n /**\n * A string of letters, each of which set an options\n * e.g. `deinprstux`\n */\n flags: string\n }\n): string | undefined {\n base = base || target.value\n const opts = options || {}\n contentType = contentType || TurtleContentType // text/n3 if complex?\n var documentString: string | undefined = undefined\n try {\n var sz = Serializer(kb)\n if ((opts as any).flags) sz.setFlags((opts as any).flags)\n var newSts = kb!.statementsMatching(undefined, undefined, undefined, target as NamedNode)\n var n3String: string\n sz.suggestNamespaces(kb!.namespaces)\n sz.setBase(base)\n switch (contentType) {\n case RDFXMLContentType:\n documentString = sz.statementsToXML(newSts)\n return executeCallback(null, documentString)\n case N3ContentType:\n case N3LegacyContentType:\n documentString = sz.statementsToN3(newSts)\n return executeCallback(null, documentString)\n case TurtleContentType:\n case TurtleLegacyContentType:\n sz.setFlags('si') // Suppress = for sameAs and => for implies\n documentString = sz.statementsToN3(newSts)\n return executeCallback(null, documentString)\n case NTriplesContentType:\n sz.setFlags('deinprstux') // Suppress nice parts of N3 to make ntriples\n documentString = sz.statementsToNTriples(newSts)\n return executeCallback(null, documentString)\n case JSONLDContentType:\n sz.setFlags('deinprstux') // Use adapters to connect to incmpatible parser\n n3String = sz.statementsToNTriples(newSts)\n // n3String = sz.statementsToN3(newSts)\n convert.convertToJson(n3String, callback)\n break\n case NQuadsContentType:\n case NQuadsAltContentType: // @@@ just outpout the quads? Does not work for collections\n sz.setFlags('deinprstux q') // Suppress nice parts of N3 to make ntriples\n documentString = sz.statementsToNTriples(newSts) // q in flag means actually quads\n return executeCallback(null, documentString)\n // n3String = sz.statementsToN3(newSts)\n // documentString = convert.convertToNQuads(n3String, callback)\n // break\n default:\n throw new Error('Serialize: Content-type ' + contentType + ' not supported for data write.')\n }\n } catch (err) {\n if (callback) {\n // @ts-ignore\n return callback(err, undefined)\n }\n throw err // Don't hide problems from caller in sync mode\n }\n\n function executeCallback (err: Error | null | undefined, result: string | undefined): string | undefined {\n if (callback) {\n callback(err, result)\n return\n } else {\n return result as string\n }\n }\n}\n","// N3.js implementations of the RDF/JS core data types\n// See https://github.com/rdfjs/representation-task-force/blob/master/interface-spec.md\n\nimport namespaces from './IRIs';\nimport { isDefaultGraph } from './N3Util';\nconst { rdf, xsd } = namespaces;\n\n// eslint-disable-next-line prefer-const\nlet DEFAULTGRAPH;\nlet _blankNodeCounter = 0;\n\nconst escapedLiteral = /^\"(.*\".*)(?=\"[^\"]*$)/;\nconst quadId = /^<<(\"(?:\"\"|[^\"])*\"[^ ]*|[^ ]+) (\"(?:\"\"|[^\"])*\"[^ ]*|[^ ]+) (\"(?:\"\"|[^\"])*\"[^ ]*|[^ ]+) ?(\"(?:\"\"|[^\"])*\"[^ ]*|[^ ]+)?>>$/;\n\n// ## DataFactory singleton\nconst DataFactory = {\n namedNode,\n blankNode,\n variable,\n literal,\n defaultGraph,\n quad,\n triple: quad,\n};\nexport default DataFactory;\n\n// ## Term constructor\nexport class Term {\n constructor(id) {\n this.id = id;\n }\n\n // ### The value of this term\n get value() {\n return this.id;\n }\n\n // ### Returns whether this object represents the same term as the other\n equals(other) {\n // If both terms were created by this library,\n // equality can be computed through ids\n if (other instanceof Term)\n return this.id === other.id;\n // Otherwise, compare term type and value\n return !!other && this.termType === other.termType &&\n this.value === other.value;\n }\n\n // ### Returns a plain object representation of this term\n toJSON() {\n return {\n termType: this.termType,\n value: this.value,\n };\n }\n}\n\n\n// ## NamedNode constructor\nexport class NamedNode extends Term {\n // ### The term type of this term\n get termType() {\n return 'NamedNode';\n }\n}\n\n// ## Literal constructor\nexport class Literal extends Term {\n // ### The term type of this term\n get termType() {\n return 'Literal';\n }\n\n // ### The text value of this literal\n get value() {\n return this.id.substring(1, this.id.lastIndexOf('\"'));\n }\n\n // ### The language of this literal\n get language() {\n // Find the last quotation mark (e.g., '\"abc\"@en-us')\n const id = this.id;\n let atPos = id.lastIndexOf('\"') + 1;\n // If \"@\" it follows, return the remaining substring; empty otherwise\n return atPos < id.length && id[atPos++] === '@' ? id.substr(atPos).toLowerCase() : '';\n }\n\n // ### The datatype IRI of this literal\n get datatype() {\n return new NamedNode(this.datatypeString);\n }\n\n // ### The datatype string of this literal\n get datatypeString() {\n // Find the last quotation mark (e.g., '\"abc\"^^http://ex.org/types#t')\n const id = this.id, dtPos = id.lastIndexOf('\"') + 1;\n const char = dtPos < id.length ? id[dtPos] : '';\n // If \"^\" it follows, return the remaining substring\n return char === '^' ? id.substr(dtPos + 2) :\n // If \"@\" follows, return rdf:langString; xsd:string otherwise\n (char !== '@' ? xsd.string : rdf.langString);\n }\n\n // ### Returns whether this object represents the same term as the other\n equals(other) {\n // If both literals were created by this library,\n // equality can be computed through ids\n if (other instanceof Literal)\n return this.id === other.id;\n // Otherwise, compare term type, value, language, and datatype\n return !!other && !!other.datatype &&\n this.termType === other.termType &&\n this.value === other.value &&\n this.language === other.language &&\n this.datatype.value === other.datatype.value;\n }\n\n toJSON() {\n return {\n termType: this.termType,\n value: this.value,\n language: this.language,\n datatype: { termType: 'NamedNode', value: this.datatypeString },\n };\n }\n}\n\n// ## BlankNode constructor\nexport class BlankNode extends Term {\n constructor(name) {\n super(`_:${name}`);\n }\n\n // ### The term type of this term\n get termType() {\n return 'BlankNode';\n }\n\n // ### The name of this blank node\n get value() {\n return this.id.substr(2);\n }\n}\n\nexport class Variable extends Term {\n constructor(name) {\n super(`?${name}`);\n }\n\n // ### The term type of this term\n get termType() {\n return 'Variable';\n }\n\n // ### The name of this variable\n get value() {\n return this.id.substr(1);\n }\n}\n\n// ## DefaultGraph constructor\nexport class DefaultGraph extends Term {\n constructor() {\n super('');\n return DEFAULTGRAPH || this;\n }\n\n // ### The term type of this term\n get termType() {\n return 'DefaultGraph';\n }\n\n // ### Returns whether this object represents the same term as the other\n equals(other) {\n // If both terms were created by this library,\n // equality can be computed through strict equality;\n // otherwise, compare term types.\n return (this === other) || (!!other && (this.termType === other.termType));\n }\n}\n\n// ## DefaultGraph singleton\nDEFAULTGRAPH = new DefaultGraph();\n\n\n// ### Constructs a term from the given internal string ID\nexport function termFromId(id, factory) {\n factory = factory || DataFactory;\n\n // Falsy value or empty string indicate the default graph\n if (!id)\n return factory.defaultGraph();\n\n // Identify the term type based on the first character\n switch (id[0]) {\n case '?':\n return factory.variable(id.substr(1));\n case '_':\n return factory.blankNode(id.substr(2));\n case '\"':\n // Shortcut for internal literals\n if (factory === DataFactory)\n return new Literal(id);\n // Literal without datatype or language\n if (id[id.length - 1] === '\"')\n return factory.literal(id.substr(1, id.length - 2));\n // Literal with datatype or language\n const endPos = id.lastIndexOf('\"', id.length - 1);\n return factory.literal(id.substr(1, endPos - 1),\n id[endPos + 1] === '@' ? id.substr(endPos + 2)\n : factory.namedNode(id.substr(endPos + 3)));\n case '<':\n const components = quadId.exec(id);\n return factory.quad(\n termFromId(unescapeQuotes(components[1]), factory),\n termFromId(unescapeQuotes(components[2]), factory),\n termFromId(unescapeQuotes(components[3]), factory),\n components[4] && termFromId(unescapeQuotes(components[4]), factory)\n );\n default:\n return factory.namedNode(id);\n }\n}\n\n// ### Constructs an internal string ID from the given term or ID string\nexport function termToId(term) {\n if (typeof term === 'string')\n return term;\n if (term instanceof Term && term.termType !== 'Quad')\n return term.id;\n if (!term)\n return DEFAULTGRAPH.id;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return term.value;\n case 'BlankNode': return `_:${term.value}`;\n case 'Variable': return `?${term.value}`;\n case 'DefaultGraph': return '';\n case 'Literal': return `\"${term.value}\"${\n term.language ? `@${term.language}` :\n (term.datatype && term.datatype.value !== xsd.string ? `^^${term.datatype.value}` : '')}`;\n case 'Quad':\n // To identify RDF* quad components, we escape quotes by doubling them.\n // This avoids the overhead of backslash parsing of Turtle-like syntaxes.\n return `<<${\n escapeQuotes(termToId(term.subject))\n } ${\n escapeQuotes(termToId(term.predicate))\n } ${\n escapeQuotes(termToId(term.object))\n }${\n (isDefaultGraph(term.graph)) ? '' : ` ${termToId(term.graph)}`\n }>>`;\n default: throw new Error(`Unexpected termType: ${term.termType}`);\n }\n}\n\n\n// ## Quad constructor\nexport class Quad extends Term {\n constructor(subject, predicate, object, graph) {\n super('');\n this._subject = subject;\n this._predicate = predicate;\n this._object = object;\n this._graph = graph || DEFAULTGRAPH;\n }\n\n // ### The term type of this term\n get termType() {\n return 'Quad';\n }\n\n get subject() {\n return this._subject;\n }\n\n get predicate() {\n return this._predicate;\n }\n\n get object() {\n return this._object;\n }\n\n get graph() {\n return this._graph;\n }\n\n // ### Returns a plain object representation of this quad\n toJSON() {\n return {\n termType: this.termType,\n subject: this._subject.toJSON(),\n predicate: this._predicate.toJSON(),\n object: this._object.toJSON(),\n graph: this._graph.toJSON(),\n };\n }\n\n // ### Returns whether this object represents the same quad as the other\n equals(other) {\n return !!other && this._subject.equals(other.subject) &&\n this._predicate.equals(other.predicate) &&\n this._object.equals(other.object) &&\n this._graph.equals(other.graph);\n }\n}\nexport { Quad as Triple };\n\n// ### Escapes the quotes within the given literal\nexport function escapeQuotes(id) {\n return id.replace(escapedLiteral, (_, quoted) => `\"${quoted.replace(/\"/g, '\"\"')}`);\n}\n\n// ### Unescapes the quotes within the given literal\nexport function unescapeQuotes(id) {\n return id.replace(escapedLiteral, (_, quoted) => `\"${quoted.replace(/\"\"/g, '\"')}`);\n}\n\n// ### Creates an IRI\nfunction namedNode(iri) {\n return new NamedNode(iri);\n}\n\n// ### Creates a blank node\nfunction blankNode(name) {\n return new BlankNode(name || `n3-${_blankNodeCounter++}`);\n}\n\n// ### Creates a literal\nfunction literal(value, languageOrDataType) {\n // Create a language-tagged string\n if (typeof languageOrDataType === 'string')\n return new Literal(`\"${value}\"@${languageOrDataType.toLowerCase()}`);\n\n // Automatically determine datatype for booleans and numbers\n let datatype = languageOrDataType ? languageOrDataType.value : '';\n if (datatype === '') {\n // Convert a boolean\n if (typeof value === 'boolean')\n datatype = xsd.boolean;\n // Convert an integer or double\n else if (typeof value === 'number') {\n if (Number.isFinite(value))\n datatype = Number.isInteger(value) ? xsd.integer : xsd.double;\n else {\n datatype = xsd.double;\n if (!Number.isNaN(value))\n value = value > 0 ? 'INF' : '-INF';\n }\n }\n }\n\n // Create a datatyped literal\n return (datatype === '' || datatype === xsd.string) ?\n new Literal(`\"${value}\"`) :\n new Literal(`\"${value}\"^^${datatype}`);\n}\n\n// ### Creates a variable\nfunction variable(name) {\n return new Variable(name);\n}\n\n// ### Returns the default graph\nfunction defaultGraph() {\n return DEFAULTGRAPH;\n}\n\n// ### Creates a quad\nfunction quad(subject, predicate, object, graph) {\n return new Quad(subject, predicate, object, graph);\n}\n","/**\n * RDF/XML PARSER\n *\n * Parser believed to be in full positive RDF/XML parsing compliance\n * with the possible exception of handling deprecated RDF attributes\n * appropriately. Parser is believed to comply fully with other W3C\n * and industry standards where appropriate (DOM, ECMAScript, &c.)\n *\n * Author: David Sheets <dsheets@mit.edu>\n *\n * W3C® SOFTWARE NOTICE AND LICENSE\n * http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231\n * This work (and included software, documentation such as READMEs, or\n * other related items) is being provided by the copyright holders under\n * the following license. By obtaining, using and/or copying this work,\n * you (the licensee) agree that you have read, understood, and will\n * comply with the following terms and conditions.\n *\n * Permission to copy, modify, and distribute this software and its\n * documentation, with or without modification, for any purpose and\n * without fee or royalty is hereby granted, provided that you include\n * the following on ALL copies of the software and documentation or\n * portions thereof, including modifications:\n *\n * 1. The full text of this NOTICE in a location viewable to users of\n * the redistributed or derivative work.\n * 2. Any pre-existing intellectual property disclaimers, notices, or terms and\n * conditions. If none exist, the W3C Software Short Notice should be\n * included (hypertext is preferred, text is permitted) within the body\n * of any redistributed or derivative code.\n * 3. Notice of any changes or modifications to the files, including the\n * date changes were made. (We recommend you provide URIs to the location\n * from which the code is derived.)\n *\n * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED \"AS IS,\" AND COPYRIGHT\n * HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED,\n * INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS\n * FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR\n * DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,\n * TRADEMARKS OR OTHER RIGHTS.\n *\n * COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL\n * OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR\n * DOCUMENTATION.\n *\n * The name and trademarks of copyright holders may NOT be used in\n * advertising or publicity pertaining to the software without specific,\n * written prior permission. Title to copyright in this software and any\n * associated documentation will at all times remain with copyright\n * holders.\n */\n/**\n * @class RDFParser resource object tied to an RDFStore\n *\n * @author David Sheets <dsheets@mit.edu>\n *\n*/\nimport * as uriUtil from './uri'\n\n\nexport default class RDFParser {\n\n /*\n * @constructor\n * @param {RDFStore} store An RDFStore object\n */\n constructor(store) {\n /** Our triple store reference @private */\n\n this.store = store /** Our identified blank nodes @private */\n this.bnodes = {} /** A context for context-aware stores @private */\n this.why = null /** Reification flag */\n this.reify = false\n }\n\n /** Standard namespaces that we know how to handle @final\n * @member RDFParser\n */\n static ns = {'RDF': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'RDFS': 'http://www.w3.org/2000/01/rdf-schema#'}\n\n /** DOM Level 2 node type magic numbers @final\n * @member RDFParser\n */\n static nodeType = {'ELEMENT': 1, 'ATTRIBUTE': 2, 'TEXT': 3,\n 'CDATA_SECTION': 4, 'ENTITY_REFERENCE': 5,\n 'ENTITY': 6, 'PROCESSING_INSTRUCTION': 7,\n 'COMMENT': 8, 'DOCUMENT': 9, 'DOCUMENT_TYPE': 10,\n 'DOCUMENT_FRAGMENT': 11, 'NOTATION': 12}\n\n /**\n * Frame class for namespace and base URI lookups\n * Base lookups will always resolve because the parser knows\n * the default base.\n *\n * @private\n */\n\n frameFactory(parser, parent, element) {\n return {'NODE': 1, 'ARC': 2, 'parent': parent, 'parser': parser, 'store': parser.store, 'element': element,\n 'lastChild': 0, 'base': null, 'lang': null, 'node': null, 'nodeType': null, 'listIndex': 1, 'rdfid': null, 'datatype': null, 'collection': false, /** Terminate the frame and notify the store that we're done */\n 'terminateFrame': function () {\n if (this.collection) {\n this.node.close()\n }\n }, /** Add a symbol of a certain type to the this frame */'addSymbol': function (type, uri) {\n uri = uriUtil.join(uri, this.base)\n this.node = this.store.sym(uri)\n\n this.nodeType = type\n }, /** Load any constructed triples into the store */'loadTriple': function () {\n if (this.parent.parent.collection) {\n this.parent.parent.node.append(this.node)\n } else {\n this.store.add(this.parent.parent.node, this.parent.node, this.node, this.parser.why)\n }\n if (this.parent.rdfid != null) {\n // reify\n var triple = this.store.sym(uriUtil.join('#' + this.parent.rdfid, this.base))\n this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'type'), this.store.sym(RDFParser.ns.RDF + 'Statement'), this.parser.why)\n this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'subject'), this.parent.parent.node, this.parser.why)\n this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'predicate'), this.parent.node, this.parser.why)\n\n this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'object'), this.node, this.parser.why)\n }\n }, /** Check if it's OK to load a triple */'isTripleToLoad': function () {\n return (this.parent != null && this.parent.parent != null && this.nodeType === this.NODE && this.parent.nodeType ===\n this.ARC && this.parent.parent.nodeType === this.NODE)\n }, /** Add a symbolic node to this frame */'addNode': function (uri) {\n this.addSymbol(this.NODE, uri)\n if (this.isTripleToLoad()) {\n this.loadTriple()\n }\n }, /** Add a collection node to this frame */'addCollection': function () {\n this.nodeType = this.NODE\n this.node = this.store.collection()\n this.collection = true\n if (this.isTripleToLoad()) {\n this.loadTriple()\n }\n }, /** Add a collection arc to this frame */'addCollectionArc': function () {\n this.nodeType = this.ARC\n }, /** Add a bnode to this frame */'addBNode': function (id) {\n if (id != null) {\n if (this.parser.bnodes[id] != null) {\n this.node = this.parser.bnodes[id]\n } else {\n this.node = this.parser.bnodes[id] = this.store.bnode()\n }\n } else {\n this.node = this.store.bnode()\n }\n this.nodeType = this.NODE\n if (this.isTripleToLoad()) {\n this.loadTriple()\n }\n }, /** Add an arc or property to this frame */'addArc': function (uri) {\n if (uri === RDFParser.ns.RDF + 'li') {\n uri = RDFParser.ns.RDF + '_' + this.parent.listIndex\n this.parent.listIndex++\n }\n\n this.addSymbol(this.ARC, uri)\n }, /** Add a literal to this frame */'addLiteral': function (value) {\n if (this.parent.datatype && this.parent.datatype !== RDFParser.ns.RDF +'langString') {\n this.node = this.store.literal(value, this.store.sym(this.parent.datatype))\n } else {\n this.node = this.store.literal(value, this.lang)\n }\n this.nodeType = this.NODE\n if (this.isTripleToLoad()) {\n this.loadTriple()\n }\n }\n }\n }\n\n // from the OpenLayers source .. needed to get around IE problems.\n getAttributeNodeNS(node, uri, name) {\n var attributeNode = null\n if (node.getAttributeNodeNS) {\n attributeNode = node.getAttributeNodeNS(uri, name)\n } else {\n var attributes = node.attributes\n var potentialNode, fullName\n for (var i = 0;i < attributes.length; ++i) {\n potentialNode = attributes[i]\n if (potentialNode.namespaceURI === uri) {\n fullName = (potentialNode.prefix) ? (potentialNode.prefix + ':' + name) : name\n if (fullName === potentialNode.nodeName) {\n attributeNode = potentialNode\n break\n }\n }\n }\n }\n return attributeNode\n }\n\n /**\n * Build our initial scope frame and parse the DOM into triples\n * @param {DOMTree} document The DOM to parse\n * @param {String} base The base URL to use\n * @param {Object} why The context to which this resource belongs\n */\n\n parse(document, base, why) {\n var children = document.childNodes // clean up for the next run\n this.cleanParser() // figure out the root element\n var root\n if (document.nodeType === RDFParser.nodeType.DOCUMENT) {\n for (var c = 0;c < children.length;c++) {\n if (children[c].nodeType === RDFParser.nodeType.ELEMENT) {\n root = children[c]\n break\n }\n }\n } else if (document.nodeType === RDFParser.nodeType.ELEMENT) {\n root = document\n } else {\n throw new Error(\"RDFParser: can't find root in \" + base + '. Halting. ')\n // return false\n }\n this.why = why // our topmost frame\n var f = this.frameFactory(this)\n this.base = base\n f.base = base\n f.lang = null // was '' but can't have langs like that 2015 (!)\n this.parseDOM(this.buildFrame(f, root))\n return true\n }\n\n parseDOM(frame) {\n // a DOM utility function used in parsing\n var rdfid\n var elementURI = function (el) {\n var result = ''\n if (el.namespaceURI == null) {\n throw new Error('RDF/XML syntax error: No namespace for ' + el.localName + ' in ' + this.base)\n }\n if (el.namespaceURI) {\n result = result + el.namespaceURI\n }\n if (el.localName) {\n result = result + el.localName\n } else if (el.nodeName) {\n if (el.nodeName.indexOf(':') >= 0)result = result + el.nodeName.split(':')[1]\n else result = result + el.nodeName\n }\n return result\n }.bind(this)\n var dig = true // if we'll dig down in the tree on the next iter\n while (frame.parent) {\n var dom = frame.element\n var attrs = dom.attributes\n if (dom.nodeType === RDFParser.nodeType.TEXT || dom.nodeType === RDFParser.nodeType.CDATA_SECTION) {\n // we have a literal\n if (frame.parent.nodeType === frame.NODE) {\n // must have had attributes, store as rdf:value\n frame.addArc(RDFParser.ns.RDF + 'value')\n frame = this.buildFrame(frame)\n }\n frame.addLiteral(dom.nodeValue)\n } else if (elementURI(dom) !== RDFParser.ns.RDF + 'RDF') {\n // not root\n if (frame.parent && frame.parent.collection) {\n // we're a collection element\n frame.addCollectionArc()\n frame = this.buildFrame(frame, frame.element)\n frame.parent.element = null\n }\n if (!frame.parent || !frame.parent.nodeType || frame.parent.nodeType === frame.ARC) {\n // we need a node\n var about = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'about')\n rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'ID')\n if (about && rdfid) {\n throw new Error('RDFParser: ' + dom.nodeName + ' has both rdf:id and rdf:about.' +\n ' Halting. Only one of these' + ' properties may be specified on a' + ' node.')\n }\n if (!about && rdfid) {\n frame.addNode('#' + rdfid.nodeValue)\n dom.removeAttributeNode(rdfid)\n } else if (about == null && rdfid == null) {\n var bnid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'nodeID')\n if (bnid) {\n frame.addBNode(bnid.nodeValue)\n dom.removeAttributeNode(bnid)\n } else {\n frame.addBNode()\n }\n } else {\n frame.addNode(about.nodeValue)\n dom.removeAttributeNode(about)\n }\n // Typed nodes\n var rdftype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'type')\n if (RDFParser.ns.RDF + 'Description' !== elementURI(dom)) {\n rdftype = {'nodeValue': elementURI(dom)}\n }\n if (rdftype != null) {\n this.store.add(frame.node, this.store.sym(RDFParser.ns.RDF + 'type'), this.store.sym(uriUtil.join(rdftype.nodeValue,\n frame.base)), this.why)\n if (rdftype.nodeName) {\n dom.removeAttributeNode(rdftype)\n }\n }\n // Property Attributes\n for (var x = attrs.length - 1; x >= 0; x--) {\n this.store.add(frame.node, this.store.sym(elementURI(attrs[x])), this.store.literal(attrs[x].nodeValue,\n frame.lang), this.why)\n }\n } else {\n // we should add an arc (or implicit bnode+arc)\n frame.addArc(elementURI(dom)) // save the arc's rdf:ID if it has one\n if (this.reify) {\n rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'ID')\n if (rdfid) {\n frame.rdfid = rdfid.nodeValue\n dom.removeAttributeNode(rdfid)\n }\n }\n var parsetype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'parseType')\n var datatype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'datatype')\n if (datatype) {\n frame.datatype = datatype.nodeValue\n dom.removeAttributeNode(datatype)\n }\n if (parsetype) {\n var nv = parsetype.nodeValue\n if (nv === 'Literal') {\n frame.datatype = RDFParser.ns.RDF + 'XMLLiteral'\n frame = this.buildFrame(frame)\n // Don't include the literal node, only its children\n frame.addLiteral(dom.childNodes)\n dig = false\n } else if (nv === 'Resource') {\n frame = this.buildFrame(frame, frame.element)\n frame.parent.element = null\n frame.addBNode()\n } else if (nv === 'Collection') {\n frame = this.buildFrame(frame, frame.element)\n frame.parent.element = null\n frame.addCollection()\n }\n dom.removeAttributeNode(parsetype)\n }\n if (attrs.length !== 0) {\n var resource = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'resource')\n var bnid2 = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'nodeID')\n frame = this.buildFrame(frame)\n if (resource) {\n frame.addNode(resource.nodeValue)\n dom.removeAttributeNode(resource)\n } else {\n if (bnid2) {\n frame.addBNode(bnid2.nodeValue)\n dom.removeAttributeNode(bnid2)\n } else {\n frame.addBNode()\n }\n }\n for (var x1 = attrs.length - 1; x1 >= 0; x1--) {\n var f = this.buildFrame(frame)\n f.addArc(elementURI(attrs[x1]))\n if (elementURI(attrs[x1]) === RDFParser.ns.RDF + 'type') {\n (this.buildFrame(f)).addNode(attrs[x1].nodeValue)\n } else {\n (this.buildFrame(f)).addLiteral(attrs[x1].nodeValue)\n }\n }\n } else if (dom.childNodes.length === 0) {\n (this.buildFrame(frame)).addLiteral('')\n }\n }\n } // rdf:RDF\n // dig dug\n dom = frame.element\n while (frame.parent) {\n var pframe = frame\n while (dom == null) {\n frame = frame.parent\n dom = frame.element\n }\n var candidate = dom.childNodes && dom.childNodes[frame.lastChild]\n if (!candidate || !dig) {\n frame.terminateFrame()\n if (!(frame = frame.parent)) {\n break\n } // done\n dom = frame.element\n dig = true\n } else if ((candidate.nodeType !== RDFParser.nodeType.ELEMENT &&\n candidate.nodeType !== RDFParser.nodeType.TEXT &&\n candidate.nodeType !== RDFParser.nodeType.CDATA_SECTION) ||\n ((candidate.nodeType === RDFParser.nodeType.TEXT ||\n candidate.nodeType === RDFParser.nodeType.CDATA_SECTION) &&\n dom.childNodes.length !== 1)) {\n frame.lastChild++\n } else {\n // not a leaf\n frame.lastChild++\n frame = this.buildFrame(pframe, dom.childNodes[frame.lastChild - 1])\n break\n }\n }\n } // while\n }\n\n /**\n * Cleans out state from a previous parse run\n * @private\n */\n cleanParser() {\n this.bnodes = {}\n this.why = null\n }\n\n /**\n * Builds scope frame\n * @private\n */\n buildFrame(parent, element) {\n var frame = this.frameFactory(this, parent, element)\n if (parent) {\n frame.base = parent.base\n frame.lang = parent.lang\n }\n if (!element || element.nodeType === RDFParser.nodeType.TEXT ||\n element.nodeType === RDFParser.nodeType.CDATA_SECTION) {\n return frame\n }\n var attrs = element.attributes\n var base = element.getAttributeNode('xml:base')\n if (base != null) {\n frame.base = base.nodeValue\n element.removeAttribute('xml:base')\n }\n var lang = element.getAttributeNode('xml:lang')\n if (lang != null) {\n frame.lang = lang.nodeValue\n element.removeAttribute('xml:lang')\n }\n // remove all extraneous xml and xmlns attributes\n for (var x = attrs.length - 1;x >= 0;x--) {\n if (attrs[x].nodeName.substr(0, 3) === 'xml') {\n if (attrs[x].name.slice(0, 6) === 'xmlns:') {\n var uri = attrs[x].nodeValue // alert('base for namespac attr:'+this.base)\n if (this.base) uri = uriUtil.join(uri, this.base)\n this.store.setPrefixForURI(attrs[x].name.slice(6), uri)\n }\n //\t\talert('rdfparser: xml atribute: '+attrs[x].name) //@@\n element.removeAttributeNode(attrs[x])\n }\n }\n return frame\n }\n}\n","import CanonicalDataFactory from \"./factories/canonical-data-factory\";\n\nexport function createXSD(localFactory = CanonicalDataFactory) {\n return {\n boolean: localFactory.namedNode(\"http://www.w3.org/2001/XMLSchema#boolean\"),\n dateTime: localFactory.namedNode(\n \"http://www.w3.org/2001/XMLSchema#dateTime\"\n ),\n decimal: localFactory.namedNode(\"http://www.w3.org/2001/XMLSchema#decimal\"),\n double: localFactory.namedNode(\"http://www.w3.org/2001/XMLSchema#double\"),\n integer: localFactory.namedNode(\"http://www.w3.org/2001/XMLSchema#integer\"),\n langString: localFactory.namedNode(\n \"http://www.w3.org/1999/02/22-rdf-syntax-ns#langString\"\n ),\n string: localFactory.namedNode(\"http://www.w3.org/2001/XMLSchema#string\"),\n };\n}\n\nconst defaultXSD = createXSD(CanonicalDataFactory);\n\nexport default defaultXSD;\n","/* Serialization of RDF Graphs\n**\n** Tim Berners-Lee 2006\n** This is was http://dig.csail.mit.edu/2005/ajar/ajaw/js/rdf/serialize.js\n** This is or was https://github.com/linkeddata/rdflib.js/blob/main/src/serializer.js\n** Licence: MIT\n*/\nimport NamedNode from './named-node'\nimport BlankNode from './blank-node'\nimport * as Uri from './uri'\nimport * as Util from './utils-js'\nimport CanonicalDataFactory from './factories/canonical-data-factory'\nimport { createXSD } from './xsd'\nimport solidNs from 'solid-namespace'\n\n\nexport default function createSerializer(store) {\n return new Serializer(store);\n};\n\nexport class Serializer {\n constructor(store) {\n this.flags = ''\n this.base = null\n\n this.prefixes = [] // suggested prefixes\n this.namespaces = [] // complementary\n const nsKeys = Object.keys(solidNs())\n for (const i in nsKeys) {\n const uri = solidNs()[nsKeys[i]]('')\n const prefix = nsKeys[i]\n this.prefixes[uri] = prefix\n this.namespaces[prefix] = uri\n }\n\n this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') // XML code assumes this!\n this.suggestPrefix('xml', 'reserved:reservedForFutureUse') // XML reserves xml: in the spec.\n\n this.namespacesUsed = [] // Count actually used and so needed in @prefixes\n this.keywords = ['a'] // The only one we generate at the moment\n this.prefixchars = 'abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n this.incoming = null // Array not calculated yet\n this.formulas = [] // remebering original formulae from hashes\n this.store = store\n this.rdfFactory = store.rdfFactory || CanonicalDataFactory\n this.xsd = createXSD(this.rdfFactory)\n }\n\n setBase(base) {\n this.base = base;\n return this\n }\n\n setFlags(flags) {\n this.flags = flags || '';\n return this\n }\n\n toStr(x) {\n var s = x.toNT()\n if (x.termType === 'Graph') {\n this.formulas[s] = x // remember as reverse does not work\n }\n return s\n }\n\n fromStr(s) {\n if (s[0] === '{') {\n var x = this.formulas[s]\n if (!x) console.log('No formula object for ' + s)\n return x\n }\n return this.store.fromNT(s)\n }\n\n /* Accumulate Namespaces\n **\n ** These are only hints. If two overlap, only one gets used\n ** There is therefore no guarantee in general.\n */\n suggestPrefix(prefix, uri) {\n if (prefix.slice(0, 7) === 'default') return // Try to weed these out\n if (prefix.slice(0, 2) === 'ns') return // From others inferior algos\n if (!prefix || !uri) return // empty strings not suitable\n if (prefix in this.namespaces || uri in this.prefixes) return // already used\n this.prefixes[uri] = prefix\n this.namespaces[prefix] = uri\n }\n\n // Takes a namespace -> prefix map\n suggestNamespaces(namespaces) {\n for (var px in namespaces) {\n this.suggestPrefix(px, namespaces[px])\n }\n return this\n }\n\n checkIntegrity() {\n var p, ns\n for (p in this.namespaces) {\n if (this.prefixes[this.namespaces[p]] !== p) {\n throw new Error('Serializer integity error 1: ' + p + ', ' +\n this.namespaces[p] + ', ' + this.prefixes[this.namespaces[p]] + '!')\n }\n }\n for (ns in this.prefixes) {\n if (this.namespaces[this.prefixes[ns]] !== ns) {\n throw new Error('Serializer integity error 2: ' + ns + ', ' +\n this.prefixs[ns] + ', ' + this.namespaces[this.prefixes[ns]] + '!')\n }\n }\n }\n\n // Make up an unused prefix for a random namespace\n makeUpPrefix(uri) {\n var p = uri\n function canUseMethod (pp) {\n if (!this.validPrefix.test(pp)) return false // bad format\n if (pp === 'ns') return false // boring\n if (pp in this.namespaces) return false // already used\n this.prefixes[uri] = pp\n this.namespaces[pp] = uri\n return pp\n }\n var canUse = canUseMethod.bind(this)\n\n if ('#/'.indexOf(p[p.length - 1]) >= 0) p = p.slice(0, -1)\n var slash = p.lastIndexOf('/')\n if (slash >= 0) p = p.slice(slash + 1)\n var i = 0\n while (i < p.length) {\n if (this.prefixchars.indexOf(p[i])) {\n i++\n } else {\n break\n }\n }\n p = p.slice(0, i)\n\n if (p.length < 6 && (canUse(p))) return p // exact is best\n if (canUse(p.slice(0, 3))) return p.slice(0, 3)\n if (canUse(p.slice(0, 2))) return p.slice(0, 2)\n if (canUse(p.slice(0, 4))) return p.slice(0, 4)\n if (canUse(p.slice(0, 1))) return p.slice(0, 1)\n if (canUse(p.slice(0, 5))) return p.slice(0, 5)\n if (!this.validPrefix.test(p)) {\n p = 'n' // Otherwise the loop below may never termimnate\n }\n for (var j = 0; ; j++) if (canUse(p.slice(0, 3) + j)) return p.slice(0, 3) + j\n }\n\n rootSubjects(sts) {\n var incoming = {}\n var subjects = {}\n var allBnodes = {}\n\n /* This scan is to find out which nodes will have to be the roots of trees\n ** in the serialized form. This will be any symbols, and any bnodes\n ** which hve more or less than one incoming arc, and any bnodes which have\n ** one incoming arc but it is an uninterrupted loop of such nodes back to itself.\n ** This should be kept linear time with repect to the number of statements.\n ** Note it does not use any indexing of the store.\n */\n for (var i = 0; i < sts.length; i++) {\n var st = sts[i]\n var checkMentions = function (x) {\n if (!incoming.hasOwnProperty(x)) incoming[x] = []\n incoming[x].push(st.subject) // List of things which will cause this to be printed\n }\n var st2 = [st.subject, st.predicate, st.object]\n st2.map(function (y) {\n if (y.termType === 'BlankNode') {\n allBnodes[y.toNT()] = true\n } else if (y.termType === 'Collection') {\n y.elements.forEach(function (z) {\n checkMentions(z) // bnodes in collections important\n })\n }\n })\n checkMentions(sts[i].object)\n var ss = subjects[this.toStr(st.subject)] // Statements with this as subject\n if (!ss) ss = []\n ss.push(st)\n subjects[this.toStr(st.subject)] = ss // Make hash. @@ too slow for formula?\n }\n\n var roots = []\n for (var xNT in subjects) {\n if (!subjects.hasOwnProperty(xNT)) continue\n var y = this.fromStr(xNT)\n if ((y.termType !== 'BlankNode') || !incoming[y] || (incoming[y].length !== 1)) {\n roots.push(y)\n continue\n }\n }\n this.incoming = incoming // Keep for serializing @@ Bug for nested formulas\n\n // Now do the scan using existing roots\n var rootsHash = {}\n for (var k = 0; k < roots.length; k++) {\n rootsHash[roots[k].toNT()] = true\n }\n return {'roots': roots, 'subjects': subjects,\n 'rootsHash': rootsHash, 'incoming': incoming}\n }\n\n // //////////////////////////////////////////////////////\n\n toN3(f) {\n return this.statementsToN3(f.statements)\n }\n\n _notQNameChars = '\\t\\r\\n !\"#$%&\\'()*.,+/;<=>?@[\\\\]^`{|}~'\n _notNameChars =\n (this._notQNameChars + ':')\n\n explicitURI(uri) {\n if (this.flags.indexOf('r') < 0 && this.base) {\n uri = Uri.refTo(this.base, uri)\n } else if (this.flags.indexOf('u') >= 0) { // Unicode encoding NTriples style\n uri = backslashUify(uri)\n } else {\n uri = hexify(uri)\n }\n return '<' + uri + '>'\n }\n\n statementsToNTriples(sts) {\n var sorted = sts.slice()\n sorted.sort()\n var str = ''\n var rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'\n var self = this\n var kb = this.store\n var factory = this.rdfFactory\n var termToNT = function (x) {\n if (x.termType !== 'Collection') {\n return self.atomicTermToN3(x)\n }\n var list = x.elements\n var rest = kb.sym(rdfns + 'nill')\n for (var i = list.length - 1; i >= 0; i--) {\n var bnode = factory.blankNode()\n str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'first')) + ' ' + termToNT(list[i]) + '.\\n'\n str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'rest')) + ' ' + termToNT(rest) + '.\\n'\n rest = bnode\n }\n return self.atomicTermToN3(rest)\n }\n for (var i = 0; i < sorted.length; i++) {\n var st = sorted[i]\n var s = ''\n s += termToNT(st.subject) + ' '\n s += termToNT(st.predicate) + ' '\n s += termToNT(st.object) + ' '\n if (this.flags.indexOf('q') >= 0) { // Do quads not nrtiples\n s += termToNT(st.why) + ' '\n }\n s += '.\\n'\n str += s\n }\n return str\n }\n\n statementsToN3(sts) {\n var indent = 4\n var width = 80\n var kb = this.store\n // A URI Map alows us to put the type statemnts at the top.\n var uriMap = {'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': 'aaa:00'}\n var SPO = function (x, y) { // Do limited canonicalization of bnodes\n return Util.heavyCompareSPO(x, y, kb, uriMap)\n }\n sts.sort(SPO)\n\n if (this.base && !this.defaultNamespace){\n this.defaultNamespace = this.base + '#'\n }\n\n var predMap = {}\n if (this.flags.indexOf('s') < 0) {\n predMap['http://www.w3.org/2002/07/owl#sameAs'] = '='\n }\n if (this.flags.indexOf('t') < 0) {\n predMap['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'] = 'a'\n }\n if (this.flags.indexOf('i') < 0) {\n predMap['http://www.w3.org/2000/10/swap/log#implies'] = '=>'\n }\n // //////////////////////// Arrange the bits of text\n\n var spaces = function (n) {\n var s = ''\n for (var i = 0; i < n; i++) s += ' '\n return s\n }\n\n var treeToLine = function (tree) {\n var str = ''\n for (var i = 0; i < tree.length; i++) {\n var branch = tree[i]\n var s2 = (typeof branch === 'string') ? branch : treeToLine(branch)\n // Note the space before the dot in case statement ends 123. which is in fact allowed but be conservative.\n if (i !== 0) {\n var ch = str.slice(-1) || ' '\n if (s2 === ',' || s2 === ';') {\n // no gap\n } else if (s2 === '.' && !('0123456789.'.includes(ch))) { // no gap except after number\n // no gap\n } else {\n str += ' ' // separate from previous token\n }\n }\n str += s2\n }\n return str\n }\n\n // Convert a nested tree of lists and strings to a string\n var treeToString = function (tree, level) {\n var str = ''\n var lastLength = 100000\n if (level === undefined) level = -1\n for (var i = 0; i < tree.length; i++) {\n var branch = tree[i]\n if (typeof branch !== 'string') {\n var substr = treeToString(branch, level + 1)\n if (\n substr.length < 10 * (width - indent * level) &&\n substr.indexOf('\"\"\"') < 0) { // Don't mess up multiline strings\n var line = treeToLine(branch)\n if (line.length < (width - indent * level)) {\n branch = line // Note! treat as string below\n substr = ''\n }\n }\n if (substr) lastLength = 10000\n str += substr\n }\n if (typeof branch === 'string') {\n if (branch.length === 1 && str.slice(-1) === '\\n') {\n if (',.;'.indexOf(branch) >= 0) {\n str = str.slice(0, -1) + branch + '\\n' // slip punct'n on end\n lastLength += 1\n continue\n }\n }\n if (lastLength < (indent * level + 4) || // if new line not necessary\n lastLength + branch.length + 1 < width && ';.'.indexOf(str[str.length - 2]) < 0) { // or the string fits on last line\n str = str.slice(0, -1) + ' ' + branch + '\\n' // then continue on this line\n lastLength += branch.length + 1\n } else {\n let line = spaces(indent * level) + branch\n str += line + '\\n'\n lastLength = line.length\n if (level < 0) {\n str += '\\n' // extra blank line\n lastLength = 100000 // don't touch\n }\n }\n }\n }\n return str\n }\n\n // //////////////////////////////////////////// Structure for N3\n // Convert a set of statements into a nested tree of lists and strings\n function statementListToTreeMethod (statements) {\n var stats = this.rootSubjects(statements)\n var roots = stats.roots\n var results = []\n for (var i = 0; i < roots.length; i++) {\n var root = roots[i]\n results.push(subjectTree(root, stats))\n }\n return results\n }\n var statementListToTree = statementListToTreeMethod.bind(this)\n\n // The tree for a subject\n function subjectTree (subject, stats) {\n if (subject.termType === 'BlankNode' && !stats.incoming[subject]) {\n return objectTree(subject, stats, true).concat(['.']) // Anonymous bnode subject\n }\n return [ termToN3(subject, stats) ].concat([propertyTree(subject, stats)]).concat(['.'])\n }\n // The property tree for a single subject or anonymous node\n function propertyTreeMethod (subject, stats) {\n var results = []\n var lastPred = null\n var sts = stats.subjects[this.toStr(subject)] || [] // relevant statements\n if (typeof sts === 'undefined') {\n throw new Error('Cant find statements for ' + subject)\n }\n\n var objects = []\n for (var i = 0; i < sts.length; i++) {\n var st = sts[i]\n if (st.predicate.uri === lastPred) {\n objects.push(',')\n } else {\n if (lastPred) {\n results = results.concat([objects]).concat([';'])\n objects = []\n }\n results.push(predMap[st.predicate.uri]\n ? predMap[st.predicate.uri] : termToN3(st.predicate, stats))\n }\n lastPred = st.predicate.uri\n objects.push(objectTree(st.object, stats))\n }\n results = results.concat([objects])\n return results\n }\n\n var propertyTree = propertyTreeMethod.bind(this)\n\n function objectTreeMethod(obj, stats, force) {\n if (obj.termType === 'BlankNode' &&\n (force || stats.rootsHash[obj.toNT()] === undefined)) {// if not a root\n if (stats.subjects[this.toStr(obj)]) {\n return ['[', propertyTree(obj, stats), ']']\n } else {\n return '[]'\n }\n }\n return termToN3(obj, stats)\n }\n\n var objectTree = objectTreeMethod.bind(this)\n\n function termToN3Method(expr, stats) { //\n var i, res\n switch (expr.termType) {\n case 'Graph':\n res = ['{']\n res = res.concat(statementListToTree(expr.statements))\n return res.concat(['}'])\n\n case 'Collection':\n res = ['(']\n for (i = 0; i < expr.elements.length; i++) {\n res.push([ objectTree(expr.elements[i], stats) ])\n }\n res.push(')')\n return res\n\n default:\n return this.atomicTermToN3(expr)\n }\n }\n Serializer.prototype.termToN3 = termToN3\n var termToN3 = termToN3Method.bind(this)\n\n function prefixDirectivesMethod () {\n var str = ''\n if (this.defaultNamespace) {\n str += '@prefix : ' + this.explicitURI(this.defaultNamespace) + '.\\n'\n }\n for (var ns in this.prefixes) {\n if (!this.prefixes.hasOwnProperty(ns)) continue\n if (!this.namespacesUsed[ns]) continue\n str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) +\n '.\\n'\n }\n return str + '\\n'\n }\n var prefixDirectives = prefixDirectivesMethod.bind(this)\n // Body of statementsToN3:\n var tree = statementListToTree(sts)\n return prefixDirectives() + treeToString(tree)\n }\n // //////////////////////////////////////////// Atomic Terms\n\n // Deal with term level things and nesting with no bnode structure\n atomicTermToN3 (expr, stats) {\n switch (expr.termType) {\n case 'BlankNode':\n case 'Variable':\n return expr.toNT()\n case 'Literal':\n var val = expr.value\n if (typeof val !== 'string') {\n throw new TypeError('Value of RDF literal node must be a string')\n }\n // var val = expr.value.toString() // should be a string already\n if (expr.datatype && this.flags.indexOf('x') < 0) { // Supress native numbers\n switch (expr.datatype.uri) {\n\n case 'http://www.w3.org/2001/XMLSchema#integer':\n return val\n\n case 'http://www.w3.org/2001/XMLSchema#decimal': // In urtle must have dot\n if (val.indexOf('.') < 0) val += '.0'\n return val\n\n case 'http://www.w3.org/2001/XMLSchema#double': {\n // Must force use of 'e'\n const eNotation = val.toLowerCase().indexOf('e') > 0;\n if (val.indexOf('.') < 0 && !eNotation) val += '.0'\n if (!eNotation) val += 'e0'\n return val\n }\n\n case 'http://www.w3.org/2001/XMLSchema#boolean':\n return expr.value === '1' ? 'true' : 'false'\n }\n }\n var str = this.stringToN3(expr.value)\n if (expr.language) {\n str += '@' + expr.language\n } else if (!expr.datatype.equals(this.xsd.string)) {\n str += '^^' + this.atomicTermToN3(expr.datatype, stats)\n }\n return str\n case 'NamedNode':\n return this.symbolToN3(expr)\n default:\n throw new Error('Internal: atomicTermToN3 cannot handle ' + expr + ' of termType: ' + expr.termType)\n }\n }\n\n // stringToN3: String escaping for N3\n\n validPrefix = new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/)\n\n forbidden1 = new RegExp(/[\\\\\"\\b\\f\\r\\v\\t\\n\\u0080-\\uffff]/gm)\n forbidden3 = new RegExp(/[\\\\\"\\b\\f\\r\\v\\u0080-\\uffff]/gm)\n stringToN3(str, flags) {\n if (!flags) flags = 'e'\n var res = ''\n var i, j, k\n var delim\n var forbidden\n if (str.length > 20 && // Long enough to make sense\n str.slice(-1) !== '\"' && // corner case'\n flags.indexOf('n') < 0 && // Force single line\n (str.indexOf('\\n') > 0 || str.indexOf('\"') > 0)) {\n delim = '\"\"\"'\n forbidden = this.forbidden3\n } else {\n delim = '\"'\n forbidden = this.forbidden1\n }\n for (i = 0; i < str.length;) {\n forbidden.lastIndex = 0\n var m = forbidden.exec(str.slice(i))\n if (m == null) break\n j = i + forbidden.lastIndex - 1\n res += str.slice(i, j)\n var ch = str[j]\n if (ch === '\"' && delim === '\"\"\"' && str.slice(j, j + 3) !== '\"\"\"') {\n res += ch\n } else {\n k = '\\b\\f\\r\\t\\v\\n\\\\\"'.indexOf(ch) // No escaping of bell (7)?\n if (k >= 0) {\n res += '\\\\' + 'bfrtvn\\\\\"'[k]\n } else {\n if (flags.indexOf('e') >= 0) { // Unicode escaping in strings not unix style\n res += '\\\\u' + ('000' +\n ch.charCodeAt(0).toString(16).toLowerCase()).slice(-4)\n } else { // no 'e' flag\n res += ch\n }\n }\n }\n i = j + 1\n }\n return delim + res + str.slice(i) + delim\n }\n // A single symbol, either in <> or namespace notation\n\n symbolToN3 (x) { // c.f. symbolString() in notation3.py\n var uri = x.uri\n var j = uri.indexOf('#')\n if (j < 0 && this.flags.indexOf('/') < 0) {\n j = uri.lastIndexOf('/')\n }\n if (j >= 0 && this.flags.indexOf('p') < 0 &&\n // Can split at namespace but only if http[s]: URI or file: or ws[s] (why not others?)\n (uri.indexOf('http') === 0 || uri.indexOf('ws') === 0 || uri.indexOf('file') === 0)) {\n var canSplit = true\n for (var k = j + 1; k < uri.length; k++) {\n if (this._notNameChars.indexOf(uri[k]) >= 0) {\n canSplit = false\n break\n }\n }\n/*\n if (uri.slice(0, j + 1) === this.base + '#') { // base-relative\n if (canSplit) {\n return ':' + uri.slice(j + 1) // assume deafult ns is local\n } else {\n return '<#' + uri.slice(j + 1) + '>'\n }\n }\n*/\n if (canSplit) {\n var localid = uri.slice(j + 1)\n var namesp = uri.slice(0, j + 1)\n if (this.defaultNamespace && this.defaultNamespace === namesp &&\n this.flags.indexOf('d') < 0) { // d -> suppress default\n if (this.flags.indexOf('k') >= 0 &&\n this.keyords.indexOf(localid) < 0) {\n return localid\n }\n return ':' + localid\n }\n // this.checkIntegrity() // @@@ Remove when not testing\n var prefix = this.prefixes[namesp]\n if (!prefix) prefix = this.makeUpPrefix(namesp)\n if (prefix) {\n this.namespacesUsed[namesp] = true\n return prefix + ':' + localid\n }\n // Fall though if can't do qname\n }\n }\n return this.explicitURI(uri)\n }\n\n // /////////////////////////// Quad store serialization\n\n // @para. write - a function taking a single string to be output\n //\n writeStore(write) {\n var kb = this.store\n var fetcher = kb.fetcher\n var session = fetcher && fetcher.appNode\n\n // The core data\n\n var sources = this.store.index[3]\n for (var s in sources) { // -> assume we can use -> as short for log:semantics\n var source = kb.fromNT(s)\n if (session && source.equals(session)) continue\n write('\\n' + this.atomicTermToN3(source) + ' ' +\n this.atomicTermToN3(kb.sym('http://www.w3.org/2000/10/swap/log#semantics')) +\n ' { ' + this.statementsToN3(kb.statementsMatching(\n undefined, undefined, undefined, source)) + ' }.\\n')\n }\n\n // The metadata from HTTP interactions:\n\n kb.statementsMatching(undefined,\n kb.sym('http://www.w3.org/2007/ont/link#requestedURI')).map(\n function (st) {\n write('\\n<' + st.object.value + '> log:metadata {\\n')\n var sts = kb.statementsMatching(undefined, undefined, undefined, st.subject)\n write(this.statementsToN3(this.statementsToN3(sts)))\n write('}.\\n')\n })\n\n // Inferences we have made ourselves not attributable to anyone else\n\n var metaSources = []\n if (session) metaSources.push(session)\n var metadata = []\n metaSources.map(function (source) {\n metadata = metadata.concat(kb.statementsMatching(undefined, undefined, undefined, source))\n })\n write(this.statementsToN3(metadata))\n }\n\n // ////////////////////////////////////////////// XML serialization\n\n statementsToXML(sts) {\n var indent = 4\n var width = 80\n\n var namespaceCounts = [] // which have been used\n namespaceCounts['http://www.w3.org/1999/02/22-rdf-syntax-ns#'] = true\n\n var liPrefix = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#_' // prefix for ordered list items\n\n // //////////////////////// Arrange the bits of XML text\n\n var spaces = function (n) {\n var s = ''\n for (var i = 0; i < n; i++) s += ' '\n return s\n }\n\n var XMLtreeToLine = function (tree) {\n var str = ''\n for (var i = 0; i < tree.length; i++) {\n var branch = tree[i]\n var s2 = (typeof branch === 'string') ? branch : XMLtreeToLine(branch)\n str += s2\n }\n return str\n }\n\n // Convert a nested tree of lists and strings to a string\n var XMLtreeToString = function (tree, level) {\n var str = ''\n var line\n var lastLength = 100000\n if (!level) level = 0\n for (var i = 0; i < tree.length; i++) {\n var branch = tree[i]\n if (typeof branch !== 'string') {\n var substr = XMLtreeToString(branch, level + 1)\n if (\n substr.length < 10 * (width - indent * level) &&\n substr.indexOf('\"\"\"') < 0) { // Don't mess up multiline strings\n line = XMLtreeToLine(branch)\n if (line.length < (width - indent * level)) {\n branch = ' ' + line // @@ Hack: treat as string below\n substr = ''\n }\n }\n if (substr) lastLength = 10000\n str += substr\n }\n if (typeof branch === 'string') {\n if (lastLength < (indent * level + 4)) { // continue\n str = str.slice(0, -1) + ' ' + branch + '\\n'\n lastLength += branch.length + 1\n } else {\n line = spaces(indent * level) + branch\n str += line + '\\n'\n lastLength = line.length\n }\n } else { // not string\n }\n }\n return str\n }\n\n function statementListToXMLTreeMethod (statements) {\n this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')\n var stats = this.rootSubjects(statements)\n var roots = stats.roots\n var results = []\n for (var i = 0; i < roots.length; i++) {\n var root = roots[i]\n results.push(subjectXMLTree(root, stats))\n }\n return results\n }\n var statementListToXMLTree = statementListToXMLTreeMethod.bind(this)\n\n function escapeForXML (str) {\n if (typeof str === 'undefined') return '@@@undefined@@@@'\n return str.replace(/[&<\"]/g, function (m) {\n switch (m[0]) {\n case '&':\n return '&'\n case '<':\n return '<'\n case '\"':\n return '"' // '\n }\n })\n }\n\n function relURIMethod (term) {\n return escapeForXML((this.base) ? Util.uri.refTo(this.base, term.uri) : term.uri)\n }\n var relURI = relURIMethod.bind(this)\n\n // The tree for a subject\n function subjectXMLTreeMethod (subject, stats) {\n var results = []\n var type, t, st, pred\n var sts = stats.subjects[this.toStr(subject)] // relevant statements\n if (typeof sts === 'undefined') { // empty bnode\n return propertyXMLTree(subject, stats)\n }\n\n // Sort only on the predicate, leave the order at object\n // level undisturbed. This leaves multilingual content in\n // the order of entry (for partner literals), which helps\n // readability.\n //\n // For the predicate sort, we attempt to split the uri\n // as a hint to the sequence\n sts.sort(function (a, b) {\n var ap = a.predicate.uri\n var bp = b.predicate.uri\n if (ap.substring(0, liPrefix.length) === liPrefix || bp.substring(0, liPrefix.length) === liPrefix) { // we're only interested in sorting list items\n return ap.localeCompare(bp)\n }\n\n var as = ap.substring(liPrefix.length)\n var bs = bp.substring(liPrefix.length)\n var an = parseInt(as, 10)\n var bn = parseInt(bs, 10)\n if (isNaN(an) || isNaN(bn) ||\n an !== as || bn !== bs) { // we only care about integers\n return ap.localeCompare(bp)\n }\n\n return an - bn\n })\n\n for (var i = 0; i < sts.length; i++) {\n st = sts[i]\n // look for a type\n if (st.predicate.uri === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' && !type && st.object.termType === 'NamedNode') {\n type = st.object\n continue // don't include it as a child element\n }\n\n // see whether predicate can be replaced with \"li\"\n pred = st.predicate\n if (pred.uri.substr(0, liPrefix.length) === liPrefix) {\n var number = pred.uri.substr(liPrefix.length)\n // make sure these are actually numeric list items\n var intNumber = parseInt(number, 10)\n if (number === intNumber.toString()) {\n // was numeric; don't need to worry about ordering since we've already\n // sorted the statements\n pred = this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#li')\n }\n }\n\n t = qname(pred)\n switch (st.object.termType) {\n case 'BlankNode':\n if (stats.incoming[st.object].length === 1) { // there should always be something in the incoming array for a bnode\n results = results.concat(['<' + t + ' rdf:parseType=\"Resource\">',\n subjectXMLTree(st.object, stats),\n '</' + t + '>'])\n } else {\n results = results.concat(['<' + t + ' rdf:nodeID=\"' +\n st.object.toNT().slice(2) + '\"/>'])\n }\n break\n case 'NamedNode':\n results = results.concat(['<' + t + ' rdf:resource=\"' +\n relURI(st.object) + '\"/>'])\n break\n case 'Literal':\n results = results.concat(['<' + t +\n (st.object.datatype.equals(this.xsd.string)\n ? ''\n : ' rdf:datatype=\"' + escapeForXML(st.object.datatype.uri) + '\"') +\n (st.object.language ? ' xml:lang=\"' + st.object.language + '\"' : '') +\n '>' + escapeForXML(st.object.value) +\n '</' + t + '>'])\n break\n case 'Collection':\n results = results.concat(['<' + t + ' rdf:parseType=\"Collection\">',\n collectionXMLTree(st.object, stats),\n '</' + t + '>'])\n break\n default:\n throw new Error(\"Can't serialize object of type \" + st.object.termType + ' into XML')\n } // switch\n }\n\n var tag = type ? qname(type) : 'rdf:Description'\n\n var attrs = ''\n if (subject.termType === 'BlankNode') {\n if (!stats.incoming[subject] || stats.incoming[subject].length !== 1) { // not an anonymous bnode\n attrs = ' rdf:nodeID=\"' + subject.toNT().slice(2) + '\"'\n }\n } else {\n attrs = ' rdf:about=\"' + relURI(subject) + '\"'\n }\n\n return [ '<' + tag + attrs + '>' ].concat([results]).concat(['</' + tag + '>'])\n }\n\n var subjectXMLTree = subjectXMLTreeMethod.bind(this)\n\n function collectionXMLTree (subject, stats) {\n var res = []\n for (var i = 0; i < subject.elements.length; i++) {\n res.push(subjectXMLTree(subject.elements[i], stats))\n }\n return res\n }\n\n // The property tree for a single subject or anonymos node\n function propertyXMLTreeMethod (subject, stats) {\n var results = []\n var sts = stats.subjects[this.toStr(subject)] // relevant statements\n if (!sts) return results // No relevant statements\n sts.sort()\n for (var i = 0; i < sts.length; i++) {\n var st = sts[i]\n switch (st.object.termType) {\n case 'BlankNode':\n if (stats.rootsHash[st.object.toNT()]) { // This bnode has been done as a root -- no content here @@ what bout first time\n results = results.concat(['<' + qname(st.predicate) + ' rdf:nodeID=\"' + st.object.toNT().slice(2) + '\">',\n '</' + qname(st.predicate) + '>'])\n } else {\n results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType=\"Resource\">',\n propertyXMLTree(st.object, stats),\n '</' + qname(st.predicate) + '>'])\n }\n break\n case 'NamedNode':\n results = results.concat(['<' + qname(st.predicate) + ' rdf:resource=\"' +\n relURI(st.object) + '\"/>'])\n break\n case 'Literal':\n results = results.concat(['<' + qname(st.predicate) +\n (st.object.datatype.equals(this.xsd.string) ? '' : ' rdf:datatype=\"' + escapeForXML(st.object.datatype.value) + '\"') +\n (st.object.language ? ' xml:lang=\"' + st.object.language + '\"' : '') +\n '>' + escapeForXML(st.object.value) +\n '</' + qname(st.predicate) + '>'])\n break\n case 'Collection':\n results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType=\"Collection\">',\n collectionXMLTree(st.object, stats),\n '</' + qname(st.predicate) + '>'])\n break\n default:\n throw new Error(\"Can't serialize object of type \" + st.object.termType + ' into XML')\n } // switch\n }\n return results\n }\n var propertyXMLTree = propertyXMLTreeMethod.bind(this)\n\n function qnameMethod (term) {\n var uri = term.uri\n\n var j = uri.indexOf('#')\n if (j < 0 && this.flags.indexOf('/') < 0) {\n j = uri.lastIndexOf('/')\n }\n if (j < 0) throw new Error('Cannot make qname out of <' + uri + '>')\n\n for (var k = j + 1; k < uri.length; k++) {\n if (this._notNameChars.indexOf(uri[k]) >= 0) {\n throw new Error('Invalid character \"' + uri[k] + '\" cannot be in XML qname for URI: ' + uri)\n }\n }\n var localid = uri.slice(j + 1)\n var namesp = uri.slice(0, j + 1)\n if (this.defaultNamespace && this.defaultNamespace === namesp &&\n this.flags.indexOf('d') < 0) { // d -> suppress default\n return localid\n }\n var prefix = this.prefixes[namesp]\n if (!prefix) prefix = this.makeUpPrefix(namesp)\n namespaceCounts[namesp] = true\n return prefix + ':' + localid\n }\n var qname = qnameMethod.bind(this)\n\n // Body of toXML:\n\n var tree = statementListToXMLTree(sts)\n var str = '<rdf:RDF'\n if (this.defaultNamespace) {\n str += ' xmlns=\"' + escapeForXML(this.defaultNamespace) + '\"'\n }\n for (var ns in namespaceCounts) {\n if (!namespaceCounts.hasOwnProperty(ns)) continue\n // Rel uris in xml ns is not strictly allowed in the XMLNS spec but needed in practice often\n var ns2 = (this.base && this.flags.includes('z')) ? Util.uri.refTo(this.base, ns) : ns\n str += '\\n xmlns:' + this.prefixes[ns] + '=\"' + escapeForXML(ns2) + '\"'\n }\n str += '>'\n\n var tree2 = [str, tree, '</rdf:RDF>'] // @@ namespace declrations\n return XMLtreeToString(tree2, -1)\n } // End @@ body\n}\n\n// String escaping utilities\n\nfunction hexify (str) { // also used in parser\n return encodeURI(str)\n}\n\nfunction backslashUify (str) {\n var res = ''\n var k\n for (var i = 0; i < str.length; i++) {\n k = str.charCodeAt(i)\n if (k > 65535) {\n res += '\\\\U' + ('00000000' + k.toString(16)).slice(-8) // convert to upper?\n } else if (k > 126) {\n res += '\\\\u' + ('0000' + k.toString(16)).slice(-4)\n } else {\n res += str[i]\n }\n }\n return res\n}","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","import Node from './node-internal'\nimport {\n Bindings,\n GraphType,\n ObjectType,\n PredicateType,\n SubjectType,\n DefaultGraphTermType,\n} from './types'\nimport DefaultGraphNode, { isDefaultGraph } from './default-graph'\nimport { Quad, DefaultGraph } from './tf-types'\n\nconst defaultGraph = new DefaultGraphNode()\n\n/** A Statement represents an RDF Triple or Quad. */\nexport default class Statement<\n S extends SubjectType = SubjectType,\n P extends PredicateType = PredicateType,\n O extends ObjectType = ObjectType,\n G extends GraphType = GraphType\n >\n implements Quad<S, P, O, G | DefaultGraph> {\n\n /** The subject of the triple. What the Statement is about. */\n subject: S\n\n /** The relationship which is asserted between the subject and object */\n predicate: P\n\n /** The thing or data value which is asserted to be related to the subject */\n object: O\n\n /**\n * The graph param is a named node of the document in which the triple when\n * it is stored on the web.\n */\n graph: G | DefaultGraph\n\n /**\n * Construct a new statement\n *\n * @param subject - The subject of the triple. What the fact is about\n * @param predicate - The relationship which is asserted between the subject and object\n * @param object - The thing or data value which is asserted to be related to the subject\n * @param {NamedNode} graph - The document where the triple is or was or will be stored on the web.\n *\n * The graph param is a named node of the document in which the triple when it is stored\n * on the web. It exists because when you have read data from various places in the web,\n * the “graph” tells you _why_ you have the triple. (At the moment, it is just the\n * document, in future it could be an inference step)\n *\n * When you do UpdateManager.update() then the graph’s of all the statements must be the same,\n * and give the document you are patching. In future, we may have a more\n * powerful update() which can update more than one document.\n */\n constructor (\n subject: S,\n predicate: P,\n object: O,\n graph?: G | DefaultGraph,\n ) {\n this.subject = Node.fromValue(subject)\n this.predicate = Node.fromValue(predicate)\n this.object = Node.fromValue(object)\n this.graph = graph == undefined ? defaultGraph : Node.fromValue(graph) // property currently used by rdflib\n }\n\n /** Alias for graph, favored by Tim */\n get why () {\n return this.graph\n }\n\n set why (g) {\n this.graph = g\n }\n\n /**\n * Checks whether two statements are the same\n * @param other - The other statement\n */\n equals (other: Quad): boolean {\n return (\n other.subject.equals(this.subject) &&\n other.predicate.equals(this.predicate) &&\n other.object.equals(this.object) &&\n other.graph.equals(this.graph)\n )\n }\n\n /**\n * Creates a statement with the bindings substituted\n * @param bindings The bindings\n */\n substitute (bindings: Bindings): Statement {\n const y = new Statement(\n this.subject.substitute(bindings),\n this.predicate.substitute(bindings),\n this.object.substitute(bindings),\n isDefaultGraph(this.graph) ? this.graph :\n (this.graph as G).substitute(bindings)\n ) // 2016\n console.log('@@@ statement substitute:' + y)\n return y\n }\n\n /** Creates a canonical string representation of this statement. */\n toCanonical (): string {\n let terms = [\n this.subject.toCanonical(),\n this.predicate.toCanonical(),\n this.object.toCanonical()\n ]\n if (this.graph && this.graph.termType !== DefaultGraphTermType) {\n terms.push(this.graph.toCanonical())\n }\n return terms.join(' ') + ' .'\n }\n\n /** Creates a n-triples string representation of this statement */\n toNT (): string {\n return [\n this.subject.toNT(),\n this.predicate.toNT(),\n this.object.toNT(),\n ].join(' ') + ' .'\n }\n\n /** Creates a n-quads string representation of this statement */\n toNQ (): string {\n return [\n this.subject.toNT(),\n this.predicate.toNT(),\n this.object.toNT(),\n isDefaultGraph(this.graph) ? '' : (this.graph as G).toNT()\n ].join(' ') + ' .'\n }\n\n /** Creates a string representation of this statement */\n toString (): string {\n return this.toNT()\n }\n}\n","import DataFactory from './factories/extended-term-factory'\nimport jsonldParser from './jsonldparser'\n// @ts-ignore is this injected?\nimport { Parser as N3jsParser } from 'n3' // @@ Goal: remove this dependency\nimport N3Parser from './n3parser'\nimport { parseRDFaDOM } from './rdfaparser'\nimport RDFParser from './rdfxmlparser'\nimport sparqlUpdateParser from './patch-parser'\nimport * as Util from './utils-js'\nimport Formula from './formula'\nimport { ContentType, TurtleContentType, N3ContentType, RDFXMLContentType, XHTMLContentType, HTMLContentType, SPARQLUpdateContentType, SPARQLUpdateSingleMatchContentType, JSONLDContentType, NQuadsContentType, NQuadsAltContentType } from './types'\nimport { Quad } from './tf-types'\n\ntype CallbackFunc = (error: any, kb: Formula | null) => void\n\n/**\n * Parse a string and put the result into the graph kb.\n * Normal method is sync.\n * Unfortunately jsdonld is currently written to need to be called async.\n * Hence the mess below with executeCallback.\n * @param str - The input string to parse\n * @param kb - The store to use\n * @param base - The base URI to use\n * @param contentType - The MIME content type string for the input - defaults to text/turtle\n * @param [callback] - The callback to call when the data has been loaded\n */\nexport default function parse (\n str: string,\n kb: Formula,\n base: string,\n contentType: string | ContentType = 'text/turtle',\n callback?: CallbackFunc\n) {\n contentType = contentType || TurtleContentType\n contentType = contentType.split(';')[0] as ContentType\n try {\n if (contentType === N3ContentType || contentType === TurtleContentType) {\n var p = N3Parser(kb, kb, base, base, null, null, '', null)\n p.loadBuf(str)\n executeCallback()\n } else if (contentType === RDFXMLContentType) {\n var parser = new RDFParser(kb)\n parser.parse(Util.parseXML(str), base, kb.sym(base))\n executeCallback()\n } else if (contentType === XHTMLContentType) {\n parseRDFaDOM(Util.parseXML(str, {contentType: XHTMLContentType}), kb, base)\n executeCallback()\n } else if (contentType === HTMLContentType) {\n parseRDFaDOM(Util.parseXML(str, {contentType: HTMLContentType}), kb, base)\n executeCallback()\n } else if ((contentType === SPARQLUpdateContentType) || (contentType === SPARQLUpdateSingleMatchContentType)) { // @@ we handle a subset\n sparqlUpdateParser(str, kb, base)\n executeCallback()\n } else if (contentType === JSONLDContentType) {\n jsonldParser(str, kb, base, executeCallback)\n } else if (contentType === NQuadsContentType ||\n contentType === NQuadsAltContentType) {\n var n3Parser = new N3jsParser({ factory: DataFactory })\n nquadCallback(null, str)\n } else if (contentType === undefined) {\n throw new Error(\"contentType is undefined\")\n } else {\n throw new Error(\"Don't know how to parse \" + contentType + ' yet')\n }\n } catch (e) {\n // @ts-ignore\n executeErrorCallback(e)\n }\n\n (parse as any).handled= {\n 'text/n3': true,\n 'text/turtle': true,\n 'application/rdf+xml': true,\n 'application/xhtml+xml': true,\n 'text/html': true,\n 'application/sparql-update': true,\n 'application/sparql-update-single-match': true,\n 'application/ld+json': true,\n 'application/nquads' : true,\n 'application/n-quads' : true\n }\n\n function executeCallback () {\n if (callback) {\n callback(null, kb)\n } else {\n return\n }\n }\n\n function executeErrorCallback (e: Error): void {\n if (\n // TODO: Always true, what is the right behavior\n contentType !== JSONLDContentType ||\n // @ts-ignore always true?\n contentType !== NQuadsContentType ||\n // @ts-ignore always true?\n contentType !== NQuadsAltContentType\n ) {\n if (callback) {\n callback(e, kb)\n } else {\n let e2 = new Error('' + e + ' while trying to parse <' + base + '> as ' + contentType)\n //@ts-ignore .cause is not a default error property\n e2.cause = e\n throw e2\n }\n }\n }\n/*\n function setJsonLdBase (doc, base) {\n if (doc instanceof Array) {\n return\n }\n if (!('@context' in doc)) {\n doc['@context'] = {}\n }\n doc['@context']['@base'] = base\n }\n*/\n function nquadCallback (err?: Error | null, nquads?: string): void {\n if (err) {\n (callback as CallbackFunc)(err, kb)\n }\n try {\n n3Parser.parse(nquads, tripleCallback)\n } catch (err) {\n (callback as CallbackFunc)(err, kb)\n }\n }\n\n function tripleCallback (err: Error, triple: Quad) {\n if (triple) {\n kb.add(triple.subject, triple.predicate, triple.object, triple.graph)\n } else {\n (callback as CallbackFunc)(err, kb)\n }\n }\n}\n","import ClassOrder from './class-order'\nimport Collection from './collection'\nimport CanonicalDataFactory from './factories/canonical-data-factory'\nimport log from './log'\nimport RDFlibNamedNode from './named-node'\nimport Namespace from './namespace'\nimport Node from './node-internal'\nimport Serializer from './serialize'\nimport Statement from './statement'\nimport {\n Bindings,\n GraphTermType,\n} from './types'\nimport { isStatement } from './utils/terms'\nimport Variable from './variable'\nimport {\n Indexable,\n TFIDFactoryTypes,\n} from './factories/factory-types'\nimport { appliedFactoryMethods, arrayToStatements } from './utils'\nimport {\n RdfJsDataFactory,\n Quad_Graph,\n Quad_Object,\n Quad_Predicate,\n Quad,\n Quad_Subject,\n Term,\n} from './tf-types'\nimport Fetcher from './fetcher'\nimport BlankNode from './blank-node'\nimport NamedNode from './named-node'\n\nexport interface FormulaOpts {\n dataCallback?: (q: Quad) => void\n rdfArrayRemove?: (arr: Quad[], q: Quad) => void\n rdfFactory?: RdfJsDataFactory\n}\n\ninterface BooleanMap {\n [uri: string]: boolean;\n}\n\ninterface MembersMap {\n [uri: string]: Quad;\n}\n\ninterface UriMap {\n [uri: string]: string;\n}\n\n/**\n * A formula, or store of RDF statements\n */\nexport default class Formula extends Node {\n termType: typeof GraphTermType = GraphTermType\n\n classOrder = ClassOrder.Graph\n\n /**\n * The accompanying fetcher instance.\n *\n * Is set by the fetcher when initialized.\n */\n fetcher?: Fetcher\n\n isVar = 0\n\n /**\n * A namespace for the specified namespace's URI\n * @param nsuri The URI for the namespace\n */\n ns = Namespace\n\n /** The factory used to generate statements and terms */\n rdfFactory: any\n\n /**\n * Initializes this formula\n * @constructor\n * @param statements - Initial array of statements\n * @param constraints - initial array of constraints\n * @param initBindings - initial bindings used in Query\n * @param optional - optional\n * @param opts\n * @param opts.rdfFactory - The rdf factory that should be used by the store\n*/\n constructor (\n public statements: Array<Statement> = [],\n public constraints: ReadonlyArray<any> = [],\n public initBindings: ReadonlyArray<any> = [],\n public optional: ReadonlyArray<any> = [],\n opts: FormulaOpts = {}\n ) {\n super('')\n\n this.rdfFactory = (opts && opts.rdfFactory) || CanonicalDataFactory\n // Enable default factory methods on this while preserving factory context.\n for(const factoryMethod of appliedFactoryMethods) {\n this[factoryMethod] = (...args) => this.rdfFactory[factoryMethod](...args)\n }\n }\n\n /** Add a statement from its parts\n * @param subject - the first part of the statement\n * @param predicate - the second part of the statement\n * @param object - the third part of the statement\n * @param graph - the last part of the statement\n */\n add (\n subject: Quad_Subject | Quad | Quad[],\n predicate?: Quad_Predicate,\n object?: Term | string,\n graph?: Quad_Graph\n ): Statement | null | this | number {\n if (arguments.length === 1) {\n (subject as Quad[]).forEach(st => this.add(st.subject, st.predicate, st.object, st.graph))\n }\n return this.statements.push(this.rdfFactory.quad(subject, predicate, object, graph))\n }\n\n /** Add a statment object\n * @param {Statement} statement - An existing constructed statement to add\n */\n addStatement (statement: Quad): Statement | null | this | number {\n return this.add(statement)\n }\n\n /**\n * Shortcut for adding blankNodes\n * @param [id]\n */\n bnode (id?: string): BlankNode {\n return this.rdfFactory.blankNode(id)\n }\n\n /**\n * Adds all the statements to this formula\n * @param statements - A collection of statements\n */\n addAll (statements: Quad[]): void {\n statements.forEach(quad => {\n this.add(quad.subject, quad.predicate, quad.object, quad.graph)\n })\n }\n\n /** Follow link from one node, using one wildcard, looking for one\n *\n * For example, any(me, knows, null, profile) - a person I know accoring to my profile .\n * any(me, knows, null, null) - a person I know accoring to anything in store .\n * any(null, knows, me, null) - a person who know me accoring to anything in store .\n *\n * @param s - A node to search for as subject, or if null, a wildcard\n * @param p - A node to search for as predicate, or if null, a wildcard\n * @param o - A node to search for as object, or if null, a wildcard\n * @param g - A node to search for as graph, or if null, a wildcard\n * @returns A node which match the wildcard position, or null\n */\n any(\n s?: Quad_Subject | null,\n p?: Quad_Predicate | null,\n o?: Quad_Object | null,\n g?: Quad_Graph | null\n ): Node | null {\n const st = this.anyStatementMatching(s, p, o, g)\n if (st == null) {\n return null\n } else if (s == null) {\n return st.subject\n } else if (p == null) {\n return st.predicate\n } else if (o == null) {\n return st.object\n }\n\n return null\n }\n\n /**\n * Gets the value of a node that matches the specified pattern\n * @param s The subject\n * @param p The predicate\n * @param o The object\n * @param g The graph that contains the statement\n */\n anyValue(\n s?: Quad_Subject | null,\n p?: Quad_Predicate | null,\n o?: Quad_Object | null,\n g?: Quad_Graph | null\n ): string | void {\n const y = this.any(s, p, o, g)\n return y ? y.value : void 0\n }\n\n /**\n * Gets the first JavaScript object equivalent to a node based on the specified pattern\n * @param s The subject\n * @param p The predicate\n * @param o The object\n * @param g The graph that contains the statement\n */\n anyJS(\n s?: Quad_Subject | null,\n p?: Quad_Predicate | null,\n o?: Quad_Object | null,\n g?: Quad_Graph | null\n ): any {\n const y = this.any(s, p, o, g)\n return y ? Node.toJS(y) : void 0\n }\n\n /**\n * Gets the first statement that matches the specified pattern\n */\n anyStatementMatching(\n s?: Quad_Subject | null,\n p?: Quad_Predicate | null,\n o?: Quad_Object | null,\n g?: Quad_Graph | null\n ): Statement | undefined {\n let x = this.statementsMatching(s, p, o, g, true)\n if (!x || x.length === 0) {\n return undefined\n }\n\n return x[0]\n }\n\n /**\n * Returns a unique index-safe identifier for the given term.\n *\n * Falls back to the rdflib hashString implementation if the given factory doesn't support id.\n */\n id (term: TFIDFactoryTypes): Indexable {\n return this.rdfFactory.id(term)\n }\n\n /**\n * Search the Store\n * This is really a teaching method as to do this properly you would use IndexedFormula\n *\n * @param s - A node to search for as subject, or if null, a wildcard\n * @param p - A node to search for as predicate, or if null, a wildcard\n * @param o - A node to search for as object, or if null, a wildcard\n * @param g - A node to search for as graph, or if null, a wildcard\n * @param justOne - flag - stop when found one rather than get all of them?\n * @returns {Array<Node>} - An array of nodes which match the wildcard position\n */\n statementsMatching<JustOne extends boolean = false>(\n s?: Quad_Subject | null,\n p?: Quad_Predicate | null,\n o?: Quad_Object | null,\n g?: Quad_Graph | null,\n justOne?: boolean\n ): Statement[] {\n const sts = this.statements.filter(st =>\n (!s || s.equals(st.subject)) &&\n (!p || p.equals(st.predicate)) &&\n (!o || o.equals(st.object)) &&\n (!g || g.equals(st.graph))\n )\n\n if (justOne) {\n return sts.length === 0 ? [] : [sts[0]]\n }\n\n return sts\n }\n\n /**\n * Finds the types in the list which have no *stored* subtypes\n * These are a set of classes which provide by themselves complete\n * information -- the other classes are redundant for those who\n * know the class DAG.\n * @param types A map of the types\n */\n bottomTypeURIs (types) {\n let bots\n let bottom\n let elt\n let i\n let len\n let ref\n let subs\n let v\n bots = []\n for (let k in types) {\n if (!types.hasOwnProperty(k)) continue\n v = types[k]\n subs = this.each(\n void 0,\n this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'),\n this.rdfFactory.namedNode(k)\n )\n bottom = true\n i = 0\n for (len = subs.length; i < len; i++) {\n elt = subs[i]\n ref = elt.uri\n if (ref in types) { // the subclass is one we know\n bottom = false\n break\n }\n }\n if (bottom) {\n bots[k] = v\n }\n }\n return bots\n }\n\n /** Creates a new collection */\n collection (): Collection {\n return new Collection()\n }\n\n /** Follow links from one node, using one wildcard.\n *\n * For example, each(me, knows, null, profile) - people I know accoring to my profile .\n * each(me, knows, null, null) - people I know accoring to anything in store .\n * each(null, knows, me, null) - people who know me accoring to anything in store .\n *\n * @param s - A node to search for as subject, or if null, a wildcard\n * @param p - A node to search for as predicate, or if null, a wildcard\n * @param o - A node to search for as object, or if null, a wildcard\n * @param g - A node to search for as graph, or if null, a wildcard\n * @returns {Array<Node>} - An array of nodes which match the wildcard position\n */\n each(\n s?: Quad_Subject | null,\n p?: Quad_Predicate | null,\n o?: Quad_Object | null,\n g?: Quad_Graph | null\n ): Node[] {\n const results: Node[] = []\n let sts = this.statementsMatching(s, p, o, g, false)\n if (s == null) {\n for (let i = 0, len = sts.length; i < len; i++) {\n results.push(sts[i].subject)\n }\n } else if (p == null) {\n for (let l = 0, len1 = sts.length; l < len1; l++) {\n results.push(sts[l].predicate)\n }\n } else if (o == null) {\n for (let m = 0, len2 = sts.length; m < len2; m++) {\n results.push(sts[m].object)\n }\n } else if (g == null) {\n for (let q = 0, len3 = sts.length; q < len3; q++) {\n results.push(new NamedNode(sts[q].graph.value))\n }\n }\n\n return results\n }\n\n /**\n * Test whether this formula is equals to {other}\n * @param other - The other formula\n */\n equals(other: Formula): boolean {\n if (!other) {\n return false\n }\n return this.hashString() === other.hashString()\n }\n\n /**\n * For thisClass or any subclass, anything which has it is its type\n * or is the object of something which has the type as its range, or subject\n * of something which has the type as its domain\n * We don't bother doing subproperty (yet?)as it doesn't seeem to be used\n * much.\n * Get all the Classes of which we can RDFS-infer the subject is a member\n * @return a hash of URIs\n */\n findMembersNT (thisClass) {\n let len2: number\n let len4: number\n let m: number\n let members: MembersMap\n let pred: Quad_Predicate\n let ref\n let ref1: Quad[]\n let ref2: Term[]\n let ref3: Quad[]\n let ref4: Term[]\n let ref5: Quad[]\n let seeds\n let st\n let u: number\n seeds = {}\n seeds[thisClass.toNT()] = true\n members = {}\n ref = this.transitiveClosure(seeds, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true)\n for (let t in ref) {\n if (!ref.hasOwnProperty(t)) continue\n ref1 = this.statementsMatching(void 0,\n this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),\n this.fromNT(t))\n for (let i = 0, len = ref1.length; i < len; i++) {\n st = ref1[i]\n members[st.subject.toNT()] = st\n }\n ref2 = this.each(void 0,\n this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain'),\n this.fromNT(t))\n for (let l = 0, len1 = ref2.length; l < len1; l++) {\n pred = ref2[l] as Quad_Predicate\n ref3 = this.statementsMatching(void 0, pred)\n for (m = 0, len2 = ref3.length; m < len2; m++) {\n st = ref3[m]\n members[st.subject.toNT()] = st\n }\n }\n ref4 = this.each(void 0,\n this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range'),\n this.fromNT(t))\n for (let q = 0, len3 = ref4.length; q < len3; q++) {\n pred = ref4[q] as Quad_Predicate\n ref5 = this.statementsMatching(void 0, pred)\n for (u = 0, len4 = ref5.length; u < len4; u++) {\n st = ref5[u]\n members[st.object.toNT()] = st\n }\n }\n }\n\n return members\n }\n\n /**\n * For thisClass or any subclass, anything which has it is its type\n * or is the object of something which has the type as its range, or subject\n * of something which has the type as its domain\n * We don't bother doing subproperty (yet?)as it doesn't seeem to be used\n * much.\n * Get all the Classes of which we can RDFS-infer the subject is a member\n * @param subject - A named node\n */\n findMemberURIs(subject: Node): UriMap {\n return this.NTtoURI(this.findMembersNT(subject))\n }\n\n /**\n * Get all the Classes of which we can RDFS-infer the subject is a superclass\n * Returns a hash table where key is NT of type and value is statement why we\n * think so.\n * Does NOT return terms, returns URI strings.\n * We use NT representations in this version because they handle blank nodes.\n */\n findSubClassesNT(subject: Node): { [uri: string]: boolean } {\n let types = {}\n types[subject.toNT()] = true\n return this.transitiveClosure(\n types,\n this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'),\n true\n )\n }\n\n /**\n * Get all the Classes of which we can RDFS-infer the subject is a subclass\n * @param {RDFlibNamedNode} subject - The thing whose classes are to be found\n * @returns a hash table where key is NT of type and value is statement why we\n * think so.\n * Does NOT return terms, returns URI strings.\n * We use NT representations in this version because they handle blank nodes.\n */\n findSuperClassesNT(subject: Node): { [uri: string]: boolean } {\n let types = {}\n types[subject.toNT()] = true\n return this.transitiveClosure(types,\n this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false)\n }\n\n /**\n * Get all the Classes of which we can RDFS-infer the subject is a member\n * todo: This will loop is there is a class subclass loop (Sublass loops are\n * not illegal)\n * @param {RDFlibNamedNode} subject - The thing whose classes are to be found\n * @returns a hash table where key is NT of type and value is statement why we think so.\n * Does NOT return terms, returns URI strings.\n * We use NT representations in this version because they handle blank nodes.\n */\n findTypesNT (subject) {\n let domain\n let range\n let rdftype\n let ref\n let ref1\n let ref2\n let ref3\n let st\n let types\n rdftype = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'\n types = []\n ref = this.statementsMatching(subject, void 0, void 0)\n for (let i = 0, len = ref.length; i < len; i++) {\n st = ref[i]\n if (st.predicate.uri === rdftype) {\n types[st.object.toNT()] = st\n } else {\n ref1 = this.each(\n st.predicate,\n this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain')\n )\n for (let l = 0, len1 = ref1.length; l < len1; l++) {\n range = ref1[l]\n types[range.toNT()] = st\n }\n }\n }\n ref2 = this.statementsMatching(void 0, void 0, subject)\n for (let m = 0, len2 = ref2.length; m < len2; m++) {\n st = ref2[m]\n ref3 = this.each(\n st.predicate,\n this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range')\n )\n for (let q = 0, len3 = ref3.length; q < len3; q++) {\n domain = ref3[q]\n types[domain.toNT()] = st\n }\n }\n return this.transitiveClosure(\n types,\n this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'),\n false\n )\n }\n\n /**\n * Get all the Classes of which we can RDFS-infer the subject is a member\n * todo: This will loop is there is a class subclass loop (Sublass loops are\n * not illegal)\n * Returns a hash table where key is NT of type and value is statement why we\n * think so.\n * Does NOT return terms, returns URI strings.\n * We use NT representations in this version because they handle blank nodes.\n * @param subject - A subject node\n */\n findTypeURIs(subject: Quad_Subject): UriMap {\n return this.NTtoURI(this.findTypesNT(subject))\n }\n\n /** Trace statements which connect directly, or through bnodes\n *\n * @param subject - The node to start looking for statments\n * @param doc - The document to be searched, or null to search all documents\n * @returns an array of statements, duplicate statements are suppresssed.\n */\n connectedStatements(\n subject: Quad_Subject,\n doc: Quad_Graph,\n excludePredicateURIs?: ReadonlyArray<string>\n ): Statement[] {\n excludePredicateURIs = excludePredicateURIs || []\n let todo = [subject]\n let done: { [k: string]: boolean } = {}\n let doneArcs: { [k: string]: boolean } = {}\n let result: Statement[] = []\n let self = this\n let follow = function (x) {\n let queue = function (x) {\n if (x.termType === 'BlankNode' && !done[x.value]) {\n done[x.value] = true\n todo.push(x)\n }\n }\n let sts = self.statementsMatching(null, null, x, doc)\n .concat(self.statementsMatching(x, null, null, doc))\n sts = sts.filter(function (st): boolean {\n if (excludePredicateURIs![st.predicate.value]) return false\n let hash = (st as Statement).toNT()\n if (doneArcs[hash]) return false\n doneArcs[hash] = true\n return true\n }\n )\n sts.forEach(function (st) {\n queue(st.subject)\n queue(st.object)\n })\n result = result.concat(sts)\n }\n while (todo.length) {\n follow(todo.shift())\n }\n // console.log('' + result.length + ' statements about ' + subject)\n return result\n }\n\n /**\n * Creates a new empty formula\n *\n * @param _features - Not applicable, but necessary for typing to pass\n */\n formula(_features?: ReadonlyArray<string>): Formula {\n return new Formula()\n }\n\n /**\n * Transforms an NTriples string format into a Node.\n * The blank node bit should not be used on program-external values; designed\n * for internal work such as storing a blank node id in an HTML attribute.\n * This will only parse the strings generated by the various toNT() methods.\n */\n fromNT (str) {\n let dt, k, lang\n switch (str[0]) {\n case '<':\n return this.sym(str.slice(1, -1))\n case '\"':\n lang = void 0\n dt = void 0\n k = str.lastIndexOf('\"')\n if (k < str.length - 1) {\n if (str[k + 1] === '@') {\n lang = str.slice(k + 2)\n } else if (str.slice(k + 1, k + 3) === '^^') {\n dt = this.fromNT(str.slice(k + 3))\n } else {\n throw new Error(\"Can't convert string from NT: \" + str)\n }\n }\n str = str.slice(1, k)\n str = str.replace(/\\\\\"/g, '\"')\n str = str.replace(/\\\\n/g, '\\n')\n str = str.replace(/\\\\\\\\/g, '\\\\')\n return this.rdfFactory.literal(str, lang || dt)\n case '_':\n return this.rdfFactory.blankNode(str.slice(2))\n case '?':\n return new Variable(str.slice(1))\n }\n throw new Error(\"Can't convert from NT: \" + str)\n }\n\n /** Returns true if this formula holds the specified statement(s) */\n holds (s: any | any[], p?, o?, g?): boolean {\n let i\n if (arguments.length === 1) {\n if (!s) {\n return true\n }\n if (s instanceof Array) {\n for (i = 0; i < s.length; i++) {\n if (!this.holds(s[i])) {\n return false\n }\n }\n return true\n } else if (isStatement(s)) {\n return this.holds(s.subject, s.predicate, s.object, s.graph)\n } else if (s.statements) {\n return this.holds(s.statements)\n }\n }\n\n let st = this.anyStatementMatching(s, p, o, g)\n return st != null\n }\n\n /**\n * Returns true if this formula holds the specified {statement}\n */\n holdsStatement (statement) {\n return this.holds(\n statement.subject,\n statement.predicate,\n statement.object,\n statement.graph,\n )\n }\n\n /**\n * Used by the n3parser to generate list elements\n * @param values - The values of the collection\n * @param context - The store\n * @return {BlankNode|Collection} - The term for the statement\n */\n list (values, context) {\n if (context.rdfFactory.supports[\"COLLECTIONS\"]) {\n const collection = context.rdfFactory.collection()\n values.forEach(function (val) {\n collection.append(val)\n })\n return collection\n } else {\n const node = context.rdfFactory.blankNode()\n const statements = arrayToStatements(context.rdfFactory, node, values)\n context.addAll(statements)\n return node\n }\n }\n\n /**\n * Transform a collection of NTriple URIs into their URI strings\n * @param t - Some iterable collection of NTriple URI strings\n * @return A collection of the URIs as strings\n * todo: explain why it is important to go through NT\n */\n NTtoURI (t) {\n let k, v\n let uris = {}\n for (k in t) {\n if (!t.hasOwnProperty(k)) continue\n v = t[k]\n if (k[0] === '<') {\n uris[k.slice(1, -1)] = v\n }\n }\n return uris\n }\n\n /**\n * Serializes this formula\n * @param base - The base string\n * @param contentType - The content type of the syntax to use\n * @param provenance - The provenance URI\n */\n serialize (base, contentType, provenance) {\n let documentString\n let sts\n let sz\n sz = Serializer(this)\n sz.suggestNamespaces(this.ns)\n sz.setBase(base)\n if (provenance) {\n sts = this.statementsMatching(void 0, void 0, void 0, provenance)\n } else {\n sts = this.statements\n }\n switch (\n contentType != null ? contentType : 'text/n3') {\n case 'application/rdf+xml':\n documentString = sz.statementsToXML(sts)\n break\n case 'text/n3':\n case 'text/turtle':\n documentString = sz.statementsToN3(sts)\n break\n default:\n throw new Error('serialize: Content-type ' + contentType +\n ' not supported.')\n }\n return documentString\n }\n\n /**\n * Creates a new formula with the substituting bindings applied\n * @param bindings - The bindings to substitute\n */\n substitute<T extends Node = Formula>(bindings: Bindings): T {\n let statementsCopy = this.statements.map(function (ea) {\n return (ea as Statement).substitute(bindings)\n })\n console.log('Formula subs statmnts:' + statementsCopy)\n const y = new Formula()\n y.addAll(statementsCopy as Quad[])\n console.log('indexed-form subs formula:' + y)\n return y as unknown as T\n }\n\n sym (uri: string, name?): NamedNode {\n if (name) {\n throw new Error('This feature (kb.sym with 2 args) is removed. Do not assume prefix mappings.')\n }\n return this.rdfFactory.namedNode(uri)\n }\n\n /**\n * Gets the node matching the specified pattern. Throws when no match could be made.\n * @param s - The subject\n * @param p - The predicate\n * @param o - The object\n * @param g - The graph that contains the statement\n */\n the (\n s?: Quad_Subject | null,\n p?: Quad_Predicate | null,\n o?: Quad_Object | null,\n g?: Quad_Graph | null\n ): Node | null | undefined {\n let x = this.any(s, p, o, g)\n if (x == null) {\n log.error('No value found for the() {' + s + ' ' + p + ' ' + o + '}.')\n }\n\n return x\n }\n\n /**\n * RDFS Inference\n * These are hand-written implementations of a backward-chaining reasoner\n * over the RDFS axioms.\n * @param seeds - A hash of NTs of classes to start with\n * @param predicate - The property to trace though\n * @param inverse - Trace inverse direction\n */\n transitiveClosure(\n seeds: BooleanMap,\n predicate: Quad_Predicate,\n inverse?: boolean\n ): {\n [uri: string]: boolean;\n } {\n let elt, i, len, s, sups, t\n let agenda = {}\n Object.assign(agenda, seeds) // make a copy\n let done = {} // classes we have looked up\n while (true) {\n t = (function () {\n for (let p in agenda) {\n if (!agenda.hasOwnProperty(p)) continue\n return p\n }\n })()\n if (t == null) {\n return done\n }\n sups = inverse ?\n this.each(void 0, predicate, this.fromNT(t))\n : this.each(this.fromNT(t) as Quad_Predicate, predicate)\n for (i = 0, len = sups.length; i < len; i++) {\n elt = sups[i]\n s = elt.toNT()\n if (s in done) {\n continue\n }\n if (s in agenda) {\n continue\n }\n agenda[s] = agenda[t]\n }\n done[t] = agenda[t]\n delete agenda[t]\n }\n }\n\n /**\n * Finds the types in the list which have no *stored* supertypes\n * We exclude the universal class, owl:Things and rdf:Resource, as it is\n * information-free.\n * @param types - The types\n */\n topTypeURIs(types: {\n [id: string]: string | RDFlibNamedNode;\n }): {\n [id: string]: string | RDFlibNamedNode;\n } {\n let i\n let j\n let k\n let len\n let n\n let ref\n let tops\n let v\n tops = []\n for (k in types) {\n if (!types.hasOwnProperty(k)) continue\n v = types[k]\n n = 0\n ref = this.each(\n this.rdfFactory.namedNode(k),\n this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf')\n )\n for (i = 0, len = ref.length; i < len; i++) {\n j = ref[i]\n if (j.uri !== 'http://www.w3.org/2000/01/rdf-schema#Resource') {\n n++\n break\n }\n }\n if (!n) {\n tops[k] = v\n }\n }\n if (tops['http://www.w3.org/2000/01/rdf-schema#Resource']) {\n delete tops['http://www.w3.org/2000/01/rdf-schema#Resource']\n }\n if (tops['http://www.w3.org/2002/07/owl#Thing']) {\n delete tops['http://www.w3.org/2002/07/owl#Thing']\n }\n return tops\n }\n\n /**\n * Serializes this formula to a string\n */\n toString(): string {\n return '{' + this.statements.join('\\n') + '}'\n }\n\n /**\n * Gets a new variable\n * @param name - The variable's name\n */\n public variable(name: string): Variable {\n return new Variable(name)\n }\n\n /**\n * Gets the number of statements in this formula that matches the specified pattern\n * @param s - The subject\n * @param p - The predicate\n * @param o - The object\n * @param g - The graph that contains the statement\n */\n whether(\n s?: Quad_Subject | null,\n p?: Quad_Predicate | null,\n o?: Quad_Object | null,\n g?: Quad_Graph | null\n ): number {\n return this.statementsMatching(s, p, o, g, false).length\n }\n}\n","import Collection from '../collection'\nimport CanonicalDataFactory from './canonical-data-factory'\nimport { ValueType, CollectionTermType } from '../types'\nimport { DataFactory, DefaultFactoryTypes, Feature, Indexable } from './factory-types'\nimport { isCollection, isVariable } from '../utils/terms'\nimport Variable from '../variable'\nimport { Term } from '../tf-types'\n\ninterface CollectionFactory extends DataFactory {\n collection(elements: ReadonlyArray<ValueType>): Collection\n}\n\n/**\n * Data factory which also supports Collections\n *\n * Necessary for preventing circular dependencies.\n */\nconst ExtendedTermFactory: CollectionFactory = {\n ...CanonicalDataFactory,\n\n supports: {\n [Feature.collections]: true,\n [Feature.defaultGraphType]: false,\n [Feature.equalsMethod]: true,\n [Feature.identity]: false,\n [Feature.id]: true,\n [Feature.reversibleId]: false,\n [Feature.variableType]: true,\n },\n\n /**\n * Creates a new collection\n * @param elements - The initial element\n */\n collection (elements: ReadonlyArray<ValueType>): Collection {\n return new Collection(elements)\n },\n\n id (term: Term | DefaultFactoryTypes): Indexable {\n if (isCollection(term)) {\n return `( ${term.elements.map((e) => {\n return this.id(e) }).join(', ')} )`\n }\n\n if (isVariable(term)) {\n return Variable.toString(term)\n }\n\n return CanonicalDataFactory.id(term)\n },\n\n termToNQ (term: Term): string {\n if (term.termType === CollectionTermType) {\n return Collection.toNT(term)\n }\n\n return CanonicalDataFactory.termToNQ(term)\n }\n}\n\nexport default ExtendedTermFactory\n","var global = typeof self !== 'undefined' ? self : this;\nvar __self__ = (function () {\nfunction F() {\nthis.fetch = false;\nthis.DOMException = global.DOMException\n}\nF.prototype = global;\nreturn new F();\n})();\n(function(self) {\n\nvar irrelevant = (function (exports) {\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob:\n 'FileReader' in self &&\n 'Blob' in self &&\n (function() {\n try {\n new Blob();\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n };\n\n function isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ];\n\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n };\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name);\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value);\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift();\n return {done: value === undefined, value: value}\n }\n };\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n };\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {};\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value);\n }, this);\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1]);\n }, this);\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name]);\n }, this);\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name);\n value = normalizeValue(value);\n var oldValue = this.map[name];\n this.map[name] = oldValue ? oldValue + ', ' + value : value;\n };\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)];\n };\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name);\n return this.has(name) ? this.map[name] : null\n };\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n };\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value);\n };\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this);\n }\n }\n };\n\n Headers.prototype.keys = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push(name);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.values = function() {\n var items = [];\n this.forEach(function(value) {\n items.push(value);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.entries = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push([name, value]);\n });\n return iteratorFor(items)\n };\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries;\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true;\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result);\n };\n reader.onerror = function() {\n reject(reader.error);\n };\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsArrayBuffer(blob);\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsText(blob);\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf);\n var chars = new Array(view.length);\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i]);\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength);\n view.set(new Uint8Array(buf));\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false;\n\n this._initBody = function(body) {\n this._bodyInit = body;\n if (!body) {\n this._bodyText = '';\n } else if (typeof body === 'string') {\n this._bodyText = body;\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body;\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body;\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString();\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer);\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer]);\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body);\n } else {\n this._bodyText = body = Object.prototype.toString.call(body);\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8');\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type);\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n }\n }\n };\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n };\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n };\n }\n\n this.text = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n };\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n };\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n };\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase();\n return methods.indexOf(upcased) > -1 ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {};\n var body = options.body;\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url;\n this.credentials = input.credentials;\n if (!options.headers) {\n this.headers = new Headers(input.headers);\n }\n this.method = input.method;\n this.mode = input.mode;\n this.signal = input.signal;\n if (!body && input._bodyInit != null) {\n body = input._bodyInit;\n input.bodyUsed = true;\n }\n } else {\n this.url = String(input);\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin';\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers);\n }\n this.method = normalizeMethod(options.method || this.method || 'GET');\n this.mode = options.mode || this.mode || null;\n this.signal = options.signal || this.signal;\n this.referrer = null;\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body);\n }\n\n Request.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n };\n\n function decode(body) {\n var form = new FormData();\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=');\n var name = split.shift().replace(/\\+/g, ' ');\n var value = split.join('=').replace(/\\+/g, ' ');\n form.append(decodeURIComponent(name), decodeURIComponent(value));\n }\n });\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers();\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ');\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':');\n var key = parts.shift().trim();\n if (key) {\n var value = parts.join(':').trim();\n headers.append(key, value);\n }\n });\n return headers\n }\n\n Body.call(Request.prototype);\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {};\n }\n\n this.type = 'default';\n this.status = options.status === undefined ? 200 : options.status;\n this.ok = this.status >= 200 && this.status < 300;\n this.statusText = 'statusText' in options ? options.statusText : 'OK';\n this.headers = new Headers(options.headers);\n this.url = options.url || '';\n this._initBody(bodyInit);\n }\n\n Body.call(Response.prototype);\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n };\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''});\n response.type = 'error';\n return response\n };\n\n var redirectStatuses = [301, 302, 303, 307, 308];\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n };\n\n exports.DOMException = self.DOMException;\n try {\n new exports.DOMException();\n } catch (err) {\n exports.DOMException = function(message, name) {\n this.message = message;\n this.name = name;\n var error = Error(message);\n this.stack = error.stack;\n };\n exports.DOMException.prototype = Object.create(Error.prototype);\n exports.DOMException.prototype.constructor = exports.DOMException;\n }\n\n function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init);\n\n if (request.signal && request.signal.aborted) {\n return reject(new exports.DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest();\n\n function abortXhr() {\n xhr.abort();\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n };\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');\n var body = 'response' in xhr ? xhr.response : xhr.responseText;\n resolve(new Response(body, options));\n };\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.onabort = function() {\n reject(new exports.DOMException('Aborted', 'AbortError'));\n };\n\n xhr.open(request.method, request.url, true);\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true;\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false;\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob';\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value);\n });\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr);\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr);\n }\n };\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);\n })\n }\n\n fetch.polyfill = true;\n\n if (!self.fetch) {\n self.fetch = fetch;\n self.Headers = Headers;\n self.Request = Request;\n self.Response = Response;\n }\n\n exports.Headers = Headers;\n exports.Request = Request;\n exports.Response = Response;\n exports.fetch = fetch;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n return exports;\n\n}({}));\n})(__self__);\n__self__.fetch.ponyfill = true;\n// Remove \"polyfill\" property added by whatwg-fetch\ndelete __self__.fetch.polyfill;\n// Choose between native implementation (global) or custom implementation (__self__)\n// var ctx = global.fetch ? global : __self__;\nvar ctx = __self__; // this line disable service worker support temporarily\nexports = ctx.fetch // To enable: import fetch from 'cross-fetch'\nexports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.\nexports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'\nexports.Headers = ctx.Headers\nexports.Request = ctx.Request\nexports.Response = ctx.Response\nmodule.exports = exports\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {isKeyword} = require('./context');\nconst graphTypes = require('./graphTypes');\nconst types = require('./types');\nconst util = require('./util');\nconst JsonLdError = require('./JsonLdError');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Creates a merged JSON-LD node map (node ID => node).\n *\n * @param input the expanded JSON-LD to create a node map of.\n * @param [options] the options to use:\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n *\n * @return the node map.\n */\napi.createMergedNodeMap = (input, options) => {\n options = options || {};\n\n // produce a map of all subjects and name each bnode\n const issuer = options.issuer || new util.IdentifierIssuer('_:b');\n const graphs = {'@default': {}};\n api.createNodeMap(input, graphs, '@default', issuer);\n\n // add all non-default graphs to default graph\n return api.mergeNodeMaps(graphs);\n};\n\n/**\n * Recursively flattens the subjects in the given JSON-LD expanded input\n * into a node map.\n *\n * @param input the JSON-LD expanded input.\n * @param graphs a map of graph name to subject map.\n * @param graph the name of the current graph.\n * @param issuer the blank node identifier issuer.\n * @param name the name assigned to the current input if it is a bnode.\n * @param list the list to append to, null for none.\n */\napi.createNodeMap = (input, graphs, graph, issuer, name, list) => {\n // recurse through array\n if(types.isArray(input)) {\n for(const node of input) {\n api.createNodeMap(node, graphs, graph, issuer, undefined, list);\n }\n return;\n }\n\n // add non-object to list\n if(!types.isObject(input)) {\n if(list) {\n list.push(input);\n }\n return;\n }\n\n // add values to list\n if(graphTypes.isValue(input)) {\n if('@type' in input) {\n let type = input['@type'];\n // rename @type blank node\n if(type.indexOf('_:') === 0) {\n input['@type'] = type = issuer.getId(type);\n }\n }\n if(list) {\n list.push(input);\n }\n return;\n } else if(list && graphTypes.isList(input)) {\n const _list = [];\n api.createNodeMap(input['@list'], graphs, graph, issuer, name, _list);\n list.push({'@list': _list});\n return;\n }\n\n // Note: At this point, input must be a subject.\n\n // spec requires @type to be named first, so assign names early\n if('@type' in input) {\n const types = input['@type'];\n for(const type of types) {\n if(type.indexOf('_:') === 0) {\n issuer.getId(type);\n }\n }\n }\n\n // get name for subject\n if(types.isUndefined(name)) {\n name = graphTypes.isBlankNode(input) ?\n issuer.getId(input['@id']) : input['@id'];\n }\n\n // add subject reference to list\n if(list) {\n list.push({'@id': name});\n }\n\n // create new subject or merge into existing one\n const subjects = graphs[graph];\n const subject = subjects[name] = subjects[name] || {};\n subject['@id'] = name;\n const properties = Object.keys(input).sort();\n for(let property of properties) {\n // skip @id\n if(property === '@id') {\n continue;\n }\n\n // handle reverse properties\n if(property === '@reverse') {\n const referencedNode = {'@id': name};\n const reverseMap = input['@reverse'];\n for(const reverseProperty in reverseMap) {\n const items = reverseMap[reverseProperty];\n for(const item of items) {\n let itemName = item['@id'];\n if(graphTypes.isBlankNode(item)) {\n itemName = issuer.getId(itemName);\n }\n api.createNodeMap(item, graphs, graph, issuer, itemName);\n util.addValue(\n subjects[itemName], reverseProperty, referencedNode,\n {propertyIsArray: true, allowDuplicate: false});\n }\n }\n continue;\n }\n\n // recurse into graph\n if(property === '@graph') {\n // add graph subjects map entry\n if(!(name in graphs)) {\n graphs[name] = {};\n }\n api.createNodeMap(input[property], graphs, name, issuer);\n continue;\n }\n\n // recurse into included\n if(property === '@included') {\n api.createNodeMap(input[property], graphs, graph, issuer);\n continue;\n }\n\n // copy non-@type keywords\n if(property !== '@type' && isKeyword(property)) {\n if(property === '@index' && property in subject &&\n (input[property] !== subject[property] ||\n input[property]['@id'] !== subject[property]['@id'])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; conflicting @index property detected.',\n 'jsonld.SyntaxError',\n {code: 'conflicting indexes', subject});\n }\n subject[property] = input[property];\n continue;\n }\n\n // iterate over objects\n const objects = input[property];\n\n // if property is a bnode, assign it a new id\n if(property.indexOf('_:') === 0) {\n property = issuer.getId(property);\n }\n\n // ensure property is added for empty arrays\n if(objects.length === 0) {\n util.addValue(subject, property, [], {propertyIsArray: true});\n continue;\n }\n for(let o of objects) {\n if(property === '@type') {\n // rename @type blank nodes\n o = (o.indexOf('_:') === 0) ? issuer.getId(o) : o;\n }\n\n // handle embedded subject or subject reference\n if(graphTypes.isSubject(o) || graphTypes.isSubjectReference(o)) {\n // skip null @id\n if('@id' in o && !o['@id']) {\n continue;\n }\n\n // relabel blank node @id\n const id = graphTypes.isBlankNode(o) ?\n issuer.getId(o['@id']) : o['@id'];\n\n // add reference and recurse\n util.addValue(\n subject, property, {'@id': id},\n {propertyIsArray: true, allowDuplicate: false});\n api.createNodeMap(o, graphs, graph, issuer, id);\n } else if(graphTypes.isValue(o)) {\n util.addValue(\n subject, property, o,\n {propertyIsArray: true, allowDuplicate: false});\n } else if(graphTypes.isList(o)) {\n // handle @list\n const _list = [];\n api.createNodeMap(o['@list'], graphs, graph, issuer, name, _list);\n o = {'@list': _list};\n util.addValue(\n subject, property, o,\n {propertyIsArray: true, allowDuplicate: false});\n } else {\n // handle @value\n api.createNodeMap(o, graphs, graph, issuer, name);\n util.addValue(\n subject, property, o, {propertyIsArray: true, allowDuplicate: false});\n }\n }\n }\n};\n\n/**\n * Merge separate named graphs into a single merged graph including\n * all nodes from the default graph and named graphs.\n *\n * @param graphs a map of graph name to subject map.\n *\n * @return the merged graph map.\n */\napi.mergeNodeMapGraphs = graphs => {\n const merged = {};\n for(const name of Object.keys(graphs).sort()) {\n for(const id of Object.keys(graphs[name]).sort()) {\n const node = graphs[name][id];\n if(!(id in merged)) {\n merged[id] = {'@id': id};\n }\n const mergedNode = merged[id];\n\n for(const property of Object.keys(node).sort()) {\n if(isKeyword(property) && property !== '@type') {\n // copy keywords\n mergedNode[property] = util.clone(node[property]);\n } else {\n // merge objects\n for(const value of node[property]) {\n util.addValue(\n mergedNode, property, util.clone(value),\n {propertyIsArray: true, allowDuplicate: false});\n }\n }\n }\n }\n }\n\n return merged;\n};\n\napi.mergeNodeMaps = graphs => {\n // add all non-default graphs to default graph\n const defaultGraph = graphs['@default'];\n const graphNames = Object.keys(graphs).sort();\n for(const graphName of graphNames) {\n if(graphName === '@default') {\n continue;\n }\n const nodeMap = graphs[graphName];\n let subject = defaultGraph[graphName];\n if(!subject) {\n defaultGraph[graphName] = subject = {\n '@id': graphName,\n '@graph': []\n };\n } else if(!('@graph' in subject)) {\n subject['@graph'] = [];\n }\n const graph = subject['@graph'];\n for(const id of Object.keys(nodeMap).sort()) {\n const node = nodeMap[id];\n // only add full subjects\n if(!graphTypes.isSubjectReference(node)) {\n graph.push(node);\n }\n }\n }\n return defaultGraph;\n};\n","// Parse a simple SPARL-Update subset syntax for patches.\n//\n// This parses\n// WHERE {xxx} DELETE {yyy} INSERT DATA {zzz}\n// (not necessarily in that order)\n// as though it were the n3\n// <#query> patch:where {xxx}; patch:delete {yyy}; patch:insert {zzz}.\nimport N3Parser from './n3parser'\nimport Namespace from './namespace'\n\nexport default function sparqlUpdateParser (str, kb, base) {\n var i, j, k\n var keywords = [ 'INSERT', 'DELETE', 'WHERE' ]\n var SQNS = Namespace('http://www.w3.org/ns/pim/patch#')\n var p = N3Parser(kb, kb, base, base, null, null, '', null)\n var clauses = {}\n\n var badSyntax = function (uri, lines, str, i, why) {\n return ('Line ' + (lines + 1) + ' of <' + uri + '>: Bad syntax:\\n ' +\n why + '\\n at: \"' + str.slice(i, (i + 30)) + '\"')\n }\n\n // var check = function (next, last, message) {\n // if (next < 0) {\n // throw badSyntax(p._thisDoc, p.lines, str, j, last, message)\n // }\n // return next\n // }\n i = 0\n var query = kb.sym(base + '#query') // Invent a URI for the query\n clauses['query'] = query // A way of accessing it in its N3 model.\n\n while (true) {\n // console.log(\"A Now at i = \" + i)\n j = p.skipSpace(str, i)\n if (j < 0) {\n return clauses\n }\n // console.log(\"B After space at j= \" + j)\n if (str[j] === ';') {\n i = p.skipSpace(str, j + 1)\n if (i < 0) {\n return clauses // Allow end in a\n }\n j = i\n }\n var found = false\n for (k = 0; k < keywords.length; k++) {\n var key = keywords[k]\n if (str.slice(j, j + key.length) === key) {\n i = p.skipSpace(str, j + key.length)\n if (i < 0) {\n throw badSyntax(p._thisDoc, p.lines, str, j + key.length, 'found EOF, needed {...} after ' + key)\n }\n if (((key === 'INSERT') || (key === 'DELETE')) && str.slice(i, i + 4) === 'DATA') { // Some wanted 'DATA'. Whatever\n j = p.skipSpace(str, i + 4)\n if (j < 0) {\n throw badSyntax(p._thisDoc, p.lines, str, i + 4, 'needed {...} after INSERT DATA ' + key)\n }\n i = j\n }\n var res2 = []\n j = p.node(str, i, res2) // Parse all the complexity of the clause\n\n if (j < 0) {\n throw badSyntax(p._thisDoc, p.lines, str, i,\n 'bad syntax or EOF in {...} after ' + key)\n }\n clauses[key.toLowerCase()] = res2[0]\n kb.add(query, SQNS(key.toLowerCase()), res2[0]) // , kb.sym(base)\n // key is the keyword and res2 has the contents\n found = true\n i = j\n }\n }\n if (!found && str.slice(j, j + 7) === '@prefix') {\n i = p.directive(str, j)\n if (i < 0) {\n throw badSyntax(p._thisDoc, p.lines, str, i,\n 'bad syntax or EOF after @prefix ')\n }\n // console.log(\"P before dot i= \" + i)\n i = p.checkDot(str, i)\n // console.log(\"Q after dot i= \" + i)\n found = true\n }\n if (!found) {\n // console.log(\"Bad syntax \" + j)\n throw badSyntax(p._thisDoc, p.lines, str, j,\n \"Unknown syntax at start of statememt: '\" + str.slice(j).slice(0, 20) + \"'\")\n }\n } // while\n// return clauses\n}\n","/**\n * Creates a continuation function with some arguments already applied.\n *\n * Useful as a shorthand when combined with other control flow functions. Any\n * arguments passed to the returned function are added to the arguments\n * originally passed to apply.\n *\n * @name apply\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {Function} fn - The function you want to eventually apply all\n * arguments to. Invokes with (arguments...).\n * @param {...*} arguments... - Any number of arguments to automatically apply\n * when the continuation is called.\n * @returns {Function} the partially-applied function\n * @example\n *\n * // using apply\n * async.parallel([\n * async.apply(fs.writeFile, 'testfile1', 'test1'),\n * async.apply(fs.writeFile, 'testfile2', 'test2')\n * ]);\n *\n *\n * // the same process without using apply\n * async.parallel([\n * function(callback) {\n * fs.writeFile('testfile1', 'test1', callback);\n * },\n * function(callback) {\n * fs.writeFile('testfile2', 'test2', callback);\n * }\n * ]);\n *\n * // It's possible to pass any number of additional arguments when calling the\n * // continuation:\n *\n * node> var fn = async.apply(sys.puts, 'one');\n * node> fn('two', 'three');\n * one\n * two\n * three\n */\nfunction apply(fn, ...args) {\n return (...callArgs) => fn(...args,...callArgs);\n}\n\nfunction initialParams (fn) {\n return function (...args/*, callback*/) {\n var callback = args.pop();\n return fn.call(this, args, callback);\n };\n}\n\n/* istanbul ignore file */\n\nvar hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;\nvar hasSetImmediate = typeof setImmediate === 'function' && setImmediate;\nvar hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';\n\nfunction fallback(fn) {\n setTimeout(fn, 0);\n}\n\nfunction wrap(defer) {\n return (fn, ...args) => defer(() => fn(...args));\n}\n\nvar _defer;\n\nif (hasQueueMicrotask) {\n _defer = queueMicrotask;\n} else if (hasSetImmediate) {\n _defer = setImmediate;\n} else if (hasNextTick) {\n _defer = process.nextTick;\n} else {\n _defer = fallback;\n}\n\nvar setImmediate$1 = wrap(_defer);\n\n/**\n * Take a sync function and make it async, passing its return value to a\n * callback. This is useful for plugging sync functions into a waterfall,\n * series, or other async functions. Any arguments passed to the generated\n * function will be passed to the wrapped function (except for the final\n * callback argument). Errors thrown will be passed to the callback.\n *\n * If the function passed to `asyncify` returns a Promise, that promises's\n * resolved/rejected state will be used to call the callback, rather than simply\n * the synchronous return value.\n *\n * This also means you can asyncify ES2017 `async` functions.\n *\n * @name asyncify\n * @static\n * @memberOf module:Utils\n * @method\n * @alias wrapSync\n * @category Util\n * @param {Function} func - The synchronous function, or Promise-returning\n * function to convert to an {@link AsyncFunction}.\n * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be\n * invoked with `(args..., callback)`.\n * @example\n *\n * // passing a regular synchronous function\n * async.waterfall([\n * async.apply(fs.readFile, filename, \"utf8\"),\n * async.asyncify(JSON.parse),\n * function (data, next) {\n * // data is the result of parsing the text.\n * // If there was a parsing error, it would have been caught.\n * }\n * ], callback);\n *\n * // passing a function returning a promise\n * async.waterfall([\n * async.apply(fs.readFile, filename, \"utf8\"),\n * async.asyncify(function (contents) {\n * return db.model.create(contents);\n * }),\n * function (model, next) {\n * // `model` is the instantiated model object.\n * // If there was an error, this function would be skipped.\n * }\n * ], callback);\n *\n * // es2017 example, though `asyncify` is not needed if your JS environment\n * // supports async functions out of the box\n * var q = async.queue(async.asyncify(async function(file) {\n * var intermediateStep = await processFile(file);\n * return await somePromise(intermediateStep)\n * }));\n *\n * q.push(files);\n */\nfunction asyncify(func) {\n if (isAsync(func)) {\n return function (...args/*, callback*/) {\n const callback = args.pop();\n const promise = func.apply(this, args);\n return handlePromise(promise, callback)\n }\n }\n\n return initialParams(function (args, callback) {\n var result;\n try {\n result = func.apply(this, args);\n } catch (e) {\n return callback(e);\n }\n // if result is Promise object\n if (result && typeof result.then === 'function') {\n return handlePromise(result, callback)\n } else {\n callback(null, result);\n }\n });\n}\n\nfunction handlePromise(promise, callback) {\n return promise.then(value => {\n invokeCallback(callback, null, value);\n }, err => {\n invokeCallback(callback, err && err.message ? err : new Error(err));\n });\n}\n\nfunction invokeCallback(callback, error, value) {\n try {\n callback(error, value);\n } catch (err) {\n setImmediate$1(e => { throw e }, err);\n }\n}\n\nfunction isAsync(fn) {\n return fn[Symbol.toStringTag] === 'AsyncFunction';\n}\n\nfunction isAsyncGenerator(fn) {\n return fn[Symbol.toStringTag] === 'AsyncGenerator';\n}\n\nfunction isAsyncIterable(obj) {\n return typeof obj[Symbol.asyncIterator] === 'function';\n}\n\nfunction wrapAsync(asyncFn) {\n if (typeof asyncFn !== 'function') throw new Error('expected a function')\n return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;\n}\n\n// conditionally promisify a function.\n// only return a promise if a callback is omitted\nfunction awaitify (asyncFn, arity = asyncFn.length) {\n if (!arity) throw new Error('arity is undefined')\n function awaitable (...args) {\n if (typeof args[arity - 1] === 'function') {\n return asyncFn.apply(this, args)\n }\n\n return new Promise((resolve, reject) => {\n args[arity - 1] = (err, ...cbArgs) => {\n if (err) return reject(err)\n resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);\n };\n asyncFn.apply(this, args);\n })\n }\n\n return awaitable\n}\n\nfunction applyEach (eachfn) {\n return function applyEach(fns, ...callArgs) {\n const go = awaitify(function (callback) {\n var that = this;\n return eachfn(fns, (fn, cb) => {\n wrapAsync(fn).apply(that, callArgs.concat(cb));\n }, callback);\n });\n return go;\n };\n}\n\nfunction _asyncMap(eachfn, arr, iteratee, callback) {\n arr = arr || [];\n var results = [];\n var counter = 0;\n var _iteratee = wrapAsync(iteratee);\n\n return eachfn(arr, (value, _, iterCb) => {\n var index = counter++;\n _iteratee(value, (err, v) => {\n results[index] = v;\n iterCb(err);\n });\n }, err => {\n callback(err, results);\n });\n}\n\nfunction isArrayLike(value) {\n return value &&\n typeof value.length === 'number' &&\n value.length >= 0 &&\n value.length % 1 === 0;\n}\n\n// A temporary value used to identify if the loop should be broken.\n// See #1064, #1293\nconst breakLoop = {};\n\nfunction once(fn) {\n function wrapper (...args) {\n if (fn === null) return;\n var callFn = fn;\n fn = null;\n callFn.apply(this, args);\n }\n Object.assign(wrapper, fn);\n return wrapper\n}\n\nfunction getIterator (coll) {\n return coll[Symbol.iterator] && coll[Symbol.iterator]();\n}\n\nfunction createArrayIterator(coll) {\n var i = -1;\n var len = coll.length;\n return function next() {\n return ++i < len ? {value: coll[i], key: i} : null;\n }\n}\n\nfunction createES2015Iterator(iterator) {\n var i = -1;\n return function next() {\n var item = iterator.next();\n if (item.done)\n return null;\n i++;\n return {value: item.value, key: i};\n }\n}\n\nfunction createObjectIterator(obj) {\n var okeys = obj ? Object.keys(obj) : [];\n var i = -1;\n var len = okeys.length;\n return function next() {\n var key = okeys[++i];\n if (key === '__proto__') {\n return next();\n }\n return i < len ? {value: obj[key], key} : null;\n };\n}\n\nfunction createIterator(coll) {\n if (isArrayLike(coll)) {\n return createArrayIterator(coll);\n }\n\n var iterator = getIterator(coll);\n return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);\n}\n\nfunction onlyOnce(fn) {\n return function (...args) {\n if (fn === null) throw new Error(\"Callback was already called.\");\n var callFn = fn;\n fn = null;\n callFn.apply(this, args);\n };\n}\n\n// for async generators\nfunction asyncEachOfLimit(generator, limit, iteratee, callback) {\n let done = false;\n let canceled = false;\n let awaiting = false;\n let running = 0;\n let idx = 0;\n\n function replenish() {\n //console.log('replenish')\n if (running >= limit || awaiting || done) return\n //console.log('replenish awaiting')\n awaiting = true;\n generator.next().then(({value, done: iterDone}) => {\n //console.log('got value', value)\n if (canceled || done) return\n awaiting = false;\n if (iterDone) {\n done = true;\n if (running <= 0) {\n //console.log('done nextCb')\n callback(null);\n }\n return;\n }\n running++;\n iteratee(value, idx, iterateeCallback);\n idx++;\n replenish();\n }).catch(handleError);\n }\n\n function iterateeCallback(err, result) {\n //console.log('iterateeCallback')\n running -= 1;\n if (canceled) return\n if (err) return handleError(err)\n\n if (err === false) {\n done = true;\n canceled = true;\n return\n }\n\n if (result === breakLoop || (done && running <= 0)) {\n done = true;\n //console.log('done iterCb')\n return callback(null);\n }\n replenish();\n }\n\n function handleError(err) {\n if (canceled) return\n awaiting = false;\n done = true;\n callback(err);\n }\n\n replenish();\n}\n\nvar eachOfLimit = (limit) => {\n return (obj, iteratee, callback) => {\n callback = once(callback);\n if (limit <= 0) {\n throw new RangeError('concurrency limit cannot be less than 1')\n }\n if (!obj) {\n return callback(null);\n }\n if (isAsyncGenerator(obj)) {\n return asyncEachOfLimit(obj, limit, iteratee, callback)\n }\n if (isAsyncIterable(obj)) {\n return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)\n }\n var nextElem = createIterator(obj);\n var done = false;\n var canceled = false;\n var running = 0;\n var looping = false;\n\n function iterateeCallback(err, value) {\n if (canceled) return\n running -= 1;\n if (err) {\n done = true;\n callback(err);\n }\n else if (err === false) {\n done = true;\n canceled = true;\n }\n else if (value === breakLoop || (done && running <= 0)) {\n done = true;\n return callback(null);\n }\n else if (!looping) {\n replenish();\n }\n }\n\n function replenish () {\n looping = true;\n while (running < limit && !done) {\n var elem = nextElem();\n if (elem === null) {\n done = true;\n if (running <= 0) {\n callback(null);\n }\n return;\n }\n running += 1;\n iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));\n }\n looping = false;\n }\n\n replenish();\n };\n};\n\n/**\n * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name eachOfLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.eachOf]{@link module:Collections.eachOf}\n * @alias forEachOfLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each\n * item in `coll`. The `key` is the item's key, or index in the case of an\n * array.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction eachOfLimit$1(coll, limit, iteratee, callback) {\n return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);\n}\n\nvar eachOfLimit$2 = awaitify(eachOfLimit$1, 4);\n\n// eachOf implementation optimized for array-likes\nfunction eachOfArrayLike(coll, iteratee, callback) {\n callback = once(callback);\n var index = 0,\n completed = 0,\n {length} = coll,\n canceled = false;\n if (length === 0) {\n callback(null);\n }\n\n function iteratorCallback(err, value) {\n if (err === false) {\n canceled = true;\n }\n if (canceled === true) return\n if (err) {\n callback(err);\n } else if ((++completed === length) || value === breakLoop) {\n callback(null);\n }\n }\n\n for (; index < length; index++) {\n iteratee(coll[index], index, onlyOnce(iteratorCallback));\n }\n}\n\n// a generic version of eachOf which can handle array, object, and iterator cases.\nfunction eachOfGeneric (coll, iteratee, callback) {\n return eachOfLimit$2(coll, Infinity, iteratee, callback);\n}\n\n/**\n * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument\n * to the iteratee.\n *\n * @name eachOf\n * @static\n * @memberOf module:Collections\n * @method\n * @alias forEachOf\n * @category Collection\n * @see [async.each]{@link module:Collections.each}\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each\n * item in `coll`.\n * The `key` is the item's key, or index in the case of an array.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * // dev.json is a file containing a valid json object config for dev environment\n * // dev.json is a file containing a valid json object config for test environment\n * // prod.json is a file containing a valid json object config for prod environment\n * // invalid.json is a file with a malformed json object\n *\n * let configs = {}; //global variable\n * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};\n * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};\n *\n * // asynchronous function that reads a json file and parses the contents as json object\n * function parseFile(file, key, callback) {\n * fs.readFile(file, \"utf8\", function(err, data) {\n * if (err) return calback(err);\n * try {\n * configs[key] = JSON.parse(data);\n * } catch (e) {\n * return callback(e);\n * }\n * callback();\n * });\n * }\n *\n * // Using callbacks\n * async.forEachOf(validConfigFileMap, parseFile, function (err) {\n * if (err) {\n * console.error(err);\n * } else {\n * console.log(configs);\n * // configs is now a map of JSON data, e.g.\n * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}\n * }\n * });\n *\n * //Error handing\n * async.forEachOf(invalidConfigFileMap, parseFile, function (err) {\n * if (err) {\n * console.error(err);\n * // JSON parse error exception\n * } else {\n * console.log(configs);\n * }\n * });\n *\n * // Using Promises\n * async.forEachOf(validConfigFileMap, parseFile)\n * .then( () => {\n * console.log(configs);\n * // configs is now a map of JSON data, e.g.\n * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}\n * }).catch( err => {\n * console.error(err);\n * });\n *\n * //Error handing\n * async.forEachOf(invalidConfigFileMap, parseFile)\n * .then( () => {\n * console.log(configs);\n * }).catch( err => {\n * console.error(err);\n * // JSON parse error exception\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.forEachOf(validConfigFileMap, parseFile);\n * console.log(configs);\n * // configs is now a map of JSON data, e.g.\n * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * //Error handing\n * async () => {\n * try {\n * let result = await async.forEachOf(invalidConfigFileMap, parseFile);\n * console.log(configs);\n * }\n * catch (err) {\n * console.log(err);\n * // JSON parse error exception\n * }\n * }\n *\n */\nfunction eachOf(coll, iteratee, callback) {\n var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;\n return eachOfImplementation(coll, wrapAsync(iteratee), callback);\n}\n\nvar eachOf$1 = awaitify(eachOf, 3);\n\n/**\n * Produces a new collection of values by mapping each value in `coll` through\n * the `iteratee` function. The `iteratee` is called with an item from `coll`\n * and a callback for when it has finished processing. Each of these callbacks\n * takes 2 arguments: an `error`, and the transformed item from `coll`. If\n * `iteratee` passes an error to its callback, the main `callback` (for the\n * `map` function) is immediately called with the error.\n *\n * Note, that since this function applies the `iteratee` to each item in\n * parallel, there is no guarantee that the `iteratee` functions will complete\n * in order. However, the results array will be in the same order as the\n * original `coll`.\n *\n * If `map` is passed an Object, the results will be an Array. The results\n * will roughly be in the order of the original Objects' keys (but this can\n * vary across JavaScript engines).\n *\n * @name map\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with the transformed item.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an Array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // file1.txt is a file that is 1000 bytes in size\n * // file2.txt is a file that is 2000 bytes in size\n * // file3.txt is a file that is 3000 bytes in size\n * // file4.txt does not exist\n *\n * const fileList = ['file1.txt','file2.txt','file3.txt'];\n * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];\n *\n * // asynchronous function that returns the file size in bytes\n * function getFileSizeInBytes(file, callback) {\n * fs.stat(file, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * callback(null, stat.size);\n * });\n * }\n *\n * // Using callbacks\n * async.map(fileList, getFileSizeInBytes, function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // results is now an array of the file size in bytes for each file, e.g.\n * // [ 1000, 2000, 3000]\n * }\n * });\n *\n * // Error Handling\n * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {\n * if (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * } else {\n * console.log(results);\n * }\n * });\n *\n * // Using Promises\n * async.map(fileList, getFileSizeInBytes)\n * .then( results => {\n * console.log(results);\n * // results is now an array of the file size in bytes for each file, e.g.\n * // [ 1000, 2000, 3000]\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.map(withMissingFileList, getFileSizeInBytes)\n * .then( results => {\n * console.log(results);\n * }).catch( err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let results = await async.map(fileList, getFileSizeInBytes);\n * console.log(results);\n * // results is now an array of the file size in bytes for each file, e.g.\n * // [ 1000, 2000, 3000]\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * let results = await async.map(withMissingFileList, getFileSizeInBytes);\n * console.log(results);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * }\n * }\n *\n */\nfunction map (coll, iteratee, callback) {\n return _asyncMap(eachOf$1, coll, iteratee, callback)\n}\nvar map$1 = awaitify(map, 3);\n\n/**\n * Applies the provided arguments to each function in the array, calling\n * `callback` after all functions have completed. If you only provide the first\n * argument, `fns`, then it will return a function which lets you pass in the\n * arguments as if it were a single function call. If more arguments are\n * provided, `callback` is required while `args` is still optional. The results\n * for each of the applied async functions are passed to the final callback\n * as an array.\n *\n * @name applyEach\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s\n * to all call with the same arguments\n * @param {...*} [args] - any number of separate arguments to pass to the\n * function.\n * @param {Function} [callback] - the final argument should be the callback,\n * called when all functions have completed processing.\n * @returns {AsyncFunction} - Returns a function that takes no args other than\n * an optional callback, that is the result of applying the `args` to each\n * of the functions.\n * @example\n *\n * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')\n *\n * appliedFn((err, results) => {\n * // results[0] is the results for `enableSearch`\n * // results[1] is the results for `updateSchema`\n * });\n *\n * // partial application example:\n * async.each(\n * buckets,\n * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),\n * callback\n * );\n */\nvar applyEach$1 = applyEach(map$1);\n\n/**\n * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.\n *\n * @name eachOfSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.eachOf]{@link module:Collections.eachOf}\n * @alias forEachOfSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction eachOfSeries(coll, iteratee, callback) {\n return eachOfLimit$2(coll, 1, iteratee, callback)\n}\nvar eachOfSeries$1 = awaitify(eachOfSeries, 3);\n\n/**\n * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.\n *\n * @name mapSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with the transformed item.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction mapSeries (coll, iteratee, callback) {\n return _asyncMap(eachOfSeries$1, coll, iteratee, callback)\n}\nvar mapSeries$1 = awaitify(mapSeries, 3);\n\n/**\n * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.\n *\n * @name applyEachSeries\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.applyEach]{@link module:ControlFlow.applyEach}\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all\n * call with the same arguments\n * @param {...*} [args] - any number of separate arguments to pass to the\n * function.\n * @param {Function} [callback] - the final argument should be the callback,\n * called when all functions have completed processing.\n * @returns {AsyncFunction} - A function, that when called, is the result of\n * appling the `args` to the list of functions. It takes no args, other than\n * a callback.\n */\nvar applyEachSeries = applyEach(mapSeries$1);\n\nconst PROMISE_SYMBOL = Symbol('promiseCallback');\n\nfunction promiseCallback () {\n let resolve, reject;\n function callback (err, ...args) {\n if (err) return reject(err)\n resolve(args.length > 1 ? args : args[0]);\n }\n\n callback[PROMISE_SYMBOL] = new Promise((res, rej) => {\n resolve = res,\n reject = rej;\n });\n\n return callback\n}\n\n/**\n * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on\n * their requirements. Each function can optionally depend on other functions\n * being completed first, and each function is run as soon as its requirements\n * are satisfied.\n *\n * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence\n * will stop. Further tasks will not execute (so any other functions depending\n * on it will not run), and the main `callback` is immediately called with the\n * error.\n *\n * {@link AsyncFunction}s also receive an object containing the results of functions which\n * have completed so far as the first argument, if they have dependencies. If a\n * task function has no dependencies, it will only be passed a callback.\n *\n * @name auto\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Object} tasks - An object. Each of its properties is either a\n * function or an array of requirements, with the {@link AsyncFunction} itself the last item\n * in the array. The object's key of a property serves as the name of the task\n * defined by that property, i.e. can be used when specifying requirements for\n * other tasks. The function receives one or two arguments:\n * * a `results` object, containing the results of the previously executed\n * functions, only passed if the task has any dependencies,\n * * a `callback(err, result)` function, which must be called when finished,\n * passing an `error` (which can be `null`) and the result of the function's\n * execution.\n * @param {number} [concurrency=Infinity] - An optional `integer` for\n * determining the maximum number of tasks that can be run in parallel. By\n * default, as many as possible.\n * @param {Function} [callback] - An optional callback which is called when all\n * the tasks have been completed. It receives the `err` argument if any `tasks`\n * pass an error to their callback. Results are always returned; however, if an\n * error occurs, no further `tasks` will be performed, and the results object\n * will only contain partial results. Invoked with (err, results).\n * @returns {Promise} a promise, if a callback is not passed\n * @example\n *\n * //Using Callbacks\n * async.auto({\n * get_data: function(callback) {\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: ['get_data', 'make_folder', function(results, callback) {\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(results, callback) {\n * // once the file is written let's email a link to it...\n * callback(null, {'file':results.write_file, 'email':'user@example.com'});\n * }]\n * }, function(err, results) {\n * if (err) {\n * console.log('err = ', err);\n * }\n * console.log('results = ', results);\n * // results = {\n * // get_data: ['data', 'converted to array']\n * // make_folder; 'folder',\n * // write_file: 'filename'\n * // email_link: { file: 'filename', email: 'user@example.com' }\n * // }\n * });\n *\n * //Using Promises\n * async.auto({\n * get_data: function(callback) {\n * console.log('in get_data');\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * console.log('in make_folder');\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: ['get_data', 'make_folder', function(results, callback) {\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(results, callback) {\n * // once the file is written let's email a link to it...\n * callback(null, {'file':results.write_file, 'email':'user@example.com'});\n * }]\n * }).then(results => {\n * console.log('results = ', results);\n * // results = {\n * // get_data: ['data', 'converted to array']\n * // make_folder; 'folder',\n * // write_file: 'filename'\n * // email_link: { file: 'filename', email: 'user@example.com' }\n * // }\n * }).catch(err => {\n * console.log('err = ', err);\n * });\n *\n * //Using async/await\n * async () => {\n * try {\n * let results = await async.auto({\n * get_data: function(callback) {\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: ['get_data', 'make_folder', function(results, callback) {\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(results, callback) {\n * // once the file is written let's email a link to it...\n * callback(null, {'file':results.write_file, 'email':'user@example.com'});\n * }]\n * });\n * console.log('results = ', results);\n * // results = {\n * // get_data: ['data', 'converted to array']\n * // make_folder; 'folder',\n * // write_file: 'filename'\n * // email_link: { file: 'filename', email: 'user@example.com' }\n * // }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction auto(tasks, concurrency, callback) {\n if (typeof concurrency !== 'number') {\n // concurrency is optional, shift the args.\n callback = concurrency;\n concurrency = null;\n }\n callback = once(callback || promiseCallback());\n var numTasks = Object.keys(tasks).length;\n if (!numTasks) {\n return callback(null);\n }\n if (!concurrency) {\n concurrency = numTasks;\n }\n\n var results = {};\n var runningTasks = 0;\n var canceled = false;\n var hasError = false;\n\n var listeners = Object.create(null);\n\n var readyTasks = [];\n\n // for cycle detection:\n var readyToCheck = []; // tasks that have been identified as reachable\n // without the possibility of returning to an ancestor task\n var uncheckedDependencies = {};\n\n Object.keys(tasks).forEach(key => {\n var task = tasks[key];\n if (!Array.isArray(task)) {\n // no dependencies\n enqueueTask(key, [task]);\n readyToCheck.push(key);\n return;\n }\n\n var dependencies = task.slice(0, task.length - 1);\n var remainingDependencies = dependencies.length;\n if (remainingDependencies === 0) {\n enqueueTask(key, task);\n readyToCheck.push(key);\n return;\n }\n uncheckedDependencies[key] = remainingDependencies;\n\n dependencies.forEach(dependencyName => {\n if (!tasks[dependencyName]) {\n throw new Error('async.auto task `' + key +\n '` has a non-existent dependency `' +\n dependencyName + '` in ' +\n dependencies.join(', '));\n }\n addListener(dependencyName, () => {\n remainingDependencies--;\n if (remainingDependencies === 0) {\n enqueueTask(key, task);\n }\n });\n });\n });\n\n checkForDeadlocks();\n processQueue();\n\n function enqueueTask(key, task) {\n readyTasks.push(() => runTask(key, task));\n }\n\n function processQueue() {\n if (canceled) return\n if (readyTasks.length === 0 && runningTasks === 0) {\n return callback(null, results);\n }\n while(readyTasks.length && runningTasks < concurrency) {\n var run = readyTasks.shift();\n run();\n }\n\n }\n\n function addListener(taskName, fn) {\n var taskListeners = listeners[taskName];\n if (!taskListeners) {\n taskListeners = listeners[taskName] = [];\n }\n\n taskListeners.push(fn);\n }\n\n function taskComplete(taskName) {\n var taskListeners = listeners[taskName] || [];\n taskListeners.forEach(fn => fn());\n processQueue();\n }\n\n\n function runTask(key, task) {\n if (hasError) return;\n\n var taskCallback = onlyOnce((err, ...result) => {\n runningTasks--;\n if (err === false) {\n canceled = true;\n return\n }\n if (result.length < 2) {\n [result] = result;\n }\n if (err) {\n var safeResults = {};\n Object.keys(results).forEach(rkey => {\n safeResults[rkey] = results[rkey];\n });\n safeResults[key] = result;\n hasError = true;\n listeners = Object.create(null);\n if (canceled) return\n callback(err, safeResults);\n } else {\n results[key] = result;\n taskComplete(key);\n }\n });\n\n runningTasks++;\n var taskFn = wrapAsync(task[task.length - 1]);\n if (task.length > 1) {\n taskFn(results, taskCallback);\n } else {\n taskFn(taskCallback);\n }\n }\n\n function checkForDeadlocks() {\n // Kahn's algorithm\n // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm\n // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html\n var currentTask;\n var counter = 0;\n while (readyToCheck.length) {\n currentTask = readyToCheck.pop();\n counter++;\n getDependents(currentTask).forEach(dependent => {\n if (--uncheckedDependencies[dependent] === 0) {\n readyToCheck.push(dependent);\n }\n });\n }\n\n if (counter !== numTasks) {\n throw new Error(\n 'async.auto cannot execute tasks due to a recursive dependency'\n );\n }\n }\n\n function getDependents(taskName) {\n var result = [];\n Object.keys(tasks).forEach(key => {\n const task = tasks[key];\n if (Array.isArray(task) && task.indexOf(taskName) >= 0) {\n result.push(key);\n }\n });\n return result;\n }\n\n return callback[PROMISE_SYMBOL]\n}\n\nvar FN_ARGS = /^(?:async\\s+)?(?:function)?\\s*\\w*\\s*\\(\\s*([^)]+)\\s*\\)(?:\\s*{)/;\nvar ARROW_FN_ARGS = /^(?:async\\s+)?\\(?\\s*([^)=]+)\\s*\\)?(?:\\s*=>)/;\nvar FN_ARG_SPLIT = /,/;\nvar FN_ARG = /(=.+)?(\\s*)$/;\nvar STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\n\nfunction parseParams(func) {\n const src = func.toString().replace(STRIP_COMMENTS, '');\n let match = src.match(FN_ARGS);\n if (!match) {\n match = src.match(ARROW_FN_ARGS);\n }\n if (!match) throw new Error('could not parse args in autoInject\\nSource:\\n' + src)\n let [, args] = match;\n return args\n .replace(/\\s/g, '')\n .split(FN_ARG_SPLIT)\n .map((arg) => arg.replace(FN_ARG, '').trim());\n}\n\n/**\n * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent\n * tasks are specified as parameters to the function, after the usual callback\n * parameter, with the parameter names matching the names of the tasks it\n * depends on. This can provide even more readable task graphs which can be\n * easier to maintain.\n *\n * If a final callback is specified, the task results are similarly injected,\n * specified as named parameters after the initial error parameter.\n *\n * The autoInject function is purely syntactic sugar and its semantics are\n * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.\n *\n * @name autoInject\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.auto]{@link module:ControlFlow.auto}\n * @category Control Flow\n * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of\n * the form 'func([dependencies...], callback). The object's key of a property\n * serves as the name of the task defined by that property, i.e. can be used\n * when specifying requirements for other tasks.\n * * The `callback` parameter is a `callback(err, result)` which must be called\n * when finished, passing an `error` (which can be `null`) and the result of\n * the function's execution. The remaining parameters name other tasks on\n * which the task is dependent, and the results from those tasks are the\n * arguments of those parameters.\n * @param {Function} [callback] - An optional callback which is called when all\n * the tasks have been completed. It receives the `err` argument if any `tasks`\n * pass an error to their callback, and a `results` object with any completed\n * task results, similar to `auto`.\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // The example from `auto` can be rewritten as follows:\n * async.autoInject({\n * get_data: function(callback) {\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: function(get_data, make_folder, callback) {\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * },\n * email_link: function(write_file, callback) {\n * // once the file is written let's email a link to it...\n * // write_file contains the filename returned by write_file.\n * callback(null, {'file':write_file, 'email':'user@example.com'});\n * }\n * }, function(err, results) {\n * console.log('err = ', err);\n * console.log('email_link = ', results.email_link);\n * });\n *\n * // If you are using a JS minifier that mangles parameter names, `autoInject`\n * // will not work with plain functions, since the parameter names will be\n * // collapsed to a single letter identifier. To work around this, you can\n * // explicitly specify the names of the parameters your task function needs\n * // in an array, similar to Angular.js dependency injection.\n *\n * // This still has an advantage over plain `auto`, since the results a task\n * // depends on are still spread into arguments.\n * async.autoInject({\n * //...\n * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(write_file, callback) {\n * callback(null, {'file':write_file, 'email':'user@example.com'});\n * }]\n * //...\n * }, function(err, results) {\n * console.log('err = ', err);\n * console.log('email_link = ', results.email_link);\n * });\n */\nfunction autoInject(tasks, callback) {\n var newTasks = {};\n\n Object.keys(tasks).forEach(key => {\n var taskFn = tasks[key];\n var params;\n var fnIsAsync = isAsync(taskFn);\n var hasNoDeps =\n (!fnIsAsync && taskFn.length === 1) ||\n (fnIsAsync && taskFn.length === 0);\n\n if (Array.isArray(taskFn)) {\n params = [...taskFn];\n taskFn = params.pop();\n\n newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);\n } else if (hasNoDeps) {\n // no dependencies, use the function as-is\n newTasks[key] = taskFn;\n } else {\n params = parseParams(taskFn);\n if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) {\n throw new Error(\"autoInject task functions require explicit parameters.\");\n }\n\n // remove callback param\n if (!fnIsAsync) params.pop();\n\n newTasks[key] = params.concat(newTask);\n }\n\n function newTask(results, taskCb) {\n var newArgs = params.map(name => results[name]);\n newArgs.push(taskCb);\n wrapAsync(taskFn)(...newArgs);\n }\n });\n\n return auto(newTasks, callback);\n}\n\n// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation\n// used for queues. This implementation assumes that the node provided by the user can be modified\n// to adjust the next and last properties. We implement only the minimal functionality\n// for queue support.\nclass DLL {\n constructor() {\n this.head = this.tail = null;\n this.length = 0;\n }\n\n removeLink(node) {\n if (node.prev) node.prev.next = node.next;\n else this.head = node.next;\n if (node.next) node.next.prev = node.prev;\n else this.tail = node.prev;\n\n node.prev = node.next = null;\n this.length -= 1;\n return node;\n }\n\n empty () {\n while(this.head) this.shift();\n return this;\n }\n\n insertAfter(node, newNode) {\n newNode.prev = node;\n newNode.next = node.next;\n if (node.next) node.next.prev = newNode;\n else this.tail = newNode;\n node.next = newNode;\n this.length += 1;\n }\n\n insertBefore(node, newNode) {\n newNode.prev = node.prev;\n newNode.next = node;\n if (node.prev) node.prev.next = newNode;\n else this.head = newNode;\n node.prev = newNode;\n this.length += 1;\n }\n\n unshift(node) {\n if (this.head) this.insertBefore(this.head, node);\n else setInitial(this, node);\n }\n\n push(node) {\n if (this.tail) this.insertAfter(this.tail, node);\n else setInitial(this, node);\n }\n\n shift() {\n return this.head && this.removeLink(this.head);\n }\n\n pop() {\n return this.tail && this.removeLink(this.tail);\n }\n\n toArray() {\n return [...this]\n }\n\n *[Symbol.iterator] () {\n var cur = this.head;\n while (cur) {\n yield cur.data;\n cur = cur.next;\n }\n }\n\n remove (testFn) {\n var curr = this.head;\n while(curr) {\n var {next} = curr;\n if (testFn(curr)) {\n this.removeLink(curr);\n }\n curr = next;\n }\n return this;\n }\n}\n\nfunction setInitial(dll, node) {\n dll.length = 1;\n dll.head = dll.tail = node;\n}\n\nfunction queue(worker, concurrency, payload) {\n if (concurrency == null) {\n concurrency = 1;\n }\n else if(concurrency === 0) {\n throw new RangeError('Concurrency must not be zero');\n }\n\n var _worker = wrapAsync(worker);\n var numRunning = 0;\n var workersList = [];\n const events = {\n error: [],\n drain: [],\n saturated: [],\n unsaturated: [],\n empty: []\n };\n\n function on (event, handler) {\n events[event].push(handler);\n }\n\n function once (event, handler) {\n const handleAndRemove = (...args) => {\n off(event, handleAndRemove);\n handler(...args);\n };\n events[event].push(handleAndRemove);\n }\n\n function off (event, handler) {\n if (!event) return Object.keys(events).forEach(ev => events[ev] = [])\n if (!handler) return events[event] = []\n events[event] = events[event].filter(ev => ev !== handler);\n }\n\n function trigger (event, ...args) {\n events[event].forEach(handler => handler(...args));\n }\n\n var processingScheduled = false;\n function _insert(data, insertAtFront, rejectOnError, callback) {\n if (callback != null && typeof callback !== 'function') {\n throw new Error('task callback must be a function');\n }\n q.started = true;\n\n var res, rej;\n function promiseCallback (err, ...args) {\n // we don't care about the error, let the global error handler\n // deal with it\n if (err) return rejectOnError ? rej(err) : res()\n if (args.length <= 1) return res(args[0])\n res(args);\n }\n\n var item = {\n data,\n callback: rejectOnError ?\n promiseCallback :\n (callback || promiseCallback)\n };\n\n if (insertAtFront) {\n q._tasks.unshift(item);\n } else {\n q._tasks.push(item);\n }\n\n if (!processingScheduled) {\n processingScheduled = true;\n setImmediate$1(() => {\n processingScheduled = false;\n q.process();\n });\n }\n\n if (rejectOnError || !callback) {\n return new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n })\n }\n }\n\n function _createCB(tasks) {\n return function (err, ...args) {\n numRunning -= 1;\n\n for (var i = 0, l = tasks.length; i < l; i++) {\n var task = tasks[i];\n\n var index = workersList.indexOf(task);\n if (index === 0) {\n workersList.shift();\n } else if (index > 0) {\n workersList.splice(index, 1);\n }\n\n task.callback(err, ...args);\n\n if (err != null) {\n trigger('error', err, task.data);\n }\n }\n\n if (numRunning <= (q.concurrency - q.buffer) ) {\n trigger('unsaturated');\n }\n\n if (q.idle()) {\n trigger('drain');\n }\n q.process();\n };\n }\n\n function _maybeDrain(data) {\n if (data.length === 0 && q.idle()) {\n // call drain immediately if there are no tasks\n setImmediate$1(() => trigger('drain'));\n return true\n }\n return false\n }\n\n const eventMethod = (name) => (handler) => {\n if (!handler) {\n return new Promise((resolve, reject) => {\n once(name, (err, data) => {\n if (err) return reject(err)\n resolve(data);\n });\n })\n }\n off(name);\n on(name, handler);\n\n };\n\n var isProcessing = false;\n var q = {\n _tasks: new DLL(),\n *[Symbol.iterator] () {\n yield* q._tasks[Symbol.iterator]();\n },\n concurrency,\n payload,\n buffer: concurrency / 4,\n started: false,\n paused: false,\n push (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, false, false, callback))\n }\n return _insert(data, false, false, callback);\n },\n pushAsync (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, false, true, callback))\n }\n return _insert(data, false, true, callback);\n },\n kill () {\n off();\n q._tasks.empty();\n },\n unshift (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, true, false, callback))\n }\n return _insert(data, true, false, callback);\n },\n unshiftAsync (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, true, true, callback))\n }\n return _insert(data, true, true, callback);\n },\n remove (testFn) {\n q._tasks.remove(testFn);\n },\n process () {\n // Avoid trying to start too many processing operations. This can occur\n // when callbacks resolve synchronously (#1267).\n if (isProcessing) {\n return;\n }\n isProcessing = true;\n while(!q.paused && numRunning < q.concurrency && q._tasks.length){\n var tasks = [], data = [];\n var l = q._tasks.length;\n if (q.payload) l = Math.min(l, q.payload);\n for (var i = 0; i < l; i++) {\n var node = q._tasks.shift();\n tasks.push(node);\n workersList.push(node);\n data.push(node.data);\n }\n\n numRunning += 1;\n\n if (q._tasks.length === 0) {\n trigger('empty');\n }\n\n if (numRunning === q.concurrency) {\n trigger('saturated');\n }\n\n var cb = onlyOnce(_createCB(tasks));\n _worker(data, cb);\n }\n isProcessing = false;\n },\n length () {\n return q._tasks.length;\n },\n running () {\n return numRunning;\n },\n workersList () {\n return workersList;\n },\n idle() {\n return q._tasks.length + numRunning === 0;\n },\n pause () {\n q.paused = true;\n },\n resume () {\n if (q.paused === false) { return; }\n q.paused = false;\n setImmediate$1(q.process);\n }\n };\n // define these as fixed properties, so people get useful errors when updating\n Object.defineProperties(q, {\n saturated: {\n writable: false,\n value: eventMethod('saturated')\n },\n unsaturated: {\n writable: false,\n value: eventMethod('unsaturated')\n },\n empty: {\n writable: false,\n value: eventMethod('empty')\n },\n drain: {\n writable: false,\n value: eventMethod('drain')\n },\n error: {\n writable: false,\n value: eventMethod('error')\n },\n });\n return q;\n}\n\n/**\n * Creates a `cargo` object with the specified payload. Tasks added to the\n * cargo will be processed altogether (up to the `payload` limit). If the\n * `worker` is in progress, the task is queued until it becomes available. Once\n * the `worker` has completed some tasks, each callback of those tasks is\n * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)\n * for how `cargo` and `queue` work.\n *\n * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers\n * at a time, cargo passes an array of tasks to a single worker, repeating\n * when the worker is finished.\n *\n * @name cargo\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.queue]{@link module:ControlFlow.queue}\n * @category Control Flow\n * @param {AsyncFunction} worker - An asynchronous function for processing an array\n * of queued tasks. Invoked with `(tasks, callback)`.\n * @param {number} [payload=Infinity] - An optional `integer` for determining\n * how many tasks should be processed per round; if omitted, the default is\n * unlimited.\n * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can\n * attached as certain properties to listen for specific events during the\n * lifecycle of the cargo and inner queue.\n * @example\n *\n * // create a cargo object with payload 2\n * var cargo = async.cargo(function(tasks, callback) {\n * for (var i=0; i<tasks.length; i++) {\n * console.log('hello ' + tasks[i].name);\n * }\n * callback();\n * }, 2);\n *\n * // add some items\n * cargo.push({name: 'foo'}, function(err) {\n * console.log('finished processing foo');\n * });\n * cargo.push({name: 'bar'}, function(err) {\n * console.log('finished processing bar');\n * });\n * await cargo.push({name: 'baz'});\n * console.log('finished processing baz');\n */\nfunction cargo(worker, payload) {\n return queue(worker, 1, payload);\n}\n\n/**\n * Creates a `cargoQueue` object with the specified payload. Tasks added to the\n * cargoQueue will be processed together (up to the `payload` limit) in `concurrency` parallel workers.\n * If the all `workers` are in progress, the task is queued until one becomes available. Once\n * a `worker` has completed some tasks, each callback of those tasks is\n * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)\n * for how `cargo` and `queue` work.\n *\n * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers\n * at a time, and [`cargo`]{@link module:ControlFlow.cargo} passes an array of tasks to a single worker,\n * the cargoQueue passes an array of tasks to multiple parallel workers.\n *\n * @name cargoQueue\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.queue]{@link module:ControlFlow.queue}\n * @see [async.cargo]{@link module:ControlFLow.cargo}\n * @category Control Flow\n * @param {AsyncFunction} worker - An asynchronous function for processing an array\n * of queued tasks. Invoked with `(tasks, callback)`.\n * @param {number} [concurrency=1] - An `integer` for determining how many\n * `worker` functions should be run in parallel. If omitted, the concurrency\n * defaults to `1`. If the concurrency is `0`, an error is thrown.\n * @param {number} [payload=Infinity] - An optional `integer` for determining\n * how many tasks should be processed per round; if omitted, the default is\n * unlimited.\n * @returns {module:ControlFlow.QueueObject} A cargoQueue object to manage the tasks. Callbacks can\n * attached as certain properties to listen for specific events during the\n * lifecycle of the cargoQueue and inner queue.\n * @example\n *\n * // create a cargoQueue object with payload 2 and concurrency 2\n * var cargoQueue = async.cargoQueue(function(tasks, callback) {\n * for (var i=0; i<tasks.length; i++) {\n * console.log('hello ' + tasks[i].name);\n * }\n * callback();\n * }, 2, 2);\n *\n * // add some items\n * cargoQueue.push({name: 'foo'}, function(err) {\n * console.log('finished processing foo');\n * });\n * cargoQueue.push({name: 'bar'}, function(err) {\n * console.log('finished processing bar');\n * });\n * cargoQueue.push({name: 'baz'}, function(err) {\n * console.log('finished processing baz');\n * });\n * cargoQueue.push({name: 'boo'}, function(err) {\n * console.log('finished processing boo');\n * });\n */\nfunction cargo$1(worker, concurrency, payload) {\n return queue(worker, concurrency, payload);\n}\n\n/**\n * Reduces `coll` into a single value using an async `iteratee` to return each\n * successive step. `memo` is the initial state of the reduction. This function\n * only operates in series.\n *\n * For performance reasons, it may make sense to split a call to this function\n * into a parallel map, and then use the normal `Array.prototype.reduce` on the\n * results. This function is for situations where each step in the reduction\n * needs to be async; if you can get the data before reducing it, then it's\n * probably a good idea to do so.\n *\n * @name reduce\n * @static\n * @memberOf module:Collections\n * @method\n * @alias inject\n * @alias foldl\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {*} memo - The initial state of the reduction.\n * @param {AsyncFunction} iteratee - A function applied to each item in the\n * array to produce the next step in the reduction.\n * The `iteratee` should complete with the next state of the reduction.\n * If the iteratee completes with an error, the reduction is stopped and the\n * main `callback` is immediately called with the error.\n * Invoked with (memo, item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result is the reduced value. Invoked with\n * (err, result).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // file1.txt is a file that is 1000 bytes in size\n * // file2.txt is a file that is 2000 bytes in size\n * // file3.txt is a file that is 3000 bytes in size\n * // file4.txt does not exist\n *\n * const fileList = ['file1.txt','file2.txt','file3.txt'];\n * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];\n *\n * // asynchronous function that computes the file size in bytes\n * // file size is added to the memoized value, then returned\n * function getFileSizeInBytes(memo, file, callback) {\n * fs.stat(file, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * callback(null, memo + stat.size);\n * });\n * }\n *\n * // Using callbacks\n * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(result);\n * // 6000\n * // which is the sum of the file sizes of the three files\n * }\n * });\n *\n * // Error Handling\n * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {\n * if (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * } else {\n * console.log(result);\n * }\n * });\n *\n * // Using Promises\n * async.reduce(fileList, 0, getFileSizeInBytes)\n * .then( result => {\n * console.log(result);\n * // 6000\n * // which is the sum of the file sizes of the three files\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.reduce(withMissingFileList, 0, getFileSizeInBytes)\n * .then( result => {\n * console.log(result);\n * }).catch( err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.reduce(fileList, 0, getFileSizeInBytes);\n * console.log(result);\n * // 6000\n * // which is the sum of the file sizes of the three files\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);\n * console.log(result);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * }\n * }\n *\n */\nfunction reduce(coll, memo, iteratee, callback) {\n callback = once(callback);\n var _iteratee = wrapAsync(iteratee);\n return eachOfSeries$1(coll, (x, i, iterCb) => {\n _iteratee(memo, x, (err, v) => {\n memo = v;\n iterCb(err);\n });\n }, err => callback(err, memo));\n}\nvar reduce$1 = awaitify(reduce, 4);\n\n/**\n * Version of the compose function that is more natural to read. Each function\n * consumes the return value of the previous function. It is the equivalent of\n * [compose]{@link module:ControlFlow.compose} with the arguments reversed.\n *\n * Each function is executed with the `this` binding of the composed function.\n *\n * @name seq\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.compose]{@link module:ControlFlow.compose}\n * @category Control Flow\n * @param {...AsyncFunction} functions - the asynchronous functions to compose\n * @returns {Function} a function that composes the `functions` in order\n * @example\n *\n * // Requires lodash (or underscore), express3 and dresende's orm2.\n * // Part of an app, that fetches cats of the logged user.\n * // This example uses `seq` function to avoid overnesting and error\n * // handling clutter.\n * app.get('/cats', function(request, response) {\n * var User = request.models.User;\n * async.seq(\n * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))\n * function(user, fn) {\n * user.getCats(fn); // 'getCats' has signature (callback(err, data))\n * }\n * )(req.session.user_id, function (err, cats) {\n * if (err) {\n * console.error(err);\n * response.json({ status: 'error', message: err.message });\n * } else {\n * response.json({ status: 'ok', message: 'Cats found', data: cats });\n * }\n * });\n * });\n */\nfunction seq(...functions) {\n var _functions = functions.map(wrapAsync);\n return function (...args) {\n var that = this;\n\n var cb = args[args.length - 1];\n if (typeof cb == 'function') {\n args.pop();\n } else {\n cb = promiseCallback();\n }\n\n reduce$1(_functions, args, (newargs, fn, iterCb) => {\n fn.apply(that, newargs.concat((err, ...nextargs) => {\n iterCb(err, nextargs);\n }));\n },\n (err, results) => cb(err, ...results));\n\n return cb[PROMISE_SYMBOL]\n };\n}\n\n/**\n * Creates a function which is a composition of the passed asynchronous\n * functions. Each function consumes the return value of the function that\n * follows. Composing functions `f()`, `g()`, and `h()` would produce the result\n * of `f(g(h()))`, only this version uses callbacks to obtain the return values.\n *\n * If the last argument to the composed function is not a function, a promise\n * is returned when you call it.\n *\n * Each function is executed with the `this` binding of the composed function.\n *\n * @name compose\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {...AsyncFunction} functions - the asynchronous functions to compose\n * @returns {Function} an asynchronous function that is the composed\n * asynchronous `functions`\n * @example\n *\n * function add1(n, callback) {\n * setTimeout(function () {\n * callback(null, n + 1);\n * }, 10);\n * }\n *\n * function mul3(n, callback) {\n * setTimeout(function () {\n * callback(null, n * 3);\n * }, 10);\n * }\n *\n * var add1mul3 = async.compose(mul3, add1);\n * add1mul3(4, function (err, result) {\n * // result now equals 15\n * });\n */\nfunction compose(...args) {\n return seq(...args.reverse());\n}\n\n/**\n * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.\n *\n * @name mapLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with the transformed item.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction mapLimit (coll, limit, iteratee, callback) {\n return _asyncMap(eachOfLimit(limit), coll, iteratee, callback)\n}\nvar mapLimit$1 = awaitify(mapLimit, 4);\n\n/**\n * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.\n *\n * @name concatLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.concat]{@link module:Collections.concat}\n * @category Collection\n * @alias flatMapLimit\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,\n * which should use an array as its result. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is an array\n * containing the concatenated results of the `iteratee` function. Invoked with\n * (err, results).\n * @returns A Promise, if no callback is passed\n */\nfunction concatLimit(coll, limit, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return mapLimit$1(coll, limit, (val, iterCb) => {\n _iteratee(val, (err, ...args) => {\n if (err) return iterCb(err);\n return iterCb(err, args);\n });\n }, (err, mapResults) => {\n var result = [];\n for (var i = 0; i < mapResults.length; i++) {\n if (mapResults[i]) {\n result = result.concat(...mapResults[i]);\n }\n }\n\n return callback(err, result);\n });\n}\nvar concatLimit$1 = awaitify(concatLimit, 4);\n\n/**\n * Applies `iteratee` to each item in `coll`, concatenating the results. Returns\n * the concatenated list. The `iteratee`s are called in parallel, and the\n * results are concatenated as they return. The results array will be returned in\n * the original order of `coll` passed to the `iteratee` function.\n *\n * @name concat\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @alias flatMap\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,\n * which should use an array as its result. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is an array\n * containing the concatenated results of the `iteratee` function. Invoked with\n * (err, results).\n * @returns A Promise, if no callback is passed\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * let directoryList = ['dir1','dir2','dir3'];\n * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];\n *\n * // Using callbacks\n * async.concat(directoryList, fs.readdir, function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]\n * }\n * });\n *\n * // Error Handling\n * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {\n * if (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4 does not exist\n * } else {\n * console.log(results);\n * }\n * });\n *\n * // Using Promises\n * async.concat(directoryList, fs.readdir)\n * .then(results => {\n * console.log(results);\n * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.concat(withMissingDirectoryList, fs.readdir)\n * .then(results => {\n * console.log(results);\n * }).catch(err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4 does not exist\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let results = await async.concat(directoryList, fs.readdir);\n * console.log(results);\n * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]\n * } catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * let results = await async.concat(withMissingDirectoryList, fs.readdir);\n * console.log(results);\n * } catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4 does not exist\n * }\n * }\n *\n */\nfunction concat(coll, iteratee, callback) {\n return concatLimit$1(coll, Infinity, iteratee, callback)\n}\nvar concat$1 = awaitify(concat, 3);\n\n/**\n * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.\n *\n * @name concatSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.concat]{@link module:Collections.concat}\n * @category Collection\n * @alias flatMapSeries\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.\n * The iteratee should complete with an array an array of results.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is an array\n * containing the concatenated results of the `iteratee` function. Invoked with\n * (err, results).\n * @returns A Promise, if no callback is passed\n */\nfunction concatSeries(coll, iteratee, callback) {\n return concatLimit$1(coll, 1, iteratee, callback)\n}\nvar concatSeries$1 = awaitify(concatSeries, 3);\n\n/**\n * Returns a function that when called, calls-back with the values provided.\n * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to\n * [`auto`]{@link module:ControlFlow.auto}.\n *\n * @name constant\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {...*} arguments... - Any number of arguments to automatically invoke\n * callback with.\n * @returns {AsyncFunction} Returns a function that when invoked, automatically\n * invokes the callback with the previous given arguments.\n * @example\n *\n * async.waterfall([\n * async.constant(42),\n * function (value, next) {\n * // value === 42\n * },\n * //...\n * ], callback);\n *\n * async.waterfall([\n * async.constant(filename, \"utf8\"),\n * fs.readFile,\n * function (fileData, next) {\n * //...\n * }\n * //...\n * ], callback);\n *\n * async.auto({\n * hostname: async.constant(\"https://server.net/\"),\n * port: findFreePort,\n * launchServer: [\"hostname\", \"port\", function (options, cb) {\n * startServer(options, cb);\n * }],\n * //...\n * }, callback);\n */\nfunction constant(...args) {\n return function (...ignoredArgs/*, callback*/) {\n var callback = ignoredArgs.pop();\n return callback(null, ...args);\n };\n}\n\nfunction _createTester(check, getResult) {\n return (eachfn, arr, _iteratee, cb) => {\n var testPassed = false;\n var testResult;\n const iteratee = wrapAsync(_iteratee);\n eachfn(arr, (value, _, callback) => {\n iteratee(value, (err, result) => {\n if (err || err === false) return callback(err);\n\n if (check(result) && !testResult) {\n testPassed = true;\n testResult = getResult(true, value);\n return callback(null, breakLoop);\n }\n callback();\n });\n }, err => {\n if (err) return cb(err);\n cb(null, testPassed ? testResult : getResult(false));\n });\n };\n}\n\n/**\n * Returns the first value in `coll` that passes an async truth test. The\n * `iteratee` is applied in parallel, meaning the first iteratee to return\n * `true` will fire the detect `callback` with that result. That means the\n * result might not be the first item in the original `coll` (in terms of order)\n * that passes the test.\n\n * If order within the original `coll` is important, then look at\n * [`detectSeries`]{@link module:Collections.detectSeries}.\n *\n * @name detect\n * @static\n * @memberOf module:Collections\n * @method\n * @alias find\n * @category Collections\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.\n * The iteratee must complete with a boolean value as its result.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the `iteratee` functions have finished.\n * Result will be the first item in the array that passes the truth test\n * (iteratee) or the value `undefined` if none passed. Invoked with\n * (err, result).\n * @returns A Promise, if no callback is passed\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,\n * function(err, result) {\n * console.log(result);\n * // dir1/file1.txt\n * // result now equals the first file in the list that exists\n * }\n *);\n *\n * // Using Promises\n * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)\n * .then(result => {\n * console.log(result);\n * // dir1/file1.txt\n * // result now equals the first file in the list that exists\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists);\n * console.log(result);\n * // dir1/file1.txt\n * // result now equals the file in the list that exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction detect(coll, iteratee, callback) {\n return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback)\n}\nvar detect$1 = awaitify(detect, 3);\n\n/**\n * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name detectLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.detect]{@link module:Collections.detect}\n * @alias findLimit\n * @category Collections\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.\n * The iteratee must complete with a boolean value as its result.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the `iteratee` functions have finished.\n * Result will be the first item in the array that passes the truth test\n * (iteratee) or the value `undefined` if none passed. Invoked with\n * (err, result).\n * @returns a Promise if no callback is passed\n */\nfunction detectLimit(coll, limit, iteratee, callback) {\n return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback)\n}\nvar detectLimit$1 = awaitify(detectLimit, 4);\n\n/**\n * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.\n *\n * @name detectSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.detect]{@link module:Collections.detect}\n * @alias findSeries\n * @category Collections\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.\n * The iteratee must complete with a boolean value as its result.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the `iteratee` functions have finished.\n * Result will be the first item in the array that passes the truth test\n * (iteratee) or the value `undefined` if none passed. Invoked with\n * (err, result).\n * @returns a Promise if no callback is passed\n */\nfunction detectSeries(coll, iteratee, callback) {\n return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback)\n}\n\nvar detectSeries$1 = awaitify(detectSeries, 3);\n\nfunction consoleFunc(name) {\n return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => {\n /* istanbul ignore else */\n if (typeof console === 'object') {\n /* istanbul ignore else */\n if (err) {\n /* istanbul ignore else */\n if (console.error) {\n console.error(err);\n }\n } else if (console[name]) { /* istanbul ignore else */\n resultArgs.forEach(x => console[name](x));\n }\n }\n })\n}\n\n/**\n * Logs the result of an [`async` function]{@link AsyncFunction} to the\n * `console` using `console.dir` to display the properties of the resulting object.\n * Only works in Node.js or in browsers that support `console.dir` and\n * `console.error` (such as FF and Chrome).\n * If multiple arguments are returned from the async function,\n * `console.dir` is called on each argument in order.\n *\n * @name dir\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} function - The function you want to eventually apply\n * all arguments to.\n * @param {...*} arguments... - Any number of arguments to apply to the function.\n * @example\n *\n * // in a module\n * var hello = function(name, callback) {\n * setTimeout(function() {\n * callback(null, {hello: name});\n * }, 1000);\n * };\n *\n * // in the node repl\n * node> async.dir(hello, 'world');\n * {hello: 'world'}\n */\nvar dir = consoleFunc('dir');\n\n/**\n * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in\n * the order of operations, the arguments `test` and `iteratee` are switched.\n *\n * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.\n *\n * @name doWhilst\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.whilst]{@link module:ControlFlow.whilst}\n * @category Control Flow\n * @param {AsyncFunction} iteratee - A function which is called each time `test`\n * passes. Invoked with (callback).\n * @param {AsyncFunction} test - asynchronous truth test to perform after each\n * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the\n * non-error args from the previous callback of `iteratee`.\n * @param {Function} [callback] - A callback which is called after the test\n * function has failed and repeated execution of `iteratee` has stopped.\n * `callback` will be passed an error and any arguments passed to the final\n * `iteratee`'s callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction doWhilst(iteratee, test, callback) {\n callback = onlyOnce(callback);\n var _fn = wrapAsync(iteratee);\n var _test = wrapAsync(test);\n var results;\n\n function next(err, ...args) {\n if (err) return callback(err);\n if (err === false) return;\n results = args;\n _test(...args, check);\n }\n\n function check(err, truth) {\n if (err) return callback(err);\n if (err === false) return;\n if (!truth) return callback(null, ...results);\n _fn(next);\n }\n\n return check(null, true);\n}\n\nvar doWhilst$1 = awaitify(doWhilst, 3);\n\n/**\n * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the\n * argument ordering differs from `until`.\n *\n * @name doUntil\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}\n * @category Control Flow\n * @param {AsyncFunction} iteratee - An async function which is called each time\n * `test` fails. Invoked with (callback).\n * @param {AsyncFunction} test - asynchronous truth test to perform after each\n * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the\n * non-error args from the previous callback of `iteratee`\n * @param {Function} [callback] - A callback which is called after the test\n * function has passed and repeated execution of `iteratee` has stopped. `callback`\n * will be passed an error and any arguments passed to the final `iteratee`'s\n * callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction doUntil(iteratee, test, callback) {\n const _test = wrapAsync(test);\n return doWhilst$1(iteratee, (...args) => {\n const cb = args.pop();\n _test(...args, (err, truth) => cb (err, !truth));\n }, callback);\n}\n\nfunction _withoutIndex(iteratee) {\n return (value, index, callback) => iteratee(value, callback);\n}\n\n/**\n * Applies the function `iteratee` to each item in `coll`, in parallel.\n * The `iteratee` is called with an item from the list, and a callback for when\n * it has finished. If the `iteratee` passes an error to its `callback`, the\n * main `callback` (for the `each` function) is immediately called with the\n * error.\n *\n * Note, that since this function applies `iteratee` to each item in parallel,\n * there is no guarantee that the iteratee functions will complete in order.\n *\n * @name each\n * @static\n * @memberOf module:Collections\n * @method\n * @alias forEach\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to\n * each item in `coll`. Invoked with (item, callback).\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOf`.\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];\n * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];\n *\n * // asynchronous function that deletes a file\n * const deleteFile = function(file, callback) {\n * fs.unlink(file, callback);\n * };\n *\n * // Using callbacks\n * async.each(fileList, deleteFile, function(err) {\n * if( err ) {\n * console.log(err);\n * } else {\n * console.log('All files have been deleted successfully');\n * }\n * });\n *\n * // Error Handling\n * async.each(withMissingFileList, deleteFile, function(err){\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4/file2.txt does not exist\n * // dir1/file1.txt could have been deleted\n * });\n *\n * // Using Promises\n * async.each(fileList, deleteFile)\n * .then( () => {\n * console.log('All files have been deleted successfully');\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.each(fileList, deleteFile)\n * .then( () => {\n * console.log('All files have been deleted successfully');\n * }).catch( err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4/file2.txt does not exist\n * // dir1/file1.txt could have been deleted\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * await async.each(files, deleteFile);\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * await async.each(withMissingFileList, deleteFile);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4/file2.txt does not exist\n * // dir1/file1.txt could have been deleted\n * }\n * }\n *\n */\nfunction eachLimit(coll, iteratee, callback) {\n return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);\n}\n\nvar each = awaitify(eachLimit, 3);\n\n/**\n * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.\n *\n * @name eachLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.each]{@link module:Collections.each}\n * @alias forEachLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOfLimit`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction eachLimit$1(coll, limit, iteratee, callback) {\n return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);\n}\nvar eachLimit$2 = awaitify(eachLimit$1, 4);\n\n/**\n * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.\n *\n * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item\n * in series and therefore the iteratee functions will complete in order.\n\n * @name eachSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.each]{@link module:Collections.each}\n * @alias forEachSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each\n * item in `coll`.\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOfSeries`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction eachSeries(coll, iteratee, callback) {\n return eachLimit$2(coll, 1, iteratee, callback)\n}\nvar eachSeries$1 = awaitify(eachSeries, 3);\n\n/**\n * Wrap an async function and ensure it calls its callback on a later tick of\n * the event loop. If the function already calls its callback on a next tick,\n * no extra deferral is added. This is useful for preventing stack overflows\n * (`RangeError: Maximum call stack size exceeded`) and generally keeping\n * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)\n * contained. ES2017 `async` functions are returned as-is -- they are immune\n * to Zalgo's corrupting influences, as they always resolve on a later tick.\n *\n * @name ensureAsync\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} fn - an async function, one that expects a node-style\n * callback as its last argument.\n * @returns {AsyncFunction} Returns a wrapped function with the exact same call\n * signature as the function passed in.\n * @example\n *\n * function sometimesAsync(arg, callback) {\n * if (cache[arg]) {\n * return callback(null, cache[arg]); // this would be synchronous!!\n * } else {\n * doSomeIO(arg, callback); // this IO would be asynchronous\n * }\n * }\n *\n * // this has a risk of stack overflows if many results are cached in a row\n * async.mapSeries(args, sometimesAsync, done);\n *\n * // this will defer sometimesAsync's callback if necessary,\n * // preventing stack overflows\n * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);\n */\nfunction ensureAsync(fn) {\n if (isAsync(fn)) return fn;\n return function (...args/*, callback*/) {\n var callback = args.pop();\n var sync = true;\n args.push((...innerArgs) => {\n if (sync) {\n setImmediate$1(() => callback(...innerArgs));\n } else {\n callback(...innerArgs);\n }\n });\n fn.apply(this, args);\n sync = false;\n };\n}\n\n/**\n * Returns `true` if every element in `coll` satisfies an async test. If any\n * iteratee call returns `false`, the main `callback` is immediately called.\n *\n * @name every\n * @static\n * @memberOf module:Collections\n * @method\n * @alias all\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collection in parallel.\n * The iteratee must complete with a boolean result value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result will be either `true` or `false`\n * depending on the values of the async tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];\n * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * // Using callbacks\n * async.every(fileList, fileExists, function(err, result) {\n * console.log(result);\n * // true\n * // result is true since every file exists\n * });\n *\n * async.every(withMissingFileList, fileExists, function(err, result) {\n * console.log(result);\n * // false\n * // result is false since NOT every file exists\n * });\n *\n * // Using Promises\n * async.every(fileList, fileExists)\n * .then( result => {\n * console.log(result);\n * // true\n * // result is true since every file exists\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * async.every(withMissingFileList, fileExists)\n * .then( result => {\n * console.log(result);\n * // false\n * // result is false since NOT every file exists\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.every(fileList, fileExists);\n * console.log(result);\n * // true\n * // result is true since every file exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * async () => {\n * try {\n * let result = await async.every(withMissingFileList, fileExists);\n * console.log(result);\n * // false\n * // result is false since NOT every file exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction every(coll, iteratee, callback) {\n return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback)\n}\nvar every$1 = awaitify(every, 3);\n\n/**\n * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.\n *\n * @name everyLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.every]{@link module:Collections.every}\n * @alias allLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collection in parallel.\n * The iteratee must complete with a boolean result value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result will be either `true` or `false`\n * depending on the values of the async tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction everyLimit(coll, limit, iteratee, callback) {\n return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback)\n}\nvar everyLimit$1 = awaitify(everyLimit, 4);\n\n/**\n * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.\n *\n * @name everySeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.every]{@link module:Collections.every}\n * @alias allSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collection in series.\n * The iteratee must complete with a boolean result value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result will be either `true` or `false`\n * depending on the values of the async tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction everySeries(coll, iteratee, callback) {\n return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback)\n}\nvar everySeries$1 = awaitify(everySeries, 3);\n\nfunction filterArray(eachfn, arr, iteratee, callback) {\n var truthValues = new Array(arr.length);\n eachfn(arr, (x, index, iterCb) => {\n iteratee(x, (err, v) => {\n truthValues[index] = !!v;\n iterCb(err);\n });\n }, err => {\n if (err) return callback(err);\n var results = [];\n for (var i = 0; i < arr.length; i++) {\n if (truthValues[i]) results.push(arr[i]);\n }\n callback(null, results);\n });\n}\n\nfunction filterGeneric(eachfn, coll, iteratee, callback) {\n var results = [];\n eachfn(coll, (x, index, iterCb) => {\n iteratee(x, (err, v) => {\n if (err) return iterCb(err);\n if (v) {\n results.push({index, value: x});\n }\n iterCb(err);\n });\n }, err => {\n if (err) return callback(err);\n callback(null, results\n .sort((a, b) => a.index - b.index)\n .map(v => v.value));\n });\n}\n\nfunction _filter(eachfn, coll, iteratee, callback) {\n var filter = isArrayLike(coll) ? filterArray : filterGeneric;\n return filter(eachfn, coll, wrapAsync(iteratee), callback);\n}\n\n/**\n * Returns a new array of all the values in `coll` which pass an async truth\n * test. This operation is performed in parallel, but the results array will be\n * in the same order as the original.\n *\n * @name filter\n * @static\n * @memberOf module:Collections\n * @method\n * @alias select\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n * with a boolean argument once it has completed. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n *\n * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * // Using callbacks\n * async.filter(files, fileExists, function(err, results) {\n * if(err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]\n * // results is now an array of the existing files\n * }\n * });\n *\n * // Using Promises\n * async.filter(files, fileExists)\n * .then(results => {\n * console.log(results);\n * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]\n * // results is now an array of the existing files\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let results = await async.filter(files, fileExists);\n * console.log(results);\n * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]\n * // results is now an array of the existing files\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction filter (coll, iteratee, callback) {\n return _filter(eachOf$1, coll, iteratee, callback)\n}\nvar filter$1 = awaitify(filter, 3);\n\n/**\n * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name filterLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.filter]{@link module:Collections.filter}\n * @alias selectLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n * with a boolean argument once it has completed. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction filterLimit (coll, limit, iteratee, callback) {\n return _filter(eachOfLimit(limit), coll, iteratee, callback)\n}\nvar filterLimit$1 = awaitify(filterLimit, 4);\n\n/**\n * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.\n *\n * @name filterSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.filter]{@link module:Collections.filter}\n * @alias selectSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n * with a boolean argument once it has completed. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results)\n * @returns {Promise} a promise, if no callback provided\n */\nfunction filterSeries (coll, iteratee, callback) {\n return _filter(eachOfSeries$1, coll, iteratee, callback)\n}\nvar filterSeries$1 = awaitify(filterSeries, 3);\n\n/**\n * Calls the asynchronous function `fn` with a callback parameter that allows it\n * to call itself again, in series, indefinitely.\n\n * If an error is passed to the callback then `errback` is called with the\n * error, and execution stops, otherwise it will never be called.\n *\n * @name forever\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {AsyncFunction} fn - an async function to call repeatedly.\n * Invoked with (next).\n * @param {Function} [errback] - when `fn` passes an error to it's callback,\n * this function will be called, and execution stops. Invoked with (err).\n * @returns {Promise} a promise that rejects if an error occurs and an errback\n * is not passed\n * @example\n *\n * async.forever(\n * function(next) {\n * // next is suitable for passing to things that need a callback(err [, whatever]);\n * // it will result in this function being called again.\n * },\n * function(err) {\n * // if next is called with a value in its first parameter, it will appear\n * // in here as 'err', and execution will stop.\n * }\n * );\n */\nfunction forever(fn, errback) {\n var done = onlyOnce(errback);\n var task = wrapAsync(ensureAsync(fn));\n\n function next(err) {\n if (err) return done(err);\n if (err === false) return;\n task(next);\n }\n return next();\n}\nvar forever$1 = awaitify(forever, 2);\n\n/**\n * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.\n *\n * @name groupByLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.groupBy]{@link module:Collections.groupBy}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a `key` to group the value under.\n * Invoked with (value, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Result is an `Object` whoses\n * properties are arrays of values which returned the corresponding key.\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction groupByLimit(coll, limit, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return mapLimit$1(coll, limit, (val, iterCb) => {\n _iteratee(val, (err, key) => {\n if (err) return iterCb(err);\n return iterCb(err, {key, val});\n });\n }, (err, mapResults) => {\n var result = {};\n // from MDN, handle object having an `hasOwnProperty` prop\n var {hasOwnProperty} = Object.prototype;\n\n for (var i = 0; i < mapResults.length; i++) {\n if (mapResults[i]) {\n var {key} = mapResults[i];\n var {val} = mapResults[i];\n\n if (hasOwnProperty.call(result, key)) {\n result[key].push(val);\n } else {\n result[key] = [val];\n }\n }\n }\n\n return callback(err, result);\n });\n}\n\nvar groupByLimit$1 = awaitify(groupByLimit, 4);\n\n/**\n * Returns a new object, where each value corresponds to an array of items, from\n * `coll`, that returned the corresponding key. That is, the keys of the object\n * correspond to the values passed to the `iteratee` callback.\n *\n * Note: Since this function applies the `iteratee` to each item in parallel,\n * there is no guarantee that the `iteratee` functions will complete in order.\n * However, the values for each key in the `result` will be in the same order as\n * the original `coll`. For Objects, the values will roughly be in the order of\n * the original Objects' keys (but this can vary across JavaScript engines).\n *\n * @name groupBy\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a `key` to group the value under.\n * Invoked with (value, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Result is an `Object` whoses\n * properties are arrays of values which returned the corresponding key.\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * const files = ['dir1/file1.txt','dir2','dir4']\n *\n * // asynchronous function that detects file type as none, file, or directory\n * function detectFile(file, callback) {\n * fs.stat(file, function(err, stat) {\n * if (err) {\n * return callback(null, 'none');\n * }\n * callback(null, stat.isDirectory() ? 'directory' : 'file');\n * });\n * }\n *\n * //Using callbacks\n * async.groupBy(files, detectFile, function(err, result) {\n * if(err) {\n * console.log(err);\n * } else {\n *\t console.log(result);\n * // {\n * // file: [ 'dir1/file1.txt' ],\n * // none: [ 'dir4' ],\n * // directory: [ 'dir2']\n * // }\n * // result is object containing the files grouped by type\n * }\n * });\n *\n * // Using Promises\n * async.groupBy(files, detectFile)\n * .then( result => {\n * console.log(result);\n * // {\n * // file: [ 'dir1/file1.txt' ],\n * // none: [ 'dir4' ],\n * // directory: [ 'dir2']\n * // }\n * // result is object containing the files grouped by type\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.groupBy(files, detectFile);\n * console.log(result);\n * // {\n * // file: [ 'dir1/file1.txt' ],\n * // none: [ 'dir4' ],\n * // directory: [ 'dir2']\n * // }\n * // result is object containing the files grouped by type\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction groupBy (coll, iteratee, callback) {\n return groupByLimit$1(coll, Infinity, iteratee, callback)\n}\n\n/**\n * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.\n *\n * @name groupBySeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.groupBy]{@link module:Collections.groupBy}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a `key` to group the value under.\n * Invoked with (value, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Result is an `Object` whose\n * properties are arrays of values which returned the corresponding key.\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction groupBySeries (coll, iteratee, callback) {\n return groupByLimit$1(coll, 1, iteratee, callback)\n}\n\n/**\n * Logs the result of an `async` function to the `console`. Only works in\n * Node.js or in browsers that support `console.log` and `console.error` (such\n * as FF and Chrome). If multiple arguments are returned from the async\n * function, `console.log` is called on each argument in order.\n *\n * @name log\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} function - The function you want to eventually apply\n * all arguments to.\n * @param {...*} arguments... - Any number of arguments to apply to the function.\n * @example\n *\n * // in a module\n * var hello = function(name, callback) {\n * setTimeout(function() {\n * callback(null, 'hello ' + name);\n * }, 1000);\n * };\n *\n * // in the node repl\n * node> async.log(hello, 'world');\n * 'hello world'\n */\nvar log = consoleFunc('log');\n\n/**\n * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name mapValuesLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.mapValues]{@link module:Collections.mapValues}\n * @category Collection\n * @param {Object} obj - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - A function to apply to each value and key\n * in `coll`.\n * The iteratee should complete with the transformed value as its result.\n * Invoked with (value, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. `result` is a new object consisting\n * of each key from `obj`, with each transformed value on the right-hand side.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction mapValuesLimit(obj, limit, iteratee, callback) {\n callback = once(callback);\n var newObj = {};\n var _iteratee = wrapAsync(iteratee);\n return eachOfLimit(limit)(obj, (val, key, next) => {\n _iteratee(val, key, (err, result) => {\n if (err) return next(err);\n newObj[key] = result;\n next(err);\n });\n }, err => callback(err, newObj));\n}\n\nvar mapValuesLimit$1 = awaitify(mapValuesLimit, 4);\n\n/**\n * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.\n *\n * Produces a new Object by mapping each value of `obj` through the `iteratee`\n * function. The `iteratee` is called each `value` and `key` from `obj` and a\n * callback for when it has finished processing. Each of these callbacks takes\n * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`\n * passes an error to its callback, the main `callback` (for the `mapValues`\n * function) is immediately called with the error.\n *\n * Note, the order of the keys in the result is not guaranteed. The keys will\n * be roughly in the order they complete, (but this is very engine-specific)\n *\n * @name mapValues\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Object} obj - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each value and key\n * in `coll`.\n * The iteratee should complete with the transformed value as its result.\n * Invoked with (value, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. `result` is a new object consisting\n * of each key from `obj`, with each transformed value on the right-hand side.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // file1.txt is a file that is 1000 bytes in size\n * // file2.txt is a file that is 2000 bytes in size\n * // file3.txt is a file that is 3000 bytes in size\n * // file4.txt does not exist\n *\n * const fileMap = {\n * f1: 'file1.txt',\n * f2: 'file2.txt',\n * f3: 'file3.txt'\n * };\n *\n * const withMissingFileMap = {\n * f1: 'file1.txt',\n * f2: 'file2.txt',\n * f3: 'file4.txt'\n * };\n *\n * // asynchronous function that returns the file size in bytes\n * function getFileSizeInBytes(file, key, callback) {\n * fs.stat(file, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * callback(null, stat.size);\n * });\n * }\n *\n * // Using callbacks\n * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(result);\n * // result is now a map of file size in bytes for each file, e.g.\n * // {\n * // f1: 1000,\n * // f2: 2000,\n * // f3: 3000\n * // }\n * }\n * });\n *\n * // Error handling\n * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) {\n * if (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * } else {\n * console.log(result);\n * }\n * });\n *\n * // Using Promises\n * async.mapValues(fileMap, getFileSizeInBytes)\n * .then( result => {\n * console.log(result);\n * // result is now a map of file size in bytes for each file, e.g.\n * // {\n * // f1: 1000,\n * // f2: 2000,\n * // f3: 3000\n * // }\n * }).catch (err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.mapValues(withMissingFileMap, getFileSizeInBytes)\n * .then( result => {\n * console.log(result);\n * }).catch (err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.mapValues(fileMap, getFileSizeInBytes);\n * console.log(result);\n * // result is now a map of file size in bytes for each file, e.g.\n * // {\n * // f1: 1000,\n * // f2: 2000,\n * // f3: 3000\n * // }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes);\n * console.log(result);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * }\n * }\n *\n */\nfunction mapValues(obj, iteratee, callback) {\n return mapValuesLimit$1(obj, Infinity, iteratee, callback)\n}\n\n/**\n * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.\n *\n * @name mapValuesSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.mapValues]{@link module:Collections.mapValues}\n * @category Collection\n * @param {Object} obj - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each value and key\n * in `coll`.\n * The iteratee should complete with the transformed value as its result.\n * Invoked with (value, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. `result` is a new object consisting\n * of each key from `obj`, with each transformed value on the right-hand side.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction mapValuesSeries(obj, iteratee, callback) {\n return mapValuesLimit$1(obj, 1, iteratee, callback)\n}\n\n/**\n * Caches the results of an async function. When creating a hash to store\n * function results against, the callback is omitted from the hash and an\n * optional hash function can be used.\n *\n * **Note: if the async function errs, the result will not be cached and\n * subsequent calls will call the wrapped function.**\n *\n * If no hash function is specified, the first argument is used as a hash key,\n * which may work reasonably if it is a string or a data type that converts to a\n * distinct string. Note that objects and arrays will not behave reasonably.\n * Neither will cases where the other arguments are significant. In such cases,\n * specify your own hash function.\n *\n * The cache of results is exposed as the `memo` property of the function\n * returned by `memoize`.\n *\n * @name memoize\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} fn - The async function to proxy and cache results from.\n * @param {Function} hasher - An optional function for generating a custom hash\n * for storing results. It has all the arguments applied to it apart from the\n * callback, and must be synchronous.\n * @returns {AsyncFunction} a memoized version of `fn`\n * @example\n *\n * var slow_fn = function(name, callback) {\n * // do something\n * callback(null, result);\n * };\n * var fn = async.memoize(slow_fn);\n *\n * // fn can now be used as if it were slow_fn\n * fn('some name', function() {\n * // callback\n * });\n */\nfunction memoize(fn, hasher = v => v) {\n var memo = Object.create(null);\n var queues = Object.create(null);\n var _fn = wrapAsync(fn);\n var memoized = initialParams((args, callback) => {\n var key = hasher(...args);\n if (key in memo) {\n setImmediate$1(() => callback(null, ...memo[key]));\n } else if (key in queues) {\n queues[key].push(callback);\n } else {\n queues[key] = [callback];\n _fn(...args, (err, ...resultArgs) => {\n // #1465 don't memoize if an error occurred\n if (!err) {\n memo[key] = resultArgs;\n }\n var q = queues[key];\n delete queues[key];\n for (var i = 0, l = q.length; i < l; i++) {\n q[i](err, ...resultArgs);\n }\n });\n }\n });\n memoized.memo = memo;\n memoized.unmemoized = fn;\n return memoized;\n}\n\n/**\n * Calls `callback` on a later loop around the event loop. In Node.js this just\n * calls `process.nextTick`. In the browser it will use `setImmediate` if\n * available, otherwise `setTimeout(callback, 0)`, which means other higher\n * priority events may precede the execution of `callback`.\n *\n * This is used internally for browser-compatibility purposes.\n *\n * @name nextTick\n * @static\n * @memberOf module:Utils\n * @method\n * @see [async.setImmediate]{@link module:Utils.setImmediate}\n * @category Util\n * @param {Function} callback - The function to call on a later loop around\n * the event loop. Invoked with (args...).\n * @param {...*} args... - any number of additional arguments to pass to the\n * callback on the next tick.\n * @example\n *\n * var call_order = [];\n * async.nextTick(function() {\n * call_order.push('two');\n * // call_order now equals ['one','two']\n * });\n * call_order.push('one');\n *\n * async.setImmediate(function (a, b, c) {\n * // a, b, and c equal 1, 2, and 3\n * }, 1, 2, 3);\n */\nvar _defer$1;\n\nif (hasNextTick) {\n _defer$1 = process.nextTick;\n} else if (hasSetImmediate) {\n _defer$1 = setImmediate;\n} else {\n _defer$1 = fallback;\n}\n\nvar nextTick = wrap(_defer$1);\n\nvar _parallel = awaitify((eachfn, tasks, callback) => {\n var results = isArrayLike(tasks) ? [] : {};\n\n eachfn(tasks, (task, key, taskCb) => {\n wrapAsync(task)((err, ...result) => {\n if (result.length < 2) {\n [result] = result;\n }\n results[key] = result;\n taskCb(err);\n });\n }, err => callback(err, results));\n}, 3);\n\n/**\n * Run the `tasks` collection of functions in parallel, without waiting until\n * the previous function has completed. If any of the functions pass an error to\n * its callback, the main `callback` is immediately called with the value of the\n * error. Once the `tasks` have completed, the results are passed to the final\n * `callback` as an array.\n *\n * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about\n * parallel execution of code. If your tasks do not use any timers or perform\n * any I/O, they will actually be executed in series. Any synchronous setup\n * sections for each task will happen one after the other. JavaScript remains\n * single-threaded.\n *\n * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the\n * execution of other tasks when a task fails.\n *\n * It is also possible to use an object instead of an array. Each property will\n * be run as a function and the results will be passed to the final `callback`\n * as an object instead of an array. This can be a more readable way of handling\n * results from {@link async.parallel}.\n *\n * @name parallel\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of\n * [async functions]{@link AsyncFunction} to run.\n * Each async function can complete with any number of optional `result` values.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed successfully. This function gets a results array\n * (or object) containing all the result arguments passed to the task callbacks.\n * Invoked with (err, results).\n * @returns {Promise} a promise, if a callback is not passed\n *\n * @example\n *\n * //Using Callbacks\n * async.parallel([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ], function(err, results) {\n * console.log(results);\n * // results is equal to ['one','two'] even though\n * // the second function had a shorter timeout.\n * });\n *\n * // an example using an object instead of an array\n * async.parallel({\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * callback(null, 2);\n * }, 100);\n * }\n * }, function(err, results) {\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * });\n *\n * //Using Promises\n * async.parallel([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ]).then(results => {\n * console.log(results);\n * // results is equal to ['one','two'] even though\n * // the second function had a shorter timeout.\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // an example using an object instead of an array\n * async.parallel({\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * callback(null, 2);\n * }, 100);\n * }\n * }).then(results => {\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * //Using async/await\n * async () => {\n * try {\n * let results = await async.parallel([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ]);\n * console.log(results);\n * // results is equal to ['one','two'] even though\n * // the second function had a shorter timeout.\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // an example using an object instead of an array\n * async () => {\n * try {\n * let results = await async.parallel({\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * callback(null, 2);\n * }, 100);\n * }\n * });\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction parallel(tasks, callback) {\n return _parallel(eachOf$1, tasks, callback);\n}\n\n/**\n * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name parallelLimit\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.parallel]{@link module:ControlFlow.parallel}\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of\n * [async functions]{@link AsyncFunction} to run.\n * Each async function can complete with any number of optional `result` values.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed successfully. This function gets a results array\n * (or object) containing all the result arguments passed to the task callbacks.\n * Invoked with (err, results).\n * @returns {Promise} a promise, if a callback is not passed\n */\nfunction parallelLimit(tasks, limit, callback) {\n return _parallel(eachOfLimit(limit), tasks, callback);\n}\n\n/**\n * A queue of tasks for the worker function to complete.\n * @typedef {Iterable} QueueObject\n * @memberOf module:ControlFlow\n * @property {Function} length - a function returning the number of items\n * waiting to be processed. Invoke with `queue.length()`.\n * @property {boolean} started - a boolean indicating whether or not any\n * items have been pushed and processed by the queue.\n * @property {Function} running - a function returning the number of items\n * currently being processed. Invoke with `queue.running()`.\n * @property {Function} workersList - a function returning the array of items\n * currently being processed. Invoke with `queue.workersList()`.\n * @property {Function} idle - a function returning false if there are items\n * waiting or being processed, or true if not. Invoke with `queue.idle()`.\n * @property {number} concurrency - an integer for determining how many `worker`\n * functions should be run in parallel. This property can be changed after a\n * `queue` is created to alter the concurrency on-the-fly.\n * @property {number} payload - an integer that specifies how many items are\n * passed to the worker function at a time. only applies if this is a\n * [cargo]{@link module:ControlFlow.cargo} object\n * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`\n * once the `worker` has finished processing the task. Instead of a single task,\n * a `tasks` array can be submitted. The respective callback is used for every\n * task in the list. Invoke with `queue.push(task, [callback])`,\n * @property {AsyncFunction} unshift - add a new task to the front of the `queue`.\n * Invoke with `queue.unshift(task, [callback])`.\n * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns\n * a promise that rejects if an error occurs.\n * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns\n * a promise that rejects if an error occurs.\n * @property {Function} remove - remove items from the queue that match a test\n * function. The test function will be passed an object with a `data` property,\n * and a `priority` property, if this is a\n * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.\n * Invoked with `queue.remove(testFn)`, where `testFn` is of the form\n * `function ({data, priority}) {}` and returns a Boolean.\n * @property {Function} saturated - a function that sets a callback that is\n * called when the number of running workers hits the `concurrency` limit, and\n * further tasks will be queued. If the callback is omitted, `q.saturated()`\n * returns a promise for the next occurrence.\n * @property {Function} unsaturated - a function that sets a callback that is\n * called when the number of running workers is less than the `concurrency` &\n * `buffer` limits, and further tasks will not be queued. If the callback is\n * omitted, `q.unsaturated()` returns a promise for the next occurrence.\n * @property {number} buffer - A minimum threshold buffer in order to say that\n * the `queue` is `unsaturated`.\n * @property {Function} empty - a function that sets a callback that is called\n * when the last item from the `queue` is given to a `worker`. If the callback\n * is omitted, `q.empty()` returns a promise for the next occurrence.\n * @property {Function} drain - a function that sets a callback that is called\n * when the last item from the `queue` has returned from the `worker`. If the\n * callback is omitted, `q.drain()` returns a promise for the next occurrence.\n * @property {Function} error - a function that sets a callback that is called\n * when a task errors. Has the signature `function(error, task)`. If the\n * callback is omitted, `error()` returns a promise that rejects on the next\n * error.\n * @property {boolean} paused - a boolean for determining whether the queue is\n * in a paused state.\n * @property {Function} pause - a function that pauses the processing of tasks\n * until `resume()` is called. Invoke with `queue.pause()`.\n * @property {Function} resume - a function that resumes the processing of\n * queued tasks when the queue is paused. Invoke with `queue.resume()`.\n * @property {Function} kill - a function that removes the `drain` callback and\n * empties remaining tasks from the queue forcing it to go idle. No more tasks\n * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.\n *\n * @example\n * const q = async.queue(worker, 2)\n * q.push(item1)\n * q.push(item2)\n * q.push(item3)\n * // queues are iterable, spread into an array to inspect\n * const items = [...q] // [item1, item2, item3]\n * // or use for of\n * for (let item of q) {\n * console.log(item)\n * }\n *\n * q.drain(() => {\n * console.log('all done')\n * })\n * // or\n * await q.drain()\n */\n\n/**\n * Creates a `queue` object with the specified `concurrency`. Tasks added to the\n * `queue` are processed in parallel (up to the `concurrency` limit). If all\n * `worker`s are in progress, the task is queued until one becomes available.\n * Once a `worker` completes a `task`, that `task`'s callback is called.\n *\n * @name queue\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {AsyncFunction} worker - An async function for processing a queued task.\n * If you want to handle errors from an individual task, pass a callback to\n * `q.push()`. Invoked with (task, callback).\n * @param {number} [concurrency=1] - An `integer` for determining how many\n * `worker` functions should be run in parallel. If omitted, the concurrency\n * defaults to `1`. If the concurrency is `0`, an error is thrown.\n * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be\n * attached as certain properties to listen for specific events during the\n * lifecycle of the queue.\n * @example\n *\n * // create a queue object with concurrency 2\n * var q = async.queue(function(task, callback) {\n * console.log('hello ' + task.name);\n * callback();\n * }, 2);\n *\n * // assign a callback\n * q.drain(function() {\n * console.log('all items have been processed');\n * });\n * // or await the end\n * await q.drain()\n *\n * // assign an error callback\n * q.error(function(err, task) {\n * console.error('task experienced an error');\n * });\n *\n * // add some items to the queue\n * q.push({name: 'foo'}, function(err) {\n * console.log('finished processing foo');\n * });\n * // callback is optional\n * q.push({name: 'bar'});\n *\n * // add some items to the queue (batch-wise)\n * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {\n * console.log('finished processing item');\n * });\n *\n * // add some items to the front of the queue\n * q.unshift({name: 'bar'}, function (err) {\n * console.log('finished processing bar');\n * });\n */\nfunction queue$1 (worker, concurrency) {\n var _worker = wrapAsync(worker);\n return queue((items, cb) => {\n _worker(items[0], cb);\n }, concurrency, 1);\n}\n\n// Binary min-heap implementation used for priority queue.\n// Implementation is stable, i.e. push time is considered for equal priorities\nclass Heap {\n constructor() {\n this.heap = [];\n this.pushCount = Number.MIN_SAFE_INTEGER;\n }\n\n get length() {\n return this.heap.length;\n }\n\n empty () {\n this.heap = [];\n return this;\n }\n\n percUp(index) {\n let p;\n\n while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) {\n let t = this.heap[index];\n this.heap[index] = this.heap[p];\n this.heap[p] = t;\n\n index = p;\n }\n }\n\n percDown(index) {\n let l;\n\n while ((l=leftChi(index)) < this.heap.length) {\n if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) {\n l = l+1;\n }\n\n if (smaller(this.heap[index], this.heap[l])) {\n break;\n }\n\n let t = this.heap[index];\n this.heap[index] = this.heap[l];\n this.heap[l] = t;\n\n index = l;\n }\n }\n\n push(node) {\n node.pushCount = ++this.pushCount;\n this.heap.push(node);\n this.percUp(this.heap.length-1);\n }\n\n unshift(node) {\n return this.heap.push(node);\n }\n\n shift() {\n let [top] = this.heap;\n\n this.heap[0] = this.heap[this.heap.length-1];\n this.heap.pop();\n this.percDown(0);\n\n return top;\n }\n\n toArray() {\n return [...this];\n }\n\n *[Symbol.iterator] () {\n for (let i = 0; i < this.heap.length; i++) {\n yield this.heap[i].data;\n }\n }\n\n remove (testFn) {\n let j = 0;\n for (let i = 0; i < this.heap.length; i++) {\n if (!testFn(this.heap[i])) {\n this.heap[j] = this.heap[i];\n j++;\n }\n }\n\n this.heap.splice(j);\n\n for (let i = parent(this.heap.length-1); i >= 0; i--) {\n this.percDown(i);\n }\n\n return this;\n }\n}\n\nfunction leftChi(i) {\n return (i<<1)+1;\n}\n\nfunction parent(i) {\n return ((i+1)>>1)-1;\n}\n\nfunction smaller(x, y) {\n if (x.priority !== y.priority) {\n return x.priority < y.priority;\n }\n else {\n return x.pushCount < y.pushCount;\n }\n}\n\n/**\n * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and\n * completed in ascending priority order.\n *\n * @name priorityQueue\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.queue]{@link module:ControlFlow.queue}\n * @category Control Flow\n * @param {AsyncFunction} worker - An async function for processing a queued task.\n * If you want to handle errors from an individual task, pass a callback to\n * `q.push()`.\n * Invoked with (task, callback).\n * @param {number} concurrency - An `integer` for determining how many `worker`\n * functions should be run in parallel. If omitted, the concurrency defaults to\n * `1`. If the concurrency is `0`, an error is thrown.\n * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two\n * differences between `queue` and `priorityQueue` objects:\n * * `push(task, priority, [callback])` - `priority` should be a number. If an\n * array of `tasks` is given, all tasks will be assigned the same priority.\n * * The `unshift` method was removed.\n */\nfunction priorityQueue(worker, concurrency) {\n // Start with a normal queue\n var q = queue$1(worker, concurrency);\n var processingScheduled = false;\n\n q._tasks = new Heap();\n\n // Override push to accept second parameter representing priority\n q.push = function(data, priority = 0, callback = () => {}) {\n if (typeof callback !== 'function') {\n throw new Error('task callback must be a function');\n }\n q.started = true;\n if (!Array.isArray(data)) {\n data = [data];\n }\n if (data.length === 0 && q.idle()) {\n // call drain immediately if there are no tasks\n return setImmediate$1(() => q.drain());\n }\n\n for (var i = 0, l = data.length; i < l; i++) {\n var item = {\n data: data[i],\n priority,\n callback\n };\n\n q._tasks.push(item);\n }\n\n if (!processingScheduled) {\n processingScheduled = true;\n setImmediate$1(() => {\n processingScheduled = false;\n q.process();\n });\n }\n };\n\n // Remove unshift function\n delete q.unshift;\n\n return q;\n}\n\n/**\n * Runs the `tasks` array of functions in parallel, without waiting until the\n * previous function has completed. Once any of the `tasks` complete or pass an\n * error to its callback, the main `callback` is immediately called. It's\n * equivalent to `Promise.race()`.\n *\n * @name race\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}\n * to run. Each function can complete with an optional `result` value.\n * @param {Function} callback - A callback to run once any of the functions have\n * completed. This function gets an error or result from the first function that\n * completed. Invoked with (err, result).\n * @returns undefined\n * @example\n *\n * async.race([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ],\n * // main callback\n * function(err, result) {\n * // the result will be equal to 'two' as it finishes earlier\n * });\n */\nfunction race(tasks, callback) {\n callback = once(callback);\n if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));\n if (!tasks.length) return callback();\n for (var i = 0, l = tasks.length; i < l; i++) {\n wrapAsync(tasks[i])(callback);\n }\n}\n\nvar race$1 = awaitify(race, 2);\n\n/**\n * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.\n *\n * @name reduceRight\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.reduce]{@link module:Collections.reduce}\n * @alias foldr\n * @category Collection\n * @param {Array} array - A collection to iterate over.\n * @param {*} memo - The initial state of the reduction.\n * @param {AsyncFunction} iteratee - A function applied to each item in the\n * array to produce the next step in the reduction.\n * The `iteratee` should complete with the next state of the reduction.\n * If the iteratee completes with an error, the reduction is stopped and the\n * main `callback` is immediately called with the error.\n * Invoked with (memo, item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result is the reduced value. Invoked with\n * (err, result).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction reduceRight (array, memo, iteratee, callback) {\n var reversed = [...array].reverse();\n return reduce$1(reversed, memo, iteratee, callback);\n}\n\n/**\n * Wraps the async function in another function that always completes with a\n * result object, even when it errors.\n *\n * The result object has either the property `error` or `value`.\n *\n * @name reflect\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} fn - The async function you want to wrap\n * @returns {Function} - A function that always passes null to it's callback as\n * the error. The second argument to the callback will be an `object` with\n * either an `error` or a `value` property.\n * @example\n *\n * async.parallel([\n * async.reflect(function(callback) {\n * // do some stuff ...\n * callback(null, 'one');\n * }),\n * async.reflect(function(callback) {\n * // do some more stuff but error ...\n * callback('bad stuff happened');\n * }),\n * async.reflect(function(callback) {\n * // do some more stuff ...\n * callback(null, 'two');\n * })\n * ],\n * // optional callback\n * function(err, results) {\n * // values\n * // results[0].value = 'one'\n * // results[1].error = 'bad stuff happened'\n * // results[2].value = 'two'\n * });\n */\nfunction reflect(fn) {\n var _fn = wrapAsync(fn);\n return initialParams(function reflectOn(args, reflectCallback) {\n args.push((error, ...cbArgs) => {\n let retVal = {};\n if (error) {\n retVal.error = error;\n }\n if (cbArgs.length > 0){\n var value = cbArgs;\n if (cbArgs.length <= 1) {\n [value] = cbArgs;\n }\n retVal.value = value;\n }\n reflectCallback(null, retVal);\n });\n\n return _fn.apply(this, args);\n });\n}\n\n/**\n * A helper function that wraps an array or an object of functions with `reflect`.\n *\n * @name reflectAll\n * @static\n * @memberOf module:Utils\n * @method\n * @see [async.reflect]{@link module:Utils.reflect}\n * @category Util\n * @param {Array|Object|Iterable} tasks - The collection of\n * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.\n * @returns {Array} Returns an array of async functions, each wrapped in\n * `async.reflect`\n * @example\n *\n * let tasks = [\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * // do some more stuff but error ...\n * callback(new Error('bad stuff happened'));\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ];\n *\n * async.parallel(async.reflectAll(tasks),\n * // optional callback\n * function(err, results) {\n * // values\n * // results[0].value = 'one'\n * // results[1].error = Error('bad stuff happened')\n * // results[2].value = 'two'\n * });\n *\n * // an example using an object instead of an array\n * let tasks = {\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * two: function(callback) {\n * callback('two');\n * },\n * three: function(callback) {\n * setTimeout(function() {\n * callback(null, 'three');\n * }, 100);\n * }\n * };\n *\n * async.parallel(async.reflectAll(tasks),\n * // optional callback\n * function(err, results) {\n * // values\n * // results.one.value = 'one'\n * // results.two.error = 'two'\n * // results.three.value = 'three'\n * });\n */\nfunction reflectAll(tasks) {\n var results;\n if (Array.isArray(tasks)) {\n results = tasks.map(reflect);\n } else {\n results = {};\n Object.keys(tasks).forEach(key => {\n results[key] = reflect.call(this, tasks[key]);\n });\n }\n return results;\n}\n\nfunction reject(eachfn, arr, _iteratee, callback) {\n const iteratee = wrapAsync(_iteratee);\n return _filter(eachfn, arr, (value, cb) => {\n iteratee(value, (err, v) => {\n cb(err, !v);\n });\n }, callback);\n}\n\n/**\n * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.\n *\n * @name reject\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.filter]{@link module:Collections.filter}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - An async truth test to apply to each item in\n * `coll`.\n * The should complete with a boolean value as its `result`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n *\n * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * // Using callbacks\n * async.reject(fileList, fileExists, function(err, results) {\n * // [ 'dir3/file6.txt' ]\n * // results now equals an array of the non-existing files\n * });\n *\n * // Using Promises\n * async.reject(fileList, fileExists)\n * .then( results => {\n * console.log(results);\n * // [ 'dir3/file6.txt' ]\n * // results now equals an array of the non-existing files\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let results = await async.reject(fileList, fileExists);\n * console.log(results);\n * // [ 'dir3/file6.txt' ]\n * // results now equals an array of the non-existing files\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction reject$1 (coll, iteratee, callback) {\n return reject(eachOf$1, coll, iteratee, callback)\n}\nvar reject$2 = awaitify(reject$1, 3);\n\n/**\n * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name rejectLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.reject]{@link module:Collections.reject}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} iteratee - An async truth test to apply to each item in\n * `coll`.\n * The should complete with a boolean value as its `result`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction rejectLimit (coll, limit, iteratee, callback) {\n return reject(eachOfLimit(limit), coll, iteratee, callback)\n}\nvar rejectLimit$1 = awaitify(rejectLimit, 4);\n\n/**\n * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.\n *\n * @name rejectSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.reject]{@link module:Collections.reject}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - An async truth test to apply to each item in\n * `coll`.\n * The should complete with a boolean value as its `result`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction rejectSeries (coll, iteratee, callback) {\n return reject(eachOfSeries$1, coll, iteratee, callback)\n}\nvar rejectSeries$1 = awaitify(rejectSeries, 3);\n\nfunction constant$1(value) {\n return function () {\n return value;\n }\n}\n\n/**\n * Attempts to get a successful response from `task` no more than `times` times\n * before returning an error. If the task is successful, the `callback` will be\n * passed the result of the successful task. If all attempts fail, the callback\n * will be passed the error and result (if any) of the final attempt.\n *\n * @name retry\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @see [async.retryable]{@link module:ControlFlow.retryable}\n * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an\n * object with `times` and `interval` or a number.\n * * `times` - The number of attempts to make before giving up. The default\n * is `5`.\n * * `interval` - The time to wait between retries, in milliseconds. The\n * default is `0`. The interval may also be specified as a function of the\n * retry count (see example).\n * * `errorFilter` - An optional synchronous function that is invoked on\n * erroneous result. If it returns `true` the retry attempts will continue;\n * if the function returns `false` the retry flow is aborted with the current\n * attempt's error and result being returned to the final callback.\n * Invoked with (err).\n * * If `opts` is a number, the number specifies the number of times to retry,\n * with the default interval of `0`.\n * @param {AsyncFunction} task - An async function to retry.\n * Invoked with (callback).\n * @param {Function} [callback] - An optional callback which is called when the\n * task has succeeded, or after the final failed attempt. It receives the `err`\n * and `result` arguments of the last attempt at completing the `task`. Invoked\n * with (err, results).\n * @returns {Promise} a promise if no callback provided\n *\n * @example\n *\n * // The `retry` function can be used as a stand-alone control flow by passing\n * // a callback, as shown below:\n *\n * // try calling apiMethod 3 times\n * async.retry(3, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod 3 times, waiting 200 ms between each retry\n * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod 10 times with exponential backoff\n * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)\n * async.retry({\n * times: 10,\n * interval: function(retryCount) {\n * return 50 * Math.pow(2, retryCount);\n * }\n * }, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod the default 5 times no delay between each retry\n * async.retry(apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod only when error condition satisfies, all other\n * // errors will abort the retry control flow and return to final callback\n * async.retry({\n * errorFilter: function(err) {\n * return err.message === 'Temporary error'; // only retry on a specific error\n * }\n * }, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // to retry individual methods that are not as reliable within other\n * // control flow functions, use the `retryable` wrapper:\n * async.auto({\n * users: api.getUsers.bind(api),\n * payments: async.retryable(3, api.getPayments.bind(api))\n * }, function(err, results) {\n * // do something with the results\n * });\n *\n */\nconst DEFAULT_TIMES = 5;\nconst DEFAULT_INTERVAL = 0;\n\nfunction retry(opts, task, callback) {\n var options = {\n times: DEFAULT_TIMES,\n intervalFunc: constant$1(DEFAULT_INTERVAL)\n };\n\n if (arguments.length < 3 && typeof opts === 'function') {\n callback = task || promiseCallback();\n task = opts;\n } else {\n parseTimes(options, opts);\n callback = callback || promiseCallback();\n }\n\n if (typeof task !== 'function') {\n throw new Error(\"Invalid arguments for async.retry\");\n }\n\n var _task = wrapAsync(task);\n\n var attempt = 1;\n function retryAttempt() {\n _task((err, ...args) => {\n if (err === false) return\n if (err && attempt++ < options.times &&\n (typeof options.errorFilter != 'function' ||\n options.errorFilter(err))) {\n setTimeout(retryAttempt, options.intervalFunc(attempt - 1));\n } else {\n callback(err, ...args);\n }\n });\n }\n\n retryAttempt();\n return callback[PROMISE_SYMBOL]\n}\n\nfunction parseTimes(acc, t) {\n if (typeof t === 'object') {\n acc.times = +t.times || DEFAULT_TIMES;\n\n acc.intervalFunc = typeof t.interval === 'function' ?\n t.interval :\n constant$1(+t.interval || DEFAULT_INTERVAL);\n\n acc.errorFilter = t.errorFilter;\n } else if (typeof t === 'number' || typeof t === 'string') {\n acc.times = +t || DEFAULT_TIMES;\n } else {\n throw new Error(\"Invalid arguments for async.retry\");\n }\n}\n\n/**\n * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method\n * wraps a task and makes it retryable, rather than immediately calling it\n * with retries.\n *\n * @name retryable\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.retry]{@link module:ControlFlow.retry}\n * @category Control Flow\n * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional\n * options, exactly the same as from `retry`, except for a `opts.arity` that\n * is the arity of the `task` function, defaulting to `task.length`\n * @param {AsyncFunction} task - the asynchronous function to wrap.\n * This function will be passed any arguments passed to the returned wrapper.\n * Invoked with (...args, callback).\n * @returns {AsyncFunction} The wrapped function, which when invoked, will\n * retry on an error, based on the parameters specified in `opts`.\n * This function will accept the same parameters as `task`.\n * @example\n *\n * async.auto({\n * dep1: async.retryable(3, getFromFlakyService),\n * process: [\"dep1\", async.retryable(3, function (results, cb) {\n * maybeProcessData(results.dep1, cb);\n * })]\n * }, callback);\n */\nfunction retryable (opts, task) {\n if (!task) {\n task = opts;\n opts = null;\n }\n let arity = (opts && opts.arity) || task.length;\n if (isAsync(task)) {\n arity += 1;\n }\n var _task = wrapAsync(task);\n return initialParams((args, callback) => {\n if (args.length < arity - 1 || callback == null) {\n args.push(callback);\n callback = promiseCallback();\n }\n function taskFn(cb) {\n _task(...args, cb);\n }\n\n if (opts) retry(opts, taskFn, callback);\n else retry(taskFn, callback);\n\n return callback[PROMISE_SYMBOL]\n });\n}\n\n/**\n * Run the functions in the `tasks` collection in series, each one running once\n * the previous function has completed. If any functions in the series pass an\n * error to its callback, no more functions are run, and `callback` is\n * immediately called with the value of the error. Otherwise, `callback`\n * receives an array of results when `tasks` have completed.\n *\n * It is also possible to use an object instead of an array. Each property will\n * be run as a function, and the results will be passed to the final `callback`\n * as an object instead of an array. This can be a more readable way of handling\n * results from {@link async.series}.\n *\n * **Note** that while many implementations preserve the order of object\n * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)\n * explicitly states that\n *\n * > The mechanics and order of enumerating the properties is not specified.\n *\n * So if you rely on the order in which your series of functions are executed,\n * and want this to work on all platforms, consider using an array.\n *\n * @name series\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing\n * [async functions]{@link AsyncFunction} to run in series.\n * Each function can complete with any number of optional `result` values.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed. This function gets a results array (or object)\n * containing all the result arguments passed to the `task` callbacks. Invoked\n * with (err, result).\n * @return {Promise} a promise, if no callback is passed\n * @example\n *\n * //Using Callbacks\n * async.series([\n * function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 'two');\n * }, 100);\n * }\n * ], function(err, results) {\n * console.log(results);\n * // results is equal to ['one','two']\n * });\n *\n * // an example using objects instead of arrays\n * async.series({\n * one: function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 2);\n * }, 100);\n * }\n * }, function(err, results) {\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * });\n *\n * //Using Promises\n * async.series([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ]).then(results => {\n * console.log(results);\n * // results is equal to ['one','two']\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // an example using an object instead of an array\n * async.series({\n * one: function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 2);\n * }, 100);\n * }\n * }).then(results => {\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * //Using async/await\n * async () => {\n * try {\n * let results = await async.series([\n * function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 'two');\n * }, 100);\n * }\n * ]);\n * console.log(results);\n * // results is equal to ['one','two']\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // an example using an object instead of an array\n * async () => {\n * try {\n * let results = await async.parallel({\n * one: function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 2);\n * }, 100);\n * }\n * });\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction series(tasks, callback) {\n return _parallel(eachOfSeries$1, tasks, callback);\n}\n\n/**\n * Returns `true` if at least one element in the `coll` satisfies an async test.\n * If any iteratee call returns `true`, the main `callback` is immediately\n * called.\n *\n * @name some\n * @static\n * @memberOf module:Collections\n * @method\n * @alias any\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collections in parallel.\n * The iteratee should complete with a boolean `result` value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the iteratee functions have finished.\n * Result will be either `true` or `false` depending on the values of the async\n * tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * // Using callbacks\n * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,\n * function(err, result) {\n * console.log(result);\n * // true\n * // result is true since some file in the list exists\n * }\n *);\n *\n * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,\n * function(err, result) {\n * console.log(result);\n * // false\n * // result is false since none of the files exists\n * }\n *);\n *\n * // Using Promises\n * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)\n * .then( result => {\n * console.log(result);\n * // true\n * // result is true since some file in the list exists\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)\n * .then( result => {\n * console.log(result);\n * // false\n * // result is false since none of the files exists\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);\n * console.log(result);\n * // true\n * // result is true since some file in the list exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * async () => {\n * try {\n * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);\n * console.log(result);\n * // false\n * // result is false since none of the files exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction some(coll, iteratee, callback) {\n return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback)\n}\nvar some$1 = awaitify(some, 3);\n\n/**\n * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.\n *\n * @name someLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.some]{@link module:Collections.some}\n * @alias anyLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collections in parallel.\n * The iteratee should complete with a boolean `result` value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the iteratee functions have finished.\n * Result will be either `true` or `false` depending on the values of the async\n * tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction someLimit(coll, limit, iteratee, callback) {\n return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback)\n}\nvar someLimit$1 = awaitify(someLimit, 4);\n\n/**\n * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.\n *\n * @name someSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.some]{@link module:Collections.some}\n * @alias anySeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collections in series.\n * The iteratee should complete with a boolean `result` value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the iteratee functions have finished.\n * Result will be either `true` or `false` depending on the values of the async\n * tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction someSeries(coll, iteratee, callback) {\n return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback)\n}\nvar someSeries$1 = awaitify(someSeries, 3);\n\n/**\n * Sorts a list by the results of running each `coll` value through an async\n * `iteratee`.\n *\n * @name sortBy\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a value to use as the sort criteria as\n * its `result`.\n * Invoked with (item, callback).\n * @param {Function} callback - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is the items\n * from the original `coll` sorted by the values returned by the `iteratee`\n * calls. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback passed\n * @example\n *\n * // bigfile.txt is a file that is 251100 bytes in size\n * // mediumfile.txt is a file that is 11000 bytes in size\n * // smallfile.txt is a file that is 121 bytes in size\n *\n * // asynchronous function that returns the file size in bytes\n * function getFileSizeInBytes(file, callback) {\n * fs.stat(file, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * callback(null, stat.size);\n * });\n * }\n *\n * // Using callbacks\n * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,\n * function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']\n * }\n * }\n * );\n *\n * // By modifying the callback parameter the\n * // sorting order can be influenced:\n *\n * // ascending order\n * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {\n * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {\n * if (getFileSizeErr) return callback(getFileSizeErr);\n * callback(null, fileSize);\n * });\n * }, function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']\n * }\n * }\n * );\n *\n * // descending order\n * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) {\n * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {\n * if (getFileSizeErr) {\n * return callback(getFileSizeErr);\n * }\n * callback(null, fileSize * -1);\n * });\n * }, function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt']\n * }\n * }\n * );\n *\n * // Error handling\n * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes,\n * function(err, results) {\n * if (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * } else {\n * console.log(results);\n * }\n * }\n * );\n *\n * // Using Promises\n * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes)\n * .then( results => {\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Error handling\n * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes)\n * .then( results => {\n * console.log(results);\n * }).catch( err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * });\n *\n * // Using async/await\n * (async () => {\n * try {\n * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']\n * }\n * catch (err) {\n * console.log(err);\n * }\n * })();\n *\n * // Error handling\n * async () => {\n * try {\n * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);\n * console.log(results);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * }\n * }\n *\n */\nfunction sortBy (coll, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return map$1(coll, (x, iterCb) => {\n _iteratee(x, (err, criteria) => {\n if (err) return iterCb(err);\n iterCb(err, {value: x, criteria});\n });\n }, (err, results) => {\n if (err) return callback(err);\n callback(null, results.sort(comparator).map(v => v.value));\n });\n\n function comparator(left, right) {\n var a = left.criteria, b = right.criteria;\n return a < b ? -1 : a > b ? 1 : 0;\n }\n}\nvar sortBy$1 = awaitify(sortBy, 3);\n\n/**\n * Sets a time limit on an asynchronous function. If the function does not call\n * its callback within the specified milliseconds, it will be called with a\n * timeout error. The code property for the error object will be `'ETIMEDOUT'`.\n *\n * @name timeout\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} asyncFn - The async function to limit in time.\n * @param {number} milliseconds - The specified time limit.\n * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)\n * to timeout Error for more information..\n * @returns {AsyncFunction} Returns a wrapped function that can be used with any\n * of the control flow functions.\n * Invoke this function with the same parameters as you would `asyncFunc`.\n * @example\n *\n * function myFunction(foo, callback) {\n * doAsyncTask(foo, function(err, data) {\n * // handle errors\n * if (err) return callback(err);\n *\n * // do some stuff ...\n *\n * // return processed data\n * return callback(null, data);\n * });\n * }\n *\n * var wrapped = async.timeout(myFunction, 1000);\n *\n * // call `wrapped` as you would `myFunction`\n * wrapped({ bar: 'bar' }, function(err, data) {\n * // if `myFunction` takes < 1000 ms to execute, `err`\n * // and `data` will have their expected values\n *\n * // else `err` will be an Error with the code 'ETIMEDOUT'\n * });\n */\nfunction timeout(asyncFn, milliseconds, info) {\n var fn = wrapAsync(asyncFn);\n\n return initialParams((args, callback) => {\n var timedOut = false;\n var timer;\n\n function timeoutCallback() {\n var name = asyncFn.name || 'anonymous';\n var error = new Error('Callback function \"' + name + '\" timed out.');\n error.code = 'ETIMEDOUT';\n if (info) {\n error.info = info;\n }\n timedOut = true;\n callback(error);\n }\n\n args.push((...cbArgs) => {\n if (!timedOut) {\n callback(...cbArgs);\n clearTimeout(timer);\n }\n });\n\n // setup timer and call original function\n timer = setTimeout(timeoutCallback, milliseconds);\n fn(...args);\n });\n}\n\nfunction range(size) {\n var result = Array(size);\n while (size--) {\n result[size] = size;\n }\n return result;\n}\n\n/**\n * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name timesLimit\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.times]{@link module:ControlFlow.times}\n * @category Control Flow\n * @param {number} count - The number of times to run the function.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - The async function to call `n` times.\n * Invoked with the iteration index and a callback: (n, next).\n * @param {Function} callback - see [async.map]{@link module:Collections.map}.\n * @returns {Promise} a promise, if no callback is provided\n */\nfunction timesLimit(count, limit, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return mapLimit$1(range(count), limit, _iteratee, callback);\n}\n\n/**\n * Calls the `iteratee` function `n` times, and accumulates results in the same\n * manner you would use with [map]{@link module:Collections.map}.\n *\n * @name times\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Control Flow\n * @param {number} n - The number of times to run the function.\n * @param {AsyncFunction} iteratee - The async function to call `n` times.\n * Invoked with the iteration index and a callback: (n, next).\n * @param {Function} callback - see {@link module:Collections.map}.\n * @returns {Promise} a promise, if no callback is provided\n * @example\n *\n * // Pretend this is some complicated async factory\n * var createUser = function(id, callback) {\n * callback(null, {\n * id: 'user' + id\n * });\n * };\n *\n * // generate 5 users\n * async.times(5, function(n, next) {\n * createUser(n, function(err, user) {\n * next(err, user);\n * });\n * }, function(err, users) {\n * // we should now have 5 users\n * });\n */\nfunction times (n, iteratee, callback) {\n return timesLimit(n, Infinity, iteratee, callback)\n}\n\n/**\n * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.\n *\n * @name timesSeries\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.times]{@link module:ControlFlow.times}\n * @category Control Flow\n * @param {number} n - The number of times to run the function.\n * @param {AsyncFunction} iteratee - The async function to call `n` times.\n * Invoked with the iteration index and a callback: (n, next).\n * @param {Function} callback - see {@link module:Collections.map}.\n * @returns {Promise} a promise, if no callback is provided\n */\nfunction timesSeries (n, iteratee, callback) {\n return timesLimit(n, 1, iteratee, callback)\n}\n\n/**\n * A relative of `reduce`. Takes an Object or Array, and iterates over each\n * element in parallel, each step potentially mutating an `accumulator` value.\n * The type of the accumulator defaults to the type of collection passed in.\n *\n * @name transform\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {*} [accumulator] - The initial state of the transform. If omitted,\n * it will default to an empty Object or Array, depending on the type of `coll`\n * @param {AsyncFunction} iteratee - A function applied to each item in the\n * collection that potentially modifies the accumulator.\n * Invoked with (accumulator, item, key, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result is the transformed accumulator.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * // file1.txt is a file that is 1000 bytes in size\n * // file2.txt is a file that is 2000 bytes in size\n * // file3.txt is a file that is 3000 bytes in size\n *\n * // helper function that returns human-readable size format from bytes\n * function formatBytes(bytes, decimals = 2) {\n * // implementation not included for brevity\n * return humanReadbleFilesize;\n * }\n *\n * const fileList = ['file1.txt','file2.txt','file3.txt'];\n *\n * // asynchronous function that returns the file size, transformed to human-readable format\n * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.\n * function transformFileSize(acc, value, key, callback) {\n * fs.stat(value, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * acc[key] = formatBytes(stat.size);\n * callback(null);\n * });\n * }\n *\n * // Using callbacks\n * async.transform(fileList, transformFileSize, function(err, result) {\n * if(err) {\n * console.log(err);\n * } else {\n * console.log(result);\n * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]\n * }\n * });\n *\n * // Using Promises\n * async.transform(fileList, transformFileSize)\n * .then(result => {\n * console.log(result);\n * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * (async () => {\n * try {\n * let result = await async.transform(fileList, transformFileSize);\n * console.log(result);\n * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]\n * }\n * catch (err) {\n * console.log(err);\n * }\n * })();\n *\n * @example\n *\n * // file1.txt is a file that is 1000 bytes in size\n * // file2.txt is a file that is 2000 bytes in size\n * // file3.txt is a file that is 3000 bytes in size\n *\n * // helper function that returns human-readable size format from bytes\n * function formatBytes(bytes, decimals = 2) {\n * // implementation not included for brevity\n * return humanReadbleFilesize;\n * }\n *\n * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' };\n *\n * // asynchronous function that returns the file size, transformed to human-readable format\n * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.\n * function transformFileSize(acc, value, key, callback) {\n * fs.stat(value, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * acc[key] = formatBytes(stat.size);\n * callback(null);\n * });\n * }\n *\n * // Using callbacks\n * async.transform(fileMap, transformFileSize, function(err, result) {\n * if(err) {\n * console.log(err);\n * } else {\n * console.log(result);\n * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }\n * }\n * });\n *\n * // Using Promises\n * async.transform(fileMap, transformFileSize)\n * .then(result => {\n * console.log(result);\n * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.transform(fileMap, transformFileSize);\n * console.log(result);\n * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction transform (coll, accumulator, iteratee, callback) {\n if (arguments.length <= 3 && typeof accumulator === 'function') {\n callback = iteratee;\n iteratee = accumulator;\n accumulator = Array.isArray(coll) ? [] : {};\n }\n callback = once(callback || promiseCallback());\n var _iteratee = wrapAsync(iteratee);\n\n eachOf$1(coll, (v, k, cb) => {\n _iteratee(accumulator, v, k, cb);\n }, err => callback(err, accumulator));\n return callback[PROMISE_SYMBOL]\n}\n\n/**\n * It runs each task in series but stops whenever any of the functions were\n * successful. If one of the tasks were successful, the `callback` will be\n * passed the result of the successful task. If all tasks fail, the callback\n * will be passed the error and result (if any) of the final attempt.\n *\n * @name tryEach\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to\n * run, each function is passed a `callback(err, result)` it must call on\n * completion with an error `err` (which can be `null`) and an optional `result`\n * value.\n * @param {Function} [callback] - An optional callback which is called when one\n * of the tasks has succeeded, or all have failed. It receives the `err` and\n * `result` arguments of the last attempt at completing the `task`. Invoked with\n * (err, results).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n * async.tryEach([\n * function getDataFromFirstWebsite(callback) {\n * // Try getting the data from the first website\n * callback(err, data);\n * },\n * function getDataFromSecondWebsite(callback) {\n * // First website failed,\n * // Try getting the data from the backup website\n * callback(err, data);\n * }\n * ],\n * // optional callback\n * function(err, results) {\n * Now do something with the data.\n * });\n *\n */\nfunction tryEach(tasks, callback) {\n var error = null;\n var result;\n return eachSeries$1(tasks, (task, taskCb) => {\n wrapAsync(task)((err, ...args) => {\n if (err === false) return taskCb(err);\n\n if (args.length < 2) {\n [result] = args;\n } else {\n result = args;\n }\n error = err;\n taskCb(err ? null : {});\n });\n }, () => callback(error, result));\n}\n\nvar tryEach$1 = awaitify(tryEach);\n\n/**\n * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,\n * unmemoized form. Handy for testing.\n *\n * @name unmemoize\n * @static\n * @memberOf module:Utils\n * @method\n * @see [async.memoize]{@link module:Utils.memoize}\n * @category Util\n * @param {AsyncFunction} fn - the memoized function\n * @returns {AsyncFunction} a function that calls the original unmemoized function\n */\nfunction unmemoize(fn) {\n return (...args) => {\n return (fn.unmemoized || fn)(...args);\n };\n}\n\n/**\n * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when\n * stopped, or an error occurs.\n *\n * @name whilst\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {AsyncFunction} test - asynchronous truth test to perform before each\n * execution of `iteratee`. Invoked with ().\n * @param {AsyncFunction} iteratee - An async function which is called each time\n * `test` passes. Invoked with (callback).\n * @param {Function} [callback] - A callback which is called after the test\n * function has failed and repeated execution of `iteratee` has stopped. `callback`\n * will be passed an error and any arguments passed to the final `iteratee`'s\n * callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * var count = 0;\n * async.whilst(\n * function test(cb) { cb(null, count < 5); },\n * function iter(callback) {\n * count++;\n * setTimeout(function() {\n * callback(null, count);\n * }, 1000);\n * },\n * function (err, n) {\n * // 5 seconds have passed, n = 5\n * }\n * );\n */\nfunction whilst(test, iteratee, callback) {\n callback = onlyOnce(callback);\n var _fn = wrapAsync(iteratee);\n var _test = wrapAsync(test);\n var results = [];\n\n function next(err, ...rest) {\n if (err) return callback(err);\n results = rest;\n if (err === false) return;\n _test(check);\n }\n\n function check(err, truth) {\n if (err) return callback(err);\n if (err === false) return;\n if (!truth) return callback(null, ...results);\n _fn(next);\n }\n\n return _test(check);\n}\nvar whilst$1 = awaitify(whilst, 3);\n\n/**\n * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when\n * stopped, or an error occurs. `callback` will be passed an error and any\n * arguments passed to the final `iteratee`'s callback.\n *\n * The inverse of [whilst]{@link module:ControlFlow.whilst}.\n *\n * @name until\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.whilst]{@link module:ControlFlow.whilst}\n * @category Control Flow\n * @param {AsyncFunction} test - asynchronous truth test to perform before each\n * execution of `iteratee`. Invoked with (callback).\n * @param {AsyncFunction} iteratee - An async function which is called each time\n * `test` fails. Invoked with (callback).\n * @param {Function} [callback] - A callback which is called after the test\n * function has passed and repeated execution of `iteratee` has stopped. `callback`\n * will be passed an error and any arguments passed to the final `iteratee`'s\n * callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if a callback is not passed\n *\n * @example\n * const results = []\n * let finished = false\n * async.until(function test(cb) {\n * cb(null, finished)\n * }, function iter(next) {\n * fetchPage(url, (err, body) => {\n * if (err) return next(err)\n * results = results.concat(body.objects)\n * finished = !!body.next\n * next(err)\n * })\n * }, function done (err) {\n * // all pages have been fetched\n * })\n */\nfunction until(test, iteratee, callback) {\n const _test = wrapAsync(test);\n return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback);\n}\n\n/**\n * Runs the `tasks` array of functions in series, each passing their results to\n * the next in the array. However, if any of the `tasks` pass an error to their\n * own callback, the next function is not executed, and the main `callback` is\n * immediately called with the error.\n *\n * @name waterfall\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}\n * to run.\n * Each function should complete with any number of `result` values.\n * The `result` values will be passed as arguments, in order, to the next task.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed. This will be passed the results of the last task's\n * callback. Invoked with (err, [results]).\n * @returns undefined\n * @example\n *\n * async.waterfall([\n * function(callback) {\n * callback(null, 'one', 'two');\n * },\n * function(arg1, arg2, callback) {\n * // arg1 now equals 'one' and arg2 now equals 'two'\n * callback(null, 'three');\n * },\n * function(arg1, callback) {\n * // arg1 now equals 'three'\n * callback(null, 'done');\n * }\n * ], function (err, result) {\n * // result now equals 'done'\n * });\n *\n * // Or, with named functions:\n * async.waterfall([\n * myFirstFunction,\n * mySecondFunction,\n * myLastFunction,\n * ], function (err, result) {\n * // result now equals 'done'\n * });\n * function myFirstFunction(callback) {\n * callback(null, 'one', 'two');\n * }\n * function mySecondFunction(arg1, arg2, callback) {\n * // arg1 now equals 'one' and arg2 now equals 'two'\n * callback(null, 'three');\n * }\n * function myLastFunction(arg1, callback) {\n * // arg1 now equals 'three'\n * callback(null, 'done');\n * }\n */\nfunction waterfall (tasks, callback) {\n callback = once(callback);\n if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));\n if (!tasks.length) return callback();\n var taskIndex = 0;\n\n function nextTask(args) {\n var task = wrapAsync(tasks[taskIndex++]);\n task(...args, onlyOnce(next));\n }\n\n function next(err, ...args) {\n if (err === false) return\n if (err || taskIndex === tasks.length) {\n return callback(err, ...args);\n }\n nextTask(args);\n }\n\n nextTask([]);\n}\n\nvar waterfall$1 = awaitify(waterfall);\n\n/**\n * An \"async function\" in the context of Async is an asynchronous function with\n * a variable number of parameters, with the final parameter being a callback.\n * (`function (arg1, arg2, ..., callback) {}`)\n * The final callback is of the form `callback(err, results...)`, which must be\n * called once the function is completed. The callback should be called with a\n * Error as its first argument to signal that an error occurred.\n * Otherwise, if no error occurred, it should be called with `null` as the first\n * argument, and any additional `result` arguments that may apply, to signal\n * successful completion.\n * The callback must be called exactly once, ideally on a later tick of the\n * JavaScript event loop.\n *\n * This type of function is also referred to as a \"Node-style async function\",\n * or a \"continuation passing-style function\" (CPS). Most of the methods of this\n * library are themselves CPS/Node-style async functions, or functions that\n * return CPS/Node-style async functions.\n *\n * Wherever we accept a Node-style async function, we also directly accept an\n * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.\n * In this case, the `async` function will not be passed a final callback\n * argument, and any thrown error will be used as the `err` argument of the\n * implicit callback, and the return value will be used as the `result` value.\n * (i.e. a `rejected` of the returned Promise becomes the `err` callback\n * argument, and a `resolved` value becomes the `result`.)\n *\n * Note, due to JavaScript limitations, we can only detect native `async`\n * functions and not transpilied implementations.\n * Your environment must have `async`/`await` support for this to work.\n * (e.g. Node > v7.6, or a recent version of a modern browser).\n * If you are using `async` functions through a transpiler (e.g. Babel), you\n * must still wrap the function with [asyncify]{@link module:Utils.asyncify},\n * because the `async function` will be compiled to an ordinary function that\n * returns a promise.\n *\n * @typedef {Function} AsyncFunction\n * @static\n */\n\nvar index = {\n apply,\n applyEach: applyEach$1,\n applyEachSeries,\n asyncify,\n auto,\n autoInject,\n cargo,\n cargoQueue: cargo$1,\n compose,\n concat: concat$1,\n concatLimit: concatLimit$1,\n concatSeries: concatSeries$1,\n constant,\n detect: detect$1,\n detectLimit: detectLimit$1,\n detectSeries: detectSeries$1,\n dir,\n doUntil,\n doWhilst: doWhilst$1,\n each,\n eachLimit: eachLimit$2,\n eachOf: eachOf$1,\n eachOfLimit: eachOfLimit$2,\n eachOfSeries: eachOfSeries$1,\n eachSeries: eachSeries$1,\n ensureAsync,\n every: every$1,\n everyLimit: everyLimit$1,\n everySeries: everySeries$1,\n filter: filter$1,\n filterLimit: filterLimit$1,\n filterSeries: filterSeries$1,\n forever: forever$1,\n groupBy,\n groupByLimit: groupByLimit$1,\n groupBySeries,\n log,\n map: map$1,\n mapLimit: mapLimit$1,\n mapSeries: mapSeries$1,\n mapValues,\n mapValuesLimit: mapValuesLimit$1,\n mapValuesSeries,\n memoize,\n nextTick,\n parallel,\n parallelLimit,\n priorityQueue,\n queue: queue$1,\n race: race$1,\n reduce: reduce$1,\n reduceRight,\n reflect,\n reflectAll,\n reject: reject$2,\n rejectLimit: rejectLimit$1,\n rejectSeries: rejectSeries$1,\n retry,\n retryable,\n seq,\n series,\n setImmediate: setImmediate$1,\n some: some$1,\n someLimit: someLimit$1,\n someSeries: someSeries$1,\n sortBy: sortBy$1,\n timeout,\n times,\n timesLimit,\n timesSeries,\n transform,\n tryEach: tryEach$1,\n unmemoize,\n until,\n waterfall: waterfall$1,\n whilst: whilst$1,\n\n // aliases\n all: every$1,\n allLimit: everyLimit$1,\n allSeries: everySeries$1,\n any: some$1,\n anyLimit: someLimit$1,\n anySeries: someSeries$1,\n find: detect$1,\n findLimit: detectLimit$1,\n findSeries: detectSeries$1,\n flatMap: concat$1,\n flatMapLimit: concatLimit$1,\n flatMapSeries: concatSeries$1,\n forEach: each,\n forEachSeries: eachSeries$1,\n forEachLimit: eachLimit$2,\n forEachOf: eachOf$1,\n forEachOfSeries: eachOfSeries$1,\n forEachOfLimit: eachOfLimit$2,\n inject: reduce$1,\n foldl: reduce$1,\n foldr: reduceRight,\n select: filter$1,\n selectLimit: filterLimit$1,\n selectSeries: filterSeries$1,\n wrapSync: asyncify,\n during: whilst$1,\n doDuring: doWhilst$1\n};\n\nexport default index;\nexport { apply, applyEach$1 as applyEach, applyEachSeries, asyncify, auto, autoInject, cargo, cargo$1 as cargoQueue, compose, concat$1 as concat, concatLimit$1 as concatLimit, concatSeries$1 as concatSeries, constant, detect$1 as detect, detectLimit$1 as detectLimit, detectSeries$1 as detectSeries, dir, doUntil, doWhilst$1 as doWhilst, each, eachLimit$2 as eachLimit, eachOf$1 as eachOf, eachOfLimit$2 as eachOfLimit, eachOfSeries$1 as eachOfSeries, eachSeries$1 as eachSeries, ensureAsync, every$1 as every, everyLimit$1 as everyLimit, everySeries$1 as everySeries, filter$1 as filter, filterLimit$1 as filterLimit, filterSeries$1 as filterSeries, forever$1 as forever, groupBy, groupByLimit$1 as groupByLimit, groupBySeries, log, map$1 as map, mapLimit$1 as mapLimit, mapSeries$1 as mapSeries, mapValues, mapValuesLimit$1 as mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel, parallelLimit, priorityQueue, queue$1 as queue, race$1 as race, reduce$1 as reduce, reduceRight, reflect, reflectAll, reject$2 as reject, rejectLimit$1 as rejectLimit, rejectSeries$1 as rejectSeries, retry, retryable, seq, series, setImmediate$1 as setImmediate, some$1 as some, someLimit$1 as someLimit, someSeries$1 as someSeries, sortBy$1 as sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach$1 as tryEach, unmemoize, until, waterfall$1 as waterfall, whilst$1 as whilst, every$1 as all, everyLimit$1 as allLimit, everySeries$1 as allSeries, some$1 as any, someLimit$1 as anyLimit, someSeries$1 as anySeries, detect$1 as find, detectLimit$1 as findLimit, detectSeries$1 as findSeries, concat$1 as flatMap, concatLimit$1 as flatMapLimit, concatSeries$1 as flatMapSeries, each as forEach, eachSeries$1 as forEachSeries, eachLimit$2 as forEachLimit, eachOf$1 as forEachOf, eachOfSeries$1 as forEachOfSeries, eachOfLimit$2 as forEachOfLimit, reduce$1 as inject, reduce$1 as foldl, reduceRight as foldr, filter$1 as select, filterLimit$1 as selectLimit, filterSeries$1 as selectSeries, asyncify as wrapSync, whilst$1 as during, doWhilst$1 as doDuring };\n","// **N3Writer** writes N3 documents.\nimport namespaces from './IRIs';\nimport { default as N3DataFactory, Term } from './N3DataFactory';\nimport { isDefaultGraph } from './N3Util';\n\nconst DEFAULTGRAPH = N3DataFactory.defaultGraph();\n\nconst { rdf, xsd } = namespaces;\n\n// Characters in literals that require escaping\nconst escape = /[\"\\\\\\t\\n\\r\\b\\f\\u0000-\\u0019\\ud800-\\udbff]/,\n escapeAll = /[\"\\\\\\t\\n\\r\\b\\f\\u0000-\\u0019]|[\\ud800-\\udbff][\\udc00-\\udfff]/g,\n escapedCharacters = {\n '\\\\': '\\\\\\\\', '\"': '\\\\\"', '\\t': '\\\\t',\n '\\n': '\\\\n', '\\r': '\\\\r', '\\b': '\\\\b', '\\f': '\\\\f',\n };\n\n// ## Placeholder class to represent already pretty-printed terms\nclass SerializedTerm extends Term {\n // Pretty-printed nodes are not equal to any other node\n // (e.g., [] does not equal [])\n equals() {\n return false;\n }\n}\n\n// ## Constructor\nexport default class N3Writer {\n constructor(outputStream, options) {\n // ### `_prefixRegex` matches a prefixed name or IRI that begins with one of the added prefixes\n this._prefixRegex = /$0^/;\n\n // Shift arguments if the first argument is not a stream\n if (outputStream && typeof outputStream.write !== 'function')\n options = outputStream, outputStream = null;\n options = options || {};\n this._lists = options.lists;\n\n // If no output stream given, send the output as string through the end callback\n if (!outputStream) {\n let output = '';\n this._outputStream = {\n write(chunk, encoding, done) { output += chunk; done && done(); },\n end: done => { done && done(null, output); },\n };\n this._endStream = true;\n }\n else {\n this._outputStream = outputStream;\n this._endStream = options.end === undefined ? true : !!options.end;\n }\n\n // Initialize writer, depending on the format\n this._subject = null;\n if (!(/triple|quad/i).test(options.format)) {\n this._lineMode = false;\n this._graph = DEFAULTGRAPH;\n this._baseIRI = options.baseIRI;\n this._prefixIRIs = Object.create(null);\n options.prefixes && this.addPrefixes(options.prefixes);\n }\n else {\n this._lineMode = true;\n this._writeQuad = this._writeQuadLine;\n }\n }\n\n // ## Private methods\n\n // ### Whether the current graph is the default graph\n get _inDefaultGraph() {\n return DEFAULTGRAPH.equals(this._graph);\n }\n\n // ### `_write` writes the argument to the output stream\n _write(string, callback) {\n this._outputStream.write(string, 'utf8', callback);\n }\n\n // ### `_writeQuad` writes the quad to the output stream\n _writeQuad(subject, predicate, object, graph, done) {\n try {\n // Write the graph's label if it has changed\n if (!graph.equals(this._graph)) {\n // Close the previous graph and start the new one\n this._write((this._subject === null ? '' : (this._inDefaultGraph ? '.\\n' : '\\n}\\n')) +\n (DEFAULTGRAPH.equals(graph) ? '' : `${this._encodeIriOrBlank(graph)} {\\n`));\n this._graph = graph;\n this._subject = null;\n }\n // Don't repeat the subject if it's the same\n if (subject.equals(this._subject)) {\n // Don't repeat the predicate if it's the same\n if (predicate.equals(this._predicate))\n this._write(`, ${this._encodeObject(object)}`, done);\n // Same subject, different predicate\n else\n this._write(`;\\n ${\n this._encodePredicate(this._predicate = predicate)} ${\n this._encodeObject(object)}`, done);\n }\n // Different subject; write the whole quad\n else\n this._write(`${(this._subject === null ? '' : '.\\n') +\n this._encodeSubject(this._subject = subject)} ${\n this._encodePredicate(this._predicate = predicate)} ${\n this._encodeObject(object)}`, done);\n }\n catch (error) { done && done(error); }\n }\n\n // ### `_writeQuadLine` writes the quad to the output stream as a single line\n _writeQuadLine(subject, predicate, object, graph, done) {\n // Write the quad without prefixes\n delete this._prefixMatch;\n this._write(this.quadToString(subject, predicate, object, graph), done);\n }\n\n // ### `quadToString` serializes a quad as a string\n quadToString(subject, predicate, object, graph) {\n return `${this._encodeSubject(subject)} ${\n this._encodeIriOrBlank(predicate)} ${\n this._encodeObject(object)\n }${graph && graph.value ? ` ${this._encodeIriOrBlank(graph)} .\\n` : ' .\\n'}`;\n }\n\n // ### `quadsToString` serializes an array of quads as a string\n quadsToString(quads) {\n return quads.map(t => {\n return this.quadToString(t.subject, t.predicate, t.object, t.graph);\n }).join('');\n }\n\n // ### `_encodeSubject` represents a subject\n _encodeSubject(entity) {\n return entity.termType === 'Quad' ?\n this._encodeQuad(entity) : this._encodeIriOrBlank(entity);\n }\n\n // ### `_encodeIriOrBlank` represents an IRI or blank node\n _encodeIriOrBlank(entity) {\n // A blank node or list is represented as-is\n if (entity.termType !== 'NamedNode') {\n // If it is a list head, pretty-print it\n if (this._lists && (entity.value in this._lists))\n entity = this.list(this._lists[entity.value]);\n return 'id' in entity ? entity.id : `_:${entity.value}`;\n }\n let iri = entity.value;\n // Use relative IRIs if requested and possible\n if (this._baseIRI && iri.startsWith(this._baseIRI))\n iri = iri.substr(this._baseIRI.length);\n // Escape special characters\n if (escape.test(iri))\n iri = iri.replace(escapeAll, characterReplacer);\n // Try to represent the IRI as prefixed name\n const prefixMatch = this._prefixRegex.exec(iri);\n return !prefixMatch ? `<${iri}>` :\n (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]);\n }\n\n // ### `_encodeLiteral` represents a literal\n _encodeLiteral(literal) {\n // Escape special characters\n let value = literal.value;\n if (escape.test(value))\n value = value.replace(escapeAll, characterReplacer);\n\n // Write a language-tagged literal\n if (literal.language)\n return `\"${value}\"@${literal.language}`;\n\n // Write dedicated literals per data type\n if (this._lineMode) {\n // Only abbreviate strings in N-Triples or N-Quads\n if (literal.datatype.value === xsd.string)\n return `\"${value}\"`;\n }\n else {\n // Use common datatype abbreviations in Turtle or TriG\n switch (literal.datatype.value) {\n case xsd.string:\n return `\"${value}\"`;\n case xsd.boolean:\n if (value === 'true' || value === 'false')\n return value;\n break;\n case xsd.integer:\n if (/^[+-]?\\d+$/.test(value))\n return value;\n break;\n case xsd.decimal:\n if (/^[+-]?\\d*\\.\\d+$/.test(value))\n return value;\n break;\n case xsd.double:\n if (/^[+-]?(?:\\d+\\.\\d*|\\.?\\d+)[eE][+-]?\\d+$/.test(value))\n return value;\n break;\n }\n }\n\n // Write a regular datatyped literal\n return `\"${value}\"^^${this._encodeIriOrBlank(literal.datatype)}`;\n }\n\n // ### `_encodePredicate` represents a predicate\n _encodePredicate(predicate) {\n return predicate.value === rdf.type ? 'a' : this._encodeIriOrBlank(predicate);\n }\n\n // ### `_encodeObject` represents an object\n _encodeObject(object) {\n switch (object.termType) {\n case 'Quad':\n return this._encodeQuad(object);\n case 'Literal':\n return this._encodeLiteral(object);\n default:\n return this._encodeIriOrBlank(object);\n }\n }\n\n // ### `_encodeQuad` encodes an RDF* quad\n _encodeQuad({ subject, predicate, object, graph }) {\n return `<<${\n this._encodeSubject(subject)} ${\n this._encodePredicate(predicate)} ${\n this._encodeObject(object)}${\n isDefaultGraph(graph) ? '' : ` ${this._encodeIriOrBlank(graph)}`}>>`;\n }\n\n // ### `_blockedWrite` replaces `_write` after the writer has been closed\n _blockedWrite() {\n throw new Error('Cannot write because the writer has been closed.');\n }\n\n // ### `addQuad` adds the quad to the output stream\n addQuad(subject, predicate, object, graph, done) {\n // The quad was given as an object, so shift parameters\n if (object === undefined)\n this._writeQuad(subject.subject, subject.predicate, subject.object, subject.graph, predicate);\n // The optional `graph` parameter was not provided\n else if (typeof graph === 'function')\n this._writeQuad(subject, predicate, object, DEFAULTGRAPH, graph);\n // The `graph` parameter was provided\n else\n this._writeQuad(subject, predicate, object, graph || DEFAULTGRAPH, done);\n }\n\n // ### `addQuads` adds the quads to the output stream\n addQuads(quads) {\n for (let i = 0; i < quads.length; i++)\n this.addQuad(quads[i]);\n }\n\n // ### `addPrefix` adds the prefix to the output stream\n addPrefix(prefix, iri, done) {\n const prefixes = {};\n prefixes[prefix] = iri;\n this.addPrefixes(prefixes, done);\n }\n\n // ### `addPrefixes` adds the prefixes to the output stream\n addPrefixes(prefixes, done) {\n // Ignore prefixes if not supported by the serialization\n if (!this._prefixIRIs)\n return done && done();\n\n // Write all new prefixes\n let hasPrefixes = false;\n for (let prefix in prefixes) {\n let iri = prefixes[prefix];\n if (typeof iri !== 'string')\n iri = iri.value;\n hasPrefixes = true;\n // Finish a possible pending quad\n if (this._subject !== null) {\n this._write(this._inDefaultGraph ? '.\\n' : '\\n}\\n');\n this._subject = null, this._graph = '';\n }\n // Store and write the prefix\n this._prefixIRIs[iri] = (prefix += ':');\n this._write(`@prefix ${prefix} <${iri}>.\\n`);\n }\n // Recreate the prefix matcher\n if (hasPrefixes) {\n let IRIlist = '', prefixList = '';\n for (const prefixIRI in this._prefixIRIs) {\n IRIlist += IRIlist ? `|${prefixIRI}` : prefixIRI;\n prefixList += (prefixList ? '|' : '') + this._prefixIRIs[prefixIRI];\n }\n IRIlist = IRIlist.replace(/[\\]\\/\\(\\)\\*\\+\\?\\.\\\\\\$]/g, '\\\\$&');\n this._prefixRegex = new RegExp(`^(?:${prefixList})[^\\/]*$|` +\n `^(${IRIlist})([a-zA-Z][\\\\-_a-zA-Z0-9]*)$`);\n }\n // End a prefix block with a newline\n this._write(hasPrefixes ? '\\n' : '', done);\n }\n\n // ### `blank` creates a blank node with the given content\n blank(predicate, object) {\n let children = predicate, child, length;\n // Empty blank node\n if (predicate === undefined)\n children = [];\n // Blank node passed as blank(Term(\"predicate\"), Term(\"object\"))\n else if (predicate.termType)\n children = [{ predicate: predicate, object: object }];\n // Blank node passed as blank({ predicate: predicate, object: object })\n else if (!('length' in predicate))\n children = [predicate];\n\n switch (length = children.length) {\n // Generate an empty blank node\n case 0:\n return new SerializedTerm('[]');\n // Generate a non-nested one-triple blank node\n case 1:\n child = children[0];\n if (!(child.object instanceof SerializedTerm))\n return new SerializedTerm(`[ ${this._encodePredicate(child.predicate)} ${\n this._encodeObject(child.object)} ]`);\n // Generate a multi-triple or nested blank node\n default:\n let contents = '[';\n // Write all triples in order\n for (let i = 0; i < length; i++) {\n child = children[i];\n // Write only the object is the predicate is the same as the previous\n if (child.predicate.equals(predicate))\n contents += `, ${this._encodeObject(child.object)}`;\n // Otherwise, write the predicate and the object\n else {\n contents += `${(i ? ';\\n ' : '\\n ') +\n this._encodePredicate(child.predicate)} ${\n this._encodeObject(child.object)}`;\n predicate = child.predicate;\n }\n }\n return new SerializedTerm(`${contents}\\n]`);\n }\n }\n\n // ### `list` creates a list node with the given content\n list(elements) {\n const length = elements && elements.length || 0, contents = new Array(length);\n for (let i = 0; i < length; i++)\n contents[i] = this._encodeObject(elements[i]);\n return new SerializedTerm(`(${contents.join(' ')})`);\n }\n\n // ### `end` signals the end of the output stream\n end(done) {\n // Finish a possible pending quad\n if (this._subject !== null) {\n this._write(this._inDefaultGraph ? '.\\n' : '\\n}\\n');\n this._subject = null;\n }\n // Disallow further writing\n this._write = this._blockedWrite;\n\n // Try to end the underlying stream, ensuring done is called exactly one time\n let singleDone = done && ((error, result) => { singleDone = null, done(error, result); });\n if (this._endStream) {\n try { return this._outputStream.end(singleDone); }\n catch (error) { /* error closing stream */ }\n }\n singleDone && singleDone();\n }\n}\n\n// Replaces a character by its escaped version\nfunction characterReplacer(character) {\n // Replace a single character by its escaped version\n let result = escapedCharacters[character];\n if (result === undefined) {\n // Replace a single character with its 4-bit unicode escape sequence\n if (character.length === 1) {\n result = character.charCodeAt(0).toString(16);\n result = '\\\\u0000'.substr(0, 6 - result.length) + result;\n }\n // Replace a surrogate pair with its 8-bit unicode escape sequence\n else {\n result = ((character.charCodeAt(0) - 0xD800) * 0x400 +\n character.charCodeAt(1) + 0x2400).toString(16);\n result = '\\\\U00000000'.substr(0, 10 - result.length) + result;\n }\n }\n return result;\n}\n","import asyncLib from 'async' // @@ Goal: remove this dependency\nimport jsonld from 'jsonld'\nimport { Parser, Writer } from 'n3' // @@ Goal: remove this dependency\n\nexport function convertToJson (n3String, jsonCallback) {\n var jsonString\n var n3Parser = new Parser()\n var n3Writer = new Writer({\n format: 'N-Quads'\n })\n asyncLib.waterfall([\n function (callback) {\n n3Parser.parse(n3String, function (error, quad, prefixes) {\n if (error) {\n callback(error);\n } else if (quad !== null) {\n n3Writer.addQuad(quad);\n } else {\n n3Writer.end(callback);\n }\n });\n },\n function (result, callback) {\n try {\n jsonld.fromRDF(result, {\n format: 'application/nquads'\n }).then((result) => {\n callback(null, result)\n })\n } catch (err) {\n callback(err)\n }\n },\n function (json, callback) {\n jsonString = JSON.stringify(json)\n jsonCallback(null, jsonString)\n }\n ], function (err, result) {\n jsonCallback(err, jsonString)\n }\n )\n}\n\nexport function convertToNQuads (n3String, nquadCallback) {\n var nquadString\n var n3Parser = new Parser()\n var n3Writer = new Writer({\n format: 'N-Quads'\n })\n asyncLib.waterfall([\n function (callback) {\n n3Parser.parse(n3String, function (error, triple, prefixes) {\n if (error) {\n callback(error);\n } else if (quad !== null) {\n n3Writer.addQuad(quad);\n } else {\n n3Writer.end(callback);\n }\n });\n },\n function (result, callback) {\n nquadString = result\n nquadCallback(null, nquadString)\n }\n ], function (err, result) {\n nquadCallback(err, nquadString)\n }\n )\n}\n","import jsonld from 'jsonld'\n\nimport { arrayToStatements } from './utils'\n\n/**\n * Parses json-ld formatted JS objects to a rdf Term.\n * @param kb - The DataFactory to use.\n * @param obj - The json-ld object to process.\n * @return {Literal|NamedNode|BlankNode|Collection}\n */\nexport function jsonldObjectToTerm (kb, obj) {\n if (typeof obj === 'string') {\n return kb.rdfFactory.literal(obj)\n }\n\n if (Object.prototype.hasOwnProperty.call(obj, '@list')) {\n if (kb.rdfFactory.supports[\"COLLECTIONS\"] === true) {\n return listToCollection(kb, obj['@list'])\n }\n\n return listToStatements(kb, obj)\n }\n\n if (Object.prototype.hasOwnProperty.call(obj, '@id')) {\n return kb.rdfFactory.namedNode(obj['@id'])\n }\n\n if (Object.prototype.hasOwnProperty.call(obj, '@language')) {\n return kb.rdfFactory.literal(obj['@value'], obj['@language'])\n }\n\n if (Object.prototype.hasOwnProperty.call(obj, '@type')) {\n return kb.rdfFactory.literal(obj['@value'], kb.rdfFactory.namedNode(obj['@type']))\n }\n\n if (Object.prototype.hasOwnProperty.call(obj, '@value')) {\n return kb.rdfFactory.literal(obj['@value'])\n }\n\n return kb.rdfFactory.literal(obj)\n}\n\n/**\n * Adds the statements in a json-ld list object to {kb}.\n */\nfunction listToStatements (kb, obj) {\n const listId = obj['@id'] ? kb.rdfFactory.namedNode(obj['@id']) : kb.rdfFactory.blankNode()\n\n const items = obj['@list'].map((listItem => jsonldObjectToTerm(kb, listItem)))\n const statements = arrayToStatements(kb.rdfFactory, listId, items)\n kb.addAll(statements)\n\n return listId\n}\n\nfunction listToCollection (kb, obj) {\n if (!Array.isArray(obj)) {\n throw new TypeError(\"Object must be an array\")\n }\n return kb.rdfFactory.collection(obj.map((o) => jsonldObjectToTerm(kb, o)))\n}\n\n/**\n * Takes a json-ld formatted string {str} and adds its statements to {kb}.\n *\n * Ensure that {kb.rdfFactory} is a DataFactory.\n */\nexport default function jsonldParser (str, kb, base, callback) {\n const baseString = base && Object.prototype.hasOwnProperty.call(base, 'termType')\n ? base.value\n : base\n\n return jsonld\n .flatten(JSON.parse(str), null, { base: baseString })\n .then((flattened) => flattened.reduce((store, flatResource) => {\n const id = flatResource['@id']\n ? kb.rdfFactory.namedNode(flatResource['@id'])\n : kb.rdfFactory.blankNode()\n\n for (const property of Object.keys(flatResource)) {\n if (property === '@id') {\n continue\n }\n const value = flatResource[property]\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n kb.addStatement(createStatement(kb, id, property, value[i], base))\n }\n } else {\n kb.addStatement(createStatement(kb, id, property, value, base))\n }\n }\n\n return kb\n }, kb))\n .then(callback)\n .catch(callback)\n}\n\n/**\n * Create statement quad depending on @type being a type node\n * @param kb\n * @param subject id\n * @param property\n * @param value\n * @return quad statement\n */\nfunction createStatement(kb, id, property, value, base) {\n let predicate, object\n if (property === \"@type\") {\n predicate = kb.rdfFactory.namedNode(\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\")\n object = kb.rdfFactory.namedNode(value)\n } else {\n predicate = kb.rdfFactory.namedNode(property)\n object = jsonldObjectToTerm(kb, value)\n }\n return kb.rdfFactory.quad(id, predicate, object, kb.rdfFactory.namedNode(base))\n}\n","/**\n * A JavaScript implementation of the JSON-LD API.\n *\n * @author Dave Longley\n *\n * @license BSD 3-Clause License\n * Copyright (c) 2011-2019 Digital Bazaar, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * Neither the name of the Digital Bazaar, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nconst canonize = require('rdf-canonize');\nconst platform = require('./platform');\nconst util = require('./util');\nconst ContextResolver = require('./ContextResolver');\nconst IdentifierIssuer = util.IdentifierIssuer;\nconst JsonLdError = require('./JsonLdError');\nconst LRU = require('lru-cache');\nconst NQuads = require('./NQuads');\n\nconst {expand: _expand} = require('./expand');\nconst {flatten: _flatten} = require('./flatten');\nconst {fromRDF: _fromRDF} = require('./fromRdf');\nconst {toRDF: _toRDF} = require('./toRdf');\n\nconst {\n frameMergedOrDefault: _frameMergedOrDefault,\n cleanupNull: _cleanupNull\n} = require('./frame');\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isString: _isString\n} = require('./types');\n\nconst {\n isSubjectReference: _isSubjectReference,\n} = require('./graphTypes');\n\nconst {\n expandIri: _expandIri,\n getInitialContext: _getInitialContext,\n process: _processContext,\n processingMode: _processingMode\n} = require('./context');\n\nconst {\n compact: _compact,\n compactIri: _compactIri\n} = require('./compact');\n\nconst {\n createNodeMap: _createNodeMap,\n createMergedNodeMap: _createMergedNodeMap,\n mergeNodeMaps: _mergeNodeMaps\n} = require('./nodeMap');\n\n/* eslint-disable indent */\n// attaches jsonld API to the given object\nconst wrapper = function(jsonld) {\n\n/** Registered RDF dataset parsers hashed by content-type. */\nconst _rdfParsers = {};\n\n// resolved context cache\n// TODO: consider basing max on context size rather than number\nconst RESOLVED_CONTEXT_CACHE_MAX_SIZE = 100;\nconst _resolvedContextCache = new LRU({max: RESOLVED_CONTEXT_CACHE_MAX_SIZE});\n\n/* Core API */\n\n/**\n * Performs JSON-LD compaction.\n *\n * @param input the JSON-LD input to compact.\n * @param ctx the context to compact with.\n * @param [options] options to use:\n * [base] the base IRI to use.\n * [compactArrays] true to compact arrays to single values when\n * appropriate, false not to (default: true).\n * [compactToRelative] true to compact IRIs to be relative to document\n * base, false to keep absolute (default: true)\n * [graph] true to always output a top-level graph (default: false).\n * [expandContext] a context to expand with.\n * [skipExpansion] true to assume the input is expanded and skip\n * expansion, false not to, defaults to false.\n * [documentLoader(url, options)] the document loader.\n * [expansionMap(info)] a function that can be used to custom map\n * unmappable values (or to throw an error when they are detected);\n * if this function returns `undefined` then the default behavior\n * will be used.\n * [framing] true if compaction is occuring during a framing operation.\n * [compactionMap(info)] a function that can be used to custom map\n * unmappable values (or to throw an error when they are detected);\n * if this function returns `undefined` then the default behavior\n * will be used.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the compacted output.\n */\njsonld.compact = async function(input, ctx, options) {\n if(arguments.length < 2) {\n throw new TypeError('Could not compact, too few arguments.');\n }\n\n if(ctx === null) {\n throw new JsonLdError(\n 'The compaction context must not be null.',\n 'jsonld.CompactError', {code: 'invalid local context'});\n }\n\n // nothing to compact\n if(input === null) {\n return null;\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n compactArrays: true,\n compactToRelative: true,\n graph: false,\n skipExpansion: false,\n link: false,\n issuer: new IdentifierIssuer('_:b'),\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n if(options.link) {\n // force skip expansion when linking, \"link\" is not part of the public\n // API, it should only be called from framing\n options.skipExpansion = true;\n }\n if(!options.compactToRelative) {\n delete options.base;\n }\n\n // expand input\n let expanded;\n if(options.skipExpansion) {\n expanded = input;\n } else {\n expanded = await jsonld.expand(input, options);\n }\n\n // process context\n const activeCtx = await jsonld.processContext(\n _getInitialContext(options), ctx, options);\n\n // do compaction\n let compacted = await _compact({\n activeCtx,\n element: expanded,\n options,\n compactionMap: options.compactionMap\n });\n\n // perform clean up\n if(options.compactArrays && !options.graph && _isArray(compacted)) {\n if(compacted.length === 1) {\n // simplify to a single item\n compacted = compacted[0];\n } else if(compacted.length === 0) {\n // simplify to an empty object\n compacted = {};\n }\n } else if(options.graph && _isObject(compacted)) {\n // always use array if graph option is on\n compacted = [compacted];\n }\n\n // follow @context key\n if(_isObject(ctx) && '@context' in ctx) {\n ctx = ctx['@context'];\n }\n\n // build output context\n ctx = util.clone(ctx);\n if(!_isArray(ctx)) {\n ctx = [ctx];\n }\n // remove empty contexts\n const tmp = ctx;\n ctx = [];\n for(let i = 0; i < tmp.length; ++i) {\n if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) {\n ctx.push(tmp[i]);\n }\n }\n\n // remove array if only one context\n const hasContext = (ctx.length > 0);\n if(ctx.length === 1) {\n ctx = ctx[0];\n }\n\n // add context and/or @graph\n if(_isArray(compacted)) {\n // use '@graph' keyword\n const graphAlias = _compactIri({\n activeCtx, iri: '@graph', relativeTo: {vocab: true}\n });\n const graph = compacted;\n compacted = {};\n if(hasContext) {\n compacted['@context'] = ctx;\n }\n compacted[graphAlias] = graph;\n } else if(_isObject(compacted) && hasContext) {\n // reorder keys so @context is first\n const graph = compacted;\n compacted = {'@context': ctx};\n for(const key in graph) {\n compacted[key] = graph[key];\n }\n }\n\n return compacted;\n};\n\n/**\n * Performs JSON-LD expansion.\n *\n * @param input the JSON-LD input to expand.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [keepFreeFloatingNodes] true to keep free-floating nodes,\n * false not to, defaults to false.\n * [documentLoader(url, options)] the document loader.\n * [expansionMap(info)] a function that can be used to custom map\n * unmappable values (or to throw an error when they are detected);\n * if this function returns `undefined` then the default behavior\n * will be used.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the expanded output.\n */\njsonld.expand = async function(input, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not expand, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n keepFreeFloatingNodes: false,\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n if(options.expansionMap === false) {\n options.expansionMap = undefined;\n }\n\n // build set of objects that may have @contexts to resolve\n const toResolve = {};\n\n // build set of contexts to process prior to expansion\n const contextsToProcess = [];\n\n // if an `expandContext` has been given ensure it gets resolved\n if('expandContext' in options) {\n const expandContext = util.clone(options.expandContext);\n if(_isObject(expandContext) && '@context' in expandContext) {\n toResolve.expandContext = expandContext;\n } else {\n toResolve.expandContext = {'@context': expandContext};\n }\n contextsToProcess.push(toResolve.expandContext);\n }\n\n // if input is a string, attempt to dereference remote document\n let defaultBase;\n if(!_isString(input)) {\n // input is not a URL, do not need to retrieve it first\n toResolve.input = util.clone(input);\n } else {\n // load remote doc\n const remoteDoc = await jsonld.get(input, options);\n defaultBase = remoteDoc.documentUrl;\n toResolve.input = remoteDoc.document;\n if(remoteDoc.contextUrl) {\n // context included in HTTP link header and must be resolved\n toResolve.remoteContext = {'@context': remoteDoc.contextUrl};\n contextsToProcess.push(toResolve.remoteContext);\n }\n }\n\n // set default base\n if(!('base' in options)) {\n options.base = defaultBase || '';\n }\n\n // process any additional contexts\n let activeCtx = _getInitialContext(options);\n for(const localCtx of contextsToProcess) {\n activeCtx = await _processContext({activeCtx, localCtx, options});\n }\n\n // expand resolved input\n let expanded = await _expand({\n activeCtx,\n element: toResolve.input,\n options,\n expansionMap: options.expansionMap\n });\n\n // optimize away @graph with no other properties\n if(_isObject(expanded) && ('@graph' in expanded) &&\n Object.keys(expanded).length === 1) {\n expanded = expanded['@graph'];\n } else if(expanded === null) {\n expanded = [];\n }\n\n // normalize to an array\n if(!_isArray(expanded)) {\n expanded = [expanded];\n }\n\n return expanded;\n};\n\n/**\n * Performs JSON-LD flattening.\n *\n * @param input the JSON-LD to flatten.\n * @param ctx the context to use to compact the flattened output, or null.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [documentLoader(url, options)] the document loader.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the flattened output.\n */\njsonld.flatten = async function(input, ctx, options) {\n if(arguments.length < 1) {\n return new TypeError('Could not flatten, too few arguments.');\n }\n\n if(typeof ctx === 'function') {\n ctx = null;\n } else {\n ctx = ctx || null;\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // expand input\n const expanded = await jsonld.expand(input, options);\n\n // do flattening\n const flattened = _flatten(expanded);\n\n if(ctx === null) {\n // no compaction required\n return flattened;\n }\n\n // compact result (force @graph option to true, skip expansion)\n options.graph = true;\n options.skipExpansion = true;\n const compacted = await jsonld.compact(flattened, ctx, options);\n\n return compacted;\n};\n\n/**\n * Performs JSON-LD framing.\n *\n * @param input the JSON-LD input to frame.\n * @param frame the JSON-LD frame to use.\n * @param [options] the framing options.\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [embed] default @embed flag: '@last', '@always', '@never', '@link'\n * (default: '@last').\n * [explicit] default @explicit flag (default: false).\n * [requireAll] default @requireAll flag (default: true).\n * [omitDefault] default @omitDefault flag (default: false).\n * [documentLoader(url, options)] the document loader.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the framed output.\n */\njsonld.frame = async function(input, frame, options) {\n if(arguments.length < 2) {\n throw new TypeError('Could not frame, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n embed: '@once',\n explicit: false,\n requireAll: false,\n omitDefault: false,\n bnodesToClear: [],\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // if frame is a string, attempt to dereference remote document\n if(_isString(frame)) {\n // load remote doc\n const remoteDoc = await jsonld.get(frame, options);\n frame = remoteDoc.document;\n\n if(remoteDoc.contextUrl) {\n // inject link header @context into frame\n let ctx = frame['@context'];\n if(!ctx) {\n ctx = remoteDoc.contextUrl;\n } else if(_isArray(ctx)) {\n ctx.push(remoteDoc.contextUrl);\n } else {\n ctx = [ctx, remoteDoc.contextUrl];\n }\n frame['@context'] = ctx;\n }\n }\n\n const frameContext = frame ? frame['@context'] || {} : {};\n\n // process context\n const activeCtx = await jsonld.processContext(\n _getInitialContext(options), frameContext, options);\n\n // mode specific defaults\n if(!options.hasOwnProperty('omitGraph')) {\n options.omitGraph = _processingMode(activeCtx, 1.1);\n }\n if(!options.hasOwnProperty('pruneBlankNodeIdentifiers')) {\n options.pruneBlankNodeIdentifiers = _processingMode(activeCtx, 1.1);\n }\n\n // expand input\n const expanded = await jsonld.expand(input, options);\n\n // expand frame\n const opts = {...options};\n opts.isFrame = true;\n opts.keepFreeFloatingNodes = true;\n const expandedFrame = await jsonld.expand(frame, opts);\n\n // if the unexpanded frame includes a key expanding to @graph, frame the\n // default graph, otherwise, the merged graph\n const frameKeys = Object.keys(frame)\n .map(key => _expandIri(activeCtx, key, {vocab: true}));\n opts.merged = !frameKeys.includes('@graph');\n opts.is11 = _processingMode(activeCtx, 1.1);\n\n // do framing\n const framed = _frameMergedOrDefault(expanded, expandedFrame, opts);\n\n opts.graph = !options.omitGraph;\n opts.skipExpansion = true;\n opts.link = {};\n opts.framing = true;\n let compacted = await jsonld.compact(framed, frameContext, opts);\n\n // replace @null with null, compacting arrays\n opts.link = {};\n compacted = _cleanupNull(compacted, opts);\n\n return compacted;\n};\n\n/**\n * **Experimental**\n *\n * Links a JSON-LD document's nodes in memory.\n *\n * @param input the JSON-LD document to link.\n * @param [ctx] the JSON-LD context to apply.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [documentLoader(url, options)] the document loader.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the linked output.\n */\njsonld.link = async function(input, ctx, options) {\n // API matches running frame with a wildcard frame and embed: '@link'\n // get arguments\n const frame = {};\n if(ctx) {\n frame['@context'] = ctx;\n }\n frame['@embed'] = '@link';\n return jsonld.frame(input, frame, options);\n};\n\n/**\n * Performs RDF dataset normalization on the given input. The input is JSON-LD\n * unless the 'inputFormat' option is used. The output is an RDF dataset\n * unless the 'format' option is used.\n *\n * @param input the input to normalize as JSON-LD or as a format specified by\n * the 'inputFormat' option.\n * @param [options] the options to use:\n * [algorithm] the normalization algorithm to use, `URDNA2015` or\n * `URGNA2012` (default: `URDNA2015`).\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [skipExpansion] true to assume the input is expanded and skip\n * expansion, false not to, defaults to false.\n * [inputFormat] the format if input is not JSON-LD:\n * 'application/n-quads' for N-Quads.\n * [format] the format if output is a string:\n * 'application/n-quads' for N-Quads.\n * [documentLoader(url, options)] the document loader.\n * [useNative] true to use a native canonize algorithm\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the normalized output.\n */\njsonld.normalize = jsonld.canonize = async function(input, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not canonize, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n algorithm: 'URDNA2015',\n skipExpansion: false,\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n if('inputFormat' in options) {\n if(options.inputFormat !== 'application/n-quads' &&\n options.inputFormat !== 'application/nquads') {\n throw new JsonLdError(\n 'Unknown canonicalization input format.',\n 'jsonld.CanonizeError');\n }\n // TODO: `await` for async parsers\n const parsedInput = NQuads.parse(input);\n\n // do canonicalization\n return canonize.canonize(parsedInput, options);\n }\n\n // convert to RDF dataset then do normalization\n const opts = {...options};\n delete opts.format;\n opts.produceGeneralizedRdf = false;\n const dataset = await jsonld.toRDF(input, opts);\n\n // do canonicalization\n return canonize.canonize(dataset, options);\n};\n\n/**\n * Converts an RDF dataset to JSON-LD.\n *\n * @param dataset a serialized string of RDF in a format specified by the\n * format option or an RDF dataset to convert.\n * @param [options] the options to use:\n * [format] the format if dataset param must first be parsed:\n * 'application/n-quads' for N-Quads (default).\n * [rdfParser] a custom RDF-parser to use to parse the dataset.\n * [useRdfType] true to use rdf:type, false to use @type\n * (default: false).\n * [useNativeTypes] true to convert XSD types into native types\n * (boolean, integer, double), false not to (default: false).\n *\n * @return a Promise that resolves to the JSON-LD document.\n */\njsonld.fromRDF = async function(dataset, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not convert from RDF, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n format: _isString(dataset) ? 'application/n-quads' : undefined\n });\n\n const {format} = options;\n let {rdfParser} = options;\n\n // handle special format\n if(format) {\n // check supported formats\n rdfParser = rdfParser || _rdfParsers[format];\n if(!rdfParser) {\n throw new JsonLdError(\n 'Unknown input format.',\n 'jsonld.UnknownFormat', {format});\n }\n } else {\n // no-op parser, assume dataset already parsed\n rdfParser = () => dataset;\n }\n\n // rdfParser must be synchronous or return a promise, no callback support\n const parsedDataset = await rdfParser(dataset);\n return _fromRDF(parsedDataset, options);\n};\n\n/**\n * Outputs the RDF dataset found in the given JSON-LD object.\n *\n * @param input the JSON-LD input.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [skipExpansion] true to assume the input is expanded and skip\n * expansion, false not to, defaults to false.\n * [format] the format to use to output a string:\n * 'application/n-quads' for N-Quads.\n * [produceGeneralizedRdf] true to output generalized RDF, false\n * to produce only standard RDF (default: false).\n * [documentLoader(url, options)] the document loader.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the RDF dataset.\n */\njsonld.toRDF = async function(input, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not convert to RDF, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n skipExpansion: false,\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // TODO: support toRDF custom map?\n let expanded;\n if(options.skipExpansion) {\n expanded = input;\n } else {\n // expand input\n expanded = await jsonld.expand(input, options);\n }\n\n // output RDF dataset\n const dataset = _toRDF(expanded, options);\n if(options.format) {\n if(options.format === 'application/n-quads' ||\n options.format === 'application/nquads') {\n return NQuads.serialize(dataset);\n }\n throw new JsonLdError(\n 'Unknown output format.',\n 'jsonld.UnknownFormat', {format: options.format});\n }\n\n return dataset;\n};\n\n/**\n * **Experimental**\n *\n * Recursively flattens the nodes in the given JSON-LD input into a merged\n * map of node ID => node. All graphs will be merged into the default graph.\n *\n * @param input the JSON-LD input.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n * [documentLoader(url, options)] the document loader.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the merged node map.\n */\njsonld.createNodeMap = async function(input, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not create node map, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // expand input\n const expanded = await jsonld.expand(input, options);\n\n return _createMergedNodeMap(expanded, options);\n};\n\n/**\n * **Experimental**\n *\n * Merges two or more JSON-LD documents into a single flattened document.\n *\n * @param docs the JSON-LD documents to merge together.\n * @param ctx the context to use to compact the merged result, or null.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n * [mergeNodes] true to merge properties for nodes with the same ID,\n * false to ignore new properties for nodes with the same ID once\n * the ID has been defined; note that this may not prevent merging\n * new properties where a node is in the `object` position\n * (default: true).\n * [documentLoader(url, options)] the document loader.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the merged output.\n */\njsonld.merge = async function(docs, ctx, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not merge, too few arguments.');\n }\n if(!_isArray(docs)) {\n throw new TypeError('Could not merge, \"docs\" must be an array.');\n }\n\n if(typeof ctx === 'function') {\n ctx = null;\n } else {\n ctx = ctx || null;\n }\n\n // set default options\n options = _setDefaults(options, {\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // expand all documents\n const expanded = await Promise.all(docs.map(doc => {\n const opts = {...options};\n return jsonld.expand(doc, opts);\n }));\n\n let mergeNodes = true;\n if('mergeNodes' in options) {\n mergeNodes = options.mergeNodes;\n }\n\n const issuer = options.issuer || new IdentifierIssuer('_:b');\n const graphs = {'@default': {}};\n\n for(let i = 0; i < expanded.length; ++i) {\n // uniquely relabel blank nodes\n const doc = util.relabelBlankNodes(expanded[i], {\n issuer: new IdentifierIssuer('_:b' + i + '-')\n });\n\n // add nodes to the shared node map graphs if merging nodes, to a\n // separate graph set if not\n const _graphs = (mergeNodes || i === 0) ? graphs : {'@default': {}};\n _createNodeMap(doc, _graphs, '@default', issuer);\n\n if(_graphs !== graphs) {\n // merge document graphs but don't merge existing nodes\n for(const graphName in _graphs) {\n const _nodeMap = _graphs[graphName];\n if(!(graphName in graphs)) {\n graphs[graphName] = _nodeMap;\n continue;\n }\n const nodeMap = graphs[graphName];\n for(const key in _nodeMap) {\n if(!(key in nodeMap)) {\n nodeMap[key] = _nodeMap[key];\n }\n }\n }\n }\n }\n\n // add all non-default graphs to default graph\n const defaultGraph = _mergeNodeMaps(graphs);\n\n // produce flattened output\n const flattened = [];\n const keys = Object.keys(defaultGraph).sort();\n for(let ki = 0; ki < keys.length; ++ki) {\n const node = defaultGraph[keys[ki]];\n // only add full subjects to top-level\n if(!_isSubjectReference(node)) {\n flattened.push(node);\n }\n }\n\n if(ctx === null) {\n return flattened;\n }\n\n // compact result (force @graph option to true, skip expansion)\n options.graph = true;\n options.skipExpansion = true;\n const compacted = await jsonld.compact(flattened, ctx, options);\n\n return compacted;\n};\n\n/**\n * The default document loader for external documents.\n *\n * @param url the URL to load.\n *\n * @return a promise that resolves to the remote document.\n */\nObject.defineProperty(jsonld, 'documentLoader', {\n get: () => jsonld._documentLoader,\n set: v => jsonld._documentLoader = v\n});\n// default document loader not implemented\njsonld.documentLoader = async url => {\n throw new JsonLdError(\n 'Could not retrieve a JSON-LD document from the URL. URL ' +\n 'dereferencing not implemented.', 'jsonld.LoadDocumentError',\n {code: 'loading document failed', url});\n};\n\n/**\n * Gets a remote JSON-LD document using the default document loader or\n * one given in the passed options.\n *\n * @param url the URL to fetch.\n * @param [options] the options to use:\n * [documentLoader] the document loader to use.\n *\n * @return a Promise that resolves to the retrieved remote document.\n */\njsonld.get = async function(url, options) {\n let load;\n if(typeof options.documentLoader === 'function') {\n load = options.documentLoader;\n } else {\n load = jsonld.documentLoader;\n }\n\n const remoteDoc = await load(url);\n\n try {\n if(!remoteDoc.document) {\n throw new JsonLdError(\n 'No remote document found at the given URL.',\n 'jsonld.NullRemoteDocument');\n }\n if(_isString(remoteDoc.document)) {\n remoteDoc.document = JSON.parse(remoteDoc.document);\n }\n } catch(e) {\n throw new JsonLdError(\n 'Could not retrieve a JSON-LD document from the URL.',\n 'jsonld.LoadDocumentError', {\n code: 'loading document failed',\n cause: e,\n remoteDoc\n });\n }\n\n return remoteDoc;\n};\n\n/**\n * Processes a local context, resolving any URLs as necessary, and returns a\n * new active context.\n *\n * @param activeCtx the current active context.\n * @param localCtx the local context to process.\n * @param [options] the options to use:\n * [documentLoader(url, options)] the document loader.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the new active context.\n */\njsonld.processContext = async function(\n activeCtx, localCtx, options) {\n // set default options\n options = _setDefaults(options, {\n base: '',\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // return initial context early for null context\n if(localCtx === null) {\n return _getInitialContext(options);\n }\n\n // get URLs in localCtx\n localCtx = util.clone(localCtx);\n if(!(_isObject(localCtx) && '@context' in localCtx)) {\n localCtx = {'@context': localCtx};\n }\n\n return _processContext({activeCtx, localCtx, options});\n};\n\n// backwards compatibility\njsonld.getContextValue = require('./context').getContextValue;\n\n/**\n * Document loaders.\n */\njsonld.documentLoaders = {};\n\n/**\n * Assigns the default document loader for external document URLs to a built-in\n * default. Supported types currently include: 'xhr' and 'node'.\n *\n * @param type the type to set.\n * @param [params] the parameters required to use the document loader.\n */\njsonld.useDocumentLoader = function(type) {\n if(!(type in jsonld.documentLoaders)) {\n throw new JsonLdError(\n 'Unknown document loader type: \"' + type + '\"',\n 'jsonld.UnknownDocumentLoader',\n {type});\n }\n\n // set document loader\n jsonld.documentLoader = jsonld.documentLoaders[type].apply(\n jsonld, Array.prototype.slice.call(arguments, 1));\n};\n\n/**\n * Registers an RDF dataset parser by content-type, for use with\n * jsonld.fromRDF. An RDF dataset parser will always be given one parameter,\n * a string of input. An RDF dataset parser can be synchronous or\n * asynchronous (by returning a promise).\n *\n * @param contentType the content-type for the parser.\n * @param parser(input) the parser function (takes a string as a parameter\n * and either returns an RDF dataset or a Promise that resolves to one.\n */\njsonld.registerRDFParser = function(contentType, parser) {\n _rdfParsers[contentType] = parser;\n};\n\n/**\n * Unregisters an RDF dataset parser by content-type.\n *\n * @param contentType the content-type for the parser.\n */\njsonld.unregisterRDFParser = function(contentType) {\n delete _rdfParsers[contentType];\n};\n\n// register the N-Quads RDF parser\njsonld.registerRDFParser('application/n-quads', NQuads.parse);\njsonld.registerRDFParser('application/nquads', NQuads.parse);\n\n/* URL API */\njsonld.url = require('./url');\n\n/* Utility API */\njsonld.util = util;\n// backwards compatibility\nObject.assign(jsonld, util);\n\n// reexpose API as jsonld.promises for backwards compatability\njsonld.promises = jsonld;\n\n// backwards compatibility\njsonld.RequestQueue = require('./RequestQueue');\n\n/* WebIDL API */\njsonld.JsonLdProcessor = require('./JsonLdProcessor')(jsonld);\n\nplatform.setupGlobals(jsonld);\nplatform.setupDocumentLoaders(jsonld);\n\nfunction _setDefaults(options, {\n documentLoader = jsonld.documentLoader,\n ...defaults\n}) {\n return Object.assign({}, {documentLoader}, defaults, options);\n}\n\n// end of jsonld API `wrapper` factory\nreturn jsonld;\n};\n\n// external APIs:\n\n// used to generate a new jsonld API instance\nconst factory = function() {\n return wrapper(function() {\n return factory();\n });\n};\n\n// wrap the main jsonld API instance\nwrapper(factory);\n// export API\nmodule.exports = factory;\n","// **N3Util** provides N3 utility functions.\n\nimport N3DataFactory from './N3DataFactory';\n\n// Tests whether the given term represents an IRI\nexport function isNamedNode(term) {\n return !!term && term.termType === 'NamedNode';\n}\n\n// Tests whether the given term represents a blank node\nexport function isBlankNode(term) {\n return !!term && term.termType === 'BlankNode';\n}\n\n// Tests whether the given term represents a literal\nexport function isLiteral(term) {\n return !!term && term.termType === 'Literal';\n}\n\n// Tests whether the given term represents a variable\nexport function isVariable(term) {\n return !!term && term.termType === 'Variable';\n}\n\n// Tests whether the given term represents the default graph\nexport function isDefaultGraph(term) {\n return !!term && term.termType === 'DefaultGraph';\n}\n\n// Tests whether the given quad is in the default graph\nexport function inDefaultGraph(quad) {\n return isDefaultGraph(quad.graph);\n}\n\n// Creates a function that prepends the given IRI to a local name\nexport function prefix(iri, factory) {\n return prefixes({ '': iri }, factory)('');\n}\n\n// Creates a function that allows registering and expanding prefixes\nexport function prefixes(defaultPrefixes, factory) {\n // Add all of the default prefixes\n const prefixes = Object.create(null);\n for (const prefix in defaultPrefixes)\n processPrefix(prefix, defaultPrefixes[prefix]);\n // Set the default factory if none was specified\n factory = factory || N3DataFactory;\n\n // Registers a new prefix (if an IRI was specified)\n // or retrieves a function that expands an existing prefix (if no IRI was specified)\n function processPrefix(prefix, iri) {\n // Create a new prefix if an IRI is specified or the prefix doesn't exist\n if (typeof iri === 'string') {\n // Create a function that expands the prefix\n const cache = Object.create(null);\n prefixes[prefix] = local => {\n return cache[local] || (cache[local] = factory.namedNode(iri + local));\n };\n }\n else if (!(prefix in prefixes)) {\n throw new Error(`Unknown prefix: ${prefix}`);\n }\n return prefixes[prefix];\n }\n return processPrefix;\n}\n","module.exports = __WEBPACK_EXTERNAL_MODULE__56__;","/**\n * An implementation of the RDF Dataset Normalization specification.\n *\n * @author Dave Longley\n *\n * Copyright 2010-2021 Digital Bazaar, Inc.\n */\nmodule.exports = require('./lib');\n","/*\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nmodule.exports = class IdentifierIssuer {\n /**\n * Creates a new IdentifierIssuer. A IdentifierIssuer issues unique\n * identifiers, keeping track of any previously issued identifiers.\n *\n * @param prefix the prefix to use ('<prefix><counter>').\n * @param existing an existing Map to use.\n * @param counter the counter to use.\n */\n constructor(prefix, existing = new Map(), counter = 0) {\n this.prefix = prefix;\n this._existing = existing;\n this.counter = counter;\n }\n\n /**\n * Copies this IdentifierIssuer.\n *\n * @return a copy of this IdentifierIssuer.\n */\n clone() {\n const {prefix, _existing, counter} = this;\n return new IdentifierIssuer(prefix, new Map(_existing), counter);\n }\n\n /**\n * Gets the new identifier for the given old identifier, where if no old\n * identifier is given a new identifier will be generated.\n *\n * @param [old] the old identifier to get the new identifier for.\n *\n * @return the new identifier.\n */\n getId(old) {\n // return existing old identifier\n const existing = old && this._existing.get(old);\n if(existing) {\n return existing;\n }\n\n // get next identifier\n const identifier = this.prefix + this.counter;\n this.counter++;\n\n // save mapping\n if(old) {\n this._existing.set(old, identifier);\n }\n\n return identifier;\n }\n\n /**\n * Returns true if the given old identifer has already been assigned a new\n * identifier.\n *\n * @param old the old identifier to check.\n *\n * @return true if the old identifier has been assigned a new identifier,\n * false if not.\n */\n hasId(old) {\n return this._existing.has(old);\n }\n\n /**\n * Returns all of the IDs that have been issued new IDs in the order in\n * which they were issued new IDs.\n *\n * @return the list of old IDs that has been issued new IDs in order.\n */\n getOldIds() {\n return [...this._existing.keys()];\n }\n};\n","/*\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\n// eslint-disable-next-line no-unused-vars\nconst TERMS = ['subject', 'predicate', 'object', 'graph'];\nconst RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';\nconst RDF_LANGSTRING = RDF + 'langString';\nconst XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string';\n\nconst TYPE_NAMED_NODE = 'NamedNode';\nconst TYPE_BLANK_NODE = 'BlankNode';\nconst TYPE_LITERAL = 'Literal';\nconst TYPE_DEFAULT_GRAPH = 'DefaultGraph';\n\n// build regexes\nconst REGEX = {};\n(() => {\n const iri = '(?:<([^:]+:[^>]*)>)';\n // https://www.w3.org/TR/turtle/#grammar-production-BLANK_NODE_LABEL\n const PN_CHARS_BASE =\n 'A-Z' + 'a-z' +\n '\\u00C0-\\u00D6' +\n '\\u00D8-\\u00F6' +\n '\\u00F8-\\u02FF' +\n '\\u0370-\\u037D' +\n '\\u037F-\\u1FFF' +\n '\\u200C-\\u200D' +\n '\\u2070-\\u218F' +\n '\\u2C00-\\u2FEF' +\n '\\u3001-\\uD7FF' +\n '\\uF900-\\uFDCF' +\n '\\uFDF0-\\uFFFD';\n // TODO:\n //'\\u10000-\\uEFFFF';\n const PN_CHARS_U =\n PN_CHARS_BASE +\n '_';\n const PN_CHARS =\n PN_CHARS_U +\n '0-9' +\n '-' +\n '\\u00B7' +\n '\\u0300-\\u036F' +\n '\\u203F-\\u2040';\n const BLANK_NODE_LABEL =\n '(_:' +\n '(?:[' + PN_CHARS_U + '0-9])' +\n '(?:(?:[' + PN_CHARS + '.])*(?:[' + PN_CHARS + ']))?' +\n ')';\n const bnode = BLANK_NODE_LABEL;\n const plain = '\"([^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*)\"';\n const datatype = '(?:\\\\^\\\\^' + iri + ')';\n const language = '(?:@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*))';\n const literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)';\n const ws = '[ \\\\t]+';\n const wso = '[ \\\\t]*';\n\n // define quad part regexes\n const subject = '(?:' + iri + '|' + bnode + ')' + ws;\n const property = iri + ws;\n const object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso;\n const graphName = '(?:\\\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\\\.))';\n\n // end of line and empty regexes\n REGEX.eoln = /(?:\\r\\n)|(?:\\n)|(?:\\r)/g;\n REGEX.empty = new RegExp('^' + wso + '$');\n\n // full quad regex\n REGEX.quad = new RegExp(\n '^' + wso + subject + property + object + graphName + wso + '$');\n})();\n\nmodule.exports = class NQuads {\n /**\n * Parses RDF in the form of N-Quads.\n *\n * @param input the N-Quads input to parse.\n *\n * @return an RDF dataset (an array of quads per http://rdf.js.org/).\n */\n static parse(input) {\n // build RDF dataset\n const dataset = [];\n\n const graphs = {};\n\n // split N-Quad input into lines\n const lines = input.split(REGEX.eoln);\n let lineNumber = 0;\n for(const line of lines) {\n lineNumber++;\n\n // skip empty lines\n if(REGEX.empty.test(line)) {\n continue;\n }\n\n // parse quad\n const match = line.match(REGEX.quad);\n if(match === null) {\n throw new Error('N-Quads parse error on line ' + lineNumber + '.');\n }\n\n // create RDF quad\n const quad = {subject: null, predicate: null, object: null, graph: null};\n\n // get subject\n if(match[1] !== undefined) {\n quad.subject = {termType: TYPE_NAMED_NODE, value: match[1]};\n } else {\n quad.subject = {termType: TYPE_BLANK_NODE, value: match[2]};\n }\n\n // get predicate\n quad.predicate = {termType: TYPE_NAMED_NODE, value: match[3]};\n\n // get object\n if(match[4] !== undefined) {\n quad.object = {termType: TYPE_NAMED_NODE, value: match[4]};\n } else if(match[5] !== undefined) {\n quad.object = {termType: TYPE_BLANK_NODE, value: match[5]};\n } else {\n quad.object = {\n termType: TYPE_LITERAL,\n value: undefined,\n datatype: {\n termType: TYPE_NAMED_NODE\n }\n };\n if(match[7] !== undefined) {\n quad.object.datatype.value = match[7];\n } else if(match[8] !== undefined) {\n quad.object.datatype.value = RDF_LANGSTRING;\n quad.object.language = match[8];\n } else {\n quad.object.datatype.value = XSD_STRING;\n }\n quad.object.value = _unescape(match[6]);\n }\n\n // get graph\n if(match[9] !== undefined) {\n quad.graph = {\n termType: TYPE_NAMED_NODE,\n value: match[9]\n };\n } else if(match[10] !== undefined) {\n quad.graph = {\n termType: TYPE_BLANK_NODE,\n value: match[10]\n };\n } else {\n quad.graph = {\n termType: TYPE_DEFAULT_GRAPH,\n value: ''\n };\n }\n\n // only add quad if it is unique in its graph\n if(!(quad.graph.value in graphs)) {\n graphs[quad.graph.value] = [quad];\n dataset.push(quad);\n } else {\n let unique = true;\n const quads = graphs[quad.graph.value];\n for(const q of quads) {\n if(_compareTriples(q, quad)) {\n unique = false;\n break;\n }\n }\n if(unique) {\n quads.push(quad);\n dataset.push(quad);\n }\n }\n }\n\n return dataset;\n }\n\n /**\n * Converts an RDF dataset to N-Quads.\n *\n * @param dataset (array of quads) the RDF dataset to convert.\n *\n * @return the N-Quads string.\n */\n static serialize(dataset) {\n if(!Array.isArray(dataset)) {\n dataset = NQuads.legacyDatasetToQuads(dataset);\n }\n const quads = [];\n for(const quad of dataset) {\n quads.push(NQuads.serializeQuad(quad));\n }\n return quads.sort().join('');\n }\n\n /**\n * Converts an RDF quad to an N-Quad string (a single quad).\n *\n * @param quad the RDF quad convert.\n *\n * @return the N-Quad string.\n */\n static serializeQuad(quad) {\n const s = quad.subject;\n const p = quad.predicate;\n const o = quad.object;\n const g = quad.graph;\n\n let nquad = '';\n\n // subject can only be NamedNode or BlankNode\n if(s.termType === TYPE_NAMED_NODE) {\n nquad += `<${s.value}>`;\n } else {\n nquad += `${s.value}`;\n }\n\n // predicate can only be NamedNode\n nquad += ` <${p.value}> `;\n\n // object is NamedNode, BlankNode, or Literal\n if(o.termType === TYPE_NAMED_NODE) {\n nquad += `<${o.value}>`;\n } else if(o.termType === TYPE_BLANK_NODE) {\n nquad += o.value;\n } else {\n nquad += `\"${_escape(o.value)}\"`;\n if(o.datatype.value === RDF_LANGSTRING) {\n if(o.language) {\n nquad += `@${o.language}`;\n }\n } else if(o.datatype.value !== XSD_STRING) {\n nquad += `^^<${o.datatype.value}>`;\n }\n }\n\n // graph can only be NamedNode or BlankNode (or DefaultGraph, but that\n // does not add to `nquad`)\n if(g.termType === TYPE_NAMED_NODE) {\n nquad += ` <${g.value}>`;\n } else if(g.termType === TYPE_BLANK_NODE) {\n nquad += ` ${g.value}`;\n }\n\n nquad += ' .\\n';\n return nquad;\n }\n\n /**\n * Converts a legacy-formatted dataset to an array of quads dataset per\n * http://rdf.js.org/.\n *\n * @param dataset the legacy dataset to convert.\n *\n * @return the array of quads dataset.\n */\n static legacyDatasetToQuads(dataset) {\n const quads = [];\n\n const termTypeMap = {\n 'blank node': TYPE_BLANK_NODE,\n IRI: TYPE_NAMED_NODE,\n literal: TYPE_LITERAL\n };\n\n for(const graphName in dataset) {\n const triples = dataset[graphName];\n triples.forEach(triple => {\n const quad = {};\n for(const componentName in triple) {\n const oldComponent = triple[componentName];\n const newComponent = {\n termType: termTypeMap[oldComponent.type],\n value: oldComponent.value\n };\n if(newComponent.termType === TYPE_LITERAL) {\n newComponent.datatype = {\n termType: TYPE_NAMED_NODE\n };\n if('datatype' in oldComponent) {\n newComponent.datatype.value = oldComponent.datatype;\n }\n if('language' in oldComponent) {\n if(!('datatype' in oldComponent)) {\n newComponent.datatype.value = RDF_LANGSTRING;\n }\n newComponent.language = oldComponent.language;\n } else if(!('datatype' in oldComponent)) {\n newComponent.datatype.value = XSD_STRING;\n }\n }\n quad[componentName] = newComponent;\n }\n if(graphName === '@default') {\n quad.graph = {\n termType: TYPE_DEFAULT_GRAPH,\n value: ''\n };\n } else {\n quad.graph = {\n termType: graphName.startsWith('_:') ?\n TYPE_BLANK_NODE : TYPE_NAMED_NODE,\n value: graphName\n };\n }\n quads.push(quad);\n });\n }\n\n return quads;\n }\n};\n\n/**\n * Compares two RDF triples for equality.\n *\n * @param t1 the first triple.\n * @param t2 the second triple.\n *\n * @return true if the triples are the same, false if not.\n */\nfunction _compareTriples(t1, t2) {\n // compare subject and object types first as it is the quickest check\n if(!(t1.subject.termType === t2.subject.termType &&\n t1.object.termType === t2.object.termType)) {\n return false;\n }\n // compare values\n if(!(t1.subject.value === t2.subject.value &&\n t1.predicate.value === t2.predicate.value &&\n t1.object.value === t2.object.value)) {\n return false;\n }\n if(t1.object.termType !== TYPE_LITERAL) {\n // no `datatype` or `language` to check\n return true;\n }\n return (\n (t1.object.datatype.termType === t2.object.datatype.termType) &&\n (t1.object.language === t2.object.language) &&\n (t1.object.datatype.value === t2.object.datatype.value)\n );\n}\n\nconst _escapeRegex = /[\"\\\\\\n\\r]/g;\n/**\n * Escape string to N-Quads literal\n */\nfunction _escape(s) {\n return s.replace(_escapeRegex, function(match) {\n switch(match) {\n case '\"': return '\\\\\"';\n case '\\\\': return '\\\\\\\\';\n case '\\n': return '\\\\n';\n case '\\r': return '\\\\r';\n }\n });\n}\n\nconst _unescapeRegex =\n /(?:\\\\([tbnrf\"'\\\\]))|(?:\\\\u([0-9A-Fa-f]{4}))|(?:\\\\U([0-9A-Fa-f]{8}))/g;\n/**\n * Unescape N-Quads literal to string\n */\nfunction _unescape(s) {\n return s.replace(_unescapeRegex, function(match, code, u, U) {\n if(code) {\n switch(code) {\n case 't': return '\\t';\n case 'b': return '\\b';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 'f': return '\\f';\n case '\"': return '\"';\n case '\\'': return '\\'';\n case '\\\\': return '\\\\';\n }\n }\n if(u) {\n return String.fromCharCode(parseInt(u, 16));\n }\n if(U) {\n // FIXME: support larger values\n throw new Error('Unsupported U escape');\n }\n });\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';\nconst XSD = 'http://www.w3.org/2001/XMLSchema#';\n\nmodule.exports = {\n // TODO: Deprecated and will be removed later. Use LINK_HEADER_CONTEXT.\n LINK_HEADER_REL: 'http://www.w3.org/ns/json-ld#context',\n\n LINK_HEADER_CONTEXT: 'http://www.w3.org/ns/json-ld#context',\n\n RDF,\n RDF_LIST: RDF + 'List',\n RDF_FIRST: RDF + 'first',\n RDF_REST: RDF + 'rest',\n RDF_NIL: RDF + 'nil',\n RDF_TYPE: RDF + 'type',\n RDF_PLAIN_LITERAL: RDF + 'PlainLiteral',\n RDF_XML_LITERAL: RDF + 'XMLLiteral',\n RDF_JSON_LITERAL: RDF + 'JSON',\n RDF_OBJECT: RDF + 'object',\n RDF_LANGSTRING: RDF + 'langString',\n\n XSD,\n XSD_BOOLEAN: XSD + 'boolean',\n XSD_DOUBLE: XSD + 'double',\n XSD_INTEGER: XSD + 'integer',\n XSD_STRING: XSD + 'string',\n};\n","import Node from './node-internal'\nimport { EmptyTermType } from './types'\nimport { Term } from './tf-types'\n\n/**\n* An empty node\n*/\nexport default class Empty extends Node implements Term {\n termType: typeof EmptyTermType = EmptyTermType\n\n constructor () {\n super('')\n }\n\n toString () {\n return '()'\n }\n}\n","export default (function () {\r\n return {\r\n parseJSON: function (data, source, store) {\r\n var subject, predicate, object\r\n var bnodes = {}\r\n var why = store.sym(source)\r\n for (var x in data) {\r\n if (x.indexOf('_:') === 0) {\r\n if (bnodes[x]) {\r\n subject = bnodes[x]\r\n } else {\r\n subject = store.bnode(x)\r\n bnodes[x] = subject\r\n }\r\n } else {\r\n subject = store.sym(x)\r\n }\r\n var preds = data[x]\r\n for (var y in preds) {\r\n var objects = preds[y]\r\n predicate = store.sym(y)\r\n for (var z in objects) {\r\n var obj = objects[z]\r\n if (obj.type === 'uri') {\r\n object = store.sym(obj.value)\r\n store.add(subject, predicate, object, why)\r\n } else if (obj.type === 'BlankNode') {\r\n if (bnodes[obj.value]) {\r\n object = bnodes[obj.value]\r\n } else {\r\n object = store.bnode(obj.value)\r\n bnodes[obj.value] = object\r\n }\r\n store.add(subject, predicate, object, why)\r\n } else if (obj.type === 'Literal') {\r\n // var datatype\r\n if (obj.datatype) {\r\n object = store.literal(obj.value, undefined, store.sym(obj.datatype))\r\n } else if (obj.lang) {\r\n object = store.literal(obj.value, obj.lang)\r\n } else {\r\n object = store.literal(obj.value)\r\n }\r\n store.add(subject, predicate, object, why)\r\n } else {\r\n throw new Error('error: unexpected termtype: ' + z.type)\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n})()\r\n","import log from './log'\n\nexport default function queryToSPARQL (query) {\n var indent = 0\n function getSelect (query) {\n var str = addIndent() + 'SELECT '\n for (var i = 0; i < query.vars.length; i++) {\n str += query.vars[i] + ' '\n }\n str += '\\n'\n return str\n }\n\n function getPattern (pat) {\n var str = ''\n var st = pat.statements\n for (var x in st) {\n log.debug('Found statement: ' + st)\n str += addIndent() + st[x] + '\\n'\n }\n return str\n }\n\n function getConstraints (pat) {\n var str = ''\n for (var v in pat.constraints) {\n var foo = pat.constraints[v]\n str += addIndent() + 'FILTER ( ' + foo.describe(v) + ' ) ' + '\\n'\n }\n return str\n }\n\n function getOptionals (pat) {\n var str = ''\n for (var x = 0; x < pat.optional.length; x++) {\n // alert(pat.optional.termType)\n log.debug('Found optional query')\n str += addIndent() + 'OPTIONAL { ' + '\\n'\n indent++\n str += getPattern(pat.optional[x])\n str += getConstraints(pat.optional[x])\n str += getOptionals(pat.optional[x])\n indent--\n str += addIndent() + '}' + '\\n'\n }\n return str\n }\n\n function getWhere (pat) {\n var str = addIndent() + 'WHERE \\n' + '{ \\n'\n indent++\n str += getPattern(pat)\n str += getConstraints(pat)\n str += getOptionals(pat)\n indent--\n str += '}'\n return str\n }\n\n function addIndent () {\n var str = ''\n for (var i = 0; i < indent; i++) {\n str += ' '\n }\n return str\n }\n\n function getSPARQL (query) {\n return getSelect(query) + getWhere(query.pat)\n }\n\n return getSPARQL(query)\n}\n","// Converting between SPARQL queries and the $rdf query API\n/*\n\nfunction SQuery () {\n this.terms = []\n return this\n}\n\nSTerm.prototype.toString = STerm.val\nSQuery.prototype.add = function (str) {this.terms.push()}*/\n\nimport log from './log'\nimport { Query } from './query'\n\n/**\n * @SPARQL: SPARQL text that is converted to a query object which is returned.\n * @testMode: testing flag. Prevents loading of sources.\n */\nexport default function SPARQLToQuery (SPARQL, testMode, kb) {\n // AJAR_ClearTable()\n var variableHash = []\n function makeVar (name) {\n if (variableHash[name]) {\n return variableHash[name]\n }\n var newVar = kb.variable(name)\n variableHash[name] = newVar\n return newVar\n }\n\n // term type functions\n function isRealText (term) {\n return (typeof term === 'string' && term.match(/[^ \\n\\t]/))\n }\n function isVar (term) {\n return (typeof term === 'string' && term.match(/^[\\?\\$]/))\n }\n function fixSymbolBrackets (term) {\n if (typeof term === 'string') {\n return term.replace(/^</, '<').replace(/>$/, '>')\n } else {\n return term\n }\n }\n function isSymbol (term) {\n return (typeof term === 'string' && term.match(/^<[^>]*>$/))\n }\n function isBnode (term) {\n return (typeof term === 'string' && (term.match(/^_:/) || term.match(/^$/)))\n }\n function isPrefix (term) {\n return (typeof term === 'string' && term.match(/:$/))\n }\n function isPrefixedSymbol (term) {\n return (typeof term === 'string' && term.match(/^:|^[^_][^:]*:/))\n }\n function getPrefix (term) {\n var a = term.split(':')\n return a[0]\n }\n function getSuffix (term) {\n var a = term.split(':')\n return a[1]\n }\n function removeBrackets (term) {\n if (isSymbol(term)) {\n return term.slice(1, term.length - 1)\n } else {\n return term\n }\n }\n // takes a string and returns an array of strings and Literals in the place of literals\n function parseLiterals (str) {\n // var sin = (str.indexOf(/[ \\n]\\'/)==-1)?null:str.indexOf(/[ \\n]\\'/), doub = (str.indexOf(/[ \\n]\\\"/)==-1)?null:str.indexOf(/[ \\n]\\\"/)\n var sin = (str.indexOf(\"'\") === -1)\n ? null\n : str.indexOf(\"'\")\n var doub = (str.indexOf('\"') === -1)\n ? null\n : str.indexOf('\"')\n // alert(\"S: \"+sin+\" D: \"+doub)\n if (!sin && !doub) {\n var a = new Array(1)\n a[0] = str\n return a\n }\n var res = new Array(2)\n var br\n var ind\n if (!sin || (doub && doub < sin)) {\n br = '\"'\n ind = doub\n } else if (!doub || (sin && sin < doub)) {\n br = \"'\"\n ind = sin\n } else {\n log.error('SQARQL QUERY OOPS!')\n return res\n }\n res[0] = str.slice(0, ind)\n var end = str.slice(ind + 1).indexOf(br)\n if (end === -1) {\n log.error('SPARQL parsing error: no matching parentheses in literal ' + str)\n return str\n }\n // alert(str.slice(end + ind + 2).match(/^\\^\\^/))\n var end2\n if (str.slice(end + ind + 2).match(/^\\^\\^/)) {\n end2 = str.slice(end + ind + 2).indexOf(' ')\n // alert(end2)\n res[1] = kb.literal(\n str.slice(ind + 1, ind + 1 + end),\n kb.sym(removeBrackets(\n str.slice(ind + 4 + end, ind + 2 + end + end2))\n )\n )\n // alert(res[1].datatype.uri)\n res = res.concat(parseLiterals(str.slice(end + ind + 3 + end2)))\n } else if (str.slice(end + ind + 2).match(/^@/)) {\n end2 = str.slice(end + ind + 2).indexOf(' ')\n // alert(end2)\n res[1] = kb.literal(\n str.slice(ind + 1, ind + 1 + end),\n str.slice(ind + 3 + end, ind + 2 + end + end2), null\n )\n // alert(res[1].datatype.uri)\n res = res.concat(\n parseLiterals(str.slice(end + ind + 2 + end2))\n )\n } else {\n res[1] = kb.literal(str.slice(ind + 1, ind + 1 + end))\n log.info('Literal found: ' + res[1])\n res = res.concat(parseLiterals(str.slice(end + ind + 2))) // finds any other literals\n }\n return res\n }\n\n function spaceDelimit (str) {\n str = str.replace(/\\(/g, ' ( ')\n .replace(/\\)/g, ' ) ')\n .replace(/</g, ' <')\n .replace(/>/g, '> ')\n .replace(/{/g, ' { ')\n .replace(/}/g, ' } ')\n .replace(/[\\t\\n\\r]/g, ' ')\n .replace(/; /g, ' ; ')\n .replace(/\\. /g, ' . ')\n .replace(/, /g, ' , ')\n log.info('New str into spaceDelimit: \\n' + str)\n var res = []\n var br = str.split(' ')\n for (var x in br) {\n if (isRealText(br[x])) {\n res = res.concat(br[x])\n }\n }\n return res\n }\n\n function replaceKeywords (input) {\n var strarr = input\n for (var x = 0; x < strarr.length; x++) {\n if (strarr[x] === 'a') {\n strarr[x] = '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>'\n }\n if (strarr[x] === 'is' && strarr[x + 2] === 'of') {\n strarr.splice(x, 1)\n strarr.splice(x + 1, 1)\n var s = strarr[x - 1]\n strarr[x - 1] = strarr[x + 1]\n strarr[x + 1] = s\n }\n }\n return strarr\n }\n\n function toTerms (input) {\n var res = []\n for (var x = 0; x < input.length; x++) {\n if (typeof input[x] !== 'string') {\n res[x] = input[x]\n continue\n }\n input[x] = fixSymbolBrackets(input[x])\n if (isVar(input[x])) {\n res[x] = makeVar(input[x].slice(1))\n } else if (isBnode(input[x])) {\n log.info(input[x] + ' was identified as a bnode.')\n res[x] = kb.bnode()\n } else if (isSymbol(input[x])) {\n log.info(input[x] + ' was identified as a symbol.')\n res[x] = kb.sym(removeBrackets(input[x]))\n } else if (isPrefixedSymbol(input[x])) {\n log.info(input[x] + ' was identified as a prefixed symbol')\n if (prefixes[getPrefix(input[x])]) {\n res[x] = kb.sym(input[x] = prefixes[getPrefix(input[x])] +\n getSuffix(input[x]))\n } else {\n log.error('SPARQL error: ' + input[x] + ' with prefix ' +\n getPrefix(input[x]) + ' does not have a correct prefix entry.')\n res[x] = input[x]\n }\n } else {\n res[x] = input[x]\n }\n }\n return res\n }\n\n function tokenize (str) {\n var token1 = parseLiterals(str)\n var token2 = []\n for (var x in token1) {\n if (typeof token1[x] === 'string') {\n token2 = token2.concat(spaceDelimit(token1[x]))\n } else {\n token2 = token2.concat(token1[x])\n }\n }\n token2 = replaceKeywords(token2)\n log.info('SPARQL Tokens: ' + token2)\n return token2\n }\n\n // CASE-INSENSITIVE\n function arrayIndexOf (str, arr) {\n for (var i = 0; i < arr.length; i++) {\n if (typeof arr[i] !== 'string') {\n continue\n }\n if (arr[i].toLowerCase() === str.toLowerCase()) {\n return i\n }\n }\n // log.warn(\"No instance of \"+str+\" in array \"+arr)\n return null\n }\n\n // CASE-INSENSITIVE\n function arrayIndicesOf (str, arr) {\n var ind = []\n for (var i = 0; i < arr.length; i++) {\n if (typeof arr[i] !== 'string') {\n continue\n }\n if (arr[i].toLowerCase() === str.toLowerCase()) {\n ind.push(i)\n }\n }\n return ind\n }\n\n function setVars (input, query) {\n log.info('SPARQL vars: ' + input)\n for (var x in input) {\n if (isVar(input[x])) {\n log.info('Added ' + input[x] + ' to query variables from SPARQL')\n var v = makeVar(input[x].slice(1))\n query.vars.push(v)\n v.label = input[x].slice(1)\n } else {\n log.warn('Incorrect SPARQL variable in SELECT: ' + input[x])\n }\n }\n }\n\n function getPrefixDeclarations (input) {\n var prefInd = arrayIndicesOf('PREFIX', input)\n var res = []\n for (var i in prefInd) {\n var a = input[prefInd[i] + 1]\n var b = input[prefInd[i] + 2]\n if (!isPrefix(a)) {\n log.error('Invalid SPARQL prefix: ' + a)\n } else if (!isSymbol(b)) {\n log.error('Invalid SPARQL symbol: ' + b)\n } else {\n log.info('Prefix found: ' + a + ' -> ' + b)\n var pref = getPrefix(a)\n var symbol = removeBrackets(b)\n res[pref] = symbol\n }\n }\n return res\n }\n\n function getMatchingBracket (arr, open, close) {\n log.info('Looking for a close bracket of type ' + close + ' in ' + arr)\n var index = 0\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] === open) {\n index++\n }\n if (arr[i] === close) {\n index--\n }\n if (index < 0) {\n return i\n }\n }\n log.error('Statement had no close parenthesis in SPARQL query')\n return 0\n }\n\n function constraintGreaterThan (value) {\n this.describe = function (varstr) {\n return varstr + ' > ' + value.toNT()\n }\n this.test = function (term) {\n if (term.value.match(/[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?/)) {\n return (parseFloat(term.value) > parseFloat(value))\n } else {\n return (term.toNT() > value.toNT())\n }\n }\n return this\n }\n\n function constraintLessThan (value) { // this is not the recommended usage. Should only work on literal, numeric, dateTime\n this.describe = function (varstr) {\n return varstr + ' < ' + value.toNT()\n }\n this.test = function (term) {\n // this.describe = function (varstr) { return varstr + \" < \"+value }\n if (term.value.match(/[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?/)) {\n return (parseFloat(term.value) < parseFloat(value))\n } else {\n return (term.toNT() < value.toNT())\n }\n }\n return this\n }\n // This should only work on literals but doesn't.\n function ConstraintEqualTo (value) {\n this.describe = function (varstr) {\n return varstr + ' = ' + value.toNT()\n }\n this.test = function (term) {\n return value.equals(term)\n }\n return this\n }\n\n // value must be a literal\n function ConstraintRegexp (value) {\n this.describe = function (varstr) {\n return \"REGEXP( '\" + value + \"' , \" + varstr + ' )'\n }\n this.test = function (term) {\n var str = value\n // str = str.replace(/^//,\"\").replace(//$/,\"\")\n var rg = new RegExp(str)\n if (term.value) {\n return rg.test(term.value)\n } else {\n return false\n }\n }\n }\n\n function setConstraint (input, pat) {\n if (input.length === 3 && input[0].termType === 'Variable' &&\n (input[2].termType === 'NamedNode' || input[2].termType === 'Literal')) {\n if (input[1] === '=') {\n log.debug('Constraint added: ' + input)\n pat.constraints[input[0]] = new ConstraintEqualTo(input[2])\n } else if (input[1] === '>') {\n log.debug('Constraint added: ' + input)\n pat.constraints[input[0]] = new ConstraintEqualTo(input[2])\n } else if (input[1] === '<') {\n log.debug('Constraint added: ' + input)\n pat.constraints[input[0]] = new ConstraintEqualTo(input[2])\n } else {\n log.warn(\"I don't know how to handle the constraint: \" + input)\n }\n } else if (input.length === 6 && typeof input[0] === 'string' &&\n input[0].toLowerCase() === 'regexp' &&\n input[1] === '(' && input[5] === ')' && input[3] === ',' &&\n input[4].termType === 'Variable' && input[2].termType === 'Literal') {\n log.debug('Constraint added: ' + input)\n pat.constraints[input[4]] = new ConstraintRegexp(input[2].value)\n }\n // log.warn(\"I don't know how to handle the constraint: \"+input)\n // alert(\"length: \"+input.length+\" input 0 type: \"+input[0].termType+\" input 1: \"+input[1]+\" input[2] type: \"+input[2].termType)\n }\n\n function setOptional (terms, pat) {\n log.debug('Optional query: ' + terms + ' not yet implemented.')\n var opt = kb.formula()\n setWhere(terms, opt)\n pat.optional.push(opt)\n }\n\n function setWhere (input, pat) {\n var terms = toTerms(input)\n var end\n log.debug('WHERE: ' + terms)\n var opt\n // var opt = arrayIndicesOf(\"OPTIONAL\",terms)\n while (arrayIndexOf('OPTIONAL', terms)) {\n opt = arrayIndexOf('OPTIONAL', terms)\n log.debug('OPT: ' + opt + ' ' + terms[opt] + ' in ' + terms)\n if (terms[opt + 1] !== '{') {\n log.warn('Bad optional opening bracket in word ' + opt)\n }\n end = getMatchingBracket(terms.slice(opt + 2), '{', '}')\n if (end === -1) {\n log.error('No matching bracket in word ' + opt)\n } else {\n setOptional(terms.slice(opt + 2, opt + 2 + end), pat)\n // alert(pat.statements[0].toNT())\n opt = arrayIndexOf('OPTIONAL', terms)\n end = getMatchingBracket(terms.slice(opt + 2), '{', '}')\n terms.splice(opt, end + 3)\n }\n }\n log.debug('WHERE after optionals: ' + terms)\n while (arrayIndexOf('FILTER', terms)) {\n var filt = arrayIndexOf('FILTER', terms)\n if (terms[filt + 1] !== '(') {\n log.warn('Bad filter opening bracket in word ' + filt)\n }\n end = getMatchingBracket(terms.slice(filt + 2), '(', ')')\n if (end === -1) {\n log.error('No matching bracket in word ' + filt)\n } else {\n setConstraint(terms.slice(filt + 2, filt + 2 + end), pat)\n filt = arrayIndexOf('FILTER', terms)\n end = getMatchingBracket(terms.slice(filt + 2), '(', ')')\n terms.splice(filt, end + 3)\n }\n }\n log.debug('WHERE after filters and optionals: ' + terms)\n extractStatements(terms, pat)\n }\n\n function extractStatements (terms, formula) {\n var arrayZero = new Array(1)\n arrayZero[0] = -1 // this is just to add the beginning of the where to the periods index.\n var per = arrayZero.concat(arrayIndicesOf('.', terms))\n var stat = []\n for (var x = 0; x < per.length - 1; x++) {\n stat[x] = terms.slice(per[x] + 1, per[x + 1])\n }\n // Now it's in an array of statements\n for (x in stat) { // THIS MUST BE CHANGED FOR COMMA, SEMICOLON\n log.info('s+p+o ' + x + ' = ' + stat[x])\n var subj = stat[x][0]\n stat[x].splice(0, 1)\n var sem = arrayZero.concat(arrayIndicesOf(';', stat[x]))\n sem.push(stat[x].length)\n var stat2 = []\n for (var y = 0; y < sem.length - 1; y++) {\n stat2[y] = stat[x].slice(sem[y] + 1, sem[y + 1])\n }\n for (x in stat2) {\n log.info('p+o ' + x + ' = ' + stat[x])\n var pred = stat2[x][0]\n stat2[x].splice(0, 1)\n var com = arrayZero.concat(arrayIndicesOf(',', stat2[x]))\n com.push(stat2[x].length)\n var stat3 = []\n for (y = 0; y < com.length - 1; y++) {\n stat3[y] = stat2[x].slice(com[y] + 1, com[y + 1])\n }\n for (x in stat3) {\n var obj = stat3[x][0]\n log.info('Subj=' + subj + ' Pred=' + pred + ' Obj=' + obj)\n formula.add(subj, pred, obj)\n }\n }\n }\n }\n\n // ******************************* Body of SPARQLToQuery ***************************//\n log.info('SPARQL input: \\n' + SPARQL)\n var q = new Query()\n var sp = tokenize(SPARQL) // first tokenize everything\n var prefixes = getPrefixDeclarations(sp)\n if (!prefixes.rdf) {\n prefixes.rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'\n }\n if (!prefixes.rdfs) {\n prefixes.rdfs = 'http://www.w3.org/2000/01/rdf-schema#'\n }\n var selectLoc = arrayIndexOf('SELECT', sp)\n var whereLoc = arrayIndexOf('WHERE', sp)\n if (selectLoc < 0 || whereLoc < 0 || selectLoc > whereLoc) {\n log.error('Invalid or nonexistent SELECT and WHERE tags in SPARQL query')\n return false\n }\n setVars(sp.slice(selectLoc + 1, whereLoc), q)\n\n setWhere(sp.slice(whereLoc + 2, sp.length - 1), q.pat)\n\n if (testMode) {\n return q\n }\n\n for (var x in q.pat.statements) {\n var st = q.pat.statements[x]\n if (st.subject.termType === 'NamedNode') {\n if (kb.fetcher) {\n kb.fetcher.lookUpThing(st.subject, 'sparql:' + st.subject)\n }\n }\n if (st.object.termType === 'NamedNode') {\n if (kb.fetcher) {\n kb.fetcher.lookUpThing(st.object, 'sparql:' + st.object)\n }\n }\n }\n // alert(q.pat)\n return q\n// checkVars()\n// *******************************************************************//\n}\n","/* @file Update Manager Class\n**\n** 2007-07-15 originall sparl update module by Joe Presbrey <presbrey@mit.edu>\n** 2010-08-08 TimBL folded in Kenny's WEBDAV\n** 2010-12-07 TimBL addred local file write code\n*/\nimport IndexedFormula from './store'\nimport { docpart } from './uri'\nimport Fetcher from './fetcher'\nimport Namespace from './namespace'\nimport Serializer from './serializer'\nimport { join as uriJoin } from './uri'\nimport { isStore, isBlankNode } from './utils/terms'\nimport * as Util from './utils-js'\nimport Statement from './statement'\nimport RDFlibNamedNode from './named-node'\nimport { termValue } from './utils/termValue'\nimport {\n BlankNode,\n NamedNode,\n Quad_Graph,\n Quad_Object,\n Quad_Predicate,\n Quad_Subject,\n Quad,\n Term,\n} from './tf-types'\n\ninterface UpdateManagerFormula extends IndexedFormula {\n fetcher: Fetcher\n}\n\ntype CallBackFunction = (uri: string, ok: boolean, message: string, response: Error | Response) => {} | void\n\n/**\n* The UpdateManager is a helper object for a store.\n* Just as a Fetcher provides the store with the ability to read and write,\n* the Update Manager provides functionality for making small patches in real time,\n* and also looking out for concurrent updates from other agents\n*/\nexport default class UpdateManager {\n\n store: UpdateManagerFormula\n\n ifps: {}\n\n fps: {}\n\n /** Index of objects for coordinating incoming and outgoing patches */\n patchControl: []\n\n /** Object of namespaces */\n ns: any\n\n /**\n * @param store - The quadstore to store data and metadata. Created if not passed.\n */\n constructor (store?: IndexedFormula) {\n store = store || new IndexedFormula()\n if (store.updater) {\n throw new Error(\"You can't have two UpdateManagers for the same store\")\n }\n if (!(store as UpdateManagerFormula).fetcher) {\n (store as UpdateManagerFormula).fetcher = new Fetcher(store)\n }\n this.store = store as UpdateManagerFormula\n store.updater = this\n this.ifps = {}\n this.fps = {}\n this.ns = {}\n this.ns.link = Namespace('http://www.w3.org/2007/ont/link#')\n this.ns.http = Namespace('http://www.w3.org/2007/ont/http#')\n this.ns.httph = Namespace('http://www.w3.org/2007/ont/httph#')\n this.ns.ldp = Namespace('http://www.w3.org/ns/ldp#')\n this.ns.rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')\n this.ns.rdfs = Namespace('http://www.w3.org/2000/01/rdf-schema#')\n this.ns.rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')\n this.ns.owl = Namespace('http://www.w3.org/2002/07/owl#')\n\n this.patchControl = []\n }\n\n patchControlFor (doc: NamedNode) {\n if (!this.patchControl[doc.value]) {\n this.patchControl[doc.value] = []\n }\n return this.patchControl[doc.value]\n }\n\n isHttpUri(uri:string){\n return( uri.slice(0,4) === 'http' )\n }\n\n\n /**\n * Tests whether a file is editable.\n * If the file has a specific annotation that it is machine written,\n * for safety, it is editable (this doesn't actually check for write access)\n * If the file has wac-allow and accept patch headers, those are respected.\n * and local write access is determined by those headers.\n * This version only looks at past HTTP requests, does not make new ones.\n *\n * @returns The method string SPARQL or DAV or\n * LOCALFILE or false if known, undefined if not known.\n */\n editable (uri: string | NamedNode, kb?: IndexedFormula): string | boolean | undefined {\n if (!uri) {\n return false // Eg subject is bnode, no known doc to write to\n }\n if (!kb) {\n kb = this.store\n }\n uri = termValue(uri)\n\n if ( !this.isHttpUri(uri as string) ) {\n if (kb.holds(\n this.store.rdfFactory.namedNode(uri),\n this.store.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),\n this.store.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#MachineEditableDocument'))) {\n return 'LOCALFILE'\n }\n }\n\n var request\n var definitive = false\n // @ts-ignore passes a string to kb.each, which expects a term. Should this work?\n var requests = kb.each(undefined, this.ns.link('requestedURI'), docpart(uri))\n var method: string\n for (var r = 0; r < requests.length; r++) {\n request = requests[r]\n if (request !== undefined) {\n var response = kb.any(request, this.ns.link('response')) as Quad_Subject\n if (request !== undefined) {\n var wacAllow = kb.anyValue(response, this.ns.httph('wac-allow'))\n if (wacAllow) {\n for (var bit of wacAllow.split(',')) {\n var lr = bit.split('=')\n if (lr[0].includes('user') && !lr[1].includes('write') && !lr[1].includes('append') ) {\n // console.log(' editable? excluded by WAC-Allow: ', wacAllow)\n return false\n }\n }\n }\n var acceptPatch = kb.each(response, this.ns.httph('accept-patch'))\n if (acceptPatch.length) {\n for (let i = 0; i < acceptPatch.length; i++) {\n method = acceptPatch[i].value.trim()\n if (method.indexOf('application/sparql-update') >= 0) return 'SPARQL'\n if (method.indexOf('application/sparql-update-single-match') >= 0) return 'SPARQL'\n }\n }\n var authorVia = kb.each(response, this.ns.httph('ms-author-via'))\n if (authorVia.length) {\n for (let i = 0; i < authorVia.length; i++) {\n method = authorVia[i].value.trim()\n if (method.indexOf('SPARQL') >= 0) {\n return 'SPARQL'\n }\n if (method.indexOf('DAV') >= 0) {\n return 'DAV'\n }\n }\n }\n\n if ( !this.isHttpUri(uri as string) ) {\n if( !wacAllow ) return false;\n else return 'LOCALFILE';\n }\n\n var status = kb.each(response, this.ns.http('status'))\n if (status.length) {\n for (let i = 0; i < status.length; i++) {\n // @ts-ignore since statuses should be TFTerms, this should always be false\n if (status[i] === 200 || status[i] === 404) {\n definitive = true\n // return false // A definitive answer\n }\n }\n }\n } else {\n // console.log('UpdateManager.editable: No response for ' + uri + '\\n')\n }\n }\n }\n if (requests.length === 0) {\n // console.log('UpdateManager.editable: No request for ' + uri + '\\n')\n } else {\n if (definitive) {\n return false // We have got a request and it did NOT say editable => not editable\n }\n }\n // console.log('UpdateManager.editable: inconclusive for ' + uri + '\\n')\n return undefined // We don't know (yet) as we haven't had a response (yet)\n }\n\n anonymize (obj) {\n return (obj.toNT().substr(0, 2) === '_:' && this.mentioned(obj))\n ? '?' + obj.toNT().substr(2)\n : obj.toNT()\n }\n\n anonymizeNT (stmt: Quad) {\n return this.anonymize(stmt.subject) + ' ' +\n this.anonymize(stmt.predicate) + ' ' +\n this.anonymize(stmt.object) + ' .'\n }\n\n /**\n * Returns a list of all bnodes occurring in a statement\n * @private\n */\n statementBnodes (st: Quad): BlankNode[] {\n return [st.subject, st.predicate, st.object].filter(function (x) {\n return isBlankNode(x)\n }) as BlankNode[]\n }\n\n /**\n * Returns a list of all bnodes occurring in a list of statements\n * @private\n */\n statementArrayBnodes (sts: Quad[]) {\n var bnodes: BlankNode[] = []\n for (let i = 0; i < sts.length; i++) {\n bnodes = bnodes.concat(this.statementBnodes(sts[i]))\n }\n bnodes.sort() // in place sort - result may have duplicates\n var bnodes2: BlankNode[] = []\n for (let j = 0; j < bnodes.length; j++) {\n if (j === 0 || !bnodes[j].equals(bnodes[j - 1])) {\n bnodes2.push(bnodes[j])\n }\n }\n return bnodes2\n }\n\n /**\n * Makes a cached list of [Inverse-]Functional properties\n * @private\n */\n cacheIfps () {\n this.ifps = {}\n var a = this.store.each(undefined, this.ns.rdf('type'),\n this.ns.owl('InverseFunctionalProperty'))\n for (let i = 0; i < a.length; i++) {\n this.ifps[a[i].value] = true\n }\n this.fps = {}\n a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('FunctionalProperty'))\n for (let i = 0; i < a.length; i++) {\n this.fps[a[i].value] = true\n }\n }\n\n /**\n * Returns a context to bind a given node, up to a given depth\n * @private\n */\n bnodeContext2 (x, source, depth) {\n // Return a list of statements which indirectly identify a node\n // Depth > 1 if try further indirection.\n // Return array of statements (possibly empty), or null if failure\n var sts = this.store.statementsMatching(undefined, undefined, x, source) // incoming links\n var y\n var res\n for (let i = 0; i < sts.length; i++) {\n if (this.fps[sts[i].predicate.value]) {\n y = sts[i].subject\n if (!y.isBlank) {\n return [ sts[i] ]\n }\n if (depth) {\n res = this.bnodeContext2(y, source, depth - 1)\n if (res) {\n return res.concat([ sts[i] ])\n }\n }\n }\n }\n // outgoing links\n sts = this.store.statementsMatching(x, undefined, undefined, source)\n for (let i = 0; i < sts.length; i++) {\n if (this.ifps[sts[i].predicate.value]) {\n y = sts[i].object\n if (!y.isBlank) {\n return [ sts[i] ]\n }\n if (depth) {\n res = this.bnodeContext2(y, source, depth - 1)\n if (res) {\n return res.concat([ sts[i] ])\n }\n }\n }\n }\n return null // Failure\n }\n\n /**\n * Returns the smallest context to bind a given single bnode\n * @private\n */\n bnodeContext1 (x, source) {\n // Return a list of statements which indirectly identify a node\n // Breadth-first\n for (var depth = 0; depth < 3; depth++) { // Try simple first\n var con = this.bnodeContext2(x, source, depth)\n if (con !== null) return con\n }\n // If we can't guarantee unique with logic just send all info about node\n return this.store.connectedStatements(x, source) // was:\n // throw new Error('Unable to uniquely identify bnode: ' + x.toNT())\n }\n\n /**\n * @private\n */\n mentioned (x) {\n return this.store.statementsMatching(x, null, null, null).length !== 0 || // Don't pin fresh bnodes\n this.store.statementsMatching(null, x).length !== 0 ||\n this.store.statementsMatching(null, null, x).length !== 0\n }\n\n /**\n * @private\n */\n bnodeContext (bnodes, doc) {\n var context = []\n if (bnodes.length) {\n this.cacheIfps()\n for (let i = 0; i < bnodes.length; i++) { // Does this occur in old graph?\n var bnode = bnodes[i]\n if (!this.mentioned(bnode)) continue\n context = context.concat(this.bnodeContext1(bnode, doc))\n }\n }\n return context\n }\n\n /**\n * Returns the best context for a single statement\n * @private\n */\n statementContext (st: Quad) {\n var bnodes = this.statementBnodes(st)\n return this.bnodeContext(bnodes, st.graph)\n }\n\n /**\n * @private\n */\n contextWhere (context) {\n var updater = this\n return (!context || context.length === 0)\n ? ''\n : 'WHERE { ' +\n context.map(function (x) {\n return updater.anonymizeNT(x)\n }).join('\\n') + ' }\\n'\n }\n\n /**\n * @private\n */\n fire (\n uri: string,\n query: string,\n callbackFunction: CallBackFunction\n ): Promise<void> {\n return Promise.resolve()\n .then(() => {\n if (!uri) {\n throw new Error('No URI given for remote editing operation: ' + query)\n }\n // console.log('UpdateManager: sending update to <' + uri + '>')\n\n let options = {\n noMeta: true,\n contentType: 'application/sparql-update',\n body: query\n }\n\n return this.store.fetcher.webOperation('PATCH', uri, options)\n })\n .then(response => {\n if (!response.ok) {\n let message = 'UpdateManager: update failed for <' + uri + '> status=' +\n response.status + ', ' + response.statusText +\n '\\n for query: ' + query\n // console.log(message)\n throw new Error(message)\n }\n\n // console.log('UpdateManager: update Ok for <' + uri + '>')\n\n callbackFunction(uri, response.ok, response.responseText as string, response)\n })\n .catch(err => {\n callbackFunction(uri, false, err.message, err)\n })\n }\n\n// ARE THESE THEE FUNCTIONS USED? DEPROCATE?\n\n /** return a statemnet updating function\n *\n * This does NOT update the statement.\n * It returns an object which includes\n * function which can be used to change the object of the statement.\n */\n update_statement (statement: Quad) {\n if (statement && !statement.graph) {\n return\n }\n var updater = this\n var context = this.statementContext(statement)\n\n return {\n statement: statement ? [statement.subject, statement.predicate, statement.object, statement.graph] : undefined,\n statementNT: statement ? this.anonymizeNT(statement) : undefined,\n where: updater.contextWhere(context),\n\n set_object: function (obj, callbackFunction) {\n var query = this.where\n query += 'DELETE DATA { ' + this.statementNT + ' } ;\\n'\n query += 'INSERT DATA { ' +\n // @ts-ignore `this` might refer to the wrong scope. Does this work?\n this.anonymize(this.statement[0]) + ' ' +\n // @ts-ignore\n this.anonymize(this.statement[1]) + ' ' +\n // @ts-ignore\n this.anonymize(obj) + ' ' + ' . }\\n'\n\n updater.fire((this.statement as [Quad_Subject, Quad_Predicate, Quad_Object, Quad_Graph])[3].value, query, callbackFunction)\n }\n }\n }\n\n insert_statement (st: Quad, callbackFunction: CallBackFunction): void {\n var st0 = st instanceof Array ? st[0] : st\n var query = this.contextWhere(this.statementContext(st0))\n\n if (st instanceof Array) {\n var stText = ''\n for (let i = 0; i < st.length; i++) stText += st[i] + '\\n'\n query += 'INSERT DATA { ' + stText + ' }\\n'\n } else {\n query += 'INSERT DATA { ' +\n this.anonymize(st.subject) + ' ' +\n this.anonymize(st.predicate) + ' ' +\n this.anonymize(st.object) + ' ' + ' . }\\n'\n }\n\n this.fire(st0.graph.value, query, callbackFunction)\n }\n\n delete_statement (st: Quad | Quad[], callbackFunction: CallBackFunction): void {\n var st0 = st instanceof Array ? st[0] : st\n var query = this.contextWhere(this.statementContext(st0))\n\n if (st instanceof Array) {\n var stText = ''\n for (let i = 0; i < st.length; i++) stText += st[i] + '\\n'\n query += 'DELETE DATA { ' + stText + ' }\\n'\n } else {\n query += 'DELETE DATA { ' +\n this.anonymize(st.subject) + ' ' +\n this.anonymize(st.predicate) + ' ' +\n this.anonymize(st.object) + ' ' + ' . }\\n'\n }\n\n this.fire(st0.graph.value, query, callbackFunction)\n }\n\n/// //////////////////////\n\n /**\n * Requests a now or future action to refresh changes coming downstream\n * This is designed to allow the system to re-request the server version,\n * when a websocket has pinged to say there are changes.\n * If the websocket, by contrast, has sent a patch, then this may not be necessary.\n *\n * @param doc\n * @param action\n */\n requestDownstreamAction (doc: NamedNode, action): void {\n var control = this.patchControlFor(doc)\n if (!control.pendingUpstream) {\n action(doc)\n } else {\n if (control.downstreamAction) {\n if ('' + control.downstreamAction !== '' + action) { // Kludge compare\n throw new Error(\"Can't wait for > 1 different downstream actions\")\n }\n } else {\n control.downstreamAction = action\n }\n }\n }\n\n /**\n * We want to start counting websocket notifications\n * to distinguish the ones from others from our own.\n */\n clearUpstreamCount (doc: NamedNode): void {\n var control = this.patchControlFor(doc)\n control.upstreamCount = 0\n }\n\n getUpdatesVia (doc: NamedNode): string | null {\n var linkHeaders = this.store.fetcher.getHeader(doc, 'updates-via')\n if (!linkHeaders || !linkHeaders.length) return null\n return linkHeaders[0].trim()\n }\n\n addDownstreamChangeListener (doc: NamedNode, listener): void {\n var control = this.patchControlFor(doc)\n if (!control.downstreamChangeListeners) { control.downstreamChangeListeners = [] }\n control.downstreamChangeListeners.push(listener)\n this.setRefreshHandler(doc, (doc: NamedNode) => {\n this.reloadAndSync(doc)\n })\n }\n\n reloadAndSync (doc: NamedNode): void {\n var control = this.patchControlFor(doc)\n var updater = this\n\n if (control.reloading) {\n // console.log(' Already reloading - note this load may be out of date')\n control.outOfDate = true\n return // once only needed @@ Not true, has changed again\n }\n control.reloading = true\n var retryTimeout = 1000 // ms\n var tryReload = function () {\n // console.log('try reload - timeout = ' + retryTimeout)\n updater.reload(updater.store, doc, function (ok, message, response) {\n if (ok) {\n if (control.downstreamChangeListeners) {\n for (let i = 0; i < control.downstreamChangeListeners.length; i++) {\n // console.log(' Calling downstream listener ' + i)\n control.downstreamChangeListeners[i]()\n }\n }\n control.reloading = false\n if (control.outOfDate){\n // console.log(' Extra reload because of extra update.')\n control.outOfDate = false\n tryReload()\n }\n } else {\n control.reloading = false\n if ((response as Response).status === 0) {\n // console.log('Network error refreshing the data. Retrying in ' +\n // retryTimeout / 1000)\n control.reloading = true\n retryTimeout = retryTimeout * 2\n setTimeout(tryReload, retryTimeout)\n } else {\n // console.log('Error ' + (response as Response).status + 'refreshing the data:' +\n // message + '. Stopped' + doc)\n }\n }\n })\n }\n tryReload()\n }\n\n /**\n * Sets up websocket to listen on\n *\n * There is coordination between upstream changes and downstream ones\n * so that a reload is not done in the middle of an upstream patch.\n * If you use this API then you get called when a change happens, and you\n * have to reload the file yourself, and then refresh the UI.\n * Alternative is addDownstreamChangeListener(), where you do not\n * have to do the reload yourself. Do mot mix them.\n *\n * kb contains the HTTP metadata from previous operations\n *\n * @param doc\n * @param handler\n *\n * @returns {boolean}\n */\n setRefreshHandler (doc: NamedNode, handler): boolean {\n let wssURI = this.getUpdatesVia(doc) // relative\n // var kb = this.store\n var theHandler = handler\n var self = this\n var updater = this\n var retryTimeout = 1500 // *2 will be 3 Seconds, 6, 12, etc\n var retries = 0\n\n if (!wssURI) {\n // console.log('Server does not support live updates through Updates-Via :-(')\n return false\n }\n\n wssURI = uriJoin(wssURI, doc.value)\n const validWssURI = wssURI.replace(/^http:/, 'ws:').replace(/^https:/, 'wss:')\n // console.log('Web socket URI ' + wssURI)\n\n var openWebsocket = function () {\n // From https://github.com/solid/solid-spec#live-updates\n var socket\n if (typeof WebSocket !== 'undefined') {\n socket = new WebSocket(validWssURI)\n } else if (typeof window !== 'undefined' && window.WebSocket) {\n socket = (window as any).WebSocket(validWssURI)\n } else {\n // console.log('Live update disabled, as WebSocket not supported by platform :-(')\n return\n }\n socket.onopen = function () {\n // console.log(' websocket open')\n retryTimeout = 1500 // reset timeout to fast on success\n this.send('sub ' + doc.value)\n if (retries) {\n // console.log('Web socket has been down, better check for any news.')\n updater.requestDownstreamAction(doc, theHandler)\n }\n }\n var control = self.patchControlFor(doc)\n control.upstreamCount = 0\n\n socket.onerror = function onerror (err: Error) {\n // console.log('Error on Websocket:', err)\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent\n //\n // 1000 CLOSE_NORMAL Normal closure; the connection successfully completed whatever purpose for which it was created.\n // 1001 CLOSE_GOING_AWAY The endpoint is going away, either\n // because of a server failure or because the browser is navigating away from the page that opened the connection.\n // 1002 CLOSE_PROTOCOL_ERROR The endpoint is terminating the connection due to a protocol error.\n // 1003 CLOSE_UNSUPPORTED The connection is being terminated because the endpoint\n // received data of a type it cannot accept (for example, a text-only endpoint received binary data).\n // 1004 Reserved. A meaning might be defined in the future.\n // 1005 CLOSE_NO_STATUS Reserved. Indicates that no status code was provided even though one was expected.\n // 1006 CLOSE_ABNORMAL Reserved. Used to indicate that a connection was closed abnormally (\n //\n //\n socket.onclose = function (event: CloseEvent) {\n // console.log('*** Websocket closed with code ' + event.code +\n // \", reason '\" + event.reason + \"' clean = \" + event.wasClean)\n retryTimeout *= 2\n retries += 1\n // console.log('Retrying in ' + retryTimeout + 'ms') // (ask user?)\n setTimeout(function () {\n // console.log('Trying websocket again')\n openWebsocket()\n }, retryTimeout)\n }\n socket.onmessage = function (msg: MessageEvent) {\n if (msg.data && msg.data.slice(0, 3) === 'pub') {\n if ('upstreamCount' in control) {\n control.upstreamCount -= 1\n if (control.upstreamCount >= 0) {\n // console.log('just an echo: ' + control.upstreamCount)\n return // Just an echo\n }\n }\n // console.log('Assume a real downstream change: ' + control.upstreamCount + ' -> 0')\n control.upstreamCount = 0\n self.requestDownstreamAction(doc, theHandler)\n }\n }\n } // openWebsocket\n openWebsocket()\n\n return true\n }\n\n /**\n * This high-level function updates the local store iff the web is changed successfully.\n * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).\n * The `why` property of each statement must be the give the web document to be updated.\n * The statements to be deleted and inserted may span more than one web document.\n * @param deletions - Statement or statements to be deleted.\n * @param insertions - Statement or statements to be inserted.\n * @returns a promise\n */\n updateMany(\n deletions: ReadonlyArray<Statement>,\n insertions: ReadonlyArray<Statement> = []\n ): Promise<void[]> {\n const docs = deletions.concat(insertions).map(st => st.why)\n const thisUpdater = this\n const uniqueDocs: Array<NamedNode> = []\n docs.forEach(doc => {\n if (!uniqueDocs.find(uniqueDoc => uniqueDoc.equals(doc))) uniqueDocs.push(doc as NamedNode)\n })\n const updates = uniqueDocs.map(doc =>\n thisUpdater.update(deletions.filter(st => st.why.equals(doc)),\n insertions.filter(st => st.why.equals(doc))))\n if (updates.length > 1) {\n console.log(`@@ updateMany to ${updates.length}: ${uniqueDocs}`)\n }\n return Promise.all(updates)\n }\n\n /**\n * This high-level function updates the local store iff the web is changed successfully.\n * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).\n * The `why` property of each statement must be the same and give the web document to be updated.\n * @param deletions - Statement or statements to be deleted.\n * @param insertions - Statement or statements to be inserted.\n * @param callback - called as callbackFunction(uri, success, errorbody)\n * OR returns a promise\n */\n update(\n deletions: ReadonlyArray<Statement>,\n insertions: ReadonlyArray<Statement>,\n callback?: (\n uri: string | undefined | null,\n success: boolean,\n errorBody?: string,\n response?: Response | Error\n ) => void,\n secondTry?: boolean\n ): void | Promise<void> {\n if (!callback) {\n var thisUpdater = this\n return new Promise(function (resolve, reject) { // Promise version\n thisUpdater.update(deletions, insertions, function (uri, ok, errorBody) {\n if (!ok) {\n reject(new Error(errorBody))\n } else {\n resolve()\n }\n }) // callbackFunction\n }) // promise\n } // if\n\n try {\n var kb = this.store\n var ds = !deletions ? []\n : isStore(deletions) ? deletions.statements\n : deletions instanceof Array ? deletions : [ deletions ]\n var is = !insertions ? []\n : isStore(insertions) ? insertions.statements\n : insertions instanceof Array ? insertions : [ insertions ]\n if (!(ds instanceof Array)) {\n throw new Error('Type Error ' + (typeof ds) + ': ' + ds)\n }\n if (!(is instanceof Array)) {\n throw new Error('Type Error ' + (typeof is) + ': ' + is)\n }\n if (ds.length === 0 && is.length === 0) {\n return callback(null, true) // success -- nothing needed to be done.\n }\n var doc = ds.length ? ds[0].graph : is[0].graph\n if (!doc) {\n let message = 'Error patching: statement does not specify which document to patch:' + ds[0] + ', ' + is[0]\n // console.log(message)\n throw new Error(message)\n }\n var control = this.patchControlFor(doc)\n var startTime = Date.now()\n\n var props = ['subject', 'predicate', 'object', 'why']\n var verbs = ['insert', 'delete']\n var clauses = { 'delete': ds, 'insert': is }\n verbs.map(function (verb) {\n clauses[verb].map(function (st: Quad) {\n if (!doc.equals(st.graph)) {\n throw new Error('update: destination ' + doc +\n ' inconsistent with delete quad ' + st.graph)\n }\n props.map(function (prop) {\n if (typeof st[prop] === 'undefined') {\n throw new Error('update: undefined ' + prop + ' of statement.')\n }\n })\n })\n })\n\n var protocol = this.editable(doc.value, kb)\n if (protocol === false) {\n throw new Error('Update: Can\\'t make changes in uneditable ' + doc)\n }\n if (protocol === undefined) { // Not enough metadata\n if (secondTry) {\n throw new Error('Update: Loaded ' + doc + \"but stil can't figure out what editing protcol it supports.\")\n }\n // console.log(`Update: have not loaded ${doc} before: loading now...`);\n (this.store.fetcher.load(doc) as Promise<Response>).then(response => {\n this.update(deletions, insertions, callback, true)\n }, err => {\n if (err.response.status === 404) { // nonexistent files are fine\n this.update(deletions, insertions, callback, true)\n } else {\n throw new Error(`Update: Can't get updatability status ${doc} before patching: ${err}`)\n }\n })\n return\n } else if ((protocol as string).indexOf('SPARQL') >= 0) {\n var bnodes: BlankNode[] = []\n if (ds.length) bnodes = this.statementArrayBnodes(ds)\n if (is.length) bnodes = bnodes.concat(this.statementArrayBnodes(is))\n var context = this.bnodeContext(bnodes, doc)\n var whereClause = this.contextWhere(context)\n var query = ''\n if (whereClause.length) { // Is there a WHERE clause?\n if (ds.length) {\n query += 'DELETE { '\n for (let i = 0; i < ds.length; i++) {\n query += this.anonymizeNT(ds[i]) + '\\n'\n }\n query += ' }\\n'\n }\n if (is.length) {\n query += 'INSERT { '\n for (let i = 0; i < is.length; i++) {\n query += this.anonymizeNT(is[i]) + '\\n'\n }\n query += ' }\\n'\n }\n query += whereClause\n } else { // no where clause\n if (ds.length) {\n query += 'DELETE DATA { '\n for (let i = 0; i < ds.length; i++) {\n query += this.anonymizeNT(ds[i]) + '\\n'\n }\n query += ' } \\n'\n }\n if (is.length) {\n if (ds.length) query += ' ; '\n query += 'INSERT DATA { '\n for (let i = 0; i < is.length; i++) {\n query += this.anonymizeNT(is[i]) + '\\n'\n }\n query += ' }\\n'\n }\n }\n // Track pending upstream patches until they have finished their callbackFunction\n control.pendingUpstream = control.pendingUpstream ? control.pendingUpstream + 1 : 1\n if ('upstreamCount' in control) {\n control.upstreamCount += 1 // count changes we originated ourselves\n // console.log('upstream count up to : ' + control.upstreamCount)\n }\n\n this.fire(doc.value, query, (uri, success, body, response) => {\n (response as any).elapsedTimeMs = Date.now() - startTime\n console.log(' UpdateManager: Return ' +\n (success ? 'success ' : 'FAILURE ') + (response as Response).status +\n ' elapsed ' + (response as any).elapsedTimeMs + 'ms')\n if (success) {\n try {\n kb.remove(ds)\n } catch (e) {\n success = false\n body = 'Remote Ok BUT error deleting ' + ds.length + ' from store!!! ' + e\n } // Add in any case -- help recover from weirdness??\n for (let i = 0; i < is.length; i++) {\n kb.add(is[i].subject, is[i].predicate, is[i].object, doc)\n }\n }\n\n callback(uri, success, body, response)\n control.pendingUpstream -= 1\n // When upstream patches have been sent, reload state if downstream waiting\n if (control.pendingUpstream === 0 && control.downstreamAction) {\n var downstreamAction = control.downstreamAction\n delete control.downstreamAction\n // console.log('delayed downstream action:')\n downstreamAction(doc)\n }\n })\n } else if ((protocol as string).indexOf('DAV') >= 0) {\n this.updateDav(doc, ds, is, callback)\n } else {\n if ((protocol as string).indexOf('LOCALFILE') >= 0) {\n try {\n this.updateLocalFile(doc, ds, is, callback)\n } catch (e) {\n callback(doc.value, false,\n 'Exception trying to write back file <' + doc.value + '>\\n'\n // + tabulator.Util.stackString(e))\n )\n }\n } else {\n throw new Error(\"Unhandled edit method: '\" + protocol + \"' for \" + doc)\n }\n }\n } catch (e) {\n callback(undefined, false, 'Exception in update: ' + e + '\\n' +\n Util.stackString(e))\n }\n }\n\n updateDav (\n doc: Quad_Subject,\n ds,\n is,\n callbackFunction\n ): null | Promise<void> {\n let kb = this.store\n // The code below is derived from Kenny's UpdateCenter.js\n var request = kb.any(doc, this.ns.link('request'))\n if (!request) {\n throw new Error('No record of our HTTP GET request for document: ' +\n doc)\n } // should not happen\n var response = kb.any(request as NamedNode, this.ns.link('response')) as Quad_Subject\n if (!response) {\n return null // throw \"No record HTTP GET response for document: \"+doc\n }\n var contentType = (kb.the(response, this.ns.httph('content-type'))as Term).value\n\n // prepare contents of revised document\n let newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice() // copy!\n for (let i = 0; i < ds.length; i++) {\n Util.RDFArrayRemove(newSts, ds[i])\n }\n for (let i = 0; i < is.length; i++) {\n newSts.push(is[i])\n }\n\n const documentString = this.serialize(doc.value, newSts, contentType)\n\n // Write the new version back\n var candidateTarget = kb.the(response, this.ns.httph('content-location'))\n var targetURI\n if (candidateTarget) {\n targetURI = uriJoin(candidateTarget.value, targetURI)\n }\n\n let options = {\n contentType,\n noMeta: true,\n body: documentString\n }\n\n return kb.fetcher.webOperation('PUT', targetURI, options)\n .then(response => {\n if (!response.ok) {\n throw new Error(response.error)\n }\n\n for (let i = 0; i < ds.length; i++) {\n kb.remove(ds[i])\n }\n for (let i = 0; i < is.length; i++) {\n kb.add(is[i].subject, is[i].predicate, is[i].object, doc)\n }\n\n callbackFunction(doc.value, response.ok, response.responseText, response)\n })\n .catch(err => {\n callbackFunction(doc.value, false, err.message, err)\n })\n }\n\n /**\n * Likely deprecated, since this lib no longer deals with browser extension\n *\n * @param doc\n * @param ds\n * @param is\n * @param callbackFunction\n */\n updateLocalFile (doc: NamedNode, ds, is, callbackFunction): void {\n const kb = this.store\n // console.log('Writing back to local file\\n')\n\n // prepare contents of revised document\n let newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice() // copy!\n\n for (let i = 0; i < ds.length; i++) {\n Util.RDFArrayRemove(newSts, ds[ i ])\n }\n for (let i = 0; i < is.length; i++) {\n newSts.push(is[ i ])\n }\n // serialize to the appropriate format\n var dot = doc.value.lastIndexOf('.')\n if (dot < 1) {\n throw new Error('Rewriting file: No filename extension: ' + doc.value)\n }\n var ext = doc.value.slice(dot + 1)\n\n let contentType = Fetcher.CONTENT_TYPE_BY_EXT[ ext ]\n if (!contentType) {\n throw new Error('File extension .' + ext + ' not supported for data write')\n }\n\n const documentString = this.serialize(doc.value, newSts, contentType)\n\n kb.fetcher.webOperation('PUT',doc.value,{\n \"body\" : documentString,\n contentType : contentType,\n }).then( (response)=>{\n if(!response.ok) return callbackFunction(doc.value,false,response.error)\n for (let i = 0; i < ds.length; i++) {\n kb.remove(ds[i]);\n }\n for (let i = 0; i < is.length; i++) {\n kb.add(is[i].subject, is[i].predicate, is[i].object, doc);\n }\n callbackFunction(doc.value, true, '') // success!\n })\n }\n\n /**\n * @throws {Error} On unsupported content type\n *\n * @returns {string}\n */\n serialize (uri: string, data: string | Quad[], contentType: string): string {\n const kb = this.store\n let documentString\n\n if (typeof data === 'string') {\n return data\n }\n\n // serialize to the appropriate format\n var sz = Serializer(kb)\n sz.suggestNamespaces(kb.namespaces)\n sz.setBase(uri)\n switch (contentType) {\n case 'text/xml':\n case 'application/rdf+xml':\n documentString = sz.statementsToXML(data)\n break\n case 'text/n3':\n case 'text/turtle':\n case 'application/x-turtle': // Legacy\n case 'application/n3': // Legacy\n documentString = sz.statementsToN3(data)\n break\n default:\n throw new Error('Content-type ' + contentType +\n ' not supported for data serialization')\n }\n\n return documentString\n }\n\n /**\n * This is suitable for an initial creation of a document.\n */\n put(\n doc: RDFlibNamedNode,\n data: string | Quad[],\n contentType: string,\n callback: (uri: string, ok: boolean, errorMessage?: string, response?: unknown) => void,\n ): Promise<void> {\n const kb = this.store\n let documentString: string\n\n return Promise.resolve()\n .then(() => {\n documentString = this.serialize(doc.value, data, contentType)\n\n return kb.fetcher\n .webOperation('PUT', doc.value, { contentType, body: documentString })\n })\n .then(response => {\n if (!response.ok) {\n return callback(doc.value, response.ok, response.error, response)\n }\n\n delete kb.fetcher.nonexistent[doc.value]\n delete kb.fetcher.requested[doc.value] // @@ could this mess with the requested state machine? if a fetch is in progress\n\n if (typeof data !== 'string') {\n data.map((st) => {\n kb.addStatement(st)\n })\n }\n\n callback(doc.value, response.ok, '', response)\n })\n .catch(err => {\n callback(doc.value, false, err.message)\n })\n }\n\n /**\n * Reloads a document.\n *\n * Fast and cheap, no metadata. Measure times for the document.\n * Load it provisionally.\n * Don't delete the statements before the load, or it will leave a broken\n * document in the meantime.\n *\n * @param kb\n * @param doc {RDFlibNamedNode}\n * @param callbackFunction\n */\n reload (\n kb: IndexedFormula,\n doc: docReloadType,\n callbackFunction: (ok: boolean, message?: string, response?: Error | Response) => {} | void\n ): void {\n var startTime = Date.now()\n // force sets no-cache and\n const options = {\n force: true,\n noMeta: true,\n clearPreviousData: true,\n };\n\n (kb as any).fetcher.nowOrWhenFetched(doc.value, options, function (ok: boolean, body: Body, response: Response) {\n if (!ok) {\n // console.log(' ERROR reloading data: ' + body)\n callbackFunction(false, 'Error reloading data: ' + body, response)\n //@ts-ignore Where does onErrorWasCalled come from?\n } else if (response.onErrorWasCalled || response.status !== 200) {\n // console.log(' Non-HTTP error reloading data! onErrorWasCalled=' +\n //@ts-ignore Where does onErrorWasCalled come from?\n // response.onErrorWasCalled + ' status: ' + response.status)\n callbackFunction(false, 'Non-HTTP error reloading data: ' + body, response)\n } else {\n var elapsedTimeMs = Date.now() - startTime\n\n if (!doc.reloadTimeTotal) doc.reloadTimeTotal = 0\n if (!doc.reloadTimeCount) doc.reloadTimeCount = 0\n\n doc.reloadTimeTotal += elapsedTimeMs\n doc.reloadTimeCount += 1\n\n // console.log(' Fetch took ' + elapsedTimeMs + 'ms, av. of ' +\n // doc.reloadTimeCount + ' = ' +\n // (doc.reloadTimeTotal / doc.reloadTimeCount) + 'ms.')\n\n callbackFunction(true)\n }\n })\n }\n}\n\ninterface docReloadType extends NamedNode {\n reloadTimeCount?: number\n reloadTimeTotal?: number\n}\n","import {\n IRDFlibDataFactory,\n} from '../types'\nimport Literal from '../literal'\nimport Statement from '../statement'\nimport IndexedFormula from '../store'\nimport Fetcher from '../fetcher'\nimport ExtendedTermFactory from './extended-term-factory'\nimport { NamedNode, Quad_Subject, Quad_Predicate, Quad_Object, Quad_Graph } from '../tf-types'\n\n/** Full RDFLib.js Data Factory */\nconst RDFlibDataFactory: IRDFlibDataFactory = {\n ...ExtendedTermFactory,\n\n /**\n * Creates a new fetcher\n * @param store - The store to use\n * @param options - The options\n */\n fetcher (store: IndexedFormula, options: any): Fetcher {\n return new Fetcher(store, options)\n },\n\n /**\n * Creates a new graph (store)\n */\n graph (features = undefined, opts = undefined): IndexedFormula {\n return new IndexedFormula(features, opts || {rdfFactory: ExtendedTermFactory})\n },\n\n /**\n * Creates a new literal node\n * @param val The lexical value\n * @param lang The language\n * @param dt The datatype\n */\n lit (val: string, lang?: string, dt?: NamedNode): Literal {\n return this.literal('' + val, lang || dt)\n },\n\n /**\n * Creates a new statement\n * @param subject The subject\n * @param predicate The predicate\n * @param object The object\n * @param graph The containing graph\n */\n st (\n subject: Quad_Subject,\n predicate: Quad_Predicate,\n object: Quad_Object,\n graph?: Quad_Graph\n ): Statement {\n return this.quad(subject, predicate, object, graph)\n },\n}\n\nexport default RDFlibDataFactory\n","/*\n * Updates-Via\n */\nimport DataFactory from './factories/rdflib-data-factory'\n\nexport class UpdatesSocket {\n constructor (parent, via) {\n this.parent = parent\n this.via = via\n this.connected = false\n this.pending = {}\n this.subscribed = {}\n this.socket = {}\n try {\n this.socket = new WebSocket(via)\n this.socket.onopen = this.onOpen\n this.socket.onclose = this.onClose\n this.socket.onmessage = this.onMessage\n this.socket.onerror = this.onError\n } catch (error) {\n this.onError(error)\n }\n }\n _decode (q) {\n var elt\n var i\n var k\n var r\n var ref\n var ref1\n var v\n r = {}\n ref = (function () {\n var j, len, ref, results\n ref = q.split('&')\n results = []\n for (j = 0, len = ref.length; j < len; j++) {\n elt = ref[j]\n results.push(elt.split('='))\n }\n return results\n })()\n for (i in ref) {\n elt = ref[i]\n ref1 = [decodeURIComponent(elt[0]), decodeURIComponent(elt[1])]\n k = ref1[0]\n v = ref1[1]\n if (r[k] == null) {\n r[k] = []\n }\n r[k].push(v)\n }\n return r\n }\n _send (method, uri, data) {\n var base, message\n message = [method, uri, data].join(' ')\n return typeof (base = this.socket).send === 'function' ? base.send(message) : void 0\n }\n _subscribe (uri) {\n this._send('sub', uri, '')\n this.subscribed[uri] = true\n return this.subscribed[uri]\n }\n onClose (e) {\n var uri\n this.connected = false\n for (uri in this.subscribed) {\n this.pending[uri] = true\n }\n this.subscribed = {}\n return this.subscribed\n }\n onError (e) {\n throw new Error('onError' + e)\n }\n onMessage (e) {\n var base, message\n message = e.data.split(' ')\n if (message[0] === 'ping') {\n return typeof (base = this.socket).send === 'function' ? base.send('pong ' + message.slice(1).join(' ')) : void 0\n } else if (message[0] === 'pub') {\n return this.parent.onUpdate(message[1], this._decode(message[2]))\n }\n }\n onOpen (e) {\n var results, uri\n this.connected = true\n results = []\n for (uri in this.pending) {\n delete this.pending[uri]\n results.push(this._subscribe(uri))\n }\n return results\n }\n subscribe (uri) {\n if (this.connected) {\n return this._subscribe(uri)\n } else {\n this.pending[uri] = true\n return this.pending[uri]\n }\n }\n}\n\nexport class UpdatesVia {\n constructor (fetcher) {\n this.fetcher = fetcher\n this.graph = {}\n this.via = {}\n this.fetcher.addCallback('headers', this.onHeaders)\n }\n onHeaders (d) {\n var etag, uri, via\n if (d.headers == null) {\n return true\n }\n if (typeof WebSocket === 'undefined' || WebSocket === null) {\n return true\n }\n etag = d.headers['etag']\n via = d.headers['updates-via']\n uri = d.uri\n if (etag && via) {\n this.graph[uri] = {\n etag: etag,\n via: via\n }\n this.register(via, uri)\n }\n return true\n }\n onUpdate (uri, d) {\n return this.fetcher.refresh(DataFactory.namedNode(uri))\n }\n register (via, uri) {\n if (this.via[via] == null) {\n this.via[via] = new UpdatesSocket(this, via)\n }\n return this.via[via].subscribe(uri)\n }\n}\n","import { IRDFlibDataFactory } from './types'\n\nimport BlankNode from './blank-node'\nimport Collection from './collection'\nimport * as convert from './convert'\nimport Empty from './empty'\nimport Fetcher from './fetcher'\nimport Formula from './formula'\nimport Store from './store'\nimport jsonParser from './jsonparser'\nimport Literal from './literal'\nimport log from './log'\nimport N3Parser from './n3parser'\nimport NamedNode from './named-node'\nimport Namespace from './namespace'\nimport Node from './node'\nimport parse from './parse'\nimport { Query } from './query'\nimport queryToSPARQL from './query-to-sparql'\nimport RDFaProcessor from './rdfaparser'\nimport RDFParser from './rdfxmlparser'\nimport serialize from './serialize'\nimport Serializer from './serializer'\nimport SPARQLToQuery from './sparql-to-query'\nimport sparqlUpdateParser from './patch-parser'\nimport Statement from './statement'\nimport UpdateManager from './update-manager'\nimport { UpdatesSocket } from './updates-via'\nimport { UpdatesVia } from './updates-via'\nimport * as uri from './uri'\nimport * as Util from './utils-js'\nimport Variable from './variable'\nimport DataFactory from './factories/rdflib-data-factory'\n\n// Prepare bound versions of data factory methods for export\nconst boundDataFactory = {} as IRDFlibDataFactory\nfor (const name in DataFactory) {\n if (typeof DataFactory[name] === 'function')\n boundDataFactory[name] = DataFactory[name].bind(DataFactory);\n}\nconst {\n fetcher,\n graph,\n lit,\n st,\n namedNode,\n variable,\n blankNode,\n defaultGraph,\n literal,\n quad,\n triple,\n} = boundDataFactory\n\nconst formula = new Formula();\nconst fromNT = str => formula.fromNT(str);\n\nconst term = Node.fromValue\n\n// TODO: this export is broken;\n// it exports the _current_ value of nextId, which is always 0\nconst NextId = BlankNode.nextId\n\nexport * from './utils/terms'\nexport type { AutoInitOptions, ExtendedResponse, FetchError } from './fetcher'\nexport {\n BlankNode,\n Collection,\n convert,\n DataFactory,\n Empty,\n Fetcher,\n Formula,\n Store,\n jsonParser,\n Literal,\n log,\n N3Parser,\n NamedNode,\n Namespace,\n Node,\n parse,\n Query,\n queryToSPARQL,\n RDFaProcessor,\n RDFParser,\n serialize,\n Serializer,\n SPARQLToQuery,\n sparqlUpdateParser,\n Statement,\n term,\n UpdateManager,\n UpdatesSocket,\n UpdatesVia,\n uri,\n Util,\n Variable,\n\n Store as IndexedFormula, // Alias\n\n NextId,\n\n fromNT,\n fetcher,\n graph,\n lit,\n st,\n namedNode as sym,\n\n // RDFJS DataFactory interface\n blankNode,\n defaultGraph,\n literal,\n namedNode,\n quad,\n triple,\n variable,\n}\nexport { termValue } from './utils/termValue'\n","module.exports = require(\"regenerator-runtime\");\n","/**\n * Provides a way to access commonly used namespaces\n *\n * Usage:\n *\n * ```\n * const $rdf = require('rdflib'); //or any other RDF/JS-compatible library\n * const ns = require('solid-namespace')($rdf);\n * const store = $rdf.graph();\n *\n * let me = ...;\n * let name = store.any(me, ns.vcard(‘fn’)) || store.any(me, ns.foaf(‘name’));\n * ```\n * @module vocab\n */\nconst aliases = {\n acl: 'http://www.w3.org/ns/auth/acl#',\n arg: 'http://www.w3.org/ns/pim/arg#',\n as: 'https://www.w3.org/ns/activitystreams#',\n cal: 'http://www.w3.org/2002/12/cal/ical#',\n cert: 'http://www.w3.org/ns/auth/cert#',\n contact: 'http://www.w3.org/2000/10/swap/pim/contact#',\n dc: 'http://purl.org/dc/elements/1.1/',\n dct: 'http://purl.org/dc/terms/',\n doap: 'http://usefulinc.com/ns/doap#',\n foaf: 'http://xmlns.com/foaf/0.1/',\n geo: 'http://www.w3.org/2003/01/geo/wgs84_pos#',\n gpx: 'http://www.w3.org/ns/pim/gpx#',\n http: 'http://www.w3.org/2007/ont/http#',\n httph: 'http://www.w3.org/2007/ont/httph#',\n icalTZ: 'http://www.w3.org/2002/12/cal/icaltzd#', // Beware: not cal:\n ldp: 'http://www.w3.org/ns/ldp#',\n link: 'http://www.w3.org/2007/ont/link#',\n log: 'http://www.w3.org/2000/10/swap/log#',\n meeting: 'http://www.w3.org/ns/pim/meeting#',\n mo: 'http://purl.org/ontology/mo/',\n org: 'http://www.w3.org/ns/org#',\n owl: 'http://www.w3.org/2002/07/owl#',\n pad: 'http://www.w3.org/ns/pim/pad#',\n patch: 'http://www.w3.org/ns/pim/patch#',\n prov: 'http://www.w3.org/ns/prov#',\n qu: 'http://www.w3.org/2000/10/swap/pim/qif#',\n trip: 'http://www.w3.org/ns/pim/trip#',\n rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n rdfs: 'http://www.w3.org/2000/01/rdf-schema#',\n rss: 'http://purl.org/rss/1.0/',\n sched: 'http://www.w3.org/ns/pim/schedule#',\n schema: 'http://schema.org/', // @@ beware confusion with documents no 303\n sioc: 'http://rdfs.org/sioc/ns#',\n solid: 'http://www.w3.org/ns/solid/terms#',\n space: 'http://www.w3.org/ns/pim/space#',\n stat: 'http://www.w3.org/ns/posix/stat#',\n tab: 'http://www.w3.org/2007/ont/link#',\n tabont: 'http://www.w3.org/2007/ont/link#',\n ui: 'http://www.w3.org/ns/ui#',\n vcard: 'http://www.w3.org/2006/vcard/ns#',\n wf: 'http://www.w3.org/2005/01/wf/flow#',\n xsd: 'http://www.w3.org/2001/XMLSchema#',\n cco: 'http://www.ontologyrepository.com/CommonCoreOntologies/'\n}\n\n/**\n * @param [rdflib] {RDF} Optional RDF Library (such as rdflib.js or rdf-ext) to inject\n */\nfunction vocab (rdf = { namedNode: u => u }) {\n const namespaces = {}\n for (const alias in aliases) {\n const expansion = aliases[alias]\n namespaces[alias] = function (localName = '') {\n return rdf.namedNode(expansion + localName)\n }\n };\n\n return namespaces\n};\n\nmodule.exports = vocab\n","/*\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst IdentifierIssuer = require('./IdentifierIssuer');\nconst MessageDigest = require('./MessageDigest');\nconst Permuter = require('./Permuter');\nconst NQuads = require('./NQuads');\n\nmodule.exports = class URDNA2015 {\n constructor() {\n this.name = 'URDNA2015';\n this.blankNodeInfo = new Map();\n this.canonicalIssuer = new IdentifierIssuer('_:c14n');\n this.hashAlgorithm = 'sha256';\n this.quads = null;\n }\n\n // 4.4) Normalization Algorithm\n async main(dataset) {\n this.quads = dataset;\n\n // 1) Create the normalization state.\n // 2) For every quad in input dataset:\n for(const quad of dataset) {\n // 2.1) For each blank node that occurs in the quad, add a reference\n // to the quad using the blank node identifier in the blank node to\n // quads map, creating a new entry if necessary.\n this._addBlankNodeQuadInfo({quad, component: quad.subject});\n this._addBlankNodeQuadInfo({quad, component: quad.object});\n this._addBlankNodeQuadInfo({quad, component: quad.graph});\n }\n\n // 3) Create a list of non-normalized blank node identifiers\n // non-normalized identifiers and populate it using the keys from the\n // blank node to quads map.\n // Note: We use a map here and it was generated during step 2.\n\n // 4) `simple` flag is skipped -- loop is optimized away. This optimization\n // is permitted because there was a typo in the hash first degree quads\n // algorithm in the URDNA2015 spec that was implemented widely making it\n // such that it could not be fixed; the result was that the loop only\n // needs to be run once and the first degree quad hashes will never change.\n // 5.1-5.2 are skipped; first degree quad hashes are generated just once\n // for all non-normalized blank nodes.\n\n // 5.3) For each blank node identifier identifier in non-normalized\n // identifiers:\n const hashToBlankNodes = new Map();\n const nonNormalized = [...this.blankNodeInfo.keys()];\n let i = 0;\n for(const id of nonNormalized) {\n // Note: batch hashing first degree quads 100 at a time\n if(++i % 100 === 0) {\n await this._yield();\n }\n // steps 5.3.1 and 5.3.2:\n await this._hashAndTrackBlankNode({id, hashToBlankNodes});\n }\n\n // 5.4) For each hash to identifier list mapping in hash to blank\n // nodes map, lexicographically-sorted by hash:\n const hashes = [...hashToBlankNodes.keys()].sort();\n // optimize away second sort, gather non-unique hashes in order as we go\n const nonUnique = [];\n for(const hash of hashes) {\n // 5.4.1) If the length of identifier list is greater than 1,\n // continue to the next mapping.\n const idList = hashToBlankNodes.get(hash);\n if(idList.length > 1) {\n nonUnique.push(idList);\n continue;\n }\n\n // 5.4.2) Use the Issue Identifier algorithm, passing canonical\n // issuer and the single blank node identifier in identifier\n // list, identifier, to issue a canonical replacement identifier\n // for identifier.\n const id = idList[0];\n this.canonicalIssuer.getId(id);\n\n // Note: These steps are skipped, optimized away since the loop\n // only needs to be run once.\n // 5.4.3) Remove identifier from non-normalized identifiers.\n // 5.4.4) Remove hash from the hash to blank nodes map.\n // 5.4.5) Set simple to true.\n }\n\n // 6) For each hash to identifier list mapping in hash to blank nodes map,\n // lexicographically-sorted by hash:\n // Note: sort optimized away, use `nonUnique`.\n for(const idList of nonUnique) {\n // 6.1) Create hash path list where each item will be a result of\n // running the Hash N-Degree Quads algorithm.\n const hashPathList = [];\n\n // 6.2) For each blank node identifier identifier in identifier list:\n for(const id of idList) {\n // 6.2.1) If a canonical identifier has already been issued for\n // identifier, continue to the next identifier.\n if(this.canonicalIssuer.hasId(id)) {\n continue;\n }\n\n // 6.2.2) Create temporary issuer, an identifier issuer\n // initialized with the prefix _:b.\n const issuer = new IdentifierIssuer('_:b');\n\n // 6.2.3) Use the Issue Identifier algorithm, passing temporary\n // issuer and identifier, to issue a new temporary blank node\n // identifier for identifier.\n issuer.getId(id);\n\n // 6.2.4) Run the Hash N-Degree Quads algorithm, passing\n // temporary issuer, and append the result to the hash path list.\n const result = await this.hashNDegreeQuads(id, issuer);\n hashPathList.push(result);\n }\n\n // 6.3) For each result in the hash path list,\n // lexicographically-sorted by the hash in result:\n hashPathList.sort(_stringHashCompare);\n for(const result of hashPathList) {\n // 6.3.1) For each blank node identifier, existing identifier,\n // that was issued a temporary identifier by identifier issuer\n // in result, issue a canonical identifier, in the same order,\n // using the Issue Identifier algorithm, passing canonical\n // issuer and existing identifier.\n const oldIds = result.issuer.getOldIds();\n for(const id of oldIds) {\n this.canonicalIssuer.getId(id);\n }\n }\n }\n\n /* Note: At this point all blank nodes in the set of RDF quads have been\n assigned canonical identifiers, which have been stored in the canonical\n issuer. Here each quad is updated by assigning each of its blank nodes\n its new identifier. */\n\n // 7) For each quad, quad, in input dataset:\n const normalized = [];\n for(const quad of this.quads) {\n // 7.1) Create a copy, quad copy, of quad and replace any existing\n // blank node identifiers using the canonical identifiers\n // previously issued by canonical issuer.\n // Note: We optimize with shallow copies here.\n const q = {...quad};\n q.subject = this._useCanonicalId({component: q.subject});\n q.object = this._useCanonicalId({component: q.object});\n q.graph = this._useCanonicalId({component: q.graph});\n // 7.2) Add quad copy to the normalized dataset.\n normalized.push(NQuads.serializeQuad(q));\n }\n\n // sort normalized output\n normalized.sort();\n\n // 8) Return the normalized dataset.\n return normalized.join('');\n }\n\n // 4.6) Hash First Degree Quads\n async hashFirstDegreeQuads(id) {\n // 1) Initialize nquads to an empty list. It will be used to store quads in\n // N-Quads format.\n const nquads = [];\n\n // 2) Get the list of quads `quads` associated with the reference blank node\n // identifier in the blank node to quads map.\n const info = this.blankNodeInfo.get(id);\n const quads = info.quads;\n\n // 3) For each quad `quad` in `quads`:\n for(const quad of quads) {\n // 3.1) Serialize the quad in N-Quads format with the following special\n // rule:\n\n // 3.1.1) If any component in quad is an blank node, then serialize it\n // using a special identifier as follows:\n const copy = {\n subject: null, predicate: quad.predicate, object: null, graph: null\n };\n // 3.1.2) If the blank node's existing blank node identifier matches\n // the reference blank node identifier then use the blank node\n // identifier _:a, otherwise, use the blank node identifier _:z.\n copy.subject = this.modifyFirstDegreeComponent(\n id, quad.subject, 'subject');\n copy.object = this.modifyFirstDegreeComponent(\n id, quad.object, 'object');\n copy.graph = this.modifyFirstDegreeComponent(\n id, quad.graph, 'graph');\n nquads.push(NQuads.serializeQuad(copy));\n }\n\n // 4) Sort nquads in lexicographical order.\n nquads.sort();\n\n // 5) Return the hash that results from passing the sorted, joined nquads\n // through the hash algorithm.\n const md = new MessageDigest(this.hashAlgorithm);\n for(const nquad of nquads) {\n md.update(nquad);\n }\n info.hash = await md.digest();\n return info.hash;\n }\n\n // 4.7) Hash Related Blank Node\n async hashRelatedBlankNode(related, quad, issuer, position) {\n // 1) Set the identifier to use for related, preferring first the canonical\n // identifier for related if issued, second the identifier issued by issuer\n // if issued, and last, if necessary, the result of the Hash First Degree\n // Quads algorithm, passing related.\n let id;\n if(this.canonicalIssuer.hasId(related)) {\n id = this.canonicalIssuer.getId(related);\n } else if(issuer.hasId(related)) {\n id = issuer.getId(related);\n } else {\n id = this.blankNodeInfo.get(related).hash;\n }\n\n // 2) Initialize a string input to the value of position.\n // Note: We use a hash object instead.\n const md = new MessageDigest(this.hashAlgorithm);\n md.update(position);\n\n // 3) If position is not g, append <, the value of the predicate in quad,\n // and > to input.\n if(position !== 'g') {\n md.update(this.getRelatedPredicate(quad));\n }\n\n // 4) Append identifier to input.\n md.update(id);\n\n // 5) Return the hash that results from passing input through the hash\n // algorithm.\n return md.digest();\n }\n\n // 4.8) Hash N-Degree Quads\n async hashNDegreeQuads(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n // Note: 2) and 3) handled within `createHashToRelated`\n const md = new MessageDigest(this.hashAlgorithm);\n const hashToRelated = await this.createHashToRelated(id, issuer);\n\n // 4) Create an empty string, data to hash.\n // Note: We created a hash object `md` above instead.\n\n // 5) For each related hash to blank node list mapping in hash to related\n // blank nodes map, sorted lexicographically by related hash:\n const hashes = [...hashToRelated.keys()].sort();\n for(const hash of hashes) {\n // 5.1) Append the related hash to the data to hash.\n md.update(hash);\n\n // 5.2) Create a string chosen path.\n let chosenPath = '';\n\n // 5.3) Create an unset chosen issuer variable.\n let chosenIssuer;\n\n // 5.4) For each permutation of blank node list:\n const permuter = new Permuter(hashToRelated.get(hash));\n let i = 0;\n while(permuter.hasNext()) {\n const permutation = permuter.next();\n // Note: batch permutations 3 at a time\n if(++i % 3 === 0) {\n await this._yield();\n }\n\n // 5.4.1) Create a copy of issuer, issuer copy.\n let issuerCopy = issuer.clone();\n\n // 5.4.2) Create a string path.\n let path = '';\n\n // 5.4.3) Create a recursion list, to store blank node identifiers\n // that must be recursively processed by this algorithm.\n const recursionList = [];\n\n // 5.4.4) For each related in permutation:\n let nextPermutation = false;\n for(const related of permutation) {\n // 5.4.4.1) If a canonical identifier has been issued for\n // related, append it to path.\n if(this.canonicalIssuer.hasId(related)) {\n path += this.canonicalIssuer.getId(related);\n } else {\n // 5.4.4.2) Otherwise:\n // 5.4.4.2.1) If issuer copy has not issued an identifier for\n // related, append related to recursion list.\n if(!issuerCopy.hasId(related)) {\n recursionList.push(related);\n }\n // 5.4.4.2.2) Use the Issue Identifier algorithm, passing\n // issuer copy and related and append the result to path.\n path += issuerCopy.getId(related);\n }\n\n // 5.4.4.3) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n // Note: Comparing path length to chosen path length can be optimized\n // away; only compare lexicographically.\n if(chosenPath.length !== 0 && path > chosenPath) {\n nextPermutation = true;\n break;\n }\n }\n\n if(nextPermutation) {\n continue;\n }\n\n // 5.4.5) For each related in recursion list:\n for(const related of recursionList) {\n // 5.4.5.1) Set result to the result of recursively executing\n // the Hash N-Degree Quads algorithm, passing related for\n // identifier and issuer copy for path identifier issuer.\n const result = await this.hashNDegreeQuads(related, issuerCopy);\n\n // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer\n // copy and related and append the result to path.\n path += issuerCopy.getId(related);\n\n // 5.4.5.3) Append <, the hash in result, and > to path.\n path += `<${result.hash}>`;\n\n // 5.4.5.4) Set issuer copy to the identifier issuer in\n // result.\n issuerCopy = result.issuer;\n\n // 5.4.5.5) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n // Note: Comparing path length to chosen path length can be optimized\n // away; only compare lexicographically.\n if(chosenPath.length !== 0 && path > chosenPath) {\n nextPermutation = true;\n break;\n }\n }\n\n if(nextPermutation) {\n continue;\n }\n\n // 5.4.6) If chosen path is empty or path is lexicographically\n // less than chosen path, set chosen path to path and chosen\n // issuer to issuer copy.\n if(chosenPath.length === 0 || path < chosenPath) {\n chosenPath = path;\n chosenIssuer = issuerCopy;\n }\n }\n\n // 5.5) Append chosen path to data to hash.\n md.update(chosenPath);\n\n // 5.6) Replace issuer, by reference, with chosen issuer.\n issuer = chosenIssuer;\n }\n\n // 6) Return issuer and the hash that results from passing data to hash\n // through the hash algorithm.\n return {hash: await md.digest(), issuer};\n }\n\n // helper for modifying component during Hash First Degree Quads\n modifyFirstDegreeComponent(id, component) {\n if(component.termType !== 'BlankNode') {\n return component;\n }\n /* Note: A mistake in the URDNA2015 spec that made its way into\n implementations (and therefore must stay to avoid interop breakage)\n resulted in an assigned canonical ID, if available for\n `component.value`, not being used in place of `_:a`/`_:z`, so\n we don't use it here. */\n return {\n termType: 'BlankNode',\n value: component.value === id ? '_:a' : '_:z'\n };\n }\n\n // helper for getting a related predicate\n getRelatedPredicate(quad) {\n return `<${quad.predicate.value}>`;\n }\n\n // helper for creating hash to related blank nodes map\n async createHashToRelated(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n const hashToRelated = new Map();\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n const quads = this.blankNodeInfo.get(id).quads;\n\n // 3) For each quad in quads:\n let i = 0;\n for(const quad of quads) {\n // Note: batch hashing related blank node quads 100 at a time\n if(++i % 100 === 0) {\n await this._yield();\n }\n // 3.1) For each component in quad, if component is the subject, object,\n // and graph name and it is a blank node that is not identified by\n // identifier:\n // steps 3.1.1 and 3.1.2 occur in helpers:\n await Promise.all([\n this._addRelatedBlankNodeHash({\n quad, component: quad.subject, position: 's',\n id, issuer, hashToRelated\n }),\n this._addRelatedBlankNodeHash({\n quad, component: quad.object, position: 'o',\n id, issuer, hashToRelated\n }),\n this._addRelatedBlankNodeHash({\n quad, component: quad.graph, position: 'g',\n id, issuer, hashToRelated\n })\n ]);\n }\n\n return hashToRelated;\n }\n\n async _hashAndTrackBlankNode({id, hashToBlankNodes}) {\n // 5.3.1) Create a hash, hash, according to the Hash First Degree\n // Quads algorithm.\n const hash = await this.hashFirstDegreeQuads(id);\n\n // 5.3.2) Add hash and identifier to hash to blank nodes map,\n // creating a new entry if necessary.\n const idList = hashToBlankNodes.get(hash);\n if(!idList) {\n hashToBlankNodes.set(hash, [id]);\n } else {\n idList.push(id);\n }\n }\n\n _addBlankNodeQuadInfo({quad, component}) {\n if(component.termType !== 'BlankNode') {\n return;\n }\n const id = component.value;\n const info = this.blankNodeInfo.get(id);\n if(info) {\n info.quads.add(quad);\n } else {\n this.blankNodeInfo.set(id, {quads: new Set([quad]), hash: null});\n }\n }\n\n async _addRelatedBlankNodeHash(\n {quad, component, position, id, issuer, hashToRelated}) {\n if(!(component.termType === 'BlankNode' && component.value !== id)) {\n return;\n }\n // 3.1.1) Set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for component as\n // related, quad, path identifier issuer as issuer, and position as\n // either s, o, or g based on whether component is a subject, object,\n // graph name, respectively.\n const related = component.value;\n const hash = await this.hashRelatedBlankNode(\n related, quad, issuer, position);\n\n // 3.1.2) Add a mapping of hash to the blank node identifier for\n // component to hash to related blank nodes map, adding an entry as\n // necessary.\n const entries = hashToRelated.get(hash);\n if(entries) {\n entries.push(related);\n } else {\n hashToRelated.set(hash, [related]);\n }\n }\n\n _useCanonicalId({component}) {\n if(component.termType === 'BlankNode' &&\n !component.value.startsWith(this.canonicalIssuer.prefix)) {\n return {\n termType: 'BlankNode',\n value: this.canonicalIssuer.getId(component.value)\n };\n }\n return component;\n }\n\n async _yield() {\n return new Promise(resolve => setImmediate(resolve));\n }\n};\n\nfunction _stringHashCompare(a, b) {\n return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0;\n}\n","(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var script = doc.createElement(\"script\");\n script.onreadystatechange = function () {\n runIfPresent(handle);\n script.onreadystatechange = null;\n html.removeChild(script);\n script = null;\n };\n html.appendChild(script);\n };\n }\n\n function installSetTimeoutImplementation() {\n registerImmediate = function(handle) {\n setTimeout(runIfPresent, 0, handle);\n };\n }\n\n // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.\n var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);\n attachTo = attachTo && attachTo.setTimeout ? attachTo : global;\n\n // Don't get fooled by e.g. browserify environments.\n if ({}.toString.call(global.process) === \"[object process]\") {\n // For Node.js before 0.9\n installNextTickImplementation();\n\n } else if (canUsePostMessage()) {\n // For non-IE10 modern browsers\n installPostMessageImplementation();\n\n } else if (global.MessageChannel) {\n // For web workers, where supported\n installMessageChannelImplementation();\n\n } else if (doc && \"onreadystatechange\" in doc.createElement(\"script\")) {\n // For IE 6–8\n installReadyStateChangeImplementation();\n\n } else {\n // For older browsers\n installSetTimeoutImplementation();\n }\n\n attachTo.setImmediate = setImmediate;\n attachTo.clearImmediate = clearImmediate;\n}(typeof self === \"undefined\" ? typeof global === \"undefined\" ? this : global : self));\n","/*\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nrequire('setimmediate');\n\nconst crypto = self.crypto || self.msCrypto;\n\n// TODO: synchronous version no longer supported in browser\n\nmodule.exports = class MessageDigest {\n /**\n * Creates a new MessageDigest.\n *\n * @param algorithm the algorithm to use.\n */\n constructor(algorithm) {\n // check if crypto.subtle is available\n // check is here rather than top-level to only fail if class is used\n if(!(crypto && crypto.subtle)) {\n throw new Error('crypto.subtle not found.');\n }\n if(algorithm === 'sha256') {\n this.algorithm = {name: 'SHA-256'};\n } else if(algorithm === 'sha1') {\n this.algorithm = {name: 'SHA-1'};\n } else {\n throw new Error(`Unsupport algorithm \"${algorithm}\".`);\n }\n this._content = '';\n }\n\n update(msg) {\n this._content += msg;\n }\n\n async digest() {\n const data = new TextEncoder().encode(this._content);\n const buffer = new Uint8Array(\n await crypto.subtle.digest(this.algorithm, data));\n // return digest in hex\n let hex = '';\n for(let i = 0; i < buffer.length; ++i) {\n hex += buffer[i].toString(16).padStart(2, '0');\n }\n return hex;\n }\n};\n","/*\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\n// TODO: convert to ES6 iterable?\n\nmodule.exports = class Permuter {\n /**\n * A Permuter iterates over all possible permutations of the given array\n * of elements.\n *\n * @param list the array of elements to iterate over.\n */\n constructor(list) {\n // original array\n this.current = list.sort();\n // indicates whether there are more permutations\n this.done = false;\n // directional info for permutation algorithm\n this.dir = new Map();\n for(let i = 0; i < list.length; ++i) {\n this.dir.set(list[i], true);\n }\n }\n\n /**\n * Returns true if there is another permutation.\n *\n * @return true if there is another permutation, false if not.\n */\n hasNext() {\n return !this.done;\n }\n\n /**\n * Gets the next permutation. Call hasNext() to ensure there is another one\n * first.\n *\n * @return the next permutation.\n */\n next() {\n // copy current permutation to return it\n const {current, dir} = this;\n const rval = current.slice();\n\n /* Calculate the next permutation using the Steinhaus-Johnson-Trotter\n permutation algorithm. */\n\n // get largest mobile element k\n // (mobile: element is greater than the one it is looking at)\n let k = null;\n let pos = 0;\n const length = current.length;\n for(let i = 0; i < length; ++i) {\n const element = current[i];\n const left = dir.get(element);\n if((k === null || element > k) &&\n ((left && i > 0 && element > current[i - 1]) ||\n (!left && i < (length - 1) && element > current[i + 1]))) {\n k = element;\n pos = i;\n }\n }\n\n // no more permutations\n if(k === null) {\n this.done = true;\n } else {\n // swap k and the element it is looking at\n const swap = dir.get(k) ? pos - 1 : pos + 1;\n current[pos] = current[swap];\n current[swap] = k;\n\n // reverse the direction of all elements larger than k\n for(const element of current) {\n if(element > k) {\n dir.set(element, !dir.get(element));\n }\n }\n }\n\n return rval;\n }\n};\n","/*\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst IdentifierIssuer = require('./IdentifierIssuer');\nconst MessageDigest = require('./MessageDigest');\nconst Permuter = require('./Permuter');\nconst NQuads = require('./NQuads');\n\nmodule.exports = class URDNA2015Sync {\n constructor() {\n this.name = 'URDNA2015';\n this.blankNodeInfo = new Map();\n this.canonicalIssuer = new IdentifierIssuer('_:c14n');\n this.hashAlgorithm = 'sha256';\n this.quads = null;\n }\n\n // 4.4) Normalization Algorithm\n main(dataset) {\n this.quads = dataset;\n\n // 1) Create the normalization state.\n // 2) For every quad in input dataset:\n for(const quad of dataset) {\n // 2.1) For each blank node that occurs in the quad, add a reference\n // to the quad using the blank node identifier in the blank node to\n // quads map, creating a new entry if necessary.\n this._addBlankNodeQuadInfo({quad, component: quad.subject});\n this._addBlankNodeQuadInfo({quad, component: quad.object});\n this._addBlankNodeQuadInfo({quad, component: quad.graph});\n }\n\n // 3) Create a list of non-normalized blank node identifiers\n // non-normalized identifiers and populate it using the keys from the\n // blank node to quads map.\n // Note: We use a map here and it was generated during step 2.\n\n // 4) `simple` flag is skipped -- loop is optimized away. This optimization\n // is permitted because there was a typo in the hash first degree quads\n // algorithm in the URDNA2015 spec that was implemented widely making it\n // such that it could not be fixed; the result was that the loop only\n // needs to be run once and the first degree quad hashes will never change.\n // 5.1-5.2 are skipped; first degree quad hashes are generated just once\n // for all non-normalized blank nodes.\n\n // 5.3) For each blank node identifier identifier in non-normalized\n // identifiers:\n const hashToBlankNodes = new Map();\n const nonNormalized = [...this.blankNodeInfo.keys()];\n for(const id of nonNormalized) {\n // steps 5.3.1 and 5.3.2:\n this._hashAndTrackBlankNode({id, hashToBlankNodes});\n }\n\n // 5.4) For each hash to identifier list mapping in hash to blank\n // nodes map, lexicographically-sorted by hash:\n const hashes = [...hashToBlankNodes.keys()].sort();\n // optimize away second sort, gather non-unique hashes in order as we go\n const nonUnique = [];\n for(const hash of hashes) {\n // 5.4.1) If the length of identifier list is greater than 1,\n // continue to the next mapping.\n const idList = hashToBlankNodes.get(hash);\n if(idList.length > 1) {\n nonUnique.push(idList);\n continue;\n }\n\n // 5.4.2) Use the Issue Identifier algorithm, passing canonical\n // issuer and the single blank node identifier in identifier\n // list, identifier, to issue a canonical replacement identifier\n // for identifier.\n const id = idList[0];\n this.canonicalIssuer.getId(id);\n\n // Note: These steps are skipped, optimized away since the loop\n // only needs to be run once.\n // 5.4.3) Remove identifier from non-normalized identifiers.\n // 5.4.4) Remove hash from the hash to blank nodes map.\n // 5.4.5) Set simple to true.\n }\n\n // 6) For each hash to identifier list mapping in hash to blank nodes map,\n // lexicographically-sorted by hash:\n // Note: sort optimized away, use `nonUnique`.\n for(const idList of nonUnique) {\n // 6.1) Create hash path list where each item will be a result of\n // running the Hash N-Degree Quads algorithm.\n const hashPathList = [];\n\n // 6.2) For each blank node identifier identifier in identifier list:\n for(const id of idList) {\n // 6.2.1) If a canonical identifier has already been issued for\n // identifier, continue to the next identifier.\n if(this.canonicalIssuer.hasId(id)) {\n continue;\n }\n\n // 6.2.2) Create temporary issuer, an identifier issuer\n // initialized with the prefix _:b.\n const issuer = new IdentifierIssuer('_:b');\n\n // 6.2.3) Use the Issue Identifier algorithm, passing temporary\n // issuer and identifier, to issue a new temporary blank node\n // identifier for identifier.\n issuer.getId(id);\n\n // 6.2.4) Run the Hash N-Degree Quads algorithm, passing\n // temporary issuer, and append the result to the hash path list.\n const result = this.hashNDegreeQuads(id, issuer);\n hashPathList.push(result);\n }\n\n // 6.3) For each result in the hash path list,\n // lexicographically-sorted by the hash in result:\n hashPathList.sort(_stringHashCompare);\n for(const result of hashPathList) {\n // 6.3.1) For each blank node identifier, existing identifier,\n // that was issued a temporary identifier by identifier issuer\n // in result, issue a canonical identifier, in the same order,\n // using the Issue Identifier algorithm, passing canonical\n // issuer and existing identifier.\n const oldIds = result.issuer.getOldIds();\n for(const id of oldIds) {\n this.canonicalIssuer.getId(id);\n }\n }\n }\n\n /* Note: At this point all blank nodes in the set of RDF quads have been\n assigned canonical identifiers, which have been stored in the canonical\n issuer. Here each quad is updated by assigning each of its blank nodes\n its new identifier. */\n\n // 7) For each quad, quad, in input dataset:\n const normalized = [];\n for(const quad of this.quads) {\n // 7.1) Create a copy, quad copy, of quad and replace any existing\n // blank node identifiers using the canonical identifiers\n // previously issued by canonical issuer.\n // Note: We optimize with shallow copies here.\n const q = {...quad};\n q.subject = this._useCanonicalId({component: q.subject});\n q.object = this._useCanonicalId({component: q.object});\n q.graph = this._useCanonicalId({component: q.graph});\n // 7.2) Add quad copy to the normalized dataset.\n normalized.push(NQuads.serializeQuad(q));\n }\n\n // sort normalized output\n normalized.sort();\n\n // 8) Return the normalized dataset.\n return normalized.join('');\n }\n\n // 4.6) Hash First Degree Quads\n hashFirstDegreeQuads(id) {\n // 1) Initialize nquads to an empty list. It will be used to store quads in\n // N-Quads format.\n const nquads = [];\n\n // 2) Get the list of quads `quads` associated with the reference blank node\n // identifier in the blank node to quads map.\n const info = this.blankNodeInfo.get(id);\n const quads = info.quads;\n\n // 3) For each quad `quad` in `quads`:\n for(const quad of quads) {\n // 3.1) Serialize the quad in N-Quads format with the following special\n // rule:\n\n // 3.1.1) If any component in quad is an blank node, then serialize it\n // using a special identifier as follows:\n const copy = {\n subject: null, predicate: quad.predicate, object: null, graph: null\n };\n // 3.1.2) If the blank node's existing blank node identifier matches\n // the reference blank node identifier then use the blank node\n // identifier _:a, otherwise, use the blank node identifier _:z.\n copy.subject = this.modifyFirstDegreeComponent(\n id, quad.subject, 'subject');\n copy.object = this.modifyFirstDegreeComponent(\n id, quad.object, 'object');\n copy.graph = this.modifyFirstDegreeComponent(\n id, quad.graph, 'graph');\n nquads.push(NQuads.serializeQuad(copy));\n }\n\n // 4) Sort nquads in lexicographical order.\n nquads.sort();\n\n // 5) Return the hash that results from passing the sorted, joined nquads\n // through the hash algorithm.\n const md = new MessageDigest(this.hashAlgorithm);\n for(const nquad of nquads) {\n md.update(nquad);\n }\n info.hash = md.digest();\n return info.hash;\n }\n\n // 4.7) Hash Related Blank Node\n hashRelatedBlankNode(related, quad, issuer, position) {\n // 1) Set the identifier to use for related, preferring first the canonical\n // identifier for related if issued, second the identifier issued by issuer\n // if issued, and last, if necessary, the result of the Hash First Degree\n // Quads algorithm, passing related.\n let id;\n if(this.canonicalIssuer.hasId(related)) {\n id = this.canonicalIssuer.getId(related);\n } else if(issuer.hasId(related)) {\n id = issuer.getId(related);\n } else {\n id = this.blankNodeInfo.get(related).hash;\n }\n\n // 2) Initialize a string input to the value of position.\n // Note: We use a hash object instead.\n const md = new MessageDigest(this.hashAlgorithm);\n md.update(position);\n\n // 3) If position is not g, append <, the value of the predicate in quad,\n // and > to input.\n if(position !== 'g') {\n md.update(this.getRelatedPredicate(quad));\n }\n\n // 4) Append identifier to input.\n md.update(id);\n\n // 5) Return the hash that results from passing input through the hash\n // algorithm.\n return md.digest();\n }\n\n // 4.8) Hash N-Degree Quads\n hashNDegreeQuads(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n // Note: 2) and 3) handled within `createHashToRelated`\n const md = new MessageDigest(this.hashAlgorithm);\n const hashToRelated = this.createHashToRelated(id, issuer);\n\n // 4) Create an empty string, data to hash.\n // Note: We created a hash object `md` above instead.\n\n // 5) For each related hash to blank node list mapping in hash to related\n // blank nodes map, sorted lexicographically by related hash:\n const hashes = [...hashToRelated.keys()].sort();\n for(const hash of hashes) {\n // 5.1) Append the related hash to the data to hash.\n md.update(hash);\n\n // 5.2) Create a string chosen path.\n let chosenPath = '';\n\n // 5.3) Create an unset chosen issuer variable.\n let chosenIssuer;\n\n // 5.4) For each permutation of blank node list:\n const permuter = new Permuter(hashToRelated.get(hash));\n while(permuter.hasNext()) {\n const permutation = permuter.next();\n\n // 5.4.1) Create a copy of issuer, issuer copy.\n let issuerCopy = issuer.clone();\n\n // 5.4.2) Create a string path.\n let path = '';\n\n // 5.4.3) Create a recursion list, to store blank node identifiers\n // that must be recursively processed by this algorithm.\n const recursionList = [];\n\n // 5.4.4) For each related in permutation:\n let nextPermutation = false;\n for(const related of permutation) {\n // 5.4.4.1) If a canonical identifier has been issued for\n // related, append it to path.\n if(this.canonicalIssuer.hasId(related)) {\n path += this.canonicalIssuer.getId(related);\n } else {\n // 5.4.4.2) Otherwise:\n // 5.4.4.2.1) If issuer copy has not issued an identifier for\n // related, append related to recursion list.\n if(!issuerCopy.hasId(related)) {\n recursionList.push(related);\n }\n // 5.4.4.2.2) Use the Issue Identifier algorithm, passing\n // issuer copy and related and append the result to path.\n path += issuerCopy.getId(related);\n }\n\n // 5.4.4.3) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n // Note: Comparing path length to chosen path length can be optimized\n // away; only compare lexicographically.\n if(chosenPath.length !== 0 && path > chosenPath) {\n nextPermutation = true;\n break;\n }\n }\n\n if(nextPermutation) {\n continue;\n }\n\n // 5.4.5) For each related in recursion list:\n for(const related of recursionList) {\n // 5.4.5.1) Set result to the result of recursively executing\n // the Hash N-Degree Quads algorithm, passing related for\n // identifier and issuer copy for path identifier issuer.\n const result = this.hashNDegreeQuads(related, issuerCopy);\n\n // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer\n // copy and related and append the result to path.\n path += issuerCopy.getId(related);\n\n // 5.4.5.3) Append <, the hash in result, and > to path.\n path += `<${result.hash}>`;\n\n // 5.4.5.4) Set issuer copy to the identifier issuer in\n // result.\n issuerCopy = result.issuer;\n\n // 5.4.5.5) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n // Note: Comparing path length to chosen path length can be optimized\n // away; only compare lexicographically.\n if(chosenPath.length !== 0 && path > chosenPath) {\n nextPermutation = true;\n break;\n }\n }\n\n if(nextPermutation) {\n continue;\n }\n\n // 5.4.6) If chosen path is empty or path is lexicographically\n // less than chosen path, set chosen path to path and chosen\n // issuer to issuer copy.\n if(chosenPath.length === 0 || path < chosenPath) {\n chosenPath = path;\n chosenIssuer = issuerCopy;\n }\n }\n\n // 5.5) Append chosen path to data to hash.\n md.update(chosenPath);\n\n // 5.6) Replace issuer, by reference, with chosen issuer.\n issuer = chosenIssuer;\n }\n\n // 6) Return issuer and the hash that results from passing data to hash\n // through the hash algorithm.\n return {hash: md.digest(), issuer};\n }\n\n // helper for modifying component during Hash First Degree Quads\n modifyFirstDegreeComponent(id, component) {\n if(component.termType !== 'BlankNode') {\n return component;\n }\n /* Note: A mistake in the URDNA2015 spec that made its way into\n implementations (and therefore must stay to avoid interop breakage)\n resulted in an assigned canonical ID, if available for\n `component.value`, not being used in place of `_:a`/`_:z`, so\n we don't use it here. */\n return {\n termType: 'BlankNode',\n value: component.value === id ? '_:a' : '_:z'\n };\n }\n\n // helper for getting a related predicate\n getRelatedPredicate(quad) {\n return `<${quad.predicate.value}>`;\n }\n\n // helper for creating hash to related blank nodes map\n createHashToRelated(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n const hashToRelated = new Map();\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n const quads = this.blankNodeInfo.get(id).quads;\n\n // 3) For each quad in quads:\n for(const quad of quads) {\n // 3.1) For each component in quad, if component is the subject, object,\n // or graph name and it is a blank node that is not identified by\n // identifier:\n // steps 3.1.1 and 3.1.2 occur in helpers:\n this._addRelatedBlankNodeHash({\n quad, component: quad.subject, position: 's',\n id, issuer, hashToRelated\n });\n this._addRelatedBlankNodeHash({\n quad, component: quad.object, position: 'o',\n id, issuer, hashToRelated\n });\n this._addRelatedBlankNodeHash({\n quad, component: quad.graph, position: 'g',\n id, issuer, hashToRelated\n });\n }\n\n return hashToRelated;\n }\n\n _hashAndTrackBlankNode({id, hashToBlankNodes}) {\n // 5.3.1) Create a hash, hash, according to the Hash First Degree\n // Quads algorithm.\n const hash = this.hashFirstDegreeQuads(id);\n\n // 5.3.2) Add hash and identifier to hash to blank nodes map,\n // creating a new entry if necessary.\n const idList = hashToBlankNodes.get(hash);\n if(!idList) {\n hashToBlankNodes.set(hash, [id]);\n } else {\n idList.push(id);\n }\n }\n\n _addBlankNodeQuadInfo({quad, component}) {\n if(component.termType !== 'BlankNode') {\n return;\n }\n const id = component.value;\n const info = this.blankNodeInfo.get(id);\n if(info) {\n info.quads.add(quad);\n } else {\n this.blankNodeInfo.set(id, {quads: new Set([quad]), hash: null});\n }\n }\n\n _addRelatedBlankNodeHash(\n {quad, component, position, id, issuer, hashToRelated}) {\n if(!(component.termType === 'BlankNode' && component.value !== id)) {\n return;\n }\n // 3.1.1) Set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for component as\n // related, quad, path identifier issuer as issuer, and position as\n // either s, o, or g based on whether component is a subject, object,\n // graph name, respectively.\n const related = component.value;\n const hash = this.hashRelatedBlankNode(related, quad, issuer, position);\n\n // 3.1.2) Add a mapping of hash to the blank node identifier for\n // component to hash to related blank nodes map, adding an entry as\n // necessary.\n const entries = hashToRelated.get(hash);\n if(entries) {\n entries.push(related);\n } else {\n hashToRelated.set(hash, [related]);\n }\n }\n\n _useCanonicalId({component}) {\n if(component.termType === 'BlankNode' &&\n !component.value.startsWith(this.canonicalIssuer.prefix)) {\n return {\n termType: 'BlankNode',\n value: this.canonicalIssuer.getId(component.value)\n };\n }\n return component;\n }\n};\n\nfunction _stringHashCompare(a, b) {\n return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0;\n}\n","/*\n * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nmodule.exports = class RequestQueue {\n /**\n * Creates a simple queue for requesting documents.\n */\n constructor() {\n this._requests = {};\n }\n\n wrapLoader(loader) {\n const self = this;\n self._loader = loader;\n return function(/* url */) {\n return self.add.apply(self, arguments);\n };\n }\n\n async add(url) {\n let promise = this._requests[url];\n if(promise) {\n // URL already queued, wait for it to load\n return Promise.resolve(promise);\n }\n\n // queue URL and load it\n promise = this._requests[url] = this._loader(url);\n\n try {\n return await promise;\n } finally {\n delete this._requests[url];\n }\n }\n};\n","'use strict'\n\n// A linked list to keep track of recently-used-ness\nconst Yallist = require('yallist')\n\nconst MAX = Symbol('max')\nconst LENGTH = Symbol('length')\nconst LENGTH_CALCULATOR = Symbol('lengthCalculator')\nconst ALLOW_STALE = Symbol('allowStale')\nconst MAX_AGE = Symbol('maxAge')\nconst DISPOSE = Symbol('dispose')\nconst NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')\nconst LRU_LIST = Symbol('lruList')\nconst CACHE = Symbol('cache')\nconst UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')\n\nconst naiveLength = () => 1\n\n// lruList is a yallist where the head is the youngest\n// item, and the tail is the oldest. the list contains the Hit\n// objects as the entries.\n// Each Hit object has a reference to its Yallist.Node. This\n// never changes.\n//\n// cache is a Map (or PseudoMap) that matches the keys to\n// the Yallist.Node object.\nclass LRUCache {\n constructor (options) {\n if (typeof options === 'number')\n options = { max: options }\n\n if (!options)\n options = {}\n\n if (options.max && (typeof options.max !== 'number' || options.max < 0))\n throw new TypeError('max must be a non-negative number')\n // Kind of weird to have a default max of Infinity, but oh well.\n const max = this[MAX] = options.max || Infinity\n\n const lc = options.length || naiveLength\n this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc\n this[ALLOW_STALE] = options.stale || false\n if (options.maxAge && typeof options.maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n this[MAX_AGE] = options.maxAge || 0\n this[DISPOSE] = options.dispose\n this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false\n this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false\n this.reset()\n }\n\n // resize the cache when the max changes.\n set max (mL) {\n if (typeof mL !== 'number' || mL < 0)\n throw new TypeError('max must be a non-negative number')\n\n this[MAX] = mL || Infinity\n trim(this)\n }\n get max () {\n return this[MAX]\n }\n\n set allowStale (allowStale) {\n this[ALLOW_STALE] = !!allowStale\n }\n get allowStale () {\n return this[ALLOW_STALE]\n }\n\n set maxAge (mA) {\n if (typeof mA !== 'number')\n throw new TypeError('maxAge must be a non-negative number')\n\n this[MAX_AGE] = mA\n trim(this)\n }\n get maxAge () {\n return this[MAX_AGE]\n }\n\n // resize the cache when the lengthCalculator changes.\n set lengthCalculator (lC) {\n if (typeof lC !== 'function')\n lC = naiveLength\n\n if (lC !== this[LENGTH_CALCULATOR]) {\n this[LENGTH_CALCULATOR] = lC\n this[LENGTH] = 0\n this[LRU_LIST].forEach(hit => {\n hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)\n this[LENGTH] += hit.length\n })\n }\n trim(this)\n }\n get lengthCalculator () { return this[LENGTH_CALCULATOR] }\n\n get length () { return this[LENGTH] }\n get itemCount () { return this[LRU_LIST].length }\n\n rforEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].tail; walker !== null;) {\n const prev = walker.prev\n forEachStep(this, fn, walker, thisp)\n walker = prev\n }\n }\n\n forEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].head; walker !== null;) {\n const next = walker.next\n forEachStep(this, fn, walker, thisp)\n walker = next\n }\n }\n\n keys () {\n return this[LRU_LIST].toArray().map(k => k.key)\n }\n\n values () {\n return this[LRU_LIST].toArray().map(k => k.value)\n }\n\n reset () {\n if (this[DISPOSE] &&\n this[LRU_LIST] &&\n this[LRU_LIST].length) {\n this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))\n }\n\n this[CACHE] = new Map() // hash of items by key\n this[LRU_LIST] = new Yallist() // list of items in order of use recency\n this[LENGTH] = 0 // length of items in the list\n }\n\n dump () {\n return this[LRU_LIST].map(hit =>\n isStale(this, hit) ? false : {\n k: hit.key,\n v: hit.value,\n e: hit.now + (hit.maxAge || 0)\n }).toArray().filter(h => h)\n }\n\n dumpLru () {\n return this[LRU_LIST]\n }\n\n set (key, value, maxAge) {\n maxAge = maxAge || this[MAX_AGE]\n\n if (maxAge && typeof maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n\n const now = maxAge ? Date.now() : 0\n const len = this[LENGTH_CALCULATOR](value, key)\n\n if (this[CACHE].has(key)) {\n if (len > this[MAX]) {\n del(this, this[CACHE].get(key))\n return false\n }\n\n const node = this[CACHE].get(key)\n const item = node.value\n\n // dispose of the old one before overwriting\n // split out into 2 ifs for better coverage tracking\n if (this[DISPOSE]) {\n if (!this[NO_DISPOSE_ON_SET])\n this[DISPOSE](key, item.value)\n }\n\n item.now = now\n item.maxAge = maxAge\n item.value = value\n this[LENGTH] += len - item.length\n item.length = len\n this.get(key)\n trim(this)\n return true\n }\n\n const hit = new Entry(key, value, len, now, maxAge)\n\n // oversized objects fall out of cache automatically.\n if (hit.length > this[MAX]) {\n if (this[DISPOSE])\n this[DISPOSE](key, value)\n\n return false\n }\n\n this[LENGTH] += hit.length\n this[LRU_LIST].unshift(hit)\n this[CACHE].set(key, this[LRU_LIST].head)\n trim(this)\n return true\n }\n\n has (key) {\n if (!this[CACHE].has(key)) return false\n const hit = this[CACHE].get(key).value\n return !isStale(this, hit)\n }\n\n get (key) {\n return get(this, key, true)\n }\n\n peek (key) {\n return get(this, key, false)\n }\n\n pop () {\n const node = this[LRU_LIST].tail\n if (!node)\n return null\n\n del(this, node)\n return node.value\n }\n\n del (key) {\n del(this, this[CACHE].get(key))\n }\n\n load (arr) {\n // reset the cache\n this.reset()\n\n const now = Date.now()\n // A previous serialized cache has the most recent items first\n for (let l = arr.length - 1; l >= 0; l--) {\n const hit = arr[l]\n const expiresAt = hit.e || 0\n if (expiresAt === 0)\n // the item was created without expiration in a non aged cache\n this.set(hit.k, hit.v)\n else {\n const maxAge = expiresAt - now\n // dont add already expired items\n if (maxAge > 0) {\n this.set(hit.k, hit.v, maxAge)\n }\n }\n }\n }\n\n prune () {\n this[CACHE].forEach((value, key) => get(this, key, false))\n }\n}\n\nconst get = (self, key, doUse) => {\n const node = self[CACHE].get(key)\n if (node) {\n const hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n return undefined\n } else {\n if (doUse) {\n if (self[UPDATE_AGE_ON_GET])\n node.value.now = Date.now()\n self[LRU_LIST].unshiftNode(node)\n }\n }\n return hit.value\n }\n}\n\nconst isStale = (self, hit) => {\n if (!hit || (!hit.maxAge && !self[MAX_AGE]))\n return false\n\n const diff = Date.now() - hit.now\n return hit.maxAge ? diff > hit.maxAge\n : self[MAX_AGE] && (diff > self[MAX_AGE])\n}\n\nconst trim = self => {\n if (self[LENGTH] > self[MAX]) {\n for (let walker = self[LRU_LIST].tail;\n self[LENGTH] > self[MAX] && walker !== null;) {\n // We know that we're about to delete this one, and also\n // what the next least recently used key will be, so just\n // go ahead and set it now.\n const prev = walker.prev\n del(self, walker)\n walker = prev\n }\n }\n}\n\nconst del = (self, node) => {\n if (node) {\n const hit = node.value\n if (self[DISPOSE])\n self[DISPOSE](hit.key, hit.value)\n\n self[LENGTH] -= hit.length\n self[CACHE].delete(hit.key)\n self[LRU_LIST].removeNode(node)\n }\n}\n\nclass Entry {\n constructor (key, value, length, now, maxAge) {\n this.key = key\n this.value = value\n this.length = length\n this.now = now\n this.maxAge = maxAge || 0\n }\n}\n\nconst forEachStep = (self, fn, node, thisp) => {\n let hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n hit = undefined\n }\n if (hit)\n fn.call(thisp, hit.value, hit.key, self)\n}\n\nmodule.exports = LRUCache\n","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\n\nfunction _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n\n _next(undefined);\n });\n };\n}\n\nmodule.exports = _asyncToGenerator;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","// **N3Lexer** tokenizes N3 documents.\nimport namespaces from './IRIs';\nimport queueMicrotask from 'queue-microtask';\n\nconst { xsd } = namespaces;\n\n// Regular expression and replacement string to escape N3 strings\nconst escapeSequence = /\\\\u([a-fA-F0-9]{4})|\\\\U([a-fA-F0-9]{8})|\\\\([^])/g;\nconst escapeReplacements = {\n '\\\\': '\\\\', \"'\": \"'\", '\"': '\"',\n 'n': '\\n', 'r': '\\r', 't': '\\t', 'f': '\\f', 'b': '\\b',\n '_': '_', '~': '~', '.': '.', '-': '-', '!': '!', '$': '$', '&': '&',\n '(': '(', ')': ')', '*': '*', '+': '+', ',': ',', ';': ';', '=': '=',\n '/': '/', '?': '?', '#': '#', '@': '@', '%': '%',\n};\nconst illegalIriChars = /[\\x00-\\x20<>\\\\\"\\{\\}\\|\\^\\`]/;\n\nconst lineModeRegExps = {\n _iri: true,\n _unescapedIri: true,\n _simpleQuotedString: true,\n _langcode: true,\n _blank: true,\n _newline: true,\n _comment: true,\n _whitespace: true,\n _endOfFile: true,\n};\nconst invalidRegExp = /$0^/;\n\n// ## Constructor\nexport default class N3Lexer {\n constructor(options) {\n // ## Regular expressions\n // It's slightly faster to have these as properties than as in-scope variables\n this._iri = /^<((?:[^ <>{}\\\\]|\\\\[uU])+)>[ \\t]*/; // IRI with escape sequences; needs sanity check after unescaping\n this._unescapedIri = /^<([^\\x00-\\x20<>\\\\\"\\{\\}\\|\\^\\`]*)>[ \\t]*/; // IRI without escape sequences; no unescaping\n this._simpleQuotedString = /^\"([^\"\\\\\\r\\n]*)\"(?=[^\"])/; // string without escape sequences\n this._simpleApostropheString = /^'([^'\\\\\\r\\n]*)'(?=[^'])/;\n this._langcode = /^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\\-])/i;\n 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<])/;\n 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#()\\[\\]\\{\\}\"'<>]))/;\n 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#()\\[\\]\\{\\}\"'<>])/;\n 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#()\\[\\]\\{\\}\"'<>]))/;\n this._number = /^[\\-+]?(?:(\\d+\\.\\d*|\\.?\\d+)[eE][\\-+]?|\\d*(\\.)?)\\d+(?=\\.?[,;:\\s#()\\[\\]\\{\\}\"'<>])/;\n this._boolean = /^(?:true|false)(?=[.,;\\s#()\\[\\]\\{\\}\"'<>])/;\n this._keyword = /^@[a-z]+(?=[\\s#<:])/i;\n this._sparqlKeyword = /^(?:PREFIX|BASE|GRAPH)(?=[\\s#<])/i;\n this._shortPredicates = /^a(?=[\\s#()\\[\\]\\{\\}\"'<>])/;\n this._newline = /^[ \\t]*(?:#[^\\n\\r]*)?(?:\\r\\n|\\n|\\r)[ \\t]*/;\n this._comment = /#([^\\n\\r]*)/;\n this._whitespace = /^[ \\t]+/;\n this._endOfFile = /^(?:#[^\\n\\r]*)?$/;\n options = options || {};\n\n // In line mode (N-Triples or N-Quads), only simple features may be parsed\n if (this._lineMode = !!options.lineMode) {\n this._n3Mode = false;\n // Don't tokenize special literals\n for (const key in this) {\n if (!(key in lineModeRegExps) && this[key] instanceof RegExp)\n this[key] = invalidRegExp;\n }\n }\n // When not in line mode, enable N3 functionality by default\n else {\n this._n3Mode = options.n3 !== false;\n }\n // Don't output comment tokens by default\n this._comments = !!options.comments;\n // Cache the last tested closing position of long literals\n this._literalClosingPos = 0;\n }\n\n // ## Private methods\n\n // ### `_tokenizeToEnd` tokenizes as for as possible, emitting tokens through the callback\n _tokenizeToEnd(callback, inputFinished) {\n // Continue parsing as far as possible; the loop will return eventually\n let input = this._input;\n const outputComments = this._comments;\n while (true) {\n // Count and skip whitespace lines\n let whiteSpaceMatch, comment;\n while (whiteSpaceMatch = this._newline.exec(input)) {\n // Try to find a comment\n if (outputComments && (comment = this._comment.exec(whiteSpaceMatch[0])))\n callback(null, { line: this._line, type: 'comment', value: comment[1], prefix: '' });\n // Advance the input\n input = input.substr(whiteSpaceMatch[0].length, input.length);\n this._line++;\n }\n // Skip whitespace on current line\n if (!whiteSpaceMatch && (whiteSpaceMatch = this._whitespace.exec(input)))\n input = input.substr(whiteSpaceMatch[0].length, input.length);\n\n // Stop for now if we're at the end\n if (this._endOfFile.test(input)) {\n // If the input is finished, emit EOF\n if (inputFinished) {\n // Try to find a final comment\n if (outputComments && (comment = this._comment.exec(input)))\n callback(null, { line: this._line, type: 'comment', value: comment[1], prefix: '' });\n callback(input = null, { line: this._line, type: 'eof', value: '', prefix: '' });\n }\n return this._input = input;\n }\n\n // Look for specific token types based on the first character\n const line = this._line, firstChar = input[0];\n let type = '', value = '', prefix = '',\n match = null, matchLength = 0, inconclusive = false;\n switch (firstChar) {\n case '^':\n // We need at least 3 tokens lookahead to distinguish ^^<IRI> and ^^pre:fixed\n if (input.length < 3)\n break;\n // Try to match a type\n else if (input[1] === '^') {\n this._previousMarker = '^^';\n // Move to type IRI or prefixed name\n input = input.substr(2);\n if (input[0] !== '<') {\n inconclusive = true;\n break;\n }\n }\n // If no type, it must be a path expression\n else {\n if (this._n3Mode) {\n matchLength = 1;\n type = '^';\n }\n break;\n }\n // Fall through in case the type is an IRI\n case '<':\n // Try to find a full IRI without escape sequences\n if (match = this._unescapedIri.exec(input))\n type = 'IRI', value = match[1];\n // Try to find a full IRI with escape sequences\n else if (match = this._iri.exec(input)) {\n value = this._unescape(match[1]);\n if (value === null || illegalIriChars.test(value))\n return reportSyntaxError(this);\n type = 'IRI';\n }\n // Try to find a nested triple\n else if (input.length > 1 && input[1] === '<')\n type = '<<', matchLength = 2;\n // Try to find a backwards implication arrow\n else if (this._n3Mode && input.length > 1 && input[1] === '=')\n type = 'inverse', matchLength = 2, value = '>';\n break;\n\n case '>':\n if (input.length > 1 && input[1] === '>')\n type = '>>', matchLength = 2;\n break;\n\n case '_':\n // Try to find a blank node. Since it can contain (but not end with) a dot,\n // we always need a non-dot character before deciding it is a blank node.\n // Therefore, try inserting a space if we're at the end of the input.\n if ((match = this._blank.exec(input)) ||\n inputFinished && (match = this._blank.exec(`${input} `)))\n type = 'blank', prefix = '_', value = match[1];\n break;\n\n case '\"':\n // Try to find a literal without escape sequences\n if (match = this._simpleQuotedString.exec(input))\n value = match[1];\n // Try to find a literal wrapped in three pairs of quotes\n else {\n ({ value, matchLength } = this._parseLiteral(input));\n if (value === null)\n return reportSyntaxError(this);\n }\n if (match !== null || matchLength !== 0) {\n type = 'literal';\n this._literalClosingPos = 0;\n }\n break;\n\n case \"'\":\n if (!this._lineMode) {\n // Try to find a literal without escape sequences\n if (match = this._simpleApostropheString.exec(input))\n value = match[1];\n // Try to find a literal wrapped in three pairs of quotes\n else {\n ({ value, matchLength } = this._parseLiteral(input));\n if (value === null)\n return reportSyntaxError(this);\n }\n if (match !== null || matchLength !== 0) {\n type = 'literal';\n this._literalClosingPos = 0;\n }\n }\n break;\n\n case '?':\n // Try to find a variable\n if (this._n3Mode && (match = this._variable.exec(input)))\n type = 'var', value = match[0];\n break;\n\n case '@':\n // Try to find a language code\n if (this._previousMarker === 'literal' && (match = this._langcode.exec(input)))\n type = 'langcode', value = match[1];\n // Try to find a keyword\n else if (match = this._keyword.exec(input))\n type = match[0];\n break;\n\n case '.':\n // Try to find a dot as punctuation\n if (input.length === 1 ? inputFinished : (input[1] < '0' || input[1] > '9')) {\n type = '.';\n matchLength = 1;\n break;\n }\n // Fall through to numerical case (could be a decimal dot)\n\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n case '+':\n case '-':\n // Try to find a number. Since it can contain (but not end with) a dot,\n // we always need a non-dot character before deciding it is a number.\n // Therefore, try inserting a space if we're at the end of the input.\n if (match = this._number.exec(input) ||\n inputFinished && (match = this._number.exec(`${input} `))) {\n type = 'literal', value = match[0];\n prefix = (typeof match[1] === 'string' ? xsd.double :\n (typeof match[2] === 'string' ? xsd.decimal : xsd.integer));\n }\n break;\n\n case 'B':\n case 'b':\n case 'p':\n case 'P':\n case 'G':\n case 'g':\n // Try to find a SPARQL-style keyword\n if (match = this._sparqlKeyword.exec(input))\n type = match[0].toUpperCase();\n else\n inconclusive = true;\n break;\n\n case 'f':\n case 't':\n // Try to match a boolean\n if (match = this._boolean.exec(input))\n type = 'literal', value = match[0], prefix = xsd.boolean;\n else\n inconclusive = true;\n break;\n\n case 'a':\n // Try to find an abbreviated predicate\n if (match = this._shortPredicates.exec(input))\n type = 'abbreviation', value = 'a';\n else\n inconclusive = true;\n break;\n\n case '=':\n // Try to find an implication arrow or equals sign\n if (this._n3Mode && input.length > 1) {\n type = 'abbreviation';\n if (input[1] !== '>')\n matchLength = 1, value = '=';\n else\n matchLength = 2, value = '>';\n }\n break;\n\n case '!':\n if (!this._n3Mode)\n break;\n case ',':\n case ';':\n case '[':\n case ']':\n case '(':\n case ')':\n case '{':\n case '}':\n if (!this._lineMode) {\n matchLength = 1;\n type = firstChar;\n }\n break;\n\n default:\n inconclusive = true;\n }\n\n // Some first characters do not allow an immediate decision, so inspect more\n if (inconclusive) {\n // Try to find a prefix\n if ((this._previousMarker === '@prefix' || this._previousMarker === 'PREFIX') &&\n (match = this._prefix.exec(input)))\n type = 'prefix', value = match[1] || '';\n // Try to find a prefixed name. Since it can contain (but not end with) a dot,\n // we always need a non-dot character before deciding it is a prefixed name.\n // Therefore, try inserting a space if we're at the end of the input.\n else if ((match = this._prefixed.exec(input)) ||\n inputFinished && (match = this._prefixed.exec(`${input} `)))\n type = 'prefixed', prefix = match[1] || '', value = this._unescape(match[2]);\n }\n\n // A type token is special: it can only be emitted after an IRI or prefixed name is read\n if (this._previousMarker === '^^') {\n switch (type) {\n case 'prefixed': type = 'type'; break;\n case 'IRI': type = 'typeIRI'; break;\n default: type = '';\n }\n }\n\n // What if nothing of the above was found?\n if (!type) {\n // We could be in streaming mode, and then we just wait for more input to arrive.\n // Otherwise, a syntax error has occurred in the input.\n // One exception: error on an unaccounted linebreak (= not inside a triple-quoted literal).\n if (inputFinished || (!/^'''|^\"\"\"/.test(input) && /\\n|\\r/.test(input)))\n return reportSyntaxError(this);\n else\n return this._input = input;\n }\n\n // Emit the parsed token\n const token = { line: line, type: type, value: value, prefix: prefix };\n callback(null, token);\n this.previousToken = token;\n this._previousMarker = type;\n // Advance to next part to tokenize\n input = input.substr(matchLength || match[0].length, input.length);\n }\n\n // Signals the syntax error through the callback\n function reportSyntaxError(self) { callback(self._syntaxError(/^\\S*/.exec(input)[0])); }\n }\n\n // ### `_unescape` replaces N3 escape codes by their corresponding characters\n _unescape(item) {\n let invalid = false;\n const replaced = item.replace(escapeSequence, (sequence, unicode4, unicode8, escapedChar) => {\n // 4-digit unicode character\n if (typeof unicode4 === 'string')\n return String.fromCharCode(Number.parseInt(unicode4, 16));\n // 8-digit unicode character\n if (typeof unicode8 === 'string') {\n let charCode = Number.parseInt(unicode8, 16);\n return charCode <= 0xFFFF ? String.fromCharCode(Number.parseInt(unicode8, 16)) :\n String.fromCharCode(0xD800 + ((charCode -= 0x10000) >> 10), 0xDC00 + (charCode & 0x3FF));\n }\n // fixed escape sequence\n if (escapedChar in escapeReplacements)\n return escapeReplacements[escapedChar];\n // invalid escape sequence\n invalid = true;\n return '';\n });\n return invalid ? null : replaced;\n }\n\n // ### `_parseLiteral` parses a literal into an unescaped value\n _parseLiteral(input) {\n // Ensure we have enough lookahead to identify triple-quoted strings\n if (input.length >= 3) {\n // Identify the opening quote(s)\n const opening = input.match(/^(?:\"\"\"|\"|'''|'|)/)[0];\n const openingLength = opening.length;\n\n // Find the next candidate closing quotes\n let closingPos = Math.max(this._literalClosingPos, openingLength);\n while ((closingPos = input.indexOf(opening, closingPos)) > 0) {\n // Count backslashes right before the closing quotes\n let backslashCount = 0;\n while (input[closingPos - backslashCount - 1] === '\\\\')\n backslashCount++;\n\n // An even number of backslashes (in particular 0)\n // means these are actual, non-escaped closing quotes\n if (backslashCount % 2 === 0) {\n // Extract and unescape the value\n const raw = input.substring(openingLength, closingPos);\n const lines = raw.split(/\\r\\n|\\r|\\n/).length - 1;\n const matchLength = closingPos + openingLength;\n // Only triple-quoted strings can be multi-line\n if (openingLength === 1 && lines !== 0 ||\n openingLength === 3 && this._lineMode)\n break;\n this._line += lines;\n return { value: this._unescape(raw), matchLength };\n }\n closingPos++;\n }\n this._literalClosingPos = input.length - openingLength + 1;\n }\n return { value: '', matchLength: 0 };\n }\n\n // ### `_syntaxError` creates a syntax error for the given issue\n _syntaxError(issue) {\n this._input = null;\n const err = new Error(`Unexpected \"${issue}\" on line ${this._line}.`);\n err.context = {\n token: undefined,\n line: this._line,\n previousToken: this.previousToken,\n };\n return err;\n }\n\n // ### Strips off any starting UTF BOM mark.\n _readStartingBom(input) {\n return input.startsWith('\\ufeff') ? input.substr(1) : input;\n }\n\n // ## Public methods\n\n // ### `tokenize` starts the transformation of an N3 document into an array of tokens.\n // The input can be a string or a stream.\n tokenize(input, callback) {\n this._line = 1;\n\n // If the input is a string, continuously emit tokens through the callback until the end\n if (typeof input === 'string') {\n this._input = this._readStartingBom(input);\n // If a callback was passed, asynchronously call it\n if (typeof callback === 'function')\n queueMicrotask(() => this._tokenizeToEnd(callback, true));\n // If no callback was passed, tokenize synchronously and return\n else {\n const tokens = [];\n let error;\n this._tokenizeToEnd((e, t) => e ? (error = e) : tokens.push(t), true);\n if (error) throw error;\n return tokens;\n }\n }\n // Otherwise, the input must be a stream\n else {\n this._pendingBuffer = null;\n if (typeof input.setEncoding === 'function')\n input.setEncoding('utf8');\n // Adds the data chunk to the buffer and parses as far as possible\n input.on('data', data => {\n if (this._input !== null && data.length !== 0) {\n // Prepend any previous pending writes\n if (this._pendingBuffer) {\n data = Buffer.concat([this._pendingBuffer, data]);\n this._pendingBuffer = null;\n }\n // Hold if the buffer ends in an incomplete unicode sequence\n if (data[data.length - 1] & 0x80) {\n this._pendingBuffer = data;\n }\n // Otherwise, tokenize as far as possible\n else {\n // Only read a BOM at the start\n if (typeof this._input === 'undefined')\n this._input = this._readStartingBom(typeof data === 'string' ? data : data.toString());\n else\n this._input += data;\n this._tokenizeToEnd(callback, false);\n }\n }\n });\n // Parses until the end\n input.on('end', () => {\n if (typeof this._input === 'string')\n this._tokenizeToEnd(callback, true);\n });\n input.on('error', callback);\n }\n }\n}\n","/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\nlet promise\n\nmodule.exports = typeof queueMicrotask === 'function'\n ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)\n // reuse resolved promise, and allocate it lazily\n : cb => (promise || (promise = Promise.resolve()))\n .then(cb)\n .catch(err => setTimeout(() => { throw err }, 0))\n","function _setPrototypeOf(o, p) {\n module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n module.exports[\"default\"] = module.exports, module.exports.__esModule = true;\n return _setPrototypeOf(o, p);\n}\n\nmodule.exports = _setPrototypeOf;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = GeneratorFunctionPrototype;\n define(Gp, \"constructor\", GeneratorFunctionPrototype);\n define(GeneratorFunctionPrototype, \"constructor\", GeneratorFunction);\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n });\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n define(Gp, iteratorSymbol, function() {\n return this;\n });\n\n define(Gp, \"toString\", function() {\n return \"[object Generator]\";\n });\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, in modern engines\n // we can explicitly access globalThis. In older engines we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","module.exports = function(originalModule) {\n\tif (!originalModule.webpackPolyfill) {\n\t\tvar module = Object.create(originalModule);\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"exports\", {\n\t\t\tenumerable: true\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","/**\n * An implementation of the RDF Dataset Normalization specification.\n * This library works in the browser and node.js.\n *\n * BSD 3-Clause License\n * Copyright (c) 2016-2021 Digital Bazaar, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * Neither the name of the Digital Bazaar, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n'use strict';\n\nconst URDNA2015 = require('./URDNA2015');\nconst URGNA2012 = require('./URGNA2012');\nconst URDNA2015Sync = require('./URDNA2015Sync');\nconst URGNA2012Sync = require('./URGNA2012Sync');\n\n// optional native support\nlet rdfCanonizeNative;\ntry {\n rdfCanonizeNative = require('rdf-canonize-native');\n} catch(e) {}\n\nconst api = {};\nmodule.exports = api;\n\n// expose helpers\napi.NQuads = require('./NQuads');\napi.IdentifierIssuer = require('./IdentifierIssuer');\n\n/**\n * Get or set native API.\n *\n * @param api the native API.\n *\n * @return the currently set native API.\n */\napi._rdfCanonizeNative = function(api) {\n if(api) {\n rdfCanonizeNative = api;\n }\n return rdfCanonizeNative;\n};\n\n/**\n * Asynchronously canonizes an RDF dataset.\n *\n * @param dataset the dataset to canonize.\n * @param options the options to use:\n * algorithm the canonicalization algorithm to use, `URDNA2015` or\n * `URGNA2012`.\n * [useNative] use native implementation (default: false).\n *\n * @return a Promise that resolves to the canonicalized RDF Dataset.\n */\napi.canonize = async function(dataset, options) {\n // back-compat with legacy dataset\n if(!Array.isArray(dataset)) {\n dataset = api.NQuads.legacyDatasetToQuads(dataset);\n }\n\n if(options.useNative) {\n if(!rdfCanonizeNative) {\n throw new Error('rdf-canonize-native not available');\n }\n // TODO: convert native algorithm to Promise-based async\n return new Promise((resolve, reject) =>\n rdfCanonizeNative.canonize(dataset, options, (err, canonical) =>\n err ? reject(err) : resolve(canonical)));\n }\n\n if(options.algorithm === 'URDNA2015') {\n return new URDNA2015(options).main(dataset);\n }\n if(options.algorithm === 'URGNA2012') {\n return new URGNA2012(options).main(dataset);\n }\n if(!('algorithm' in options)) {\n throw new Error('No RDF Dataset Canonicalization algorithm specified.');\n }\n throw new Error(\n 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm);\n};\n\n/**\n * This method is no longer available in the public API, it is for testing\n * only. It synchronously canonizes an RDF dataset and does not work in the\n * browser.\n *\n * @param dataset the dataset to canonize.\n * @param options the options to use:\n * algorithm the canonicalization algorithm to use, `URDNA2015` or\n * `URGNA2012`.\n * [useNative] use native implementation (default: false).\n *\n * @return the RDF dataset in canonical form.\n */\napi._canonizeSync = function(dataset, options) {\n // back-compat with legacy dataset\n if(!Array.isArray(dataset)) {\n dataset = api.NQuads.legacyDatasetToQuads(dataset);\n }\n\n if(options.useNative) {\n if(rdfCanonizeNative) {\n return rdfCanonizeNative.canonizeSync(dataset, options);\n }\n throw new Error('rdf-canonize-native not available');\n }\n if(options.algorithm === 'URDNA2015') {\n return new URDNA2015Sync(options).main(dataset);\n }\n if(options.algorithm === 'URGNA2012') {\n return new URGNA2012Sync(options).main(dataset);\n }\n if(!('algorithm' in options)) {\n throw new Error('No RDF Dataset Canonicalization algorithm specified.');\n }\n throw new Error(\n 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm);\n};\n","var scope = (typeof global !== \"undefined\" && global) ||\n (typeof self !== \"undefined\" && self) ||\n window;\nvar apply = Function.prototype.apply;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) {\n if (timeout) {\n timeout.close();\n }\n};\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(scope, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// setimmediate attaches itself to the global object\nrequire(\"setimmediate\");\n// On some exotic environments, it's not clear which object `setimmediate` was\n// able to install onto. Search each possibility in the same order as the\n// `setimmediate` library.\nexports.setImmediate = (typeof self !== \"undefined\" && self.setImmediate) ||\n (typeof global !== \"undefined\" && global.setImmediate) ||\n (this && this.setImmediate);\nexports.clearImmediate = (typeof self !== \"undefined\" && self.clearImmediate) ||\n (typeof global !== \"undefined\" && global.clearImmediate) ||\n (this && this.clearImmediate);\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","/*\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst URDNA2015 = require('./URDNA2015');\n\nmodule.exports = class URDNA2012 extends URDNA2015 {\n constructor() {\n super();\n this.name = 'URGNA2012';\n this.hashAlgorithm = 'sha1';\n }\n\n // helper for modifying component during Hash First Degree Quads\n modifyFirstDegreeComponent(id, component, key) {\n if(component.termType !== 'BlankNode') {\n return component;\n }\n if(key === 'graph') {\n return {\n termType: 'BlankNode',\n value: '_:g'\n };\n }\n return {\n termType: 'BlankNode',\n value: (component.value === id ? '_:a' : '_:z')\n };\n }\n\n // helper for getting a related predicate\n getRelatedPredicate(quad) {\n return quad.predicate.value;\n }\n\n // helper for creating hash to related blank nodes map\n async createHashToRelated(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n const hashToRelated = new Map();\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n const quads = this.blankNodeInfo.get(id).quads;\n\n // 3) For each quad in quads:\n let i = 0;\n for(const quad of quads) {\n // 3.1) If the quad's subject is a blank node that does not match\n // identifier, set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for subject as related,\n // quad, path identifier issuer as issuer, and p as position.\n let position;\n let related;\n if(quad.subject.termType === 'BlankNode' && quad.subject.value !== id) {\n related = quad.subject.value;\n position = 'p';\n } else if(\n quad.object.termType === 'BlankNode' && quad.object.value !== id) {\n // 3.2) Otherwise, if quad's object is a blank node that does not match\n // identifier, to the result of the Hash Related Blank Node algorithm,\n // passing the blank node identifier for object as related, quad, path\n // identifier issuer as issuer, and r as position.\n related = quad.object.value;\n position = 'r';\n } else {\n // 3.3) Otherwise, continue to the next quad.\n continue;\n }\n // Note: batch hashing related blank nodes 100 at a time\n if(++i % 100 === 0) {\n await this._yield();\n }\n // 3.4) Add a mapping of hash to the blank node identifier for the\n // component that matched (subject or object) to hash to related blank\n // nodes map, adding an entry as necessary.\n const hash = await this.hashRelatedBlankNode(\n related, quad, issuer, position);\n const entries = hashToRelated.get(hash);\n if(entries) {\n entries.push(related);\n } else {\n hashToRelated.set(hash, [related]);\n }\n }\n\n return hashToRelated;\n }\n};\n","/*\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst URDNA2015Sync = require('./URDNA2015Sync');\n\nmodule.exports = class URDNA2012Sync extends URDNA2015Sync {\n constructor() {\n super();\n this.name = 'URGNA2012';\n this.hashAlgorithm = 'sha1';\n }\n\n // helper for modifying component during Hash First Degree Quads\n modifyFirstDegreeComponent(id, component, key) {\n if(component.termType !== 'BlankNode') {\n return component;\n }\n if(key === 'graph') {\n return {\n termType: 'BlankNode',\n value: '_:g'\n };\n }\n return {\n termType: 'BlankNode',\n value: (component.value === id ? '_:a' : '_:z')\n };\n }\n\n // helper for getting a related predicate\n getRelatedPredicate(quad) {\n return quad.predicate.value;\n }\n\n // helper for creating hash to related blank nodes map\n createHashToRelated(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n const hashToRelated = new Map();\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n const quads = this.blankNodeInfo.get(id).quads;\n\n // 3) For each quad in quads:\n for(const quad of quads) {\n // 3.1) If the quad's subject is a blank node that does not match\n // identifier, set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for subject as related,\n // quad, path identifier issuer as issuer, and p as position.\n let position;\n let related;\n if(quad.subject.termType === 'BlankNode' && quad.subject.value !== id) {\n related = quad.subject.value;\n position = 'p';\n } else if(\n quad.object.termType === 'BlankNode' && quad.object.value !== id) {\n // 3.2) Otherwise, if quad's object is a blank node that does not match\n // identifier, to the result of the Hash Related Blank Node algorithm,\n // passing the blank node identifier for object as related, quad, path\n // identifier issuer as issuer, and r as position.\n related = quad.object.value;\n position = 'r';\n } else {\n // 3.3) Otherwise, continue to the next quad.\n continue;\n }\n // 3.4) Add a mapping of hash to the blank node identifier for the\n // component that matched (subject or object) to hash to related blank\n // nodes map, adding an entry as necessary.\n const hash = this.hashRelatedBlankNode(related, quad, issuer, position);\n const entries = hashToRelated.get(hash);\n if(entries) {\n entries.push(related);\n } else {\n hashToRelated.set(hash, [related]);\n }\n }\n\n return hashToRelated;\n }\n};\n","/*\n * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst xhrLoader = require('./documentLoaders/xhr');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Setup browser document loaders.\n *\n * @param jsonld the jsonld api.\n */\napi.setupDocumentLoaders = function(jsonld) {\n if(typeof XMLHttpRequest !== 'undefined') {\n jsonld.documentLoaders.xhr = xhrLoader;\n // use xhr document loader by default\n jsonld.useDocumentLoader('xhr');\n }\n};\n\n/**\n * Setup browser globals.\n *\n * @param jsonld the jsonld api.\n */\napi.setupGlobals = function(jsonld) {\n // setup browser global JsonLdProcessor\n if(typeof globalThis.JsonLdProcessor === 'undefined') {\n Object.defineProperty(globalThis, 'JsonLdProcessor', {\n writable: true,\n enumerable: false,\n configurable: true,\n value: jsonld.JsonLdProcessor\n });\n }\n};\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {parseLinkHeader, buildHeaders} = require('../util');\nconst {LINK_HEADER_CONTEXT} = require('../constants');\nconst JsonLdError = require('../JsonLdError');\nconst RequestQueue = require('../RequestQueue');\nconst {prependBase} = require('../url');\n\nconst REGEX_LINK_HEADER = /(^|(\\r\\n))link:/i;\n\n/**\n * Creates a built-in XMLHttpRequest document loader.\n *\n * @param options the options to use:\n * secure: require all URLs to use HTTPS.\n * headers: an object (map) of headers which will be passed as request\n * headers for the requested document. Accept is not allowed.\n * [xhr]: the XMLHttpRequest API to use.\n *\n * @return the XMLHttpRequest document loader.\n */\nmodule.exports = ({\n secure,\n headers = {},\n xhr\n} = {headers: {}}) => {\n headers = buildHeaders(headers);\n const queue = new RequestQueue();\n return queue.wrapLoader(loader);\n\n async function loader(url) {\n if(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0) {\n throw new JsonLdError(\n 'URL could not be dereferenced; only \"http\" and \"https\" URLs are ' +\n 'supported.',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url});\n }\n if(secure && url.indexOf('https') !== 0) {\n throw new JsonLdError(\n 'URL could not be dereferenced; secure mode is enabled and ' +\n 'the URL\\'s scheme is not \"https\".',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url});\n }\n\n let req;\n try {\n req = await _get(xhr, url, headers);\n } catch(e) {\n throw new JsonLdError(\n 'URL could not be dereferenced, an error occurred.',\n 'jsonld.LoadDocumentError',\n {code: 'loading document failed', url, cause: e});\n }\n\n if(req.status >= 400) {\n throw new JsonLdError(\n 'URL could not be dereferenced: ' + req.statusText,\n 'jsonld.LoadDocumentError', {\n code: 'loading document failed',\n url,\n httpStatusCode: req.status\n });\n }\n\n let doc = {contextUrl: null, documentUrl: url, document: req.response};\n let alternate = null;\n\n // handle Link Header (avoid unsafe header warning by existence testing)\n const contentType = req.getResponseHeader('Content-Type');\n let linkHeader;\n if(REGEX_LINK_HEADER.test(req.getAllResponseHeaders())) {\n linkHeader = req.getResponseHeader('Link');\n }\n if(linkHeader && contentType !== 'application/ld+json') {\n // only 1 related link header permitted\n const linkHeaders = parseLinkHeader(linkHeader);\n const linkedContext = linkHeaders[LINK_HEADER_CONTEXT];\n if(Array.isArray(linkedContext)) {\n throw new JsonLdError(\n 'URL could not be dereferenced, it has more than one ' +\n 'associated HTTP Link Header.',\n 'jsonld.InvalidUrl',\n {code: 'multiple context link headers', url});\n }\n if(linkedContext) {\n doc.contextUrl = linkedContext.target;\n }\n\n // \"alternate\" link header is a redirect\n alternate = linkHeaders['alternate'];\n if(alternate &&\n alternate.type == 'application/ld+json' &&\n !(contentType || '').match(/^application\\/(\\w*\\+)?json$/)) {\n doc = await loader(prependBase(url, alternate.target));\n }\n }\n\n return doc;\n }\n};\n\nfunction _get(xhr, url, headers) {\n xhr = xhr || XMLHttpRequest;\n const req = new xhr();\n return new Promise((resolve, reject) => {\n req.onload = () => resolve(req);\n req.onerror = err => reject(err);\n req.open('GET', url, true);\n for(const k in headers) {\n req.setRequestHeader(k, headers[k]);\n }\n req.send();\n });\n}\n","/*\n * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isString: _isString,\n} = require('./types');\nconst {\n asArray: _asArray\n} = require('./util');\nconst {prependBase} = require('./url');\nconst JsonLdError = require('./JsonLdError');\nconst ResolvedContext = require('./ResolvedContext');\n\nconst MAX_CONTEXT_URLS = 10;\n\nmodule.exports = class ContextResolver {\n /**\n * Creates a ContextResolver.\n *\n * @param sharedCache a shared LRU cache with `get` and `set` APIs.\n */\n constructor({sharedCache}) {\n this.perOpCache = new Map();\n this.sharedCache = sharedCache;\n }\n\n async resolve({\n activeCtx, context, documentLoader, base, cycles = new Set()\n }) {\n // process `@context`\n if(context && _isObject(context) && context['@context']) {\n context = context['@context'];\n }\n\n // context is one or more contexts\n context = _asArray(context);\n\n // resolve each context in the array\n const allResolved = [];\n for(const ctx of context) {\n if(_isString(ctx)) {\n // see if `ctx` has been resolved before...\n let resolved = this._get(ctx);\n if(!resolved) {\n // not resolved yet, resolve\n resolved = await this._resolveRemoteContext(\n {activeCtx, url: ctx, documentLoader, base, cycles});\n }\n\n // add to output and continue\n if(_isArray(resolved)) {\n allResolved.push(...resolved);\n } else {\n allResolved.push(resolved);\n }\n continue;\n }\n if(ctx === null) {\n // handle `null` context, nothing to cache\n allResolved.push(new ResolvedContext({document: null}));\n continue;\n }\n if(!_isObject(ctx)) {\n _throwInvalidLocalContext(context);\n }\n // context is an object, get/create `ResolvedContext` for it\n const key = JSON.stringify(ctx);\n let resolved = this._get(key);\n if(!resolved) {\n // create a new static `ResolvedContext` and cache it\n resolved = new ResolvedContext({document: ctx});\n this._cacheResolvedContext({key, resolved, tag: 'static'});\n }\n allResolved.push(resolved);\n }\n\n return allResolved;\n }\n\n _get(key) {\n // get key from per operation cache; no `tag` is used with this cache so\n // any retrieved context will always be the same during a single operation\n let resolved = this.perOpCache.get(key);\n if(!resolved) {\n // see if the shared cache has a `static` entry for this URL\n const tagMap = this.sharedCache.get(key);\n if(tagMap) {\n resolved = tagMap.get('static');\n if(resolved) {\n this.perOpCache.set(key, resolved);\n }\n }\n }\n return resolved;\n }\n\n _cacheResolvedContext({key, resolved, tag}) {\n this.perOpCache.set(key, resolved);\n if(tag !== undefined) {\n let tagMap = this.sharedCache.get(key);\n if(!tagMap) {\n tagMap = new Map();\n this.sharedCache.set(key, tagMap);\n }\n tagMap.set(tag, resolved);\n }\n return resolved;\n }\n\n async _resolveRemoteContext({activeCtx, url, documentLoader, base, cycles}) {\n // resolve relative URL and fetch context\n url = prependBase(base, url);\n const {context, remoteDoc} = await this._fetchContext(\n {activeCtx, url, documentLoader, cycles});\n\n // update base according to remote document and resolve any relative URLs\n base = remoteDoc.documentUrl || url;\n _resolveContextUrls({context, base});\n\n // resolve, cache, and return context\n const resolved = await this.resolve(\n {activeCtx, context, documentLoader, base, cycles});\n this._cacheResolvedContext({key: url, resolved, tag: remoteDoc.tag});\n return resolved;\n }\n\n async _fetchContext({activeCtx, url, documentLoader, cycles}) {\n // check for max context URLs fetched during a resolve operation\n if(cycles.size > MAX_CONTEXT_URLS) {\n throw new JsonLdError(\n 'Maximum number of @context URLs exceeded.',\n 'jsonld.ContextUrlError',\n {\n code: activeCtx.processingMode === 'json-ld-1.0' ?\n 'loading remote context failed' :\n 'context overflow',\n max: MAX_CONTEXT_URLS\n });\n }\n\n // check for context URL cycle\n // shortcut to avoid extra work that would eventually hit the max above\n if(cycles.has(url)) {\n throw new JsonLdError(\n 'Cyclical @context URLs detected.',\n 'jsonld.ContextUrlError',\n {\n code: activeCtx.processingMode === 'json-ld-1.0' ?\n 'recursive context inclusion' :\n 'context overflow',\n url\n });\n }\n\n // track cycles\n cycles.add(url);\n\n let context;\n let remoteDoc;\n\n try {\n remoteDoc = await documentLoader(url);\n context = remoteDoc.document || null;\n // parse string context as JSON\n if(_isString(context)) {\n context = JSON.parse(context);\n }\n } catch(e) {\n throw new JsonLdError(\n 'Dereferencing a URL did not result in a valid JSON-LD object. ' +\n 'Possible causes are an inaccessible URL perhaps due to ' +\n 'a same-origin policy (ensure the server uses CORS if you are ' +\n 'using client-side JavaScript), too many redirects, a ' +\n 'non-JSON response, or more than one HTTP Link Header was ' +\n 'provided for a remote context.',\n 'jsonld.InvalidUrl',\n {code: 'loading remote context failed', url, cause: e});\n }\n\n // ensure ctx is an object\n if(!_isObject(context)) {\n throw new JsonLdError(\n 'Dereferencing a URL did not result in a JSON object. The ' +\n 'response was valid JSON, but it was not a JSON object.',\n 'jsonld.InvalidUrl', {code: 'invalid remote context', url});\n }\n\n // use empty context if no @context key is present\n if(!('@context' in context)) {\n context = {'@context': {}};\n } else {\n context = {'@context': context['@context']};\n }\n\n // append @context URL to context if given\n if(remoteDoc.contextUrl) {\n if(!_isArray(context['@context'])) {\n context['@context'] = [context['@context']];\n }\n context['@context'].push(remoteDoc.contextUrl);\n }\n\n return {context, remoteDoc};\n }\n};\n\nfunction _throwInvalidLocalContext(ctx) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context must be an object.',\n 'jsonld.SyntaxError', {\n code: 'invalid local context', context: ctx\n });\n}\n\n/**\n * Resolve all relative `@context` URLs in the given context by inline\n * replacing them with absolute URLs.\n *\n * @param context the context.\n * @param base the base IRI to use to resolve relative IRIs.\n */\nfunction _resolveContextUrls({context, base}) {\n if(!context) {\n return;\n }\n\n const ctx = context['@context'];\n\n if(_isString(ctx)) {\n context['@context'] = prependBase(base, ctx);\n return;\n }\n\n if(_isArray(ctx)) {\n for(let i = 0; i < ctx.length; ++i) {\n const element = ctx[i];\n if(_isString(element)) {\n ctx[i] = prependBase(base, element);\n continue;\n }\n if(_isObject(element)) {\n _resolveContextUrls({context: {'@context': element}, base});\n }\n }\n return;\n }\n\n if(!_isObject(ctx)) {\n // no @context URLs can be found in non-object\n return;\n }\n\n // ctx is an object, resolve any context URLs in terms\n for(const term in ctx) {\n _resolveContextUrls({context: ctx[term], base});\n }\n}\n","/*\n * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst LRU = require('lru-cache');\n\nconst MAX_ACTIVE_CONTEXTS = 10;\n\nmodule.exports = class ResolvedContext {\n /**\n * Creates a ResolvedContext.\n *\n * @param document the context document.\n */\n constructor({document}) {\n this.document = document;\n // TODO: enable customization of processed context cache\n // TODO: limit based on size of processed contexts vs. number of them\n this.cache = new LRU({max: MAX_ACTIVE_CONTEXTS});\n }\n\n getProcessed(activeCtx) {\n return this.cache.get(activeCtx);\n }\n\n setProcessed(activeCtx, processedCtx) {\n this.cache.set(activeCtx, processedCtx);\n }\n};\n","'use strict'\nmodule.exports = Yallist\n\nYallist.Node = Node\nYallist.create = Yallist\n\nfunction Yallist (list) {\n var self = this\n if (!(self instanceof Yallist)) {\n self = new Yallist()\n }\n\n self.tail = null\n self.head = null\n self.length = 0\n\n if (list && typeof list.forEach === 'function') {\n list.forEach(function (item) {\n self.push(item)\n })\n } else if (arguments.length > 0) {\n for (var i = 0, l = arguments.length; i < l; i++) {\n self.push(arguments[i])\n }\n }\n\n return self\n}\n\nYallist.prototype.removeNode = function (node) {\n if (node.list !== this) {\n throw new Error('removing node which does not belong to this list')\n }\n\n var next = node.next\n var prev = node.prev\n\n if (next) {\n next.prev = prev\n }\n\n if (prev) {\n prev.next = next\n }\n\n if (node === this.head) {\n this.head = next\n }\n if (node === this.tail) {\n this.tail = prev\n }\n\n node.list.length--\n node.next = null\n node.prev = null\n node.list = null\n\n return next\n}\n\nYallist.prototype.unshiftNode = function (node) {\n if (node === this.head) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var head = this.head\n node.list = this\n node.next = head\n if (head) {\n head.prev = node\n }\n\n this.head = node\n if (!this.tail) {\n this.tail = node\n }\n this.length++\n}\n\nYallist.prototype.pushNode = function (node) {\n if (node === this.tail) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var tail = this.tail\n node.list = this\n node.prev = tail\n if (tail) {\n tail.next = node\n }\n\n this.tail = node\n if (!this.head) {\n this.head = node\n }\n this.length++\n}\n\nYallist.prototype.push = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n push(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.unshift = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n unshift(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.pop = function () {\n if (!this.tail) {\n return undefined\n }\n\n var res = this.tail.value\n this.tail = this.tail.prev\n if (this.tail) {\n this.tail.next = null\n } else {\n this.head = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.shift = function () {\n if (!this.head) {\n return undefined\n }\n\n var res = this.head.value\n this.head = this.head.next\n if (this.head) {\n this.head.prev = null\n } else {\n this.tail = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.forEach = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.head, i = 0; walker !== null; i++) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.next\n }\n}\n\nYallist.prototype.forEachReverse = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.prev\n }\n}\n\nYallist.prototype.get = function (n) {\n for (var i = 0, walker = this.head; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.next\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.getReverse = function (n) {\n for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.prev\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.map = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.head; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.next\n }\n return res\n}\n\nYallist.prototype.mapReverse = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.tail; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.prev\n }\n return res\n}\n\nYallist.prototype.reduce = function (fn, initial) {\n var acc\n var walker = this.head\n if (arguments.length > 1) {\n acc = initial\n } else if (this.head) {\n walker = this.head.next\n acc = this.head.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = 0; walker !== null; i++) {\n acc = fn(acc, walker.value, i)\n walker = walker.next\n }\n\n return acc\n}\n\nYallist.prototype.reduceReverse = function (fn, initial) {\n var acc\n var walker = this.tail\n if (arguments.length > 1) {\n acc = initial\n } else if (this.tail) {\n walker = this.tail.prev\n acc = this.tail.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = this.length - 1; walker !== null; i--) {\n acc = fn(acc, walker.value, i)\n walker = walker.prev\n }\n\n return acc\n}\n\nYallist.prototype.toArray = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.head; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.next\n }\n return arr\n}\n\nYallist.prototype.toArrayReverse = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.tail; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.prev\n }\n return arr\n}\n\nYallist.prototype.slice = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = 0, walker = this.head; walker !== null && i < from; i++) {\n walker = walker.next\n }\n for (; walker !== null && i < to; i++, walker = walker.next) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.sliceReverse = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {\n walker = walker.prev\n }\n for (; walker !== null && i > from; i--, walker = walker.prev) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.splice = function (start, deleteCount, ...nodes) {\n if (start > this.length) {\n start = this.length - 1\n }\n if (start < 0) {\n start = this.length + start;\n }\n\n for (var i = 0, walker = this.head; walker !== null && i < start; i++) {\n walker = walker.next\n }\n\n var ret = []\n for (var i = 0; walker && i < deleteCount; i++) {\n ret.push(walker.value)\n walker = this.removeNode(walker)\n }\n if (walker === null) {\n walker = this.tail\n }\n\n if (walker !== this.head && walker !== this.tail) {\n walker = walker.prev\n }\n\n for (var i = 0; i < nodes.length; i++) {\n walker = insert(this, walker, nodes[i])\n }\n return ret;\n}\n\nYallist.prototype.reverse = function () {\n var head = this.head\n var tail = this.tail\n for (var walker = head; walker !== null; walker = walker.prev) {\n var p = walker.prev\n walker.prev = walker.next\n walker.next = p\n }\n this.head = tail\n this.tail = head\n return this\n}\n\nfunction insert (self, node, value) {\n var inserted = node === self.head ?\n new Node(value, null, node, self) :\n new Node(value, node, node.next, self)\n\n if (inserted.next === null) {\n self.tail = inserted\n }\n if (inserted.prev === null) {\n self.head = inserted\n }\n\n self.length++\n\n return inserted\n}\n\nfunction push (self, item) {\n self.tail = new Node(item, self.tail, null, self)\n if (!self.head) {\n self.head = self.tail\n }\n self.length++\n}\n\nfunction unshift (self, item) {\n self.head = new Node(item, null, self.head, self)\n if (!self.tail) {\n self.tail = self.head\n }\n self.length++\n}\n\nfunction Node (value, prev, next, list) {\n if (!(this instanceof Node)) {\n return new Node(value, prev, next, list)\n }\n\n this.list = list\n this.value = value\n\n if (prev) {\n prev.next = this\n this.prev = prev\n } else {\n this.prev = null\n }\n\n if (next) {\n next.prev = this\n this.next = next\n } else {\n this.next = null\n }\n}\n\ntry {\n // add if support for Symbol.iterator is present\n require('./iterator.js')(Yallist)\n} catch (er) {}\n","'use strict'\nmodule.exports = function (Yallist) {\n Yallist.prototype[Symbol.iterator] = function* () {\n for (let walker = this.head; walker; walker = walker.next) {\n yield walker.value\n }\n }\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\n// TODO: move `NQuads` to its own package\nmodule.exports = require('rdf-canonize').NQuads;\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst JsonLdError = require('./JsonLdError');\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isEmptyObject: _isEmptyObject,\n isString: _isString,\n isUndefined: _isUndefined\n} = require('./types');\n\nconst {\n isList: _isList,\n isValue: _isValue,\n isGraph: _isGraph,\n isSubject: _isSubject\n} = require('./graphTypes');\n\nconst {\n expandIri: _expandIri,\n getContextValue: _getContextValue,\n isKeyword: _isKeyword,\n process: _processContext,\n processingMode: _processingMode\n} = require('./context');\n\nconst {\n isAbsolute: _isAbsoluteIri\n} = require('./url');\n\nconst {\n addValue: _addValue,\n asArray: _asArray,\n getValues: _getValues,\n validateTypeValue: _validateTypeValue\n} = require('./util');\n\nconst api = {};\nmodule.exports = api;\nconst REGEX_BCP47 = /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/;\n\n/**\n * Recursively expands an element using the given context. Any context in\n * the element will be removed. All context URLs must have been retrieved\n * before calling this method.\n *\n * @param activeCtx the context to use.\n * @param activeProperty the property for the element, null for none.\n * @param element the element to expand.\n * @param options the expansion options.\n * @param insideList true if the element is a list, false if not.\n * @param insideIndex true if the element is inside an index container,\n * false if not.\n * @param typeScopedContext an optional type-scoped active context for\n * expanding values of nodes that were expressed according to\n * a type-scoped context.\n * @param expansionMap(info) a function that can be used to custom map\n * unmappable values (or to throw an error when they are detected);\n * if this function returns `undefined` then the default behavior\n * will be used.\n *\n * @return a Promise that resolves to the expanded value.\n */\napi.expand = async ({\n activeCtx,\n activeProperty = null,\n element,\n options = {},\n insideList = false,\n insideIndex = false,\n typeScopedContext = null,\n expansionMap = () => undefined\n}) => {\n // nothing to expand\n if(element === null || element === undefined) {\n return null;\n }\n\n // disable framing if activeProperty is @default\n if(activeProperty === '@default') {\n options = Object.assign({}, options, {isFrame: false});\n }\n\n if(!_isArray(element) && !_isObject(element)) {\n // drop free-floating scalars that are not in lists unless custom mapped\n if(!insideList && (activeProperty === null ||\n _expandIri(activeCtx, activeProperty, {vocab: true},\n options) === '@graph')) {\n const mapped = await expansionMap({\n unmappedValue: element,\n activeCtx,\n activeProperty,\n options,\n insideList\n });\n if(mapped === undefined) {\n return null;\n }\n return mapped;\n }\n\n // expand element according to value expansion rules\n return _expandValue({activeCtx, activeProperty, value: element, options});\n }\n\n // recursively expand array\n if(_isArray(element)) {\n let rval = [];\n const container = _getContextValue(\n activeCtx, activeProperty, '@container') || [];\n insideList = insideList || container.includes('@list');\n for(let i = 0; i < element.length; ++i) {\n // expand element\n let e = await api.expand({\n activeCtx,\n activeProperty,\n element: element[i],\n options,\n expansionMap,\n insideIndex,\n typeScopedContext\n });\n if(insideList && _isArray(e)) {\n e = {'@list': e};\n }\n\n if(e === null) {\n e = await expansionMap({\n unmappedValue: element[i],\n activeCtx,\n activeProperty,\n parent: element,\n index: i,\n options,\n expandedParent: rval,\n insideList\n });\n if(e === undefined) {\n continue;\n }\n }\n\n if(_isArray(e)) {\n rval = rval.concat(e);\n } else {\n rval.push(e);\n }\n }\n return rval;\n }\n\n // recursively expand object:\n\n // first, expand the active property\n const expandedActiveProperty = _expandIri(\n activeCtx, activeProperty, {vocab: true}, options);\n\n // Get any property-scoped context for activeProperty\n const propertyScopedCtx =\n _getContextValue(activeCtx, activeProperty, '@context');\n\n // second, determine if any type-scoped context should be reverted; it\n // should only be reverted when the following are all true:\n // 1. `element` is not a value or subject reference\n // 2. `insideIndex` is false\n typeScopedContext = typeScopedContext ||\n (activeCtx.previousContext ? activeCtx : null);\n let keys = Object.keys(element).sort();\n let mustRevert = !insideIndex;\n if(mustRevert && typeScopedContext && keys.length <= 2 &&\n !keys.includes('@context')) {\n for(const key of keys) {\n const expandedProperty = _expandIri(\n typeScopedContext, key, {vocab: true}, options);\n if(expandedProperty === '@value') {\n // value found, ensure type-scoped context is used to expand it\n mustRevert = false;\n activeCtx = typeScopedContext;\n break;\n }\n if(expandedProperty === '@id' && keys.length === 1) {\n // subject reference found, do not revert\n mustRevert = false;\n break;\n }\n }\n }\n\n if(mustRevert) {\n // revert type scoped context\n activeCtx = activeCtx.revertToPreviousContext();\n }\n\n // apply property-scoped context after reverting term-scoped context\n if(!_isUndefined(propertyScopedCtx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: propertyScopedCtx,\n propagate: true,\n overrideProtected: true,\n options\n });\n }\n\n // if element has a context, process it\n if('@context' in element) {\n activeCtx = await _processContext(\n {activeCtx, localCtx: element['@context'], options});\n }\n\n // set the type-scoped context to the context on input, for use later\n typeScopedContext = activeCtx;\n\n // Remember the first key found expanding to @type\n let typeKey = null;\n\n // look for scoped contexts on `@type`\n for(const key of keys) {\n const expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options);\n if(expandedProperty === '@type') {\n // set scoped contexts from @type\n // avoid sorting if possible\n typeKey = typeKey || key;\n const value = element[key];\n const types =\n Array.isArray(value) ?\n (value.length > 1 ? value.slice().sort() : value) : [value];\n for(const type of types) {\n const ctx = _getContextValue(typeScopedContext, type, '@context');\n if(!_isUndefined(ctx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n options,\n propagate: false\n });\n }\n }\n }\n }\n\n // process each key and value in element, ignoring @nest content\n let rval = {};\n await _expandObject({\n activeCtx,\n activeProperty,\n expandedActiveProperty,\n element,\n expandedParent: rval,\n options,\n insideList,\n typeKey,\n typeScopedContext,\n expansionMap});\n\n // get property count on expanded output\n keys = Object.keys(rval);\n let count = keys.length;\n\n if('@value' in rval) {\n // @value must only have @language or @type\n if('@type' in rval && ('@language' in rval || '@direction' in rval)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an element containing \"@value\" may not ' +\n 'contain both \"@type\" and either \"@language\" or \"@direction\".',\n 'jsonld.SyntaxError', {code: 'invalid value object', element: rval});\n }\n let validCount = count - 1;\n if('@type' in rval) {\n validCount -= 1;\n }\n if('@index' in rval) {\n validCount -= 1;\n }\n if('@language' in rval) {\n validCount -= 1;\n }\n if('@direction' in rval) {\n validCount -= 1;\n }\n if(validCount !== 0) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an element containing \"@value\" may only ' +\n 'have an \"@index\" property and either \"@type\" ' +\n 'or either or both \"@language\" or \"@direction\".',\n 'jsonld.SyntaxError', {code: 'invalid value object', element: rval});\n }\n const values = rval['@value'] === null ? [] : _asArray(rval['@value']);\n const types = _getValues(rval, '@type');\n\n // drop null @values unless custom mapped\n if(_processingMode(activeCtx, 1.1) && types.includes('@json') &&\n types.length === 1) {\n // Any value of @value is okay if @type: @json\n } else if(values.length === 0) {\n const mapped = await expansionMap({\n unmappedValue: rval,\n activeCtx,\n activeProperty,\n element,\n options,\n insideList\n });\n if(mapped !== undefined) {\n rval = mapped;\n } else {\n rval = null;\n }\n } else if(!values.every(v => (_isString(v) || _isEmptyObject(v))) &&\n '@language' in rval) {\n // if @language is present, @value must be a string\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; only strings may be language-tagged.',\n 'jsonld.SyntaxError',\n {code: 'invalid language-tagged value', element: rval});\n } else if(!types.every(t =>\n (_isAbsoluteIri(t) && !(_isString(t) && t.indexOf('_:') === 0) ||\n _isEmptyObject(t)))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an element containing \"@value\" and \"@type\" ' +\n 'must have an absolute IRI for the value of \"@type\".',\n 'jsonld.SyntaxError', {code: 'invalid typed value', element: rval});\n }\n } else if('@type' in rval && !_isArray(rval['@type'])) {\n // convert @type to an array\n rval['@type'] = [rval['@type']];\n } else if('@set' in rval || '@list' in rval) {\n // handle @set and @list\n if(count > 1 && !(count === 2 && '@index' in rval)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; if an element has the property \"@set\" ' +\n 'or \"@list\", then it can have at most one other property that is ' +\n '\"@index\".', 'jsonld.SyntaxError',\n {code: 'invalid set or list object', element: rval});\n }\n // optimize away @set\n if('@set' in rval) {\n rval = rval['@set'];\n keys = Object.keys(rval);\n count = keys.length;\n }\n } else if(count === 1 && '@language' in rval) {\n // drop objects with only @language unless custom mapped\n const mapped = await expansionMap(rval, {\n unmappedValue: rval,\n activeCtx,\n activeProperty,\n element,\n options,\n insideList\n });\n if(mapped !== undefined) {\n rval = mapped;\n } else {\n rval = null;\n }\n }\n\n // drop certain top-level objects that do not occur in lists, unless custom\n // mapped\n if(_isObject(rval) &&\n !options.keepFreeFloatingNodes && !insideList &&\n (activeProperty === null || expandedActiveProperty === '@graph')) {\n // drop empty object, top-level @value/@list, or object with only @id\n if(count === 0 || '@value' in rval || '@list' in rval ||\n (count === 1 && '@id' in rval)) {\n const mapped = await expansionMap({\n unmappedValue: rval,\n activeCtx,\n activeProperty,\n element,\n options,\n insideList\n });\n if(mapped !== undefined) {\n rval = mapped;\n } else {\n rval = null;\n }\n }\n }\n\n return rval;\n};\n\n/**\n * Expand each key and value of element adding to result\n *\n * @param activeCtx the context to use.\n * @param activeProperty the property for the element.\n * @param expandedActiveProperty the expansion of activeProperty\n * @param element the element to expand.\n * @param expandedParent the expanded result into which to add values.\n * @param options the expansion options.\n * @param insideList true if the element is a list, false if not.\n * @param typeKey first key found expanding to @type.\n * @param typeScopedContext the context before reverting.\n * @param expansionMap(info) a function that can be used to custom map\n * unmappable values (or to throw an error when they are detected);\n * if this function returns `undefined` then the default behavior\n * will be used.\n */\nasync function _expandObject({\n activeCtx,\n activeProperty,\n expandedActiveProperty,\n element,\n expandedParent,\n options = {},\n insideList,\n typeKey,\n typeScopedContext,\n expansionMap\n}) {\n const keys = Object.keys(element).sort();\n const nests = [];\n let unexpandedValue;\n\n // Figure out if this is the type for a JSON literal\n const isJsonType = element[typeKey] &&\n _expandIri(activeCtx,\n (_isArray(element[typeKey]) ? element[typeKey][0] : element[typeKey]),\n {vocab: true}, options) === '@json';\n\n for(const key of keys) {\n let value = element[key];\n let expandedValue;\n\n // skip @context\n if(key === '@context') {\n continue;\n }\n\n // expand property\n let expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options);\n\n // drop non-absolute IRI keys that aren't keywords unless custom mapped\n if(expandedProperty === null ||\n !(_isAbsoluteIri(expandedProperty) || _isKeyword(expandedProperty))) {\n // TODO: use `await` to support async\n expandedProperty = expansionMap({\n unmappedProperty: key,\n activeCtx,\n activeProperty,\n parent: element,\n options,\n insideList,\n value,\n expandedParent\n });\n if(expandedProperty === undefined) {\n continue;\n }\n }\n\n if(_isKeyword(expandedProperty)) {\n if(expandedActiveProperty === '@reverse') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a keyword cannot be used as a @reverse ' +\n 'property.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property map', value});\n }\n if(expandedProperty in expandedParent &&\n expandedProperty !== '@included' &&\n expandedProperty !== '@type') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; colliding keywords detected.',\n 'jsonld.SyntaxError',\n {code: 'colliding keywords', keyword: expandedProperty});\n }\n }\n\n // syntax error if @id is not a string\n if(expandedProperty === '@id') {\n if(!_isString(value)) {\n if(!options.isFrame) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value must a string.',\n 'jsonld.SyntaxError', {code: 'invalid @id value', value});\n }\n if(_isObject(value)) {\n // empty object is a wildcard\n if(!_isEmptyObject(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value an empty object or array ' +\n 'of strings, if framing',\n 'jsonld.SyntaxError', {code: 'invalid @id value', value});\n }\n } else if(_isArray(value)) {\n if(!value.every(v => _isString(v))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value an empty object or array ' +\n 'of strings, if framing',\n 'jsonld.SyntaxError', {code: 'invalid @id value', value});\n }\n } else {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value an empty object or array ' +\n 'of strings, if framing',\n 'jsonld.SyntaxError', {code: 'invalid @id value', value});\n }\n }\n\n _addValue(\n expandedParent, '@id',\n _asArray(value).map(v =>\n _isString(v) ? _expandIri(activeCtx, v, {base: true}, options) : v),\n {propertyIsArray: options.isFrame});\n continue;\n }\n\n if(expandedProperty === '@type') {\n // if framing, can be a default object, but need to expand\n // key to determine that\n if(_isObject(value)) {\n value = Object.fromEntries(Object.entries(value).map(([k, v]) => [\n _expandIri(typeScopedContext, k, {vocab: true}),\n _asArray(v).map(vv =>\n _expandIri(typeScopedContext, vv, {base: true, vocab: true})\n )\n ]));\n }\n _validateTypeValue(value, options.isFrame);\n _addValue(\n expandedParent, '@type',\n _asArray(value).map(v =>\n _isString(v) ?\n _expandIri(typeScopedContext, v,\n {base: true, vocab: true}, options) : v),\n {propertyIsArray: options.isFrame});\n continue;\n }\n\n // Included blocks are treated as an array of separate object nodes sharing\n // the same referencing active_property.\n // For 1.0, it is skipped as are other unknown keywords\n if(expandedProperty === '@included' && _processingMode(activeCtx, 1.1)) {\n const includedResult = _asArray(await api.expand({\n activeCtx,\n activeProperty,\n element: value,\n options,\n expansionMap\n }));\n\n // Expanded values must be node objects\n if(!includedResult.every(v => _isSubject(v))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; ' +\n 'values of @included must expand to node objects.',\n 'jsonld.SyntaxError', {code: 'invalid @included value', value});\n }\n\n _addValue(\n expandedParent, '@included', includedResult, {propertyIsArray: true});\n continue;\n }\n\n // @graph must be an array or an object\n if(expandedProperty === '@graph' &&\n !(_isObject(value) || _isArray(value))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@graph\" value must not be an ' +\n 'object or an array.',\n 'jsonld.SyntaxError', {code: 'invalid @graph value', value});\n }\n\n if(expandedProperty === '@value') {\n // capture value for later\n // \"colliding keywords\" check prevents this from being set twice\n unexpandedValue = value;\n if(isJsonType && _processingMode(activeCtx, 1.1)) {\n // no coercion to array, and retain all values\n expandedParent['@value'] = value;\n } else {\n _addValue(\n expandedParent, '@value', value, {propertyIsArray: options.isFrame});\n }\n continue;\n }\n\n // @language must be a string\n // it should match BCP47\n if(expandedProperty === '@language') {\n if(value === null) {\n // drop null @language values, they expand as if they didn't exist\n continue;\n }\n if(!_isString(value) && !options.isFrame) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@language\" value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid language-tagged string', value});\n }\n // ensure language value is lowercase\n value = _asArray(value).map(v => _isString(v) ? v.toLowerCase() : v);\n\n // ensure language tag matches BCP47\n for(const lang of value) {\n if(_isString(lang) && !lang.match(REGEX_BCP47)) {\n console.warn(`@language must be valid BCP47: ${lang}`);\n }\n }\n\n _addValue(\n expandedParent, '@language', value, {propertyIsArray: options.isFrame});\n continue;\n }\n\n // @direction must be \"ltr\" or \"rtl\"\n if(expandedProperty === '@direction') {\n if(!_isString(value) && !options.isFrame) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@direction\" value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid base direction', value});\n }\n\n value = _asArray(value);\n\n // ensure direction is \"ltr\" or \"rtl\"\n for(const dir of value) {\n if(_isString(dir) && dir !== 'ltr' && dir !== 'rtl') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@direction\" must be \"ltr\" or \"rtl\".',\n 'jsonld.SyntaxError',\n {code: 'invalid base direction', value});\n }\n }\n\n _addValue(\n expandedParent, '@direction', value,\n {propertyIsArray: options.isFrame});\n continue;\n }\n\n // @index must be a string\n if(expandedProperty === '@index') {\n if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@index\" value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid @index value', value});\n }\n _addValue(expandedParent, '@index', value);\n continue;\n }\n\n // @reverse must be an object\n if(expandedProperty === '@reverse') {\n if(!_isObject(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@reverse\" value must be an object.',\n 'jsonld.SyntaxError', {code: 'invalid @reverse value', value});\n }\n\n expandedValue = await api.expand({\n activeCtx,\n activeProperty:\n '@reverse',\n element: value,\n options,\n expansionMap\n });\n // properties double-reversed\n if('@reverse' in expandedValue) {\n for(const property in expandedValue['@reverse']) {\n _addValue(\n expandedParent, property, expandedValue['@reverse'][property],\n {propertyIsArray: true});\n }\n }\n\n // FIXME: can this be merged with code below to simplify?\n // merge in all reversed properties\n let reverseMap = expandedParent['@reverse'] || null;\n for(const property in expandedValue) {\n if(property === '@reverse') {\n continue;\n }\n if(reverseMap === null) {\n reverseMap = expandedParent['@reverse'] = {};\n }\n _addValue(reverseMap, property, [], {propertyIsArray: true});\n const items = expandedValue[property];\n for(let ii = 0; ii < items.length; ++ii) {\n const item = items[ii];\n if(_isValue(item) || _isList(item)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@reverse\" value must not be a ' +\n '@value or an @list.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property value', value: expandedValue});\n }\n _addValue(reverseMap, property, item, {propertyIsArray: true});\n }\n }\n\n continue;\n }\n\n // nested keys\n if(expandedProperty === '@nest') {\n nests.push(key);\n continue;\n }\n\n // use potential scoped context for key\n let termCtx = activeCtx;\n const ctx = _getContextValue(activeCtx, key, '@context');\n if(!_isUndefined(ctx)) {\n termCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n propagate: true,\n overrideProtected: true,\n options\n });\n }\n\n const container = _getContextValue(termCtx, key, '@container') || [];\n\n if(container.includes('@language') && _isObject(value)) {\n const direction = _getContextValue(termCtx, key, '@direction');\n // handle language map container (skip if value is not an object)\n expandedValue = _expandLanguageMap(termCtx, value, direction, options);\n } else if(container.includes('@index') && _isObject(value)) {\n // handle index container (skip if value is not an object)\n const asGraph = container.includes('@graph');\n const indexKey = _getContextValue(termCtx, key, '@index') || '@index';\n const propertyIndex = indexKey !== '@index' &&\n _expandIri(activeCtx, indexKey, {vocab: true}, options);\n\n expandedValue = await _expandIndexMap({\n activeCtx: termCtx,\n options,\n activeProperty: key,\n value,\n expansionMap,\n asGraph,\n indexKey,\n propertyIndex\n });\n } else if(container.includes('@id') && _isObject(value)) {\n // handle id container (skip if value is not an object)\n const asGraph = container.includes('@graph');\n expandedValue = await _expandIndexMap({\n activeCtx: termCtx,\n options,\n activeProperty: key,\n value,\n expansionMap,\n asGraph,\n indexKey: '@id'\n });\n } else if(container.includes('@type') && _isObject(value)) {\n // handle type container (skip if value is not an object)\n expandedValue = await _expandIndexMap({\n // since container is `@type`, revert type scoped context when expanding\n activeCtx: termCtx.revertToPreviousContext(),\n options,\n activeProperty: key,\n value,\n expansionMap,\n asGraph: false,\n indexKey: '@type'\n });\n } else {\n // recurse into @list or @set\n const isList = (expandedProperty === '@list');\n if(isList || expandedProperty === '@set') {\n let nextActiveProperty = activeProperty;\n if(isList && expandedActiveProperty === '@graph') {\n nextActiveProperty = null;\n }\n expandedValue = await api.expand({\n activeCtx: termCtx,\n activeProperty: nextActiveProperty,\n element: value,\n options,\n insideList: isList,\n expansionMap\n });\n } else if(\n _getContextValue(activeCtx, key, '@type') === '@json') {\n expandedValue = {\n '@type': '@json',\n '@value': value\n };\n } else {\n // recursively expand value with key as new active property\n expandedValue = await api.expand({\n activeCtx: termCtx,\n activeProperty: key,\n element: value,\n options,\n insideList: false,\n expansionMap\n });\n }\n }\n\n // drop null values if property is not @value\n if(expandedValue === null && expandedProperty !== '@value') {\n // TODO: use `await` to support async\n expandedValue = expansionMap({\n unmappedValue: value,\n expandedProperty,\n activeCtx: termCtx,\n activeProperty,\n parent: element,\n options,\n insideList,\n key,\n expandedParent\n });\n if(expandedValue === undefined) {\n continue;\n }\n }\n\n // convert expanded value to @list if container specifies it\n if(expandedProperty !== '@list' && !_isList(expandedValue) &&\n container.includes('@list')) {\n // ensure expanded value in @list is an array\n expandedValue = {'@list': _asArray(expandedValue)};\n }\n\n // convert expanded value to @graph if container specifies it\n // and value is not, itself, a graph\n // index cases handled above\n if(container.includes('@graph') &&\n !container.some(key => key === '@id' || key === '@index')) {\n // ensure expanded values are arrays\n expandedValue = _asArray(expandedValue)\n .map(v => ({'@graph': _asArray(v)}));\n }\n\n // FIXME: can this be merged with code above to simplify?\n // merge in reverse properties\n if(termCtx.mappings.has(key) && termCtx.mappings.get(key).reverse) {\n const reverseMap =\n expandedParent['@reverse'] = expandedParent['@reverse'] || {};\n expandedValue = _asArray(expandedValue);\n for(let ii = 0; ii < expandedValue.length; ++ii) {\n const item = expandedValue[ii];\n if(_isValue(item) || _isList(item)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@reverse\" value must not be a ' +\n '@value or an @list.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property value', value: expandedValue});\n }\n _addValue(reverseMap, expandedProperty, item, {propertyIsArray: true});\n }\n continue;\n }\n\n // add value for property\n // special keywords handled above\n _addValue(expandedParent, expandedProperty, expandedValue, {\n propertyIsArray: true\n });\n }\n\n // @value must not be an object or an array (unless framing) or if @type is\n // @json\n if('@value' in expandedParent) {\n if(expandedParent['@type'] === '@json' && _processingMode(activeCtx, 1.1)) {\n // allow any value, to be verified when the object is fully expanded and\n // the @type is @json.\n } else if((_isObject(unexpandedValue) || _isArray(unexpandedValue)) &&\n !options.isFrame) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@value\" value must not be an ' +\n 'object or an array.',\n 'jsonld.SyntaxError',\n {code: 'invalid value object value', value: unexpandedValue});\n }\n }\n\n // expand each nested key\n for(const key of nests) {\n const nestedValues = _isArray(element[key]) ? element[key] : [element[key]];\n for(const nv of nestedValues) {\n if(!_isObject(nv) || Object.keys(nv).some(k =>\n _expandIri(activeCtx, k, {vocab: true}, options) === '@value')) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; nested value must be a node object.',\n 'jsonld.SyntaxError',\n {code: 'invalid @nest value', value: nv});\n }\n await _expandObject({\n activeCtx,\n activeProperty,\n expandedActiveProperty,\n element: nv,\n expandedParent,\n options,\n insideList,\n typeScopedContext,\n typeKey,\n expansionMap});\n }\n }\n}\n\n/**\n * Expands the given value by using the coercion and keyword rules in the\n * given context.\n *\n * @param activeCtx the active context to use.\n * @param activeProperty the active property the value is associated with.\n * @param value the value to expand.\n * @param {Object} [options] - processing options.\n *\n * @return the expanded value.\n */\nfunction _expandValue({activeCtx, activeProperty, value, options}) {\n // nothing to expand\n if(value === null || value === undefined) {\n return null;\n }\n\n // special-case expand @id and @type (skips '@id' expansion)\n const expandedProperty = _expandIri(\n activeCtx, activeProperty, {vocab: true}, options);\n if(expandedProperty === '@id') {\n return _expandIri(activeCtx, value, {base: true}, options);\n } else if(expandedProperty === '@type') {\n return _expandIri(activeCtx, value, {vocab: true, base: true}, options);\n }\n\n // get type definition from context\n const type = _getContextValue(activeCtx, activeProperty, '@type');\n\n // do @id expansion (automatic for @graph)\n if((type === '@id' || expandedProperty === '@graph') && _isString(value)) {\n return {'@id': _expandIri(activeCtx, value, {base: true}, options)};\n }\n // do @id expansion w/vocab\n if(type === '@vocab' && _isString(value)) {\n return {\n '@id': _expandIri(activeCtx, value, {vocab: true, base: true}, options)\n };\n }\n\n // do not expand keyword values\n if(_isKeyword(expandedProperty)) {\n return value;\n }\n\n const rval = {};\n\n if(type && !['@id', '@vocab', '@none'].includes(type)) {\n // other type\n rval['@type'] = type;\n } else if(_isString(value)) {\n // check for language tagging for strings\n const language = _getContextValue(activeCtx, activeProperty, '@language');\n if(language !== null) {\n rval['@language'] = language;\n }\n const direction = _getContextValue(activeCtx, activeProperty, '@direction');\n if(direction !== null) {\n rval['@direction'] = direction;\n }\n }\n // do conversion of values that aren't basic JSON types to strings\n if(!['boolean', 'number', 'string'].includes(typeof value)) {\n value = value.toString();\n }\n rval['@value'] = value;\n\n return rval;\n}\n\n/**\n * Expands a language map.\n *\n * @param activeCtx the active context to use.\n * @param languageMap the language map to expand.\n * @param direction the direction to apply to values.\n * @param {Object} [options] - processing options.\n *\n * @return the expanded language map.\n */\nfunction _expandLanguageMap(activeCtx, languageMap, direction, options) {\n const rval = [];\n const keys = Object.keys(languageMap).sort();\n for(const key of keys) {\n const expandedKey = _expandIri(activeCtx, key, {vocab: true}, options);\n let val = languageMap[key];\n if(!_isArray(val)) {\n val = [val];\n }\n for(const item of val) {\n if(item === null) {\n // null values are allowed (8.5) but ignored (3.1)\n continue;\n }\n if(!_isString(item)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; language map values must be strings.',\n 'jsonld.SyntaxError',\n {code: 'invalid language map value', languageMap});\n }\n const val = {'@value': item};\n if(expandedKey !== '@none') {\n val['@language'] = key.toLowerCase();\n }\n if(direction) {\n val['@direction'] = direction;\n }\n rval.push(val);\n }\n }\n return rval;\n}\n\nasync function _expandIndexMap(\n {activeCtx, options, activeProperty, value, expansionMap, asGraph,\n indexKey, propertyIndex}) {\n const rval = [];\n const keys = Object.keys(value).sort();\n const isTypeIndex = indexKey === '@type';\n for(let key of keys) {\n // if indexKey is @type, there may be a context defined for it\n if(isTypeIndex) {\n const ctx = _getContextValue(activeCtx, key, '@context');\n if(!_isUndefined(ctx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n propagate: false,\n options\n });\n }\n }\n\n let val = value[key];\n if(!_isArray(val)) {\n val = [val];\n }\n\n val = await api.expand({\n activeCtx,\n activeProperty,\n element: val,\n options,\n insideList: false,\n insideIndex: true,\n expansionMap\n });\n\n // expand for @type, but also for @none\n let expandedKey;\n if(propertyIndex) {\n if(key === '@none') {\n expandedKey = '@none';\n } else {\n expandedKey = _expandValue(\n {activeCtx, activeProperty: indexKey, value: key, options});\n }\n } else {\n expandedKey = _expandIri(activeCtx, key, {vocab: true}, options);\n }\n\n if(indexKey === '@id') {\n // expand document relative\n key = _expandIri(activeCtx, key, {base: true}, options);\n } else if(isTypeIndex) {\n key = expandedKey;\n }\n\n for(let item of val) {\n // If this is also a @graph container, turn items into graphs\n if(asGraph && !_isGraph(item)) {\n item = {'@graph': [item]};\n }\n if(indexKey === '@type') {\n if(expandedKey === '@none') {\n // ignore @none\n } else if(item['@type']) {\n item['@type'] = [key].concat(item['@type']);\n } else {\n item['@type'] = [key];\n }\n } else if(_isValue(item) &&\n !['@language', '@type', '@index'].includes(indexKey)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; Attempt to add illegal key to value ' +\n `object: \"${indexKey}\".`,\n 'jsonld.SyntaxError',\n {code: 'invalid value object', value: item});\n } else if(propertyIndex) {\n // index is a property to be expanded, and values interpreted for that\n // property\n if(expandedKey !== '@none') {\n // expand key as a value\n _addValue(item, propertyIndex, expandedKey, {\n propertyIsArray: true,\n prependValue: true\n });\n }\n } else if(expandedKey !== '@none' && !(indexKey in item)) {\n item[indexKey] = key;\n }\n rval.push(item);\n }\n }\n return rval;\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {\n isSubjectReference: _isSubjectReference\n} = require('./graphTypes');\n\nconst {\n createMergedNodeMap: _createMergedNodeMap\n} = require('./nodeMap');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Performs JSON-LD flattening.\n *\n * @param input the expanded JSON-LD to flatten.\n *\n * @return the flattened output.\n */\napi.flatten = input => {\n const defaultGraph = _createMergedNodeMap(input);\n\n // produce flattened output\n const flattened = [];\n const keys = Object.keys(defaultGraph).sort();\n for(let ki = 0; ki < keys.length; ++ki) {\n const node = defaultGraph[keys[ki]];\n // only add full subjects to top-level\n if(!_isSubjectReference(node)) {\n flattened.push(node);\n }\n }\n return flattened;\n};\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst JsonLdError = require('./JsonLdError');\nconst graphTypes = require('./graphTypes');\nconst types = require('./types');\nconst util = require('./util');\n\n// constants\nconst {\n // RDF,\n RDF_LIST,\n RDF_FIRST,\n RDF_REST,\n RDF_NIL,\n RDF_TYPE,\n // RDF_PLAIN_LITERAL,\n // RDF_XML_LITERAL,\n RDF_JSON_LITERAL,\n // RDF_OBJECT,\n // RDF_LANGSTRING,\n\n // XSD,\n XSD_BOOLEAN,\n XSD_DOUBLE,\n XSD_INTEGER,\n XSD_STRING,\n} = require('./constants');\n\nconst REGEX_BCP47 = /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/;\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Converts an RDF dataset to JSON-LD.\n *\n * @param dataset the RDF dataset.\n * @param options the RDF serialization options.\n *\n * @return a Promise that resolves to the JSON-LD output.\n */\napi.fromRDF = async (\n dataset,\n {\n useRdfType = false,\n useNativeTypes = false,\n rdfDirection = null\n }\n) => {\n const defaultGraph = {};\n const graphMap = {'@default': defaultGraph};\n const referencedOnce = {};\n\n for(const quad of dataset) {\n // TODO: change 'name' to 'graph'\n const name = (quad.graph.termType === 'DefaultGraph') ?\n '@default' : quad.graph.value;\n if(!(name in graphMap)) {\n graphMap[name] = {};\n }\n if(name !== '@default' && !(name in defaultGraph)) {\n defaultGraph[name] = {'@id': name};\n }\n\n const nodeMap = graphMap[name];\n\n // get subject, predicate, object\n const s = quad.subject.value;\n const p = quad.predicate.value;\n const o = quad.object;\n\n if(!(s in nodeMap)) {\n nodeMap[s] = {'@id': s};\n }\n const node = nodeMap[s];\n\n const objectIsNode = o.termType.endsWith('Node');\n if(objectIsNode && !(o.value in nodeMap)) {\n nodeMap[o.value] = {'@id': o.value};\n }\n\n if(p === RDF_TYPE && !useRdfType && objectIsNode) {\n util.addValue(node, '@type', o.value, {propertyIsArray: true});\n continue;\n }\n\n const value = _RDFToObject(o, useNativeTypes, rdfDirection);\n util.addValue(node, p, value, {propertyIsArray: true});\n\n // object may be an RDF list/partial list node but we can't know easily\n // until all triples are read\n if(objectIsNode) {\n if(o.value === RDF_NIL) {\n // track rdf:nil uniquely per graph\n const object = nodeMap[o.value];\n if(!('usages' in object)) {\n object.usages = [];\n }\n object.usages.push({\n node,\n property: p,\n value\n });\n } else if(o.value in referencedOnce) {\n // object referenced more than once\n referencedOnce[o.value] = false;\n } else {\n // keep track of single reference\n referencedOnce[o.value] = {\n node,\n property: p,\n value\n };\n }\n }\n }\n\n /*\n for(let name in dataset) {\n const graph = dataset[name];\n if(!(name in graphMap)) {\n graphMap[name] = {};\n }\n if(name !== '@default' && !(name in defaultGraph)) {\n defaultGraph[name] = {'@id': name};\n }\n const nodeMap = graphMap[name];\n for(let ti = 0; ti < graph.length; ++ti) {\n const triple = graph[ti];\n\n // get subject, predicate, object\n const s = triple.subject.value;\n const p = triple.predicate.value;\n const o = triple.object;\n\n if(!(s in nodeMap)) {\n nodeMap[s] = {'@id': s};\n }\n const node = nodeMap[s];\n\n const objectIsId = (o.type === 'IRI' || o.type === 'blank node');\n if(objectIsId && !(o.value in nodeMap)) {\n nodeMap[o.value] = {'@id': o.value};\n }\n\n if(p === RDF_TYPE && !useRdfType && objectIsId) {\n util.addValue(node, '@type', o.value, {propertyIsArray: true});\n continue;\n }\n\n const value = _RDFToObject(o, useNativeTypes);\n util.addValue(node, p, value, {propertyIsArray: true});\n\n // object may be an RDF list/partial list node but we can't know easily\n // until all triples are read\n if(objectIsId) {\n if(o.value === RDF_NIL) {\n // track rdf:nil uniquely per graph\n const object = nodeMap[o.value];\n if(!('usages' in object)) {\n object.usages = [];\n }\n object.usages.push({\n node: node,\n property: p,\n value: value\n });\n } else if(o.value in referencedOnce) {\n // object referenced more than once\n referencedOnce[o.value] = false;\n } else {\n // keep track of single reference\n referencedOnce[o.value] = {\n node: node,\n property: p,\n value: value\n };\n }\n }\n }\n }*/\n\n // convert linked lists to @list arrays\n for(const name in graphMap) {\n const graphObject = graphMap[name];\n\n // no @lists to be converted, continue\n if(!(RDF_NIL in graphObject)) {\n continue;\n }\n\n // iterate backwards through each RDF list\n const nil = graphObject[RDF_NIL];\n if(!nil.usages) {\n continue;\n }\n for(let usage of nil.usages) {\n let node = usage.node;\n let property = usage.property;\n let head = usage.value;\n const list = [];\n const listNodes = [];\n\n // ensure node is a well-formed list node; it must:\n // 1. Be referenced only once.\n // 2. Have an array for rdf:first that has 1 item.\n // 3. Have an array for rdf:rest that has 1 item.\n // 4. Have no keys other than: @id, rdf:first, rdf:rest, and,\n // optionally, @type where the value is rdf:List.\n let nodeKeyCount = Object.keys(node).length;\n while(property === RDF_REST &&\n types.isObject(referencedOnce[node['@id']]) &&\n types.isArray(node[RDF_FIRST]) && node[RDF_FIRST].length === 1 &&\n types.isArray(node[RDF_REST]) && node[RDF_REST].length === 1 &&\n (nodeKeyCount === 3 ||\n (nodeKeyCount === 4 && types.isArray(node['@type']) &&\n node['@type'].length === 1 && node['@type'][0] === RDF_LIST))) {\n list.push(node[RDF_FIRST][0]);\n listNodes.push(node['@id']);\n\n // get next node, moving backwards through list\n usage = referencedOnce[node['@id']];\n node = usage.node;\n property = usage.property;\n head = usage.value;\n nodeKeyCount = Object.keys(node).length;\n\n // if node is not a blank node, then list head found\n if(!graphTypes.isBlankNode(node)) {\n break;\n }\n }\n\n // transform list into @list object\n delete head['@id'];\n head['@list'] = list.reverse();\n for(const listNode of listNodes) {\n delete graphObject[listNode];\n }\n }\n\n delete nil.usages;\n }\n\n const result = [];\n const subjects = Object.keys(defaultGraph).sort();\n for(const subject of subjects) {\n const node = defaultGraph[subject];\n if(subject in graphMap) {\n const graph = node['@graph'] = [];\n const graphObject = graphMap[subject];\n const graphSubjects = Object.keys(graphObject).sort();\n for(const graphSubject of graphSubjects) {\n const node = graphObject[graphSubject];\n // only add full subjects to top-level\n if(!graphTypes.isSubjectReference(node)) {\n graph.push(node);\n }\n }\n }\n // only add full subjects to top-level\n if(!graphTypes.isSubjectReference(node)) {\n result.push(node);\n }\n }\n\n return result;\n};\n\n/**\n * Converts an RDF triple object to a JSON-LD object.\n *\n * @param o the RDF triple object to convert.\n * @param useNativeTypes true to output native types, false not to.\n *\n * @return the JSON-LD object.\n */\nfunction _RDFToObject(o, useNativeTypes, rdfDirection) {\n // convert NamedNode/BlankNode object to JSON-LD\n if(o.termType.endsWith('Node')) {\n return {'@id': o.value};\n }\n\n // convert literal to JSON-LD\n const rval = {'@value': o.value};\n\n // add language\n if(o.language) {\n rval['@language'] = o.language;\n } else {\n let type = o.datatype.value;\n if(!type) {\n type = XSD_STRING;\n }\n if(type === RDF_JSON_LITERAL) {\n type = '@json';\n try {\n rval['@value'] = JSON.parse(rval['@value']);\n } catch(e) {\n throw new JsonLdError(\n 'JSON literal could not be parsed.',\n 'jsonld.InvalidJsonLiteral',\n {code: 'invalid JSON literal', value: rval['@value'], cause: e});\n }\n }\n // use native types for certain xsd types\n if(useNativeTypes) {\n if(type === XSD_BOOLEAN) {\n if(rval['@value'] === 'true') {\n rval['@value'] = true;\n } else if(rval['@value'] === 'false') {\n rval['@value'] = false;\n }\n } else if(types.isNumeric(rval['@value'])) {\n if(type === XSD_INTEGER) {\n const i = parseInt(rval['@value'], 10);\n if(i.toFixed(0) === rval['@value']) {\n rval['@value'] = i;\n }\n } else if(type === XSD_DOUBLE) {\n rval['@value'] = parseFloat(rval['@value']);\n }\n }\n // do not add native type\n if(![XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING].includes(type)) {\n rval['@type'] = type;\n }\n } else if(rdfDirection === 'i18n-datatype' &&\n type.startsWith('https://www.w3.org/ns/i18n#')) {\n const [, language, direction] = type.split(/[#_]/);\n if(language.length > 0) {\n rval['@language'] = language;\n if(!language.match(REGEX_BCP47)) {\n console.warn(`@language must be valid BCP47: ${language}`);\n }\n }\n rval['@direction'] = direction;\n } else if(type !== XSD_STRING) {\n rval['@type'] = type;\n }\n }\n\n return rval;\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {createNodeMap} = require('./nodeMap');\nconst {isKeyword} = require('./context');\nconst graphTypes = require('./graphTypes');\nconst jsonCanonicalize = require('canonicalize');\nconst types = require('./types');\nconst util = require('./util');\n\nconst {\n // RDF,\n // RDF_LIST,\n RDF_FIRST,\n RDF_REST,\n RDF_NIL,\n RDF_TYPE,\n // RDF_PLAIN_LITERAL,\n // RDF_XML_LITERAL,\n RDF_JSON_LITERAL,\n // RDF_OBJECT,\n RDF_LANGSTRING,\n\n // XSD,\n XSD_BOOLEAN,\n XSD_DOUBLE,\n XSD_INTEGER,\n XSD_STRING,\n} = require('./constants');\n\nconst {\n isAbsolute: _isAbsoluteIri\n} = require('./url');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Outputs an RDF dataset for the expanded JSON-LD input.\n *\n * @param input the expanded JSON-LD input.\n * @param options the RDF serialization options.\n *\n * @return the RDF dataset.\n */\napi.toRDF = (input, options) => {\n // create node map for default graph (and any named graphs)\n const issuer = new util.IdentifierIssuer('_:b');\n const nodeMap = {'@default': {}};\n createNodeMap(input, nodeMap, '@default', issuer);\n\n const dataset = [];\n const graphNames = Object.keys(nodeMap).sort();\n for(const graphName of graphNames) {\n let graphTerm;\n if(graphName === '@default') {\n graphTerm = {termType: 'DefaultGraph', value: ''};\n } else if(_isAbsoluteIri(graphName)) {\n if(graphName.startsWith('_:')) {\n graphTerm = {termType: 'BlankNode'};\n } else {\n graphTerm = {termType: 'NamedNode'};\n }\n graphTerm.value = graphName;\n } else {\n // skip relative IRIs (not valid RDF)\n continue;\n }\n _graphToRDF(dataset, nodeMap[graphName], graphTerm, issuer, options);\n }\n\n return dataset;\n};\n\n/**\n * Adds RDF quads for a particular graph to the given dataset.\n *\n * @param dataset the dataset to append RDF quads to.\n * @param graph the graph to create RDF quads for.\n * @param graphTerm the graph term for each quad.\n * @param issuer a IdentifierIssuer for assigning blank node names.\n * @param options the RDF serialization options.\n *\n * @return the array of RDF triples for the given graph.\n */\nfunction _graphToRDF(dataset, graph, graphTerm, issuer, options) {\n const ids = Object.keys(graph).sort();\n for(const id of ids) {\n const node = graph[id];\n const properties = Object.keys(node).sort();\n for(let property of properties) {\n const items = node[property];\n if(property === '@type') {\n property = RDF_TYPE;\n } else if(isKeyword(property)) {\n continue;\n }\n\n for(const item of items) {\n // RDF subject\n const subject = {\n termType: id.startsWith('_:') ? 'BlankNode' : 'NamedNode',\n value: id\n };\n\n // skip relative IRI subjects (not valid RDF)\n if(!_isAbsoluteIri(id)) {\n continue;\n }\n\n // RDF predicate\n const predicate = {\n termType: property.startsWith('_:') ? 'BlankNode' : 'NamedNode',\n value: property\n };\n\n // skip relative IRI predicates (not valid RDF)\n if(!_isAbsoluteIri(property)) {\n continue;\n }\n\n // skip blank node predicates unless producing generalized RDF\n if(predicate.termType === 'BlankNode' &&\n !options.produceGeneralizedRdf) {\n continue;\n }\n\n // convert list, value or node object to triple\n const object =\n _objectToRDF(item, issuer, dataset, graphTerm, options.rdfDirection);\n // skip null objects (they are relative IRIs)\n if(object) {\n dataset.push({\n subject,\n predicate,\n object,\n graph: graphTerm\n });\n }\n }\n }\n }\n}\n\n/**\n * Converts a @list value into linked list of blank node RDF quads\n * (an RDF collection).\n *\n * @param list the @list value.\n * @param issuer a IdentifierIssuer for assigning blank node names.\n * @param dataset the array of quads to append to.\n * @param graphTerm the graph term for each quad.\n *\n * @return the head of the list.\n */\nfunction _listToRDF(list, issuer, dataset, graphTerm, rdfDirection) {\n const first = {termType: 'NamedNode', value: RDF_FIRST};\n const rest = {termType: 'NamedNode', value: RDF_REST};\n const nil = {termType: 'NamedNode', value: RDF_NIL};\n\n const last = list.pop();\n // Result is the head of the list\n const result = last ? {termType: 'BlankNode', value: issuer.getId()} : nil;\n let subject = result;\n\n for(const item of list) {\n const object = _objectToRDF(item, issuer, dataset, graphTerm, rdfDirection);\n const next = {termType: 'BlankNode', value: issuer.getId()};\n dataset.push({\n subject,\n predicate: first,\n object,\n graph: graphTerm\n });\n dataset.push({\n subject,\n predicate: rest,\n object: next,\n graph: graphTerm\n });\n subject = next;\n }\n\n // Tail of list\n if(last) {\n const object = _objectToRDF(last, issuer, dataset, graphTerm, rdfDirection);\n dataset.push({\n subject,\n predicate: first,\n object,\n graph: graphTerm\n });\n dataset.push({\n subject,\n predicate: rest,\n object: nil,\n graph: graphTerm\n });\n }\n\n return result;\n}\n\n/**\n * Converts a JSON-LD value object to an RDF literal or a JSON-LD string,\n * node object to an RDF resource, or adds a list.\n *\n * @param item the JSON-LD value or node object.\n * @param issuer a IdentifierIssuer for assigning blank node names.\n * @param dataset the dataset to append RDF quads to.\n * @param graphTerm the graph term for each quad.\n *\n * @return the RDF literal or RDF resource.\n */\nfunction _objectToRDF(item, issuer, dataset, graphTerm, rdfDirection) {\n const object = {};\n\n // convert value object to RDF\n if(graphTypes.isValue(item)) {\n object.termType = 'Literal';\n object.value = undefined;\n object.datatype = {\n termType: 'NamedNode'\n };\n let value = item['@value'];\n const datatype = item['@type'] || null;\n\n // convert to XSD/JSON datatypes as appropriate\n if(datatype === '@json') {\n object.value = jsonCanonicalize(value);\n object.datatype.value = RDF_JSON_LITERAL;\n } else if(types.isBoolean(value)) {\n object.value = value.toString();\n object.datatype.value = datatype || XSD_BOOLEAN;\n } else if(types.isDouble(value) || datatype === XSD_DOUBLE) {\n if(!types.isDouble(value)) {\n value = parseFloat(value);\n }\n // canonical double representation\n object.value = value.toExponential(15).replace(/(\\d)0*e\\+?/, '$1E');\n object.datatype.value = datatype || XSD_DOUBLE;\n } else if(types.isNumber(value)) {\n object.value = value.toFixed(0);\n object.datatype.value = datatype || XSD_INTEGER;\n } else if(rdfDirection === 'i18n-datatype' &&\n '@direction' in item) {\n const datatype = 'https://www.w3.org/ns/i18n#' +\n (item['@language'] || '') +\n `_${item['@direction']}`;\n object.datatype.value = datatype;\n object.value = value;\n } else if('@language' in item) {\n object.value = value;\n object.datatype.value = datatype || RDF_LANGSTRING;\n object.language = item['@language'];\n } else {\n object.value = value;\n object.datatype.value = datatype || XSD_STRING;\n }\n } else if(graphTypes.isList(item)) {\n const _list =\n _listToRDF(item['@list'], issuer, dataset, graphTerm, rdfDirection);\n object.termType = _list.termType;\n object.value = _list.value;\n } else {\n // convert string/node object to RDF\n const id = types.isObject(item) ? item['@id'] : item;\n object.termType = id.startsWith('_:') ? 'BlankNode' : 'NamedNode';\n object.value = id;\n }\n\n // skip relative IRIs, not valid RDF\n if(object.termType === 'NamedNode' && !_isAbsoluteIri(object.value)) {\n return null;\n }\n\n return object;\n}\n","/* jshint esversion: 6 */\n/* jslint node: true */\n'use strict';\n\nmodule.exports = function serialize (object) {\n if (object === null || typeof object !== 'object' || object.toJSON != null) {\n return JSON.stringify(object);\n }\n\n if (Array.isArray(object)) {\n return '[' + object.reduce((t, cv, ci) => {\n const comma = ci === 0 ? '' : ',';\n const value = cv === undefined || typeof cv === 'symbol' ? null : cv;\n return t + comma + serialize(value);\n }, '') + ']';\n }\n\n return '{' + Object.keys(object).sort().reduce((t, cv, ci) => {\n if (object[cv] === undefined ||\n typeof object[cv] === 'symbol') {\n return t;\n }\n const comma = t.length === 0 ? '' : ',';\n return t + comma + serialize(cv) + ':' + serialize(object[cv]);\n }, '') + '}';\n};\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {isKeyword} = require('./context');\nconst graphTypes = require('./graphTypes');\nconst types = require('./types');\nconst util = require('./util');\nconst url = require('./url');\nconst JsonLdError = require('./JsonLdError');\nconst {\n createNodeMap: _createNodeMap,\n mergeNodeMapGraphs: _mergeNodeMapGraphs\n} = require('./nodeMap');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Performs JSON-LD `merged` framing.\n *\n * @param input the expanded JSON-LD to frame.\n * @param frame the expanded JSON-LD frame to use.\n * @param options the framing options.\n *\n * @return the framed output.\n */\napi.frameMergedOrDefault = (input, frame, options) => {\n // create framing state\n const state = {\n options,\n embedded: false,\n graph: '@default',\n graphMap: {'@default': {}},\n subjectStack: [],\n link: {},\n bnodeMap: {}\n };\n\n // produce a map of all graphs and name each bnode\n // FIXME: currently uses subjects from @merged graph only\n const issuer = new util.IdentifierIssuer('_:b');\n _createNodeMap(input, state.graphMap, '@default', issuer);\n if(options.merged) {\n state.graphMap['@merged'] = _mergeNodeMapGraphs(state.graphMap);\n state.graph = '@merged';\n }\n state.subjects = state.graphMap[state.graph];\n\n // frame the subjects\n const framed = [];\n api.frame(state, Object.keys(state.subjects).sort(), frame, framed);\n\n // If pruning blank nodes, find those to prune\n if(options.pruneBlankNodeIdentifiers) {\n // remove all blank nodes appearing only once, done in compaction\n options.bnodesToClear =\n Object.keys(state.bnodeMap).filter(id => state.bnodeMap[id].length === 1);\n }\n\n // remove @preserve from results\n options.link = {};\n return _cleanupPreserve(framed, options);\n};\n\n/**\n * Frames subjects according to the given frame.\n *\n * @param state the current framing state.\n * @param subjects the subjects to filter.\n * @param frame the frame.\n * @param parent the parent subject or top-level array.\n * @param property the parent property, initialized to null.\n */\napi.frame = (state, subjects, frame, parent, property = null) => {\n // validate the frame\n _validateFrame(frame);\n frame = frame[0];\n\n // get flags for current frame\n const options = state.options;\n const flags = {\n embed: _getFrameFlag(frame, options, 'embed'),\n explicit: _getFrameFlag(frame, options, 'explicit'),\n requireAll: _getFrameFlag(frame, options, 'requireAll')\n };\n\n // get link for current graph\n if(!state.link.hasOwnProperty(state.graph)) {\n state.link[state.graph] = {};\n }\n const link = state.link[state.graph];\n\n // filter out subjects that match the frame\n const matches = _filterSubjects(state, subjects, frame, flags);\n\n // add matches to output\n const ids = Object.keys(matches).sort();\n for(const id of ids) {\n const subject = matches[id];\n\n /* Note: In order to treat each top-level match as a compartmentalized\n result, clear the unique embedded subjects map when the property is null,\n which only occurs at the top-level. */\n if(property === null) {\n state.uniqueEmbeds = {[state.graph]: {}};\n } else {\n state.uniqueEmbeds[state.graph] = state.uniqueEmbeds[state.graph] || {};\n }\n\n if(flags.embed === '@link' && id in link) {\n // TODO: may want to also match an existing linked subject against\n // the current frame ... so different frames could produce different\n // subjects that are only shared in-memory when the frames are the same\n\n // add existing linked subject\n _addFrameOutput(parent, property, link[id]);\n continue;\n }\n\n // start output for subject\n const output = {'@id': id};\n if(id.indexOf('_:') === 0) {\n util.addValue(state.bnodeMap, id, output, {propertyIsArray: true});\n }\n link[id] = output;\n\n // validate @embed\n if((flags.embed === '@first' || flags.embed === '@last') && state.is11) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid value of @embed.',\n 'jsonld.SyntaxError', {code: 'invalid @embed value', frame});\n }\n\n if(!state.embedded && state.uniqueEmbeds[state.graph].hasOwnProperty(id)) {\n // skip adding this node object to the top level, as it was\n // already included in another node object\n continue;\n }\n\n // if embed is @never or if a circular reference would be created by an\n // embed, the subject cannot be embedded, just add the reference;\n // note that a circular reference won't occur when the embed flag is\n // `@link` as the above check will short-circuit before reaching this point\n if(state.embedded &&\n (flags.embed === '@never' ||\n _createsCircularReference(subject, state.graph, state.subjectStack))) {\n _addFrameOutput(parent, property, output);\n continue;\n }\n\n // if only the first (or once) should be embedded\n if(state.embedded &&\n (flags.embed == '@first' || flags.embed == '@once') &&\n state.uniqueEmbeds[state.graph].hasOwnProperty(id)) {\n _addFrameOutput(parent, property, output);\n continue;\n }\n\n // if only the last match should be embedded\n if(flags.embed === '@last') {\n // remove any existing embed\n if(id in state.uniqueEmbeds[state.graph]) {\n _removeEmbed(state, id);\n }\n }\n\n state.uniqueEmbeds[state.graph][id] = {parent, property};\n\n // push matching subject onto stack to enable circular embed checks\n state.subjectStack.push({subject, graph: state.graph});\n\n // subject is also the name of a graph\n if(id in state.graphMap) {\n let recurse = false;\n let subframe = null;\n if(!('@graph' in frame)) {\n recurse = state.graph !== '@merged';\n subframe = {};\n } else {\n subframe = frame['@graph'][0];\n recurse = !(id === '@merged' || id === '@default');\n if(!types.isObject(subframe)) {\n subframe = {};\n }\n }\n\n if(recurse) {\n // recurse into graph\n api.frame(\n {...state, graph: id, embedded: false},\n Object.keys(state.graphMap[id]).sort(), [subframe], output, '@graph');\n }\n }\n\n // if frame has @included, recurse over its sub-frame\n if('@included' in frame) {\n api.frame(\n {...state, embedded: false},\n subjects, frame['@included'], output, '@included');\n }\n\n // iterate over subject properties\n for(const prop of Object.keys(subject).sort()) {\n // copy keywords to output\n if(isKeyword(prop)) {\n output[prop] = util.clone(subject[prop]);\n\n if(prop === '@type') {\n // count bnode values of @type\n for(const type of subject['@type']) {\n if(type.indexOf('_:') === 0) {\n util.addValue(\n state.bnodeMap, type, output, {propertyIsArray: true});\n }\n }\n }\n continue;\n }\n\n // explicit is on and property isn't in the frame, skip processing\n if(flags.explicit && !(prop in frame)) {\n continue;\n }\n\n // add objects\n for(const o of subject[prop]) {\n const subframe = (prop in frame ?\n frame[prop] : _createImplicitFrame(flags));\n\n // recurse into list\n if(graphTypes.isList(o)) {\n const subframe =\n (frame[prop] && frame[prop][0] && frame[prop][0]['@list']) ?\n frame[prop][0]['@list'] :\n _createImplicitFrame(flags);\n\n // add empty list\n const list = {'@list': []};\n _addFrameOutput(output, prop, list);\n\n // add list objects\n const src = o['@list'];\n for(const oo of src) {\n if(graphTypes.isSubjectReference(oo)) {\n // recurse into subject reference\n api.frame(\n {...state, embedded: true},\n [oo['@id']], subframe, list, '@list');\n } else {\n // include other values automatically\n _addFrameOutput(list, '@list', util.clone(oo));\n }\n }\n } else if(graphTypes.isSubjectReference(o)) {\n // recurse into subject reference\n api.frame(\n {...state, embedded: true},\n [o['@id']], subframe, output, prop);\n } else if(_valueMatch(subframe[0], o)) {\n // include other values, if they match\n _addFrameOutput(output, prop, util.clone(o));\n }\n }\n }\n\n // handle defaults\n for(const prop of Object.keys(frame).sort()) {\n // skip keywords\n if(prop === '@type') {\n if(!types.isObject(frame[prop][0]) ||\n !('@default' in frame[prop][0])) {\n continue;\n }\n // allow through default types\n } else if(isKeyword(prop)) {\n continue;\n }\n\n // if omit default is off, then include default values for properties\n // that appear in the next frame but are not in the matching subject\n const next = frame[prop][0] || {};\n const omitDefaultOn = _getFrameFlag(next, options, 'omitDefault');\n if(!omitDefaultOn && !(prop in output)) {\n let preserve = '@null';\n if('@default' in next) {\n preserve = util.clone(next['@default']);\n }\n if(!types.isArray(preserve)) {\n preserve = [preserve];\n }\n output[prop] = [{'@preserve': preserve}];\n }\n }\n\n // if embed reverse values by finding nodes having this subject as a value\n // of the associated property\n for(const reverseProp of Object.keys(frame['@reverse'] || {}).sort()) {\n const subframe = frame['@reverse'][reverseProp];\n for(const subject of Object.keys(state.subjects)) {\n const nodeValues =\n util.getValues(state.subjects[subject], reverseProp);\n if(nodeValues.some(v => v['@id'] === id)) {\n // node has property referencing this subject, recurse\n output['@reverse'] = output['@reverse'] || {};\n util.addValue(\n output['@reverse'], reverseProp, [], {propertyIsArray: true});\n api.frame(\n {...state, embedded: true},\n [subject], subframe, output['@reverse'][reverseProp],\n property);\n }\n }\n }\n\n // add output to parent\n _addFrameOutput(parent, property, output);\n\n // pop matching subject from circular ref-checking stack\n state.subjectStack.pop();\n }\n};\n\n/**\n * Replace `@null` with `null`, removing it from arrays.\n *\n * @param input the framed, compacted output.\n * @param options the framing options used.\n *\n * @return the resulting output.\n */\napi.cleanupNull = (input, options) => {\n // recurse through arrays\n if(types.isArray(input)) {\n const noNulls = input.map(v => api.cleanupNull(v, options));\n return noNulls.filter(v => v); // removes nulls from array\n }\n\n if(input === '@null') {\n return null;\n }\n\n if(types.isObject(input)) {\n // handle in-memory linked nodes\n if('@id' in input) {\n const id = input['@id'];\n if(options.link.hasOwnProperty(id)) {\n const idx = options.link[id].indexOf(input);\n if(idx !== -1) {\n // already visited\n return options.link[id][idx];\n }\n // prevent circular visitation\n options.link[id].push(input);\n } else {\n // prevent circular visitation\n options.link[id] = [input];\n }\n }\n\n for(const key in input) {\n input[key] = api.cleanupNull(input[key], options);\n }\n }\n return input;\n};\n\n/**\n * Creates an implicit frame when recursing through subject matches. If\n * a frame doesn't have an explicit frame for a particular property, then\n * a wildcard child frame will be created that uses the same flags that the\n * parent frame used.\n *\n * @param flags the current framing flags.\n *\n * @return the implicit frame.\n */\nfunction _createImplicitFrame(flags) {\n const frame = {};\n for(const key in flags) {\n if(flags[key] !== undefined) {\n frame['@' + key] = [flags[key]];\n }\n }\n return [frame];\n}\n\n/**\n * Checks the current subject stack to see if embedding the given subject\n * would cause a circular reference.\n *\n * @param subjectToEmbed the subject to embed.\n * @param graph the graph the subject to embed is in.\n * @param subjectStack the current stack of subjects.\n *\n * @return true if a circular reference would be created, false if not.\n */\nfunction _createsCircularReference(subjectToEmbed, graph, subjectStack) {\n for(let i = subjectStack.length - 1; i >= 0; --i) {\n const subject = subjectStack[i];\n if(subject.graph === graph &&\n subject.subject['@id'] === subjectToEmbed['@id']) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Gets the frame flag value for the given flag name.\n *\n * @param frame the frame.\n * @param options the framing options.\n * @param name the flag name.\n *\n * @return the flag value.\n */\nfunction _getFrameFlag(frame, options, name) {\n const flag = '@' + name;\n let rval = (flag in frame ? frame[flag][0] : options[name]);\n if(name === 'embed') {\n // default is \"@last\"\n // backwards-compatibility support for \"embed\" maps:\n // true => \"@last\"\n // false => \"@never\"\n if(rval === true) {\n rval = '@once';\n } else if(rval === false) {\n rval = '@never';\n } else if(rval !== '@always' && rval !== '@never' && rval !== '@link' &&\n rval !== '@first' && rval !== '@last' && rval !== '@once') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid value of @embed.',\n 'jsonld.SyntaxError', {code: 'invalid @embed value', frame});\n }\n }\n return rval;\n}\n\n/**\n * Validates a JSON-LD frame, throwing an exception if the frame is invalid.\n *\n * @param frame the frame to validate.\n */\nfunction _validateFrame(frame) {\n if(!types.isArray(frame) || frame.length !== 1 || !types.isObject(frame[0])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.',\n 'jsonld.SyntaxError', {frame});\n }\n\n if('@id' in frame[0]) {\n for(const id of util.asArray(frame[0]['@id'])) {\n // @id must be wildcard or an IRI\n if(!(types.isObject(id) || url.isAbsolute(id)) ||\n (types.isString(id) && id.indexOf('_:') === 0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid @id in frame.',\n 'jsonld.SyntaxError', {code: 'invalid frame', frame});\n }\n }\n }\n\n if('@type' in frame[0]) {\n for(const type of util.asArray(frame[0]['@type'])) {\n // @id must be wildcard or an IRI\n if(!(types.isObject(type) || url.isAbsolute(type)) ||\n (types.isString(type) && type.indexOf('_:') === 0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid @type in frame.',\n 'jsonld.SyntaxError', {code: 'invalid frame', frame});\n }\n }\n }\n}\n\n/**\n * Returns a map of all of the subjects that match a parsed frame.\n *\n * @param state the current framing state.\n * @param subjects the set of subjects to filter.\n * @param frame the parsed frame.\n * @param flags the frame flags.\n *\n * @return all of the matched subjects.\n */\nfunction _filterSubjects(state, subjects, frame, flags) {\n // filter subjects in @id order\n const rval = {};\n for(const id of subjects) {\n const subject = state.graphMap[state.graph][id];\n if(_filterSubject(state, subject, frame, flags)) {\n rval[id] = subject;\n }\n }\n return rval;\n}\n\n/**\n * Returns true if the given subject matches the given frame.\n *\n * Matches either based on explicit type inclusion where the node has any\n * type listed in the frame. If the frame has empty types defined matches\n * nodes not having a @type. If the frame has a type of {} defined matches\n * nodes having any type defined.\n *\n * Otherwise, does duck typing, where the node must have all of the\n * properties defined in the frame.\n *\n * @param state the current framing state.\n * @param subject the subject to check.\n * @param frame the frame to check.\n * @param flags the frame flags.\n *\n * @return true if the subject matches, false if not.\n */\nfunction _filterSubject(state, subject, frame, flags) {\n // check ducktype\n let wildcard = true;\n let matchesSome = false;\n\n for(const key in frame) {\n let matchThis = false;\n const nodeValues = util.getValues(subject, key);\n const isEmpty = util.getValues(frame, key).length === 0;\n\n if(key === '@id') {\n // match on no @id or any matching @id, including wildcard\n if(types.isEmptyObject(frame['@id'][0] || {})) {\n matchThis = true;\n } else if(frame['@id'].length >= 0) {\n matchThis = frame['@id'].includes(nodeValues[0]);\n }\n if(!flags.requireAll) {\n return matchThis;\n }\n } else if(key === '@type') {\n // check @type (object value means 'any' type,\n // fall through to ducktyping)\n wildcard = false;\n if(isEmpty) {\n if(nodeValues.length > 0) {\n // don't match on no @type\n return false;\n }\n matchThis = true;\n } else if(frame['@type'].length === 1 &&\n types.isEmptyObject(frame['@type'][0])) {\n // match on wildcard @type if there is a type\n matchThis = nodeValues.length > 0;\n } else {\n // match on a specific @type\n for(const type of frame['@type']) {\n if(types.isObject(type) && '@default' in type) {\n // match on default object\n matchThis = true;\n } else {\n matchThis = matchThis || nodeValues.some(tt => tt === type);\n }\n }\n }\n if(!flags.requireAll) {\n return matchThis;\n }\n } else if(isKeyword(key)) {\n continue;\n } else {\n // Force a copy of this frame entry so it can be manipulated\n const thisFrame = util.getValues(frame, key)[0];\n let hasDefault = false;\n if(thisFrame) {\n _validateFrame([thisFrame]);\n hasDefault = '@default' in thisFrame;\n }\n\n // no longer a wildcard pattern if frame has any non-keyword properties\n wildcard = false;\n\n // skip, but allow match if node has no value for property, and frame has\n // a default value\n if(nodeValues.length === 0 && hasDefault) {\n continue;\n }\n\n // if frame value is empty, don't match if subject has any value\n if(nodeValues.length > 0 && isEmpty) {\n return false;\n }\n\n if(thisFrame === undefined) {\n // node does not match if values is not empty and the value of property\n // in frame is match none.\n if(nodeValues.length > 0) {\n return false;\n }\n matchThis = true;\n } else {\n if(graphTypes.isList(thisFrame)) {\n const listValue = thisFrame['@list'][0];\n if(graphTypes.isList(nodeValues[0])) {\n const nodeListValues = nodeValues[0]['@list'];\n\n if(graphTypes.isValue(listValue)) {\n // match on any matching value\n matchThis = nodeListValues.some(lv => _valueMatch(listValue, lv));\n } else if(graphTypes.isSubject(listValue) ||\n graphTypes.isSubjectReference(listValue)) {\n matchThis = nodeListValues.some(lv => _nodeMatch(\n state, listValue, lv, flags));\n }\n }\n } else if(graphTypes.isValue(thisFrame)) {\n matchThis = nodeValues.some(nv => _valueMatch(thisFrame, nv));\n } else if(graphTypes.isSubjectReference(thisFrame)) {\n matchThis =\n nodeValues.some(nv => _nodeMatch(state, thisFrame, nv, flags));\n } else if(types.isObject(thisFrame)) {\n matchThis = nodeValues.length > 0;\n } else {\n matchThis = false;\n }\n }\n }\n\n // all non-defaulted values must match if requireAll is set\n if(!matchThis && flags.requireAll) {\n return false;\n }\n\n matchesSome = matchesSome || matchThis;\n }\n\n // return true if wildcard or subject matches some properties\n return wildcard || matchesSome;\n}\n\n/**\n * Removes an existing embed.\n *\n * @param state the current framing state.\n * @param id the @id of the embed to remove.\n */\nfunction _removeEmbed(state, id) {\n // get existing embed\n const embeds = state.uniqueEmbeds[state.graph];\n const embed = embeds[id];\n const parent = embed.parent;\n const property = embed.property;\n\n // create reference to replace embed\n const subject = {'@id': id};\n\n // remove existing embed\n if(types.isArray(parent)) {\n // replace subject with reference\n for(let i = 0; i < parent.length; ++i) {\n if(util.compareValues(parent[i], subject)) {\n parent[i] = subject;\n break;\n }\n }\n } else {\n // replace subject with reference\n const useArray = types.isArray(parent[property]);\n util.removeValue(parent, property, subject, {propertyIsArray: useArray});\n util.addValue(parent, property, subject, {propertyIsArray: useArray});\n }\n\n // recursively remove dependent dangling embeds\n const removeDependents = id => {\n // get embed keys as a separate array to enable deleting keys in map\n const ids = Object.keys(embeds);\n for(const next of ids) {\n if(next in embeds && types.isObject(embeds[next].parent) &&\n embeds[next].parent['@id'] === id) {\n delete embeds[next];\n removeDependents(next);\n }\n }\n };\n removeDependents(id);\n}\n\n/**\n * Removes the @preserve keywords from expanded result of framing.\n *\n * @param input the framed, framed output.\n * @param options the framing options used.\n *\n * @return the resulting output.\n */\nfunction _cleanupPreserve(input, options) {\n // recurse through arrays\n if(types.isArray(input)) {\n return input.map(value => _cleanupPreserve(value, options));\n }\n\n if(types.isObject(input)) {\n // remove @preserve\n if('@preserve' in input) {\n return input['@preserve'][0];\n }\n\n // skip @values\n if(graphTypes.isValue(input)) {\n return input;\n }\n\n // recurse through @lists\n if(graphTypes.isList(input)) {\n input['@list'] = _cleanupPreserve(input['@list'], options);\n return input;\n }\n\n // handle in-memory linked nodes\n if('@id' in input) {\n const id = input['@id'];\n if(options.link.hasOwnProperty(id)) {\n const idx = options.link[id].indexOf(input);\n if(idx !== -1) {\n // already visited\n return options.link[id][idx];\n }\n // prevent circular visitation\n options.link[id].push(input);\n } else {\n // prevent circular visitation\n options.link[id] = [input];\n }\n }\n\n // recurse through properties\n for(const prop in input) {\n // potentially remove the id, if it is an unreference bnode\n if(prop === '@id' && options.bnodesToClear.includes(input[prop])) {\n delete input['@id'];\n continue;\n }\n\n input[prop] = _cleanupPreserve(input[prop], options);\n }\n }\n return input;\n}\n\n/**\n * Adds framing output to the given parent.\n *\n * @param parent the parent to add to.\n * @param property the parent property.\n * @param output the output to add.\n */\nfunction _addFrameOutput(parent, property, output) {\n if(types.isObject(parent)) {\n util.addValue(parent, property, output, {propertyIsArray: true});\n } else {\n parent.push(output);\n }\n}\n\n/**\n * Node matches if it is a node, and matches the pattern as a frame.\n *\n * @param state the current framing state.\n * @param pattern used to match value\n * @param value to check\n * @param flags the frame flags.\n */\nfunction _nodeMatch(state, pattern, value, flags) {\n if(!('@id' in value)) {\n return false;\n }\n const nodeObject = state.subjects[value['@id']];\n return nodeObject && _filterSubject(state, nodeObject, pattern, flags);\n}\n\n/**\n * Value matches if it is a value and matches the value pattern\n *\n * * `pattern` is empty\n * * @values are the same, or `pattern[@value]` is a wildcard, and\n * * @types are the same or `value[@type]` is not null\n * and `pattern[@type]` is `{}`, or `value[@type]` is null\n * and `pattern[@type]` is null or `[]`, and\n * * @languages are the same or `value[@language]` is not null\n * and `pattern[@language]` is `{}`, or `value[@language]` is null\n * and `pattern[@language]` is null or `[]`.\n *\n * @param pattern used to match value\n * @param value to check\n */\nfunction _valueMatch(pattern, value) {\n const v1 = value['@value'];\n const t1 = value['@type'];\n const l1 = value['@language'];\n const v2 = pattern['@value'] ?\n (types.isArray(pattern['@value']) ?\n pattern['@value'] : [pattern['@value']]) :\n [];\n const t2 = pattern['@type'] ?\n (types.isArray(pattern['@type']) ?\n pattern['@type'] : [pattern['@type']]) :\n [];\n const l2 = pattern['@language'] ?\n (types.isArray(pattern['@language']) ?\n pattern['@language'] : [pattern['@language']]) :\n [];\n\n if(v2.length === 0 && t2.length === 0 && l2.length === 0) {\n return true;\n }\n if(!(v2.includes(v1) || types.isEmptyObject(v2[0]))) {\n return false;\n }\n if(!(!t1 && t2.length === 0 || t2.includes(t1) || t1 &&\n types.isEmptyObject(t2[0]))) {\n return false;\n }\n if(!(!l1 && l2.length === 0 || l2.includes(l1) || l1 &&\n types.isEmptyObject(l2[0]))) {\n return false;\n }\n return true;\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst JsonLdError = require('./JsonLdError');\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isString: _isString,\n isUndefined: _isUndefined\n} = require('./types');\n\nconst {\n isList: _isList,\n isValue: _isValue,\n isGraph: _isGraph,\n isSimpleGraph: _isSimpleGraph,\n isSubjectReference: _isSubjectReference\n} = require('./graphTypes');\n\nconst {\n expandIri: _expandIri,\n getContextValue: _getContextValue,\n isKeyword: _isKeyword,\n process: _processContext,\n processingMode: _processingMode\n} = require('./context');\n\nconst {\n removeBase: _removeBase,\n prependBase: _prependBase\n} = require('./url');\n\nconst {\n addValue: _addValue,\n asArray: _asArray,\n compareShortestLeast: _compareShortestLeast\n} = require('./util');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Recursively compacts an element using the given active context. All values\n * must be in expanded form before this method is called.\n *\n * @param activeCtx the active context to use.\n * @param activeProperty the compacted property associated with the element\n * to compact, null for none.\n * @param element the element to compact.\n * @param options the compaction options.\n * @param compactionMap the compaction map to use.\n *\n * @return a promise that resolves to the compacted value.\n */\napi.compact = async ({\n activeCtx,\n activeProperty = null,\n element,\n options = {},\n compactionMap = () => undefined\n}) => {\n // recursively compact array\n if(_isArray(element)) {\n let rval = [];\n for(let i = 0; i < element.length; ++i) {\n // compact, dropping any null values unless custom mapped\n let compacted = await api.compact({\n activeCtx,\n activeProperty,\n element: element[i],\n options,\n compactionMap\n });\n if(compacted === null) {\n compacted = await compactionMap({\n unmappedValue: element[i],\n activeCtx,\n activeProperty,\n parent: element,\n index: i,\n options\n });\n if(compacted === undefined) {\n continue;\n }\n }\n rval.push(compacted);\n }\n if(options.compactArrays && rval.length === 1) {\n // use single element if no container is specified\n const container = _getContextValue(\n activeCtx, activeProperty, '@container') || [];\n if(container.length === 0) {\n rval = rval[0];\n }\n }\n return rval;\n }\n\n // use any scoped context on activeProperty\n const ctx = _getContextValue(activeCtx, activeProperty, '@context');\n if(!_isUndefined(ctx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n propagate: true,\n overrideProtected: true,\n options\n });\n }\n\n // recursively compact object\n if(_isObject(element)) {\n if(options.link && '@id' in element &&\n options.link.hasOwnProperty(element['@id'])) {\n // check for a linked element to reuse\n const linked = options.link[element['@id']];\n for(let i = 0; i < linked.length; ++i) {\n if(linked[i].expanded === element) {\n return linked[i].compacted;\n }\n }\n }\n\n // do value compaction on @values and subject references\n if(_isValue(element) || _isSubjectReference(element)) {\n const rval =\n api.compactValue({activeCtx, activeProperty, value: element, options});\n if(options.link && _isSubjectReference(element)) {\n // store linked element\n if(!(options.link.hasOwnProperty(element['@id']))) {\n options.link[element['@id']] = [];\n }\n options.link[element['@id']].push({expanded: element, compacted: rval});\n }\n return rval;\n }\n\n // if expanded property is @list and we're contained within a list\n // container, recursively compact this item to an array\n if(_isList(element)) {\n const container = _getContextValue(\n activeCtx, activeProperty, '@container') || [];\n if(container.includes('@list')) {\n return api.compact({\n activeCtx,\n activeProperty,\n element: element['@list'],\n options,\n compactionMap\n });\n }\n }\n\n // FIXME: avoid misuse of active property as an expanded property?\n const insideReverse = (activeProperty === '@reverse');\n\n const rval = {};\n\n // original context before applying property-scoped and local contexts\n const inputCtx = activeCtx;\n\n // revert to previous context, if there is one,\n // and element is not a value object or a node reference\n if(!_isValue(element) && !_isSubjectReference(element)) {\n activeCtx = activeCtx.revertToPreviousContext();\n }\n\n // apply property-scoped context after reverting term-scoped context\n const propertyScopedCtx =\n _getContextValue(inputCtx, activeProperty, '@context');\n if(!_isUndefined(propertyScopedCtx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: propertyScopedCtx,\n propagate: true,\n overrideProtected: true,\n options\n });\n }\n\n if(options.link && '@id' in element) {\n // store linked element\n if(!options.link.hasOwnProperty(element['@id'])) {\n options.link[element['@id']] = [];\n }\n options.link[element['@id']].push({expanded: element, compacted: rval});\n }\n\n // apply any context defined on an alias of @type\n // if key is @type and any compacted value is a term having a local\n // context, overlay that context\n let types = element['@type'] || [];\n if(types.length > 1) {\n types = Array.from(types).sort();\n }\n // find all type-scoped contexts based on current context, prior to\n // updating it\n const typeContext = activeCtx;\n for(const type of types) {\n const compactedType = api.compactIri(\n {activeCtx: typeContext, iri: type, relativeTo: {vocab: true}});\n\n // Use any type-scoped context defined on this value\n const ctx = _getContextValue(inputCtx, compactedType, '@context');\n if(!_isUndefined(ctx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n options,\n propagate: false\n });\n }\n }\n\n // process element keys in order\n const keys = Object.keys(element).sort();\n for(const expandedProperty of keys) {\n const expandedValue = element[expandedProperty];\n\n // compact @id\n if(expandedProperty === '@id') {\n let compactedValue = _asArray(expandedValue).map(\n expandedIri => api.compactIri({\n activeCtx,\n iri: expandedIri,\n relativeTo: {vocab: false},\n base: options.base\n }));\n if(compactedValue.length === 1) {\n compactedValue = compactedValue[0];\n }\n\n // use keyword alias and add value\n const alias = api.compactIri(\n {activeCtx, iri: '@id', relativeTo: {vocab: true}});\n\n rval[alias] = compactedValue;\n continue;\n }\n\n // compact @type(s)\n if(expandedProperty === '@type') {\n // resolve type values against previous context\n let compactedValue = _asArray(expandedValue).map(\n expandedIri => api.compactIri({\n activeCtx: inputCtx,\n iri: expandedIri,\n relativeTo: {vocab: true}\n }));\n if(compactedValue.length === 1) {\n compactedValue = compactedValue[0];\n }\n\n // use keyword alias and add value\n const alias = api.compactIri(\n {activeCtx, iri: '@type', relativeTo: {vocab: true}});\n const container = _getContextValue(\n activeCtx, alias, '@container') || [];\n\n // treat as array for @type if @container includes @set\n const typeAsSet =\n container.includes('@set') &&\n _processingMode(activeCtx, 1.1);\n const isArray =\n typeAsSet || (_isArray(compactedValue) && expandedValue.length === 0);\n _addValue(rval, alias, compactedValue, {propertyIsArray: isArray});\n continue;\n }\n\n // handle @reverse\n if(expandedProperty === '@reverse') {\n // recursively compact expanded value\n const compactedValue = await api.compact({\n activeCtx,\n activeProperty: '@reverse',\n element: expandedValue,\n options,\n compactionMap\n });\n\n // handle double-reversed properties\n for(const compactedProperty in compactedValue) {\n if(activeCtx.mappings.has(compactedProperty) &&\n activeCtx.mappings.get(compactedProperty).reverse) {\n const value = compactedValue[compactedProperty];\n const container = _getContextValue(\n activeCtx, compactedProperty, '@container') || [];\n const useArray = (\n container.includes('@set') || !options.compactArrays);\n _addValue(\n rval, compactedProperty, value, {propertyIsArray: useArray});\n delete compactedValue[compactedProperty];\n }\n }\n\n if(Object.keys(compactedValue).length > 0) {\n // use keyword alias and add value\n const alias = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n relativeTo: {vocab: true}\n });\n _addValue(rval, alias, compactedValue);\n }\n\n continue;\n }\n\n if(expandedProperty === '@preserve') {\n // compact using activeProperty\n const compactedValue = await api.compact({\n activeCtx,\n activeProperty,\n element: expandedValue,\n options,\n compactionMap\n });\n\n if(!(_isArray(compactedValue) && compactedValue.length === 0)) {\n _addValue(rval, expandedProperty, compactedValue);\n }\n continue;\n }\n\n // handle @index property\n if(expandedProperty === '@index') {\n // drop @index if inside an @index container\n const container = _getContextValue(\n activeCtx, activeProperty, '@container') || [];\n if(container.includes('@index')) {\n continue;\n }\n\n // use keyword alias and add value\n const alias = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n relativeTo: {vocab: true}\n });\n _addValue(rval, alias, expandedValue);\n continue;\n }\n\n // skip array processing for keywords that aren't\n // @graph, @list, or @included\n if(expandedProperty !== '@graph' && expandedProperty !== '@list' &&\n expandedProperty !== '@included' &&\n _isKeyword(expandedProperty)) {\n // use keyword alias and add value as is\n const alias = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n relativeTo: {vocab: true}\n });\n _addValue(rval, alias, expandedValue);\n continue;\n }\n\n // Note: expanded value must be an array due to expansion algorithm.\n if(!_isArray(expandedValue)) {\n throw new JsonLdError(\n 'JSON-LD expansion error; expanded value must be an array.',\n 'jsonld.SyntaxError');\n }\n\n // preserve empty arrays\n if(expandedValue.length === 0) {\n const itemActiveProperty = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n value: expandedValue,\n relativeTo: {vocab: true},\n reverse: insideReverse\n });\n const nestProperty = activeCtx.mappings.has(itemActiveProperty) ?\n activeCtx.mappings.get(itemActiveProperty)['@nest'] : null;\n let nestResult = rval;\n if(nestProperty) {\n _checkNestProperty(activeCtx, nestProperty, options);\n if(!_isObject(rval[nestProperty])) {\n rval[nestProperty] = {};\n }\n nestResult = rval[nestProperty];\n }\n _addValue(\n nestResult, itemActiveProperty, expandedValue, {\n propertyIsArray: true\n });\n }\n\n // recusively process array values\n for(const expandedItem of expandedValue) {\n // compact property and get container type\n const itemActiveProperty = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n value: expandedItem,\n relativeTo: {vocab: true},\n reverse: insideReverse\n });\n\n // if itemActiveProperty is a @nest property, add values to nestResult,\n // otherwise rval\n const nestProperty = activeCtx.mappings.has(itemActiveProperty) ?\n activeCtx.mappings.get(itemActiveProperty)['@nest'] : null;\n let nestResult = rval;\n if(nestProperty) {\n _checkNestProperty(activeCtx, nestProperty, options);\n if(!_isObject(rval[nestProperty])) {\n rval[nestProperty] = {};\n }\n nestResult = rval[nestProperty];\n }\n\n const container = _getContextValue(\n activeCtx, itemActiveProperty, '@container') || [];\n\n // get simple @graph or @list value if appropriate\n const isGraph = _isGraph(expandedItem);\n const isList = _isList(expandedItem);\n let inner;\n if(isList) {\n inner = expandedItem['@list'];\n } else if(isGraph) {\n inner = expandedItem['@graph'];\n }\n\n // recursively compact expanded item\n let compactedItem = await api.compact({\n activeCtx,\n activeProperty: itemActiveProperty,\n element: (isList || isGraph) ? inner : expandedItem,\n options,\n compactionMap\n });\n\n // handle @list\n if(isList) {\n // ensure @list value is an array\n if(!_isArray(compactedItem)) {\n compactedItem = [compactedItem];\n }\n\n if(!container.includes('@list')) {\n // wrap using @list alias\n compactedItem = {\n [api.compactIri({\n activeCtx,\n iri: '@list',\n relativeTo: {vocab: true}\n })]: compactedItem\n };\n\n // include @index from expanded @list, if any\n if('@index' in expandedItem) {\n compactedItem[api.compactIri({\n activeCtx,\n iri: '@index',\n relativeTo: {vocab: true}\n })] = expandedItem['@index'];\n }\n } else {\n _addValue(nestResult, itemActiveProperty, compactedItem, {\n valueIsArray: true,\n allowDuplicate: true\n });\n continue;\n }\n }\n\n // Graph object compaction cases\n if(isGraph) {\n if(container.includes('@graph') && (container.includes('@id') ||\n container.includes('@index') && _isSimpleGraph(expandedItem))) {\n // get or create the map object\n let mapObject;\n if(nestResult.hasOwnProperty(itemActiveProperty)) {\n mapObject = nestResult[itemActiveProperty];\n } else {\n nestResult[itemActiveProperty] = mapObject = {};\n }\n\n // index on @id or @index or alias of @none\n const key = (container.includes('@id') ?\n expandedItem['@id'] : expandedItem['@index']) ||\n api.compactIri({activeCtx, iri: '@none',\n relativeTo: {vocab: true}});\n // add compactedItem to map, using value of `@id` or a new blank\n // node identifier\n\n _addValue(\n mapObject, key, compactedItem, {\n propertyIsArray:\n (!options.compactArrays || container.includes('@set'))\n });\n } else if(container.includes('@graph') &&\n _isSimpleGraph(expandedItem)) {\n // container includes @graph but not @id or @index and value is a\n // simple graph object add compact value\n // if compactedItem contains multiple values, it is wrapped in\n // `@included`\n if(_isArray(compactedItem) && compactedItem.length > 1) {\n compactedItem = {'@included': compactedItem};\n }\n _addValue(\n nestResult, itemActiveProperty, compactedItem, {\n propertyIsArray:\n (!options.compactArrays || container.includes('@set'))\n });\n } else {\n // wrap using @graph alias, remove array if only one item and\n // compactArrays not set\n if(_isArray(compactedItem) && compactedItem.length === 1 &&\n options.compactArrays) {\n compactedItem = compactedItem[0];\n }\n compactedItem = {\n [api.compactIri({\n activeCtx,\n iri: '@graph',\n relativeTo: {vocab: true}\n })]: compactedItem\n };\n\n // include @id from expanded graph, if any\n if('@id' in expandedItem) {\n compactedItem[api.compactIri({\n activeCtx,\n iri: '@id',\n relativeTo: {vocab: true}\n })] = expandedItem['@id'];\n }\n\n // include @index from expanded graph, if any\n if('@index' in expandedItem) {\n compactedItem[api.compactIri({\n activeCtx,\n iri: '@index',\n relativeTo: {vocab: true}\n })] = expandedItem['@index'];\n }\n _addValue(\n nestResult, itemActiveProperty, compactedItem, {\n propertyIsArray:\n (!options.compactArrays || container.includes('@set'))\n });\n }\n } else if(container.includes('@language') ||\n container.includes('@index') || container.includes('@id') ||\n container.includes('@type')) {\n // handle language and index maps\n // get or create the map object\n let mapObject;\n if(nestResult.hasOwnProperty(itemActiveProperty)) {\n mapObject = nestResult[itemActiveProperty];\n } else {\n nestResult[itemActiveProperty] = mapObject = {};\n }\n\n let key;\n if(container.includes('@language')) {\n // if container is a language map, simplify compacted value to\n // a simple string\n if(_isValue(compactedItem)) {\n compactedItem = compactedItem['@value'];\n }\n key = expandedItem['@language'];\n } else if(container.includes('@index')) {\n const indexKey = _getContextValue(\n activeCtx, itemActiveProperty, '@index') || '@index';\n const containerKey = api.compactIri(\n {activeCtx, iri: indexKey, relativeTo: {vocab: true}});\n if(indexKey === '@index') {\n key = expandedItem['@index'];\n delete compactedItem[containerKey];\n } else {\n let others;\n [key, ...others] = _asArray(compactedItem[indexKey] || []);\n if(!_isString(key)) {\n // Will use @none if it isn't a string.\n key = null;\n } else {\n switch(others.length) {\n case 0:\n delete compactedItem[indexKey];\n break;\n case 1:\n compactedItem[indexKey] = others[0];\n break;\n default:\n compactedItem[indexKey] = others;\n break;\n }\n }\n }\n } else if(container.includes('@id')) {\n const idKey = api.compactIri({activeCtx, iri: '@id',\n relativeTo: {vocab: true}});\n key = compactedItem[idKey];\n delete compactedItem[idKey];\n } else if(container.includes('@type')) {\n const typeKey = api.compactIri({\n activeCtx,\n iri: '@type',\n relativeTo: {vocab: true}\n });\n let types;\n [key, ...types] = _asArray(compactedItem[typeKey] || []);\n switch(types.length) {\n case 0:\n delete compactedItem[typeKey];\n break;\n case 1:\n compactedItem[typeKey] = types[0];\n break;\n default:\n compactedItem[typeKey] = types;\n break;\n }\n\n // If compactedItem contains a single entry\n // whose key maps to @id, recompact without @type\n if(Object.keys(compactedItem).length === 1 &&\n '@id' in expandedItem) {\n compactedItem = await api.compact({\n activeCtx,\n activeProperty: itemActiveProperty,\n element: {'@id': expandedItem['@id']},\n options,\n compactionMap\n });\n }\n }\n\n // if compacting this value which has no key, index on @none\n if(!key) {\n key = api.compactIri({activeCtx, iri: '@none',\n relativeTo: {vocab: true}});\n }\n // add compact value to map object using key from expanded value\n // based on the container type\n _addValue(\n mapObject, key, compactedItem, {\n propertyIsArray: container.includes('@set')\n });\n } else {\n // use an array if: compactArrays flag is false,\n // @container is @set or @list , value is an empty\n // array, or key is @graph\n const isArray = (!options.compactArrays ||\n container.includes('@set') || container.includes('@list') ||\n (_isArray(compactedItem) && compactedItem.length === 0) ||\n expandedProperty === '@list' || expandedProperty === '@graph');\n\n // add compact value\n _addValue(\n nestResult, itemActiveProperty, compactedItem,\n {propertyIsArray: isArray});\n }\n }\n }\n\n return rval;\n }\n\n // only primitives remain which are already compact\n return element;\n};\n\n/**\n * Compacts an IRI or keyword into a term or prefix if it can be. If the\n * IRI has an associated value it may be passed.\n *\n * @param activeCtx the active context to use.\n * @param iri the IRI to compact.\n * @param value the value to check or null.\n * @param relativeTo options for how to compact IRIs:\n * vocab: true to split after @vocab, false not to.\n * @param reverse true if a reverse property is being compacted, false if not.\n * @param base the absolute URL to use for compacting document-relative IRIs.\n *\n * @return the compacted term, prefix, keyword alias, or the original IRI.\n */\napi.compactIri = ({\n activeCtx,\n iri,\n value = null,\n relativeTo = {vocab: false},\n reverse = false,\n base = null\n}) => {\n // can't compact null\n if(iri === null) {\n return iri;\n }\n\n // if context is from a property term scoped context composed with a\n // type-scoped context, then use the previous context instead\n if(activeCtx.isPropertyTermScoped && activeCtx.previousContext) {\n activeCtx = activeCtx.previousContext;\n }\n\n const inverseCtx = activeCtx.getInverse();\n\n // if term is a keyword, it may be compacted to a simple alias\n if(_isKeyword(iri) &&\n iri in inverseCtx &&\n '@none' in inverseCtx[iri] &&\n '@type' in inverseCtx[iri]['@none'] &&\n '@none' in inverseCtx[iri]['@none']['@type']) {\n return inverseCtx[iri]['@none']['@type']['@none'];\n }\n\n // use inverse context to pick a term if iri is relative to vocab\n if(relativeTo.vocab && iri in inverseCtx) {\n const defaultLanguage = activeCtx['@language'] || '@none';\n\n // prefer @index if available in value\n const containers = [];\n if(_isObject(value) && '@index' in value && !('@graph' in value)) {\n containers.push('@index', '@index@set');\n }\n\n // if value is a preserve object, use its value\n if(_isObject(value) && '@preserve' in value) {\n value = value['@preserve'][0];\n }\n\n // prefer most specific container including @graph, prefering @set\n // variations\n if(_isGraph(value)) {\n // favor indexmap if the graph is indexed\n if('@index' in value) {\n containers.push(\n '@graph@index', '@graph@index@set', '@index', '@index@set');\n }\n // favor idmap if the graph is has an @id\n if('@id' in value) {\n containers.push(\n '@graph@id', '@graph@id@set');\n }\n containers.push('@graph', '@graph@set', '@set');\n // allow indexmap if the graph is not indexed\n if(!('@index' in value)) {\n containers.push(\n '@graph@index', '@graph@index@set', '@index', '@index@set');\n }\n // allow idmap if the graph does not have an @id\n if(!('@id' in value)) {\n containers.push('@graph@id', '@graph@id@set');\n }\n } else if(_isObject(value) && !_isValue(value)) {\n containers.push('@id', '@id@set', '@type', '@set@type');\n }\n\n // defaults for term selection based on type/language\n let typeOrLanguage = '@language';\n let typeOrLanguageValue = '@null';\n\n if(reverse) {\n typeOrLanguage = '@type';\n typeOrLanguageValue = '@reverse';\n containers.push('@set');\n } else if(_isList(value)) {\n // choose the most specific term that works for all elements in @list\n // only select @list containers if @index is NOT in value\n if(!('@index' in value)) {\n containers.push('@list');\n }\n const list = value['@list'];\n if(list.length === 0) {\n // any empty list can be matched against any term that uses the\n // @list container regardless of @type or @language\n typeOrLanguage = '@any';\n typeOrLanguageValue = '@none';\n } else {\n let commonLanguage = (list.length === 0) ? defaultLanguage : null;\n let commonType = null;\n for(let i = 0; i < list.length; ++i) {\n const item = list[i];\n let itemLanguage = '@none';\n let itemType = '@none';\n if(_isValue(item)) {\n if('@direction' in item) {\n const lang = (item['@language'] || '').toLowerCase();\n const dir = item['@direction'];\n itemLanguage = `${lang}_${dir}`;\n } else if('@language' in item) {\n itemLanguage = item['@language'].toLowerCase();\n } else if('@type' in item) {\n itemType = item['@type'];\n } else {\n // plain literal\n itemLanguage = '@null';\n }\n } else {\n itemType = '@id';\n }\n if(commonLanguage === null) {\n commonLanguage = itemLanguage;\n } else if(itemLanguage !== commonLanguage && _isValue(item)) {\n commonLanguage = '@none';\n }\n if(commonType === null) {\n commonType = itemType;\n } else if(itemType !== commonType) {\n commonType = '@none';\n }\n // there are different languages and types in the list, so choose\n // the most generic term, no need to keep iterating the list\n if(commonLanguage === '@none' && commonType === '@none') {\n break;\n }\n }\n commonLanguage = commonLanguage || '@none';\n commonType = commonType || '@none';\n if(commonType !== '@none') {\n typeOrLanguage = '@type';\n typeOrLanguageValue = commonType;\n } else {\n typeOrLanguageValue = commonLanguage;\n }\n }\n } else {\n if(_isValue(value)) {\n if('@language' in value && !('@index' in value)) {\n containers.push('@language', '@language@set');\n typeOrLanguageValue = value['@language'];\n const dir = value['@direction'];\n if(dir) {\n typeOrLanguageValue = `${typeOrLanguageValue}_${dir}`;\n }\n } else if('@direction' in value && !('@index' in value)) {\n typeOrLanguageValue = `_${value['@direction']}`;\n } else if('@type' in value) {\n typeOrLanguage = '@type';\n typeOrLanguageValue = value['@type'];\n }\n } else {\n typeOrLanguage = '@type';\n typeOrLanguageValue = '@id';\n }\n containers.push('@set');\n }\n\n // do term selection\n containers.push('@none');\n\n // an index map can be used to index values using @none, so add as a low\n // priority\n if(_isObject(value) && !('@index' in value)) {\n // allow indexing even if no @index present\n containers.push('@index', '@index@set');\n }\n\n // values without type or language can use @language map\n if(_isValue(value) && Object.keys(value).length === 1) {\n // allow indexing even if no @index present\n containers.push('@language', '@language@set');\n }\n\n const term = _selectTerm(\n activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue);\n if(term !== null) {\n return term;\n }\n }\n\n // no term match, use @vocab if available\n if(relativeTo.vocab) {\n if('@vocab' in activeCtx) {\n // determine if vocab is a prefix of the iri\n const vocab = activeCtx['@vocab'];\n if(iri.indexOf(vocab) === 0 && iri !== vocab) {\n // use suffix as relative iri if it is not a term in the active context\n const suffix = iri.substr(vocab.length);\n if(!activeCtx.mappings.has(suffix)) {\n return suffix;\n }\n }\n }\n }\n\n // no term or @vocab match, check for possible CURIEs\n let choice = null;\n // TODO: make FastCurieMap a class with a method to do this lookup\n const partialMatches = [];\n let iriMap = activeCtx.fastCurieMap;\n // check for partial matches of against `iri`, which means look until\n // iri.length - 1, not full length\n const maxPartialLength = iri.length - 1;\n for(let i = 0; i < maxPartialLength && iri[i] in iriMap; ++i) {\n iriMap = iriMap[iri[i]];\n if('' in iriMap) {\n partialMatches.push(iriMap[''][0]);\n }\n }\n // check partial matches in reverse order to prefer longest ones first\n for(let i = partialMatches.length - 1; i >= 0; --i) {\n const entry = partialMatches[i];\n const terms = entry.terms;\n for(const term of terms) {\n // a CURIE is usable if:\n // 1. it has no mapping, OR\n // 2. value is null, which means we're not compacting an @value, AND\n // the mapping matches the IRI\n const curie = term + ':' + iri.substr(entry.iri.length);\n const isUsableCurie = (activeCtx.mappings.get(term)._prefix &&\n (!activeCtx.mappings.has(curie) ||\n (value === null && activeCtx.mappings.get(curie)['@id'] === iri)));\n\n // select curie if it is shorter or the same length but lexicographically\n // less than the current choice\n if(isUsableCurie && (choice === null ||\n _compareShortestLeast(curie, choice) < 0)) {\n choice = curie;\n }\n }\n }\n\n // return chosen curie\n if(choice !== null) {\n return choice;\n }\n\n // If iri could be confused with a compact IRI using a term in this context,\n // signal an error\n for(const [term, td] of activeCtx.mappings) {\n if(td && td._prefix && iri.startsWith(term + ':')) {\n throw new JsonLdError(\n `Absolute IRI \"${iri}\" confused with prefix \"${term}\".`,\n 'jsonld.SyntaxError',\n {code: 'IRI confused with prefix', context: activeCtx});\n }\n }\n\n // compact IRI relative to base\n if(!relativeTo.vocab) {\n if('@base' in activeCtx) {\n if(!activeCtx['@base']) {\n // The None case preserves rval as potentially relative\n return iri;\n } else {\n return _removeBase(_prependBase(base, activeCtx['@base']), iri);\n }\n } else {\n return _removeBase(base, iri);\n }\n }\n\n // return IRI as is\n return iri;\n};\n\n/**\n * Performs value compaction on an object with '@value' or '@id' as the only\n * property.\n *\n * @param activeCtx the active context.\n * @param activeProperty the active property that points to the value.\n * @param value the value to compact.\n * @param {Object} [options] - processing options.\n *\n * @return the compaction result.\n */\napi.compactValue = ({activeCtx, activeProperty, value, options}) => {\n // value is a @value\n if(_isValue(value)) {\n // get context rules\n const type = _getContextValue(activeCtx, activeProperty, '@type');\n const language = _getContextValue(activeCtx, activeProperty, '@language');\n const direction = _getContextValue(activeCtx, activeProperty, '@direction');\n const container =\n _getContextValue(activeCtx, activeProperty, '@container') || [];\n\n // whether or not the value has an @index that must be preserved\n const preserveIndex = '@index' in value && !container.includes('@index');\n\n // if there's no @index to preserve ...\n if(!preserveIndex && type !== '@none') {\n // matching @type or @language specified in context, compact value\n if(value['@type'] === type) {\n return value['@value'];\n }\n if('@language' in value && value['@language'] === language &&\n '@direction' in value && value['@direction'] === direction) {\n return value['@value'];\n }\n if('@language' in value && value['@language'] === language) {\n return value['@value'];\n }\n if('@direction' in value && value['@direction'] === direction) {\n return value['@value'];\n }\n }\n\n // return just the value of @value if all are true:\n // 1. @value is the only key or @index isn't being preserved\n // 2. there is no default language or @value is not a string or\n // the key has a mapping with a null @language\n const keyCount = Object.keys(value).length;\n const isValueOnlyKey = (keyCount === 1 ||\n (keyCount === 2 && '@index' in value && !preserveIndex));\n const hasDefaultLanguage = ('@language' in activeCtx);\n const isValueString = _isString(value['@value']);\n const hasNullMapping = (activeCtx.mappings.has(activeProperty) &&\n activeCtx.mappings.get(activeProperty)['@language'] === null);\n if(isValueOnlyKey &&\n type !== '@none' &&\n (!hasDefaultLanguage || !isValueString || hasNullMapping)) {\n return value['@value'];\n }\n\n const rval = {};\n\n // preserve @index\n if(preserveIndex) {\n rval[api.compactIri({\n activeCtx,\n iri: '@index',\n relativeTo: {vocab: true}\n })] = value['@index'];\n }\n\n if('@type' in value) {\n // compact @type IRI\n rval[api.compactIri({\n activeCtx,\n iri: '@type',\n relativeTo: {vocab: true}\n })] = api.compactIri(\n {activeCtx, iri: value['@type'], relativeTo: {vocab: true}});\n } else if('@language' in value) {\n // alias @language\n rval[api.compactIri({\n activeCtx,\n iri: '@language',\n relativeTo: {vocab: true}\n })] = value['@language'];\n }\n\n if('@direction' in value) {\n // alias @direction\n rval[api.compactIri({\n activeCtx,\n iri: '@direction',\n relativeTo: {vocab: true}\n })] = value['@direction'];\n }\n\n // alias @value\n rval[api.compactIri({\n activeCtx,\n iri: '@value',\n relativeTo: {vocab: true}\n })] = value['@value'];\n\n return rval;\n }\n\n // value is a subject reference\n const expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true},\n options);\n const type = _getContextValue(activeCtx, activeProperty, '@type');\n const compacted = api.compactIri({\n activeCtx,\n iri: value['@id'],\n relativeTo: {vocab: type === '@vocab'},\n base: options.base});\n\n // compact to scalar\n if(type === '@id' || type === '@vocab' || expandedProperty === '@graph') {\n return compacted;\n }\n\n return {\n [api.compactIri({\n activeCtx,\n iri: '@id',\n relativeTo: {vocab: true}\n })]: compacted\n };\n};\n\n/**\n * Picks the preferred compaction term from the given inverse context entry.\n *\n * @param activeCtx the active context.\n * @param iri the IRI to pick the term for.\n * @param value the value to pick the term for.\n * @param containers the preferred containers.\n * @param typeOrLanguage either '@type' or '@language'.\n * @param typeOrLanguageValue the preferred value for '@type' or '@language'.\n *\n * @return the preferred term.\n */\nfunction _selectTerm(\n activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) {\n if(typeOrLanguageValue === null) {\n typeOrLanguageValue = '@null';\n }\n\n // preferences for the value of @type or @language\n const prefs = [];\n\n // determine prefs for @id based on whether or not value compacts to a term\n if((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') &&\n _isObject(value) && '@id' in value) {\n // prefer @reverse first\n if(typeOrLanguageValue === '@reverse') {\n prefs.push('@reverse');\n }\n // try to compact value to a term\n const term = api.compactIri(\n {activeCtx, iri: value['@id'], relativeTo: {vocab: true}});\n if(activeCtx.mappings.has(term) &&\n activeCtx.mappings.get(term) &&\n activeCtx.mappings.get(term)['@id'] === value['@id']) {\n // prefer @vocab\n prefs.push.apply(prefs, ['@vocab', '@id']);\n } else {\n // prefer @id\n prefs.push.apply(prefs, ['@id', '@vocab']);\n }\n } else {\n prefs.push(typeOrLanguageValue);\n\n // consider direction only\n const langDir = prefs.find(el => el.includes('_'));\n if(langDir) {\n // consider _dir portion\n prefs.push(langDir.replace(/^[^_]+_/, '_'));\n }\n }\n prefs.push('@none');\n\n const containerMap = activeCtx.inverse[iri];\n for(const container of containers) {\n // if container not available in the map, continue\n if(!(container in containerMap)) {\n continue;\n }\n\n const typeOrLanguageValueMap = containerMap[container][typeOrLanguage];\n for(const pref of prefs) {\n // if type/language option not available in the map, continue\n if(!(pref in typeOrLanguageValueMap)) {\n continue;\n }\n\n // select term\n return typeOrLanguageValueMap[pref];\n }\n }\n\n return null;\n}\n\n/**\n * The value of `@nest` in the term definition must either be `@nest`, or a term\n * which resolves to `@nest`.\n *\n * @param activeCtx the active context.\n * @param nestProperty a term in the active context or `@nest`.\n * @param {Object} [options] - processing options.\n */\nfunction _checkNestProperty(activeCtx, nestProperty, options) {\n if(_expandIri(activeCtx, nestProperty, {vocab: true}, options) !== '@nest') {\n throw new JsonLdError(\n 'JSON-LD compact error; nested property must have an @nest value ' +\n 'resolving to @nest.',\n 'jsonld.SyntaxError', {code: 'invalid @nest value'});\n }\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nmodule.exports = jsonld => {\n class JsonLdProcessor {\n toString() {\n return '[object JsonLdProcessor]';\n }\n }\n Object.defineProperty(JsonLdProcessor, 'prototype', {\n writable: false,\n enumerable: false\n });\n Object.defineProperty(JsonLdProcessor.prototype, 'constructor', {\n writable: true,\n enumerable: false,\n configurable: true,\n value: JsonLdProcessor\n });\n\n // The Web IDL test harness will check the number of parameters defined in\n // the functions below. The number of parameters must exactly match the\n // required (non-optional) parameters of the JsonLdProcessor interface as\n // defined here:\n // https://www.w3.org/TR/json-ld-api/#the-jsonldprocessor-interface\n\n JsonLdProcessor.compact = function(input, ctx) {\n if(arguments.length < 2) {\n return Promise.reject(\n new TypeError('Could not compact, too few arguments.'));\n }\n return jsonld.compact(input, ctx);\n };\n JsonLdProcessor.expand = function(input) {\n if(arguments.length < 1) {\n return Promise.reject(\n new TypeError('Could not expand, too few arguments.'));\n }\n return jsonld.expand(input);\n };\n JsonLdProcessor.flatten = function(input) {\n if(arguments.length < 1) {\n return Promise.reject(\n new TypeError('Could not flatten, too few arguments.'));\n }\n return jsonld.flatten(input);\n };\n\n return JsonLdProcessor;\n};\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <http://feross.org>\n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return '<Buffer ' + str + '>'\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","// **N3Parser** parses N3 documents.\nimport N3Lexer from './N3Lexer';\nimport N3DataFactory from './N3DataFactory';\nimport namespaces from './IRIs';\n\nlet blankNodePrefix = 0;\n\n// ## Constructor\nexport default class N3Parser {\n constructor(options) {\n this._contextStack = [];\n this._graph = null;\n\n // Set the document IRI\n options = options || {};\n this._setBase(options.baseIRI);\n options.factory && initDataFactory(this, options.factory);\n\n // Set supported features depending on the format\n const format = (typeof options.format === 'string') ?\n options.format.match(/\\w*$/)[0].toLowerCase() : '',\n isTurtle = /turtle/.test(format), isTriG = /trig/.test(format),\n isNTriples = /triple/.test(format), isNQuads = /quad/.test(format),\n isN3 = this._n3Mode = /n3/.test(format),\n isLineMode = isNTriples || isNQuads;\n if (!(this._supportsNamedGraphs = !(isTurtle || isN3)))\n this._readPredicateOrNamedGraph = this._readPredicate;\n // Support triples in other graphs\n this._supportsQuads = !(isTurtle || isTriG || isNTriples || isN3);\n // Support nesting of triples\n this._supportsRDFStar = format === '' || /star|\\*$/.test(format);\n // Disable relative IRIs in N-Triples or N-Quads mode\n if (isLineMode)\n this._resolveRelativeIRI = iri => { return null; };\n this._blankNodePrefix = typeof options.blankNodePrefix !== 'string' ? '' :\n options.blankNodePrefix.replace(/^(?!_:)/, '_:');\n this._lexer = options.lexer || new N3Lexer({ lineMode: isLineMode, n3: isN3 });\n // Disable explicit quantifiers by default\n this._explicitQuantifiers = !!options.explicitQuantifiers;\n }\n\n // ## Static class methods\n\n // ### `_resetBlankNodePrefix` restarts blank node prefix identification\n static _resetBlankNodePrefix() {\n blankNodePrefix = 0;\n }\n\n // ## Private methods\n\n // ### `_setBase` sets the base IRI to resolve relative IRIs\n _setBase(baseIRI) {\n if (!baseIRI) {\n this._base = '';\n this._basePath = '';\n }\n else {\n // Remove fragment if present\n const fragmentPos = baseIRI.indexOf('#');\n if (fragmentPos >= 0)\n baseIRI = baseIRI.substr(0, fragmentPos);\n // Set base IRI and its components\n this._base = baseIRI;\n this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI :\n baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\\/\\/[^\\/]*)?/i);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n }\n\n // ### `_saveContext` stores the current parsing context\n // when entering a new scope (list, blank node, formula)\n _saveContext(type, graph, subject, predicate, object) {\n const n3Mode = this._n3Mode;\n this._contextStack.push({\n subject: subject, predicate: predicate, object: object,\n graph: graph, type: type,\n inverse: n3Mode ? this._inversePredicate : false,\n blankPrefix: n3Mode ? this._prefixes._ : '',\n quantified: n3Mode ? this._quantified : null,\n });\n // The settings below only apply to N3 streams\n if (n3Mode) {\n // Every new scope resets the predicate direction\n this._inversePredicate = false;\n // In N3, blank nodes are scoped to a formula\n // (using a dot as separator, as a blank node label cannot start with it)\n this._prefixes._ = (this._graph ? `${this._graph.id.substr(2)}.` : '.');\n // Quantifiers are scoped to a formula\n this._quantified = Object.create(this._quantified);\n }\n }\n\n // ### `_restoreContext` restores the parent context\n // when leaving a scope (list, blank node, formula)\n _restoreContext() {\n const context = this._contextStack.pop(), n3Mode = this._n3Mode;\n this._subject = context.subject;\n this._predicate = context.predicate;\n this._object = context.object;\n this._graph = context.graph;\n // The settings below only apply to N3 streams\n if (n3Mode) {\n this._inversePredicate = context.inverse;\n this._prefixes._ = context.blankPrefix;\n this._quantified = context.quantified;\n }\n }\n\n // ### `_readInTopContext` reads a token when in the top context\n _readInTopContext(token) {\n switch (token.type) {\n // If an EOF token arrives in the top context, signal that we're done\n case 'eof':\n if (this._graph !== null)\n return this._error('Unclosed graph', token);\n delete this._prefixes._;\n return this._callback(null, null, this._prefixes);\n // It could be a prefix declaration\n case 'PREFIX':\n this._sparqlStyle = true;\n case '@prefix':\n return this._readPrefix;\n // It could be a base declaration\n case 'BASE':\n this._sparqlStyle = true;\n case '@base':\n return this._readBaseIRI;\n // It could be a graph\n case '{':\n if (this._supportsNamedGraphs) {\n this._graph = '';\n this._subject = null;\n return this._readSubject;\n }\n case 'GRAPH':\n if (this._supportsNamedGraphs)\n return this._readNamedGraphLabel;\n // Otherwise, the next token must be a subject\n default:\n return this._readSubject(token);\n }\n }\n\n // ### `_readEntity` reads an IRI, prefixed name, blank node, or variable\n _readEntity(token, quantifier) {\n let value;\n switch (token.type) {\n // Read a relative or absolute IRI\n case 'IRI':\n case 'typeIRI':\n const iri = this._resolveIRI(token.value);\n if (iri === null)\n return this._error('Invalid IRI', token);\n value = this._namedNode(iri);\n break;\n // Read a prefixed name\n case 'type':\n case 'prefixed':\n const prefix = this._prefixes[token.prefix];\n if (prefix === undefined)\n return this._error(`Undefined prefix \"${token.prefix}:\"`, token);\n value = this._namedNode(prefix + token.value);\n break;\n // Read a blank node\n case 'blank':\n value = this._blankNode(this._prefixes[token.prefix] + token.value);\n break;\n // Read a variable\n case 'var':\n value = this._variable(token.value.substr(1));\n break;\n // Everything else is not an entity\n default:\n return this._error(`Expected entity but got ${token.type}`, token);\n }\n // In N3 mode, replace the entity if it is quantified\n if (!quantifier && this._n3Mode && (value.id in this._quantified))\n value = this._quantified[value.id];\n return value;\n }\n\n // ### `_readSubject` reads a quad's subject\n _readSubject(token) {\n this._predicate = null;\n switch (token.type) {\n case '[':\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph,\n this._subject = this._blankNode(), null, null);\n return this._readBlankNodeHead;\n case '(':\n // Start a new list\n this._saveContext('list', this._graph, this.RDF_NIL, null, null);\n this._subject = null;\n return this._readListItem;\n case '{':\n // Start a new formula\n if (!this._n3Mode)\n return this._error('Unexpected graph', token);\n this._saveContext('formula', this._graph,\n this._graph = this._blankNode(), null, null);\n return this._readSubject;\n case '}':\n // No subject; the graph in which we are reading is closed instead\n return this._readPunctuation(token);\n case '@forSome':\n if (!this._n3Mode)\n return this._error('Unexpected \"@forSome\"', token);\n this._subject = null;\n this._predicate = this.N3_FORSOME;\n this._quantifier = this._blankNode;\n return this._readQuantifierList;\n case '@forAll':\n if (!this._n3Mode)\n return this._error('Unexpected \"@forAll\"', token);\n this._subject = null;\n this._predicate = this.N3_FORALL;\n this._quantifier = this._variable;\n return this._readQuantifierList;\n case 'literal':\n if (!this._n3Mode)\n return this._error('Unexpected literal', token);\n\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n return this._completeSubjectLiteral;\n }\n else\n this._subject = this._literal(token.value, this._namedNode(token.prefix));\n\n break;\n case '<<':\n if (!this._supportsRDFStar)\n return this._error('Unexpected RDF* syntax', token);\n this._saveContext('<<', this._graph, null, null, null);\n this._graph = null;\n return this._readSubject;\n default:\n // Read the subject entity\n if ((this._subject = this._readEntity(token)) === undefined)\n return;\n // In N3 mode, the subject might be a path\n if (this._n3Mode)\n return this._getPathReader(this._readPredicateOrNamedGraph);\n }\n\n // The next token must be a predicate,\n // or, if the subject was actually a graph IRI, a named graph\n return this._readPredicateOrNamedGraph;\n }\n\n // ### `_readPredicate` reads a quad's predicate\n _readPredicate(token) {\n const type = token.type;\n switch (type) {\n case 'inverse':\n this._inversePredicate = true;\n case 'abbreviation':\n this._predicate = this.ABBREVIATIONS[token.value];\n break;\n case '.':\n case ']':\n case '}':\n // Expected predicate didn't come, must have been trailing semicolon\n if (this._predicate === null)\n return this._error(`Unexpected ${type}`, token);\n this._subject = null;\n return type === ']' ? this._readBlankNodeTail(token) : this._readPunctuation(token);\n case ';':\n // Additional semicolons can be safely ignored\n return this._predicate !== null ? this._readPredicate :\n this._error('Expected predicate but got ;', token);\n case 'blank':\n if (!this._n3Mode)\n return this._error('Disallowed blank node as predicate', token);\n default:\n if ((this._predicate = this._readEntity(token)) === undefined)\n return;\n }\n // The next token must be an object\n return this._readObject;\n }\n\n // ### `_readObject` reads a quad's object\n _readObject(token) {\n switch (token.type) {\n case 'literal':\n // Regular literal, can still get a datatype or language\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n return this._readDataTypeOrLang;\n }\n // Pre-datatyped string literal (prefix stores the datatype)\n else\n this._object = this._literal(token.value, this._namedNode(token.prefix));\n break;\n case '[':\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject, this._predicate,\n this._subject = this._blankNode());\n return this._readBlankNodeHead;\n case '(':\n // Start a new list\n this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL);\n this._subject = null;\n return this._readListItem;\n case '{':\n // Start a new formula\n if (!this._n3Mode)\n return this._error('Unexpected graph', token);\n this._saveContext('formula', this._graph, this._subject, this._predicate,\n this._graph = this._blankNode());\n return this._readSubject;\n case '<<':\n if (!this._supportsRDFStar)\n return this._error('Unexpected RDF* syntax', token);\n this._saveContext('<<', this._graph, this._subject, this._predicate, null);\n this._graph = null;\n return this._readSubject;\n default:\n // Read the object entity\n if ((this._object = this._readEntity(token)) === undefined)\n return;\n // In N3 mode, the object might be a path\n if (this._n3Mode)\n return this._getPathReader(this._getContextEndReader());\n }\n return this._getContextEndReader();\n }\n\n // ### `_readPredicateOrNamedGraph` reads a quad's predicate, or a named graph\n _readPredicateOrNamedGraph(token) {\n return token.type === '{' ? this._readGraph(token) : this._readPredicate(token);\n }\n\n // ### `_readGraph` reads a graph\n _readGraph(token) {\n if (token.type !== '{')\n return this._error(`Expected graph but got ${token.type}`, token);\n // The \"subject\" we read is actually the GRAPH's label\n this._graph = this._subject, this._subject = null;\n return this._readSubject;\n }\n\n // ### `_readBlankNodeHead` reads the head of a blank node\n _readBlankNodeHead(token) {\n if (token.type === ']') {\n this._subject = null;\n return this._readBlankNodeTail(token);\n }\n else {\n this._predicate = null;\n return this._readPredicate(token);\n }\n }\n\n // ### `_readBlankNodeTail` reads the end of a blank node\n _readBlankNodeTail(token) {\n if (token.type !== ']')\n return this._readBlankNodePunctuation(token);\n\n // Store blank node quad\n if (this._subject !== null)\n this._emit(this._subject, this._predicate, this._object, this._graph);\n\n // Restore the parent context containing this blank node\n const empty = this._predicate === null;\n this._restoreContext();\n // If the blank node was the subject, continue reading the predicate\n if (this._object === null)\n // If the blank node was empty, it could be a named graph label\n return empty ? this._readPredicateOrNamedGraph : this._readPredicateAfterBlank;\n // If the blank node was the object, restore previous context and read punctuation\n else\n return this._getContextEndReader();\n }\n\n // ### `_readPredicateAfterBlank` reads a predicate after an anonymous blank node\n _readPredicateAfterBlank(token) {\n switch (token.type) {\n case '.':\n case '}':\n // No predicate is coming if the triple is terminated here\n this._subject = null;\n return this._readPunctuation(token);\n default:\n return this._readPredicate(token);\n }\n }\n\n // ### `_readListItem` reads items from a list\n _readListItem(token) {\n let item = null, // The item of the list\n list = null, // The list itself\n next = this._readListItem; // The next function to execute\n const previousList = this._subject, // The previous list that contains this list\n stack = this._contextStack, // The stack of parent contexts\n parent = stack[stack.length - 1]; // The parent containing the current list\n\n switch (token.type) {\n case '[':\n // Stack the current list quad and start a new quad with a blank node as subject\n this._saveContext('blank', this._graph,\n list = this._blankNode(), this.RDF_FIRST,\n this._subject = item = this._blankNode());\n next = this._readBlankNodeHead;\n break;\n case '(':\n // Stack the current list quad and start a new list\n this._saveContext('list', this._graph,\n list = this._blankNode(), this.RDF_FIRST, this.RDF_NIL);\n this._subject = null;\n break;\n case ')':\n // Closing the list; restore the parent context\n this._restoreContext();\n // If this list is contained within a parent list, return the membership quad here.\n // This will be `<parent list element> rdf:first <this list>.`.\n if (stack.length !== 0 && stack[stack.length - 1].type === 'list')\n this._emit(this._subject, this._predicate, this._object, this._graph);\n // Was this list the parent's subject?\n if (this._predicate === null) {\n // The next token is the predicate\n next = this._readPredicate;\n // No list tail if this was an empty list\n if (this._subject === this.RDF_NIL)\n return next;\n }\n // The list was in the parent context's object\n else {\n next = this._getContextEndReader();\n // No list tail if this was an empty list\n if (this._object === this.RDF_NIL)\n return next;\n }\n // Close the list by making the head nil\n list = this.RDF_NIL;\n break;\n case 'literal':\n // Regular literal, can still get a datatype or language\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n next = this._readListItemDataTypeOrLang;\n }\n // Pre-datatyped string literal (prefix stores the datatype)\n else {\n item = this._literal(token.value, this._namedNode(token.prefix));\n next = this._getContextEndReader();\n }\n break;\n case '{':\n // Start a new formula\n if (!this._n3Mode)\n return this._error('Unexpected graph', token);\n this._saveContext('formula', this._graph, this._subject, this._predicate,\n this._graph = this._blankNode());\n return this._readSubject;\n default:\n if ((item = this._readEntity(token)) === undefined)\n return;\n }\n\n // Create a new blank node if no item head was assigned yet\n if (list === null)\n this._subject = list = this._blankNode();\n\n // Is this the first element of the list?\n if (previousList === null) {\n // This list is either the subject or the object of its parent\n if (parent.predicate === null)\n parent.subject = list;\n else\n parent.object = list;\n }\n else {\n // Continue the previous list with the current list\n this._emit(previousList, this.RDF_REST, list, this._graph);\n }\n // If an item was read, add it to the list\n if (item !== null) {\n // In N3 mode, the item might be a path\n if (this._n3Mode && (token.type === 'IRI' || token.type === 'prefixed')) {\n // Create a new context to add the item's path\n this._saveContext('item', this._graph, list, this.RDF_FIRST, item);\n this._subject = item, this._predicate = null;\n // _readPath will restore the context and output the item\n return this._getPathReader(this._readListItem);\n }\n // Output the item\n this._emit(list, this.RDF_FIRST, item, this._graph);\n }\n return next;\n }\n\n // ### `_readDataTypeOrLang` reads an _optional_ datatype or language\n _readDataTypeOrLang(token) {\n return this._completeObjectLiteral(token, false);\n }\n\n\n // ### `_readListItemDataTypeOrLang` reads an _optional_ datatype or language in a list\n _readListItemDataTypeOrLang(token) {\n return this._completeObjectLiteral(token, true);\n }\n\n // ### `_completeLiteral` completes a literal with an optional datatype or language\n _completeLiteral(token) {\n // Create a simple string literal by default\n let literal = this._literal(this._literalValue);\n\n switch (token.type) {\n // Create a datatyped literal\n case 'type':\n case 'typeIRI':\n const datatype = this._readEntity(token);\n if (datatype === undefined) return; // No datatype means an error occurred\n literal = this._literal(this._literalValue, datatype);\n token = null;\n break;\n // Create a language-tagged string\n case 'langcode':\n literal = this._literal(this._literalValue, token.value);\n token = null;\n break;\n }\n\n return { token, literal };\n }\n\n // Completes a literal in subject position\n _completeSubjectLiteral(token) {\n this._subject = this._completeLiteral(token).literal;\n return this._readPredicateOrNamedGraph;\n }\n\n // Completes a literal in object position\n _completeObjectLiteral(token, listItem) {\n const completed = this._completeLiteral(token);\n if (!completed)\n return;\n this._object = completed.literal;\n\n // If this literal was part of a list, write the item\n // (we could also check the context stack, but passing in a flag is faster)\n if (listItem)\n this._emit(this._subject, this.RDF_FIRST, this._object, this._graph);\n // If the token was consumed, continue with the rest of the input\n if (completed.token === null)\n return this._getContextEndReader();\n // Otherwise, consume the token now\n else {\n this._readCallback = this._getContextEndReader();\n return this._readCallback(completed.token);\n }\n }\n\n // ### `_readFormulaTail` reads the end of a formula\n _readFormulaTail(token) {\n if (token.type !== '}')\n return this._readPunctuation(token);\n\n // Store the last quad of the formula\n if (this._subject !== null)\n this._emit(this._subject, this._predicate, this._object, this._graph);\n\n // Restore the parent context containing this formula\n this._restoreContext();\n // If the formula was the subject, continue reading the predicate.\n // If the formula was the object, read punctuation.\n return this._object === null ? this._readPredicate : this._getContextEndReader();\n }\n\n // ### `_readPunctuation` reads punctuation between quads or quad parts\n _readPunctuation(token) {\n let next, graph = this._graph;\n const subject = this._subject, inversePredicate = this._inversePredicate;\n switch (token.type) {\n // A closing brace ends a graph\n case '}':\n if (this._graph === null)\n return this._error('Unexpected graph closing', token);\n if (this._n3Mode)\n return this._readFormulaTail(token);\n this._graph = null;\n // A dot just ends the statement, without sharing anything with the next\n case '.':\n this._subject = null;\n next = this._contextStack.length ? this._readSubject : this._readInTopContext;\n if (inversePredicate) this._inversePredicate = false;\n break;\n // Semicolon means the subject is shared; predicate and object are different\n case ';':\n next = this._readPredicate;\n break;\n // Comma means both the subject and predicate are shared; the object is different\n case ',':\n next = this._readObject;\n break;\n default:\n // An entity means this is a quad (only allowed if not already inside a graph)\n if (this._supportsQuads && this._graph === null && (graph = this._readEntity(token)) !== undefined) {\n next = this._readQuadPunctuation;\n break;\n }\n return this._error(`Expected punctuation to follow \"${this._object.id}\"`, token);\n }\n // A quad has been completed now, so return it\n if (subject !== null) {\n const predicate = this._predicate, object = this._object;\n if (!inversePredicate)\n this._emit(subject, predicate, object, graph);\n else\n this._emit(object, predicate, subject, graph);\n }\n return next;\n }\n\n // ### `_readBlankNodePunctuation` reads punctuation in a blank node\n _readBlankNodePunctuation(token) {\n let next;\n switch (token.type) {\n // Semicolon means the subject is shared; predicate and object are different\n case ';':\n next = this._readPredicate;\n break;\n // Comma means both the subject and predicate are shared; the object is different\n case ',':\n next = this._readObject;\n break;\n default:\n return this._error(`Expected punctuation to follow \"${this._object.id}\"`, token);\n }\n // A quad has been completed now, so return it\n this._emit(this._subject, this._predicate, this._object, this._graph);\n return next;\n }\n\n // ### `_readQuadPunctuation` reads punctuation after a quad\n _readQuadPunctuation(token) {\n if (token.type !== '.')\n return this._error('Expected dot to follow quad', token);\n return this._readInTopContext;\n }\n\n // ### `_readPrefix` reads the prefix of a prefix declaration\n _readPrefix(token) {\n if (token.type !== 'prefix')\n return this._error('Expected prefix to follow @prefix', token);\n this._prefix = token.value;\n return this._readPrefixIRI;\n }\n\n // ### `_readPrefixIRI` reads the IRI of a prefix declaration\n _readPrefixIRI(token) {\n if (token.type !== 'IRI')\n return this._error(`Expected IRI to follow prefix \"${this._prefix}:\"`, token);\n const prefixNode = this._readEntity(token);\n this._prefixes[this._prefix] = prefixNode.value;\n this._prefixCallback(this._prefix, prefixNode);\n return this._readDeclarationPunctuation;\n }\n\n // ### `_readBaseIRI` reads the IRI of a base declaration\n _readBaseIRI(token) {\n const iri = token.type === 'IRI' && this._resolveIRI(token.value);\n if (!iri)\n return this._error('Expected valid IRI to follow base declaration', token);\n this._setBase(iri);\n return this._readDeclarationPunctuation;\n }\n\n // ### `_readNamedGraphLabel` reads the label of a named graph\n _readNamedGraphLabel(token) {\n switch (token.type) {\n case 'IRI':\n case 'blank':\n case 'prefixed':\n return this._readSubject(token), this._readGraph;\n case '[':\n return this._readNamedGraphBlankLabel;\n default:\n return this._error('Invalid graph label', token);\n }\n }\n\n // ### `_readNamedGraphLabel` reads a blank node label of a named graph\n _readNamedGraphBlankLabel(token) {\n if (token.type !== ']')\n return this._error('Invalid graph label', token);\n this._subject = this._blankNode();\n return this._readGraph;\n }\n\n // ### `_readDeclarationPunctuation` reads the punctuation of a declaration\n _readDeclarationPunctuation(token) {\n // SPARQL-style declarations don't have punctuation\n if (this._sparqlStyle) {\n this._sparqlStyle = false;\n return this._readInTopContext(token);\n }\n\n if (token.type !== '.')\n return this._error('Expected declaration to end with a dot', token);\n return this._readInTopContext;\n }\n\n // Reads a list of quantified symbols from a @forSome or @forAll statement\n _readQuantifierList(token) {\n let entity;\n switch (token.type) {\n case 'IRI':\n case 'prefixed':\n if ((entity = this._readEntity(token, true)) !== undefined)\n break;\n default:\n return this._error(`Unexpected ${token.type}`, token);\n }\n // Without explicit quantifiers, map entities to a quantified entity\n if (!this._explicitQuantifiers)\n this._quantified[entity.id] = this._quantifier(this._blankNode().value);\n // With explicit quantifiers, output the reified quantifier\n else {\n // If this is the first item, start a new quantifier list\n if (this._subject === null)\n this._emit(this._graph || this.DEFAULTGRAPH, this._predicate,\n this._subject = this._blankNode(), this.QUANTIFIERS_GRAPH);\n // Otherwise, continue the previous list\n else\n this._emit(this._subject, this.RDF_REST,\n this._subject = this._blankNode(), this.QUANTIFIERS_GRAPH);\n // Output the list item\n this._emit(this._subject, this.RDF_FIRST, entity, this.QUANTIFIERS_GRAPH);\n }\n return this._readQuantifierPunctuation;\n }\n\n // Reads punctuation from a @forSome or @forAll statement\n _readQuantifierPunctuation(token) {\n // Read more quantifiers\n if (token.type === ',')\n return this._readQuantifierList;\n // End of the quantifier list\n else {\n // With explicit quantifiers, close the quantifier list\n if (this._explicitQuantifiers) {\n this._emit(this._subject, this.RDF_REST, this.RDF_NIL, this.QUANTIFIERS_GRAPH);\n this._subject = null;\n }\n // Read a dot\n this._readCallback = this._getContextEndReader();\n return this._readCallback(token);\n }\n }\n\n // ### `_getPathReader` reads a potential path and then resumes with the given function\n _getPathReader(afterPath) {\n this._afterPath = afterPath;\n return this._readPath;\n }\n\n // ### `_readPath` reads a potential path\n _readPath(token) {\n switch (token.type) {\n // Forward path\n case '!': return this._readForwardPath;\n // Backward path\n case '^': return this._readBackwardPath;\n // Not a path; resume reading where we left off\n default:\n const stack = this._contextStack, parent = stack.length && stack[stack.length - 1];\n // If we were reading a list item, we still need to output it\n if (parent && parent.type === 'item') {\n // The list item is the remaining subejct after reading the path\n const item = this._subject;\n // Switch back to the context of the list\n this._restoreContext();\n // Output the list item\n this._emit(this._subject, this.RDF_FIRST, item, this._graph);\n }\n return this._afterPath(token);\n }\n }\n\n // ### `_readForwardPath` reads a '!' path\n _readForwardPath(token) {\n let subject, predicate;\n const object = this._blankNode();\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's object\n if (this._predicate === null)\n subject = this._subject, this._subject = object;\n // If we were reading an object, replace the subject by the path's object\n else\n subject = this._object, this._object = object;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }\n\n // ### `_readBackwardPath` reads a '^' path\n _readBackwardPath(token) {\n const subject = this._blankNode();\n let predicate, object;\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's subject\n if (this._predicate === null)\n object = this._subject, this._subject = subject;\n // If we were reading an object, replace the subject by the path's subject\n else\n object = this._object, this._object = subject;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }\n\n // ### `_readRDFStarTailOrGraph` reads the graph of a nested RDF* quad or the end of a nested RDF* triple\n _readRDFStarTailOrGraph(token) {\n if (token.type !== '>>') {\n // An entity means this is a quad (only allowed if not already inside a graph)\n if (this._supportsQuads && this._graph === null && (this._graph = this._readEntity(token)) !== undefined)\n return this._readRDFStarTail;\n return this._error(`Expected >> to follow \"${this._object.id}\"`, token);\n }\n return this._readRDFStarTail(token);\n }\n\n // ### `_readRDFStarTail` reads the end of a nested RDF* triple\n _readRDFStarTail(token) {\n if (token.type !== '>>')\n return this._error(`Expected >> but got ${token.type}`, token);\n // Read the quad and restore the previous context\n const quad = this._quad(this._subject, this._predicate, this._object,\n this._graph || this.DEFAULTGRAPH);\n this._restoreContext();\n // If the triple was the subject, continue by reading the predicate.\n if (this._subject === null) {\n this._subject = quad;\n return this._readPredicate;\n }\n // If the triple was the object, read context end.\n else {\n this._object = quad;\n return this._getContextEndReader();\n }\n }\n\n // ### `_getContextEndReader` gets the next reader function at the end of a context\n _getContextEndReader() {\n const contextStack = this._contextStack;\n if (!contextStack.length)\n return this._readPunctuation;\n\n switch (contextStack[contextStack.length - 1].type) {\n case 'blank':\n return this._readBlankNodeTail;\n case 'list':\n return this._readListItem;\n case 'formula':\n return this._readFormulaTail;\n case '<<':\n return this._readRDFStarTailOrGraph;\n }\n }\n\n // ### `_emit` sends a quad through the callback\n _emit(subject, predicate, object, graph) {\n this._callback(null, this._quad(subject, predicate, object, graph || this.DEFAULTGRAPH));\n }\n\n // ### `_error` emits an error message through the callback\n _error(message, token) {\n const err = new Error(`${message} on line ${token.line}.`);\n err.context = {\n token: token,\n line: token.line,\n previousToken: this._lexer.previousToken,\n };\n this._callback(err);\n this._callback = noop;\n }\n\n // ### `_resolveIRI` resolves an IRI against the base path\n _resolveIRI(iri) {\n return /^[a-z][a-z0-9+.-]*:/i.test(iri) ? iri : this._resolveRelativeIRI(iri);\n }\n\n // ### `_resolveRelativeIRI` resolves an IRI against the base path,\n // assuming that a base path has been set and that the IRI is indeed relative\n _resolveRelativeIRI(iri) {\n // An empty relative IRI indicates the base IRI\n if (!iri.length)\n return this._base;\n // Decide resolving strategy based in the first character\n switch (iri[0]) {\n // Resolve relative fragment IRIs against the base IRI\n case '#': return this._base + iri;\n // Resolve relative query string IRIs by replacing the query string\n case '?': return this._base.replace(/(?:\\?.*)?$/, iri);\n // Resolve root-relative IRIs at the root of the base IRI\n case '/':\n // Resolve scheme-relative IRIs to the scheme\n return (iri[1] === '/' ? this._baseScheme : this._baseRoot) + this._removeDotSegments(iri);\n // Resolve all other IRIs at the base IRI's path\n default:\n // Relative IRIs cannot contain a colon in the first path segment\n return (/^[^/:]*:/.test(iri)) ? null : this._removeDotSegments(this._basePath + iri);\n }\n }\n\n // ### `_removeDotSegments` resolves './' and '../' path segments in an IRI as per RFC3986\n _removeDotSegments(iri) {\n // Don't modify the IRI if it does not contain any dot segments\n if (!/(^|\\/)\\.\\.?($|[/#?])/.test(iri))\n return iri;\n\n // Start with an imaginary slash before the IRI in order to resolve trailing './' and '../'\n const length = iri.length;\n let result = '', i = -1, pathStart = -1, segmentStart = 0, next = '/';\n\n while (i < length) {\n switch (next) {\n // The path starts with the first slash after the authority\n case ':':\n if (pathStart < 0) {\n // Skip two slashes before the authority\n if (iri[++i] === '/' && iri[++i] === '/')\n // Skip to slash after the authority\n while ((pathStart = i + 1) < length && iri[pathStart] !== '/')\n i = pathStart;\n }\n break;\n // Don't modify a query string or fragment\n case '?':\n case '#':\n i = length;\n break;\n // Handle '/.' or '/..' path segments\n case '/':\n if (iri[i + 1] === '.') {\n next = iri[++i + 1];\n switch (next) {\n // Remove a '/.' segment\n case '/':\n result += iri.substring(segmentStart, i - 1);\n segmentStart = i + 1;\n break;\n // Remove a trailing '/.' segment\n case undefined:\n case '?':\n case '#':\n return result + iri.substring(segmentStart, i) + iri.substr(i + 1);\n // Remove a '/..' segment\n case '.':\n next = iri[++i + 1];\n if (next === undefined || next === '/' || next === '?' || next === '#') {\n result += iri.substring(segmentStart, i - 2);\n // Try to remove the parent path from result\n if ((segmentStart = result.lastIndexOf('/')) >= pathStart)\n result = result.substr(0, segmentStart);\n // Remove a trailing '/..' segment\n if (next !== '/')\n return `${result}/${iri.substr(i + 1)}`;\n segmentStart = i + 1;\n }\n }\n }\n }\n next = iri[++i];\n }\n return result + iri.substring(segmentStart);\n }\n\n // ## Public methods\n\n // ### `parse` parses the N3 input and emits each parsed quad through the callback\n parse(input, quadCallback, prefixCallback) {\n // The read callback is the next function to be executed when a token arrives.\n // We start reading in the top context.\n this._readCallback = this._readInTopContext;\n this._sparqlStyle = false;\n this._prefixes = Object.create(null);\n this._prefixes._ = this._blankNodePrefix ? this._blankNodePrefix.substr(2)\n : `b${blankNodePrefix++}_`;\n this._prefixCallback = prefixCallback || noop;\n this._inversePredicate = false;\n this._quantified = Object.create(null);\n\n // Parse synchronously if no quad callback is given\n if (!quadCallback) {\n const quads = [];\n let error;\n this._callback = (e, t) => { e ? (error = e) : t && quads.push(t); };\n this._lexer.tokenize(input).every(token => {\n return this._readCallback = this._readCallback(token);\n });\n if (error) throw error;\n return quads;\n }\n\n // Parse asynchronously otherwise, executing the read callback when a token arrives\n this._callback = quadCallback;\n this._lexer.tokenize(input, (error, token) => {\n if (error !== null)\n this._callback(error), this._callback = noop;\n else if (this._readCallback)\n this._readCallback = this._readCallback(token);\n });\n }\n}\n\n// The empty function\nfunction noop() {}\n\n// Initializes the parser with the given data factory\nfunction initDataFactory(parser, factory) {\n // Set factory methods\n const namedNode = factory.namedNode;\n parser._namedNode = namedNode;\n parser._blankNode = factory.blankNode;\n parser._literal = factory.literal;\n parser._variable = factory.variable;\n parser._quad = factory.quad;\n parser.DEFAULTGRAPH = factory.defaultGraph();\n\n // Set common named nodes\n parser.RDF_FIRST = namedNode(namespaces.rdf.first);\n parser.RDF_REST = namedNode(namespaces.rdf.rest);\n parser.RDF_NIL = namedNode(namespaces.rdf.nil);\n parser.N3_FORALL = namedNode(namespaces.r.forAll);\n parser.N3_FORSOME = namedNode(namespaces.r.forSome);\n parser.ABBREVIATIONS = {\n 'a': namedNode(namespaces.rdf.type),\n '=': namedNode(namespaces.owl.sameAs),\n '>': namedNode(namespaces.log.implies),\n };\n parser.QUANTIFIERS_GRAPH = namedNode('urn:n3:quantifiers');\n}\ninitDataFactory(N3Parser.prototype, N3DataFactory);\n"],"sourceRoot":""}
|