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yB,EAAM,CACN7B,GAAwB,EACxB,KAjCZ,SAAa6B,GACT,IAAIH,EAAWG,EAAKH,SAChBE,EAAOC,EAAKD,KAChB,OAAQA,EAAK34B,QACb,KAAK,EACDy4B,IACA,MACJ,KAAK,EACDA,EAASE,EAAK,IACd,MACJ,KAAK,EACDF,EAASE,EAAK,GAAIA,EAAK,IACvB,MACJ,KAAK,EACDF,EAASE,EAAK,GAAIA,EAAK,GAAIA,EAAK,IAChC,MACJ,QACIF,EAASvzB,MAnDrB,UAmDsCyzB,GAGlC,CAcgBG,CAAIF,EACR,CAAE,QACEC,EAAe1B,GACfJ,GAAwB,CAC5B,CACJ,CACJ,CACJ,CA8GJ,CAzLA,CAyLkB,oBAAT/xB,UAAyC,IAAX,EAAA6sB,EAAyBvwB,KAAO,EAAAuwB,EAAS7sB","sources":["webpack://$rdf/./node_modules/canonicalize/lib/canonicalize.js","webpack://$rdf/./node_modules/jsonld/lib/ContextResolver.js","webpack://$rdf/./node_modules/jsonld/lib/JsonLdError.js","webpack://$rdf/./node_modules/jsonld/lib/JsonLdProcessor.js","webpack://$rdf/./node_modules/jsonld/lib/NQuads.js","webpack://$rdf/./node_modules/jsonld/lib/RequestQueue.js","webpack://$rdf/./node_modules/jsonld/lib/ResolvedContext.js","webpack://$rdf/./node_modules/jsonld/lib/compact.js","webpack://$rdf/./node_modules/jsonld/lib/constants.js","webpack://$rdf/./node_modules/jsonld/lib/context.js","webpack://$rdf/./node_modules/jsonld/lib/documentLoaders/xhr.js","webpack://$rdf/./node_modules/jsonld/lib/events.js","webpack://$rdf/./node_modules/jsonld/lib/expand.js","webpack://$rdf/./node_modules/jsonld/lib/flatten.js","webpack://$rdf/./node_modules/jsonld/lib/frame.js","webpack://$rdf/./node_modules/jsonld/lib/fromRdf.js","webpack://$rdf/./node_modules/jsonld/lib/graphTypes.js","webpack://$rdf/./node_modules/jsonld/lib/jsonld.js","webpack://$rdf/./node_modules/jsonld/lib/nodeMap.js","webpack://$rdf/./node_modules/jsonld/lib/platform-browser.js","webpack://$rdf/./node_modules/jsonld/lib/toRdf.js","webpack://$rdf/./node_modules/jsonld/lib/types.js","webpack://$rdf/./node_modules/jsonld/lib/url.js","webpack://$rdf/./node_modules/jsonld/lib/util.js","webpack://$rdf/./node_modules/jsonld/node_modules/lru-cache/index.js","webpack://$rdf/./node_modules/jsonld/node_modules/yallist/iterator.js","webpack://$rdf/./node_modules/jsonld/node_modules/yallist/yallist.js","webpack://$rdf/./node_modules/rdf-canonize/index.js","webpack://$rdf/./node_modules/rdf-canonize/lib/IdentifierIssuer.js","webpack://$rdf/./node_modules/rdf-canonize/lib/MessageDigest-browser.js","webpack://$rdf/./node_modules/rdf-canonize/lib/NQuads.js","webpack://$rdf/./node_modules/rdf-canonize/lib/Permuter.js","webpack://$rdf/./node_modules/rdf-canonize/lib/URDNA2015.js","webpack://$rdf/./node_modules/rdf-canonize/lib/URDNA2015Sync.js","webpack://$rdf/./node_modules/rdf-canonize/lib/URGNA2012.js","webpack://$rdf/./node_modules/rdf-canonize/lib/URGNA2012Sync.js","webpack://$rdf/./node_modules/rdf-canonize/lib/index.js","webpack://$rdf/./node_modules/setimmediate/setImmediate.js"],"sourcesContent":["/* 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) 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) 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\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 * 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-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","/*\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","/*\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 REGEX_KEYWORD,\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 *\n * @return a promise that resolves to the compacted value.\n */\napi.compact = async ({\n activeCtx,\n activeProperty = null,\n element,\n options = {}\n}) => {\n // recursively compact array\n if(_isArray(element)) {\n let rval = [];\n for(let i = 0; i < element.length; ++i) {\n const compacted = await api.compact({\n activeCtx,\n activeProperty,\n element: element[i],\n options\n });\n if(compacted === null) {\n // FIXME: need event?\n continue;\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 });\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 });\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 });\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 });\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 });\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 const _iri = _removeBase(_prependBase(base, activeCtx['@base']), iri);\n return REGEX_KEYWORD.test(_iri) ? `./${_iri}` : _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\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","/*\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 handleEvent: _handleEvent\n} = require('./events');\n\nconst {\n REGEX_BCP47,\n REGEX_KEYWORD,\n asArray: _asArray,\n compareShortestLeast: _compareShortestLeast\n} = require('./util');\n\nconst INITIAL_CONTEXT_CACHE = new Map();\nconst INITIAL_CONTEXT_CACHE_MAX_SIZE = 10000;\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 // event handler for capturing events to replay when using a cached context\n const events = [];\n const eventCaptureHandler = [\n ({event, next}) => {\n events.push(event);\n next();\n }\n ];\n // chain to original handler\n if(options.eventHandler) {\n eventCaptureHandler.push(options.eventHandler);\n }\n // store original options to use when replaying events\n const originalOptions = options;\n // shallow clone options with event capture handler\n options = {...options, eventHandler: eventCaptureHandler};\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 && Object.keys(activeCtx.protected).length !== 0) {\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 }\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 if(originalOptions.eventHandler) {\n // replay events with original non-capturing options\n for(const event of processed.events) {\n _handleEvent({event, options: originalOptions});\n }\n }\n\n rval = activeCtx = processed.context;\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 const vocab = _expandIri(rval, value, {vocab: true, base: true},\n undefined, undefined, options);\n if(!_isAbsoluteIri(vocab)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative @vocab reference',\n level: 'warning',\n message: 'Relative @vocab reference found.',\n details: {\n vocab\n }\n },\n options\n });\n }\n }\n rval['@vocab'] = vocab;\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 if(!value.match(REGEX_BCP47)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language: value\n }\n },\n options\n });\n }\n }\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, {\n context: rval,\n events\n });\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 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(REGEX_KEYWORD)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved term',\n level: 'warning',\n message:\n 'Terms beginning with \"@\" are ' +\n 'reserved for future use and dropped.',\n details: {\n term\n }\n },\n options\n });\n }\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(reverse.match(REGEX_KEYWORD)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved @reverse value',\n level: 'warning',\n message:\n '@reverse values beginning with \"@\" are ' +\n 'reserved for future use and dropped.',\n details: {\n reverse\n }\n },\n options\n });\n }\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(REGEX_KEYWORD)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved @id value',\n level: 'warning',\n message:\n '@id values beginning with \"@\" are ' +\n 'reserved for future use and dropped.',\n details: {\n id\n }\n },\n options\n });\n }\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(/[:\\/\\?#\\[\\]@]$/) !== null);\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 throw new JsonLdError(\n 'Invalid JSON-LD syntax; tried to redefine a protected term.',\n 'jsonld.SyntaxError',\n {code: 'protected term redefinition', context: localCtx, term});\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(REGEX_KEYWORD)) {\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 // A flag that captures whether the iri being expanded is\n // the value for an @type\n //let typeExpansion = false;\n\n //if(options !== undefined && options.typeExpansion !== undefined) {\n // typeExpansion = options.typeExpansion;\n //}\n\n if(relativeTo.vocab && '@vocab' in activeCtx) {\n // prepend vocab\n const prependedResult = activeCtx['@vocab'] + value;\n // FIXME: needed? may be better as debug event.\n /*\n if(options && options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'prepending @vocab during expansion',\n level: 'info',\n message: 'Prepending @vocab during expansion.',\n details: {\n type: '@vocab',\n vocab: activeCtx['@vocab'],\n value,\n result: prependedResult,\n typeExpansion\n }\n },\n options\n });\n }\n */\n // the null case preserves value as potentially relative\n value = prependedResult;\n } else if(relativeTo.base) {\n // prepend base\n let prependedResult;\n let base;\n if('@base' in activeCtx) {\n if(activeCtx['@base']) {\n base = prependBase(options.base, activeCtx['@base']);\n prependedResult = prependBase(base, value);\n } else {\n base = activeCtx['@base'];\n prependedResult = value;\n }\n } else {\n base = options.base;\n prependedResult = prependBase(options.base, value);\n }\n // FIXME: needed? may be better as debug event.\n /*\n if(options && options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'prepending @base during expansion',\n level: 'info',\n message: 'Prepending @base during expansion.',\n details: {\n type: '@base',\n base,\n value,\n result: prependedResult,\n typeExpansion\n }\n },\n options\n });\n }\n */\n // the null case preserves value as potentially relative\n value = prependedResult;\n }\n\n // FIXME: duplicate? needed? maybe just enable in a verbose debug mode\n /*\n if(!_isAbsoluteIri(value) && options && options.eventHandler) {\n // emit event indicating a relative IRI was found, which can result in it\n // being dropped when converting to other RDF representations\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative IRI after expansion',\n // FIXME: what level?\n level: 'warning',\n message: 'Relative IRI after expansion.',\n details: {\n relativeIri: value,\n typeExpansion\n }\n },\n options\n });\n // NOTE: relative reference events emitted at calling sites as needed\n }\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","/*\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) 2020 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst JsonLdError = require('./JsonLdError');\n\nconst {\n isArray: _isArray\n} = require('./types');\n\nconst {\n asArray: _asArray\n} = require('./util');\n\nconst api = {};\nmodule.exports = api;\n\n// default handler, store as null or an array\n// exposed to allow fast external pre-handleEvent() checks\napi.defaultEventHandler = null;\n\n/**\n * Setup event handler.\n *\n * Return an array event handler constructed from an optional safe mode\n * handler, an optional options event handler, and an optional default handler.\n *\n * @param {object} options - processing options\n * {function|object|array} [eventHandler] - an event handler.\n *\n * @return an array event handler.\n */\napi.setupEventHandler = ({options = {}}) => {\n // build in priority order\n const eventHandler = [].concat(\n options.safe ? api.safeEventHandler : [],\n options.eventHandler ? _asArray(options.eventHandler) : [],\n api.defaultEventHandler ? api.defaultEventHandler : []\n );\n // null if no handlers\n return eventHandler.length === 0 ? null : eventHandler;\n};\n\n/**\n * Handle an event.\n *\n * Top level APIs have a common 'eventHandler' option. This option can be a\n * function, array of functions, object mapping event.code to functions (with a\n * default to call next()), or any combination of such handlers. Handlers will\n * be called with an object with an 'event' entry and a 'next' function. Custom\n * handlers should process the event as appropriate. The 'next()' function\n * should be called to let the next handler process the event.\n *\n * NOTE: Only call this function if options.eventHandler is set and is an\n * array of hanlers. This is an optimization. Callers are expected to check\n * for an event handler before constructing events and calling this function.\n *\n * @param {object} event - event structure:\n * {string} code - event code\n * {string} level - severity level, one of: ['warning']\n * {string} message - human readable message\n * {object} details - event specific details\n * @param {object} options - processing options\n * {array} eventHandler - an event handler array.\n */\napi.handleEvent = ({\n event,\n options\n}) => {\n _handle({event, handlers: options.eventHandler});\n};\n\nfunction _handle({event, handlers}) {\n let doNext = true;\n for(let i = 0; doNext && i < handlers.length; ++i) {\n doNext = false;\n const handler = handlers[i];\n if(_isArray(handler)) {\n doNext = _handle({event, handlers: handler});\n } else if(typeof handler === 'function') {\n handler({event, next: () => {\n doNext = true;\n }});\n } else if(typeof handler === 'object') {\n if(event.code in handler) {\n handler[event.code]({event, next: () => {\n doNext = true;\n }});\n } else {\n doNext = true;\n }\n } else {\n throw new JsonLdError(\n 'Invalid event handler.',\n 'jsonld.InvalidEventHandler',\n {event});\n }\n }\n return doNext;\n}\n\nconst _notSafeEventCodes = new Set([\n 'empty object',\n 'free-floating scalar',\n 'invalid @language value',\n 'invalid property',\n // NOTE: spec edge case\n 'null @id value',\n 'null @value value',\n 'object with only @id',\n 'object with only @language',\n 'object with only @list',\n 'object with only @value',\n 'relative @id reference',\n 'relative @type reference',\n 'relative @vocab reference',\n 'reserved @id value',\n 'reserved @reverse value',\n 'reserved term',\n // toRDF\n 'blank node predicate',\n 'relative graph reference',\n 'relative object reference',\n 'relative predicate reference',\n 'relative subject reference',\n // toRDF / fromRDF\n 'rdfDirection not set'\n]);\n\n// safe handler that rejects unsafe warning conditions\napi.safeEventHandler = function safeEventHandler({event, next}) {\n // fail on all unsafe warnings\n if(event.level === 'warning' && _notSafeEventCodes.has(event.code)) {\n throw new JsonLdError(\n 'Safe mode validation error.',\n 'jsonld.ValidationError',\n {event}\n );\n }\n next();\n};\n\n// logs all events and continues\napi.logEventHandler = function logEventHandler({event, next}) {\n console.log(`EVENT: ${event.message}`, {event});\n next();\n};\n\n// log 'warning' level events\napi.logWarningEventHandler = function logWarningEventHandler({event, next}) {\n if(event.level === 'warning') {\n console.warn(`WARNING: ${event.message}`, {event});\n }\n next();\n};\n\n// fallback to throw errors for any unhandled events\napi.unhandledEventHandler = function unhandledEventHandler({event}) {\n throw new JsonLdError(\n 'No handler for event.',\n 'jsonld.UnhandledEvent',\n {event}\n );\n};\n\n/**\n * Set default event handler.\n *\n * By default, all event are unhandled. It is recommended to pass in an\n * eventHandler into each call. However, this call allows using a default\n * eventHandler when one is not otherwise provided.\n *\n * @param {object} options - default handler options:\n * {function|object|array} eventHandler - a default event handler.\n * falsey to unset.\n */\napi.setDefaultEventHandler = function({eventHandler} = {}) {\n api.defaultEventHandler = eventHandler ? _asArray(eventHandler) : null;\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 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 REGEX_BCP47,\n REGEX_KEYWORD,\n addValue: _addValue,\n asArray: _asArray,\n getValues: _getValues,\n validateTypeValue: _validateTypeValue\n} = require('./util');\n\nconst {\n handleEvent: _handleEvent\n} = require('./events');\n\nconst api = {};\nmodule.exports = api;\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 *\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}) => {\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\n if(!insideList && (activeProperty === null ||\n _expandIri(activeCtx, activeProperty, {vocab: true},\n options) === '@graph')) {\n // FIXME\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'free-floating scalar',\n level: 'warning',\n message: 'Dropping free-floating scalar not in a list.',\n details: {\n value: element\n //activeProperty\n //insideList\n }\n },\n options\n });\n }\n return null;\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 insideIndex,\n typeScopedContext\n });\n if(insideList && _isArray(e)) {\n e = {'@list': e};\n }\n\n if(e === null) {\n // FIXME: add debug event?\n //unmappedValue: element[i],\n //activeProperty,\n //parent: element,\n //index: i,\n //expandedParent: rval,\n //insideList\n\n // NOTE: no-value events emitted at calling sites as needed\n continue;\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 });\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\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 // FIXME\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'null @value value',\n level: 'warning',\n message: 'Dropping null @value value.',\n details: {\n value: rval\n }\n },\n options\n });\n }\n rval = null;\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\n // FIXME\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'object with only @language',\n level: 'warning',\n message: 'Dropping object with only @language.',\n details: {\n value: rval\n }\n },\n options\n });\n }\n rval = null;\n }\n\n // drop certain top-level objects that do not occur in lists\n if(_isObject(rval) &&\n !options.keepFreeFloatingNodes && !insideList &&\n (activeProperty === null ||\n expandedActiveProperty === '@graph' ||\n (_getContextValue(activeCtx, activeProperty, '@container') || [])\n .includes('@graph')\n )) {\n // drop empty object, top-level @value/@list, or object with only @id\n rval = _dropUnsafeObject({value: rval, count, options});\n }\n\n return rval;\n};\n\n/**\n * Drop empty object, top-level @value/@list, or object with only @id\n *\n * @param value Value to check.\n * @param count Number of properties in object.\n * @param options The expansion options.\n *\n * @return null if dropped, value otherwise.\n */\nfunction _dropUnsafeObject({\n value,\n count,\n options\n}) {\n if(count === 0 || '@value' in value || '@list' in value ||\n (count === 1 && '@id' in value)) {\n // FIXME\n if(options.eventHandler) {\n // FIXME: one event or diff event for empty, @v/@l, {@id}?\n let code;\n let message;\n if(count === 0) {\n code = 'empty object';\n message = 'Dropping empty object.';\n } else if('@value' in value) {\n code = 'object with only @value';\n message = 'Dropping object with only @value.';\n } else if('@list' in value) {\n code = 'object with only @list';\n message = 'Dropping object with only @list.';\n } else if(count === 1 && '@id' in value) {\n code = 'object with only @id';\n message = 'Dropping object with only @id.';\n }\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code,\n level: 'warning',\n message,\n details: {\n value\n }\n },\n options\n });\n }\n return null;\n }\n return value;\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 */\nasync function _expandObject({\n activeCtx,\n activeProperty,\n expandedActiveProperty,\n element,\n expandedParent,\n options = {},\n insideList,\n typeKey,\n typeScopedContext\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}, {\n ...options,\n typeExpansion: true\n }) === '@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 const expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options);\n\n // drop non-absolute IRI keys that aren't keywords\n if(expandedProperty === null ||\n !(_isAbsoluteIri(expandedProperty) || _isKeyword(expandedProperty))) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid property',\n level: 'warning',\n message: 'Dropping property that did not expand into an ' +\n 'absolute IRI or keyword.',\n details: {\n property: key,\n expandedProperty\n }\n },\n options\n });\n }\n continue;\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 if(_isString(v)) {\n const ve = _expandIri(activeCtx, v, {base: true}, options);\n if(options.eventHandler) {\n if(ve === null) {\n // NOTE: spec edge case\n // See https://github.com/w3c/json-ld-api/issues/480\n if(v === null) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'null @id value',\n level: 'warning',\n message: 'Null @id found.',\n details: {\n id: v\n }\n },\n options\n });\n } else {\n // matched KEYWORD regex\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved @id value',\n level: 'warning',\n message: 'Reserved @id found.',\n details: {\n id: v\n }\n },\n options\n });\n }\n } else if(!_isAbsoluteIri(ve)) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative @id reference',\n level: 'warning',\n message: 'Relative @id reference found.',\n details: {\n id: v,\n expandedId: ve\n }\n },\n options\n });\n }\n }\n return ve;\n }\n return v;\n }),\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 {...options, typeExpansion: true})\n )\n ]));\n }\n _validateTypeValue(value, options.isFrame);\n _addValue(\n expandedParent, '@type',\n _asArray(value).map(v => {\n if(_isString(v)) {\n const ve = _expandIri(typeScopedContext, v,\n {base: true, vocab: true},\n {...options, typeExpansion: true});\n if(ve !== '@json' && !_isAbsoluteIri(ve)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative @type reference',\n level: 'warning',\n message: 'Relative @type reference found.',\n details: {\n type: v\n }\n },\n options\n });\n }\n }\n return ve;\n }\n return v;\n }),\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 }));\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 language of value) {\n if(_isString(language) && !language.match(REGEX_BCP47)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language\n }\n },\n options\n });\n }\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: '@reverse',\n element: value,\n options\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(activeCtx, 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 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 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 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 });\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 });\n }\n }\n\n // drop null values if property is not @value\n if(expandedValue === null && expandedProperty !== '@value') {\n // FIXME: event?\n //unmappedValue: value,\n //expandedProperty,\n //key,\n continue;\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 in an array\n expandedValue = _asArray(expandedValue);\n if(!options.isFrame) {\n // drop items if needed\n expandedValue = expandedValue.filter(v => {\n const count = Object.keys(v).length;\n return _dropUnsafeObject({value: v, count, options}) !== null;\n });\n }\n if(expandedValue.length === 0) {\n // all items dropped, skip adding and continue\n continue;\n }\n // convert to graph\n expandedValue = expandedValue.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 });\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},\n {...options, typeExpansion: true});\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 const expandedValue = _expandIri(activeCtx, value, {base: true}, options);\n // NOTE: handle spec edge case and avoid invalid {\"@id\": null}\n if(expandedValue === null && value.match(REGEX_KEYWORD)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved @id value',\n level: 'warning',\n message: 'Reserved @id found.',\n details: {\n id: activeProperty\n }\n },\n options\n });\n }\n }\n return {'@id': expandedValue};\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 if(!key.match(REGEX_BCP47)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language: key\n }\n },\n options\n });\n }\n }\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, asGraph, indexKey, propertyIndex\n}) {\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 });\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 {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 // @type must be wildcard, IRI, or @json\n if(!(types.isObject(type) || url.isAbsolute(type) ||\n (type === '@json')) ||\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-2023 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst JsonLdError = require('./JsonLdError');\nconst graphTypes = require('./graphTypes');\nconst types = require('./types');\n\nconst {\n REGEX_BCP47,\n addValue: _addValue\n} = require('./util');\n\nconst {\n handleEvent: _handleEvent\n} = require('./events');\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 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 options\n) => {\n const {\n useRdfType = false,\n useNativeTypes = false,\n rdfDirection = null\n } = options;\n // FIXME: use Maps?\n const defaultGraph = {};\n const graphMap = {'@default': defaultGraph};\n const referencedOnce = {};\n if(rdfDirection) {\n if(rdfDirection === 'compound-literal') {\n throw new JsonLdError(\n 'Unsupported rdfDirection value.',\n 'jsonld.InvalidRdfDirection',\n {value: rdfDirection});\n } else if(rdfDirection !== 'i18n-datatype') {\n throw new JsonLdError(\n 'Unknown rdfDirection value.',\n 'jsonld.InvalidRdfDirection',\n {value: rdfDirection});\n }\n }\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 _addValue(node, '@type', o.value, {propertyIsArray: true});\n continue;\n }\n\n const value = _RDFToObject(o, useNativeTypes, rdfDirection, options);\n _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 _addValue(node, '@type', o.value, {propertyIsArray: true});\n continue;\n }\n\n const value = _RDFToObject(o, useNativeTypes);\n _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 * @param rdfDirection text direction mode [null, i18n-datatype]\n * @param options top level API options\n *\n * @return the JSON-LD object.\n */\nfunction _RDFToObject(o, useNativeTypes, rdfDirection, options) {\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 if(!o.language.match(REGEX_BCP47)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language: o.language\n }\n },\n options\n });\n }\n }\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 if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language\n }\n },\n options\n });\n }\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 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 that is not a string OR 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 const id = v['@id'];\n return !types.isString(id) || 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","/**\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-2022 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\nconst {\n logEventHandler: _logEventHandler,\n logWarningEventHandler: _logWarningEventHandler,\n safeEventHandler: _safeEventHandler,\n setDefaultEventHandler: _setDefaultEventHandler,\n setupEventHandler: _setupEventHandler,\n strictEventHandler: _strictEventHandler,\n unhandledEventHandler: _unhandledEventHandler\n} = require('./events');\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. Some well-formed\n * and safe-mode checks may be omitted.\n * [documentLoader(url, options)] the document loader.\n * [framing] true if compaction is occuring during a framing operation.\n * [safe] true to use safe mode. (default: false)\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 });\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 * [safe] true to use safe mode. (default: false)\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\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 });\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 * [safe] true to use safe mode. (default: false)\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 * [safe] true to use safe mode. (default: false)\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 * Note: Canonicalization sets `safe` to `true` and `base` to `null` by\n * default in order to produce safe outputs and \"fail closed\" by default. This\n * is different from the other API transformations in this version which\n * allow unsafe defaults (for cryptographic usage) in order to comply with the\n * JSON-LD 1.1 specification.\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 (default: `null`).\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. Some well-formed\n * and safe-mode checks may be omitted.\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 * [rdfDirection] null or 'i18n-datatype' to support RDF\n * transformation of @direction (default: null).\n * [safe] true to use safe mode. (default: true).\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 : null,\n algorithm: 'URDNA2015',\n skipExpansion: false,\n safe: true,\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 * [rdfDirection] null or 'i18n-datatype' to support RDF\n * transformation of @direction (default: null).\n * [safe] true to use safe mode. (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. Some well-formed\n * and safe-mode checks may be omitted.\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 * [safe] true to use safe mode. (default: false)\n * [rdfDirection] null or 'i18n-datatype' to support RDF\n * transformation of @direction (default: null).\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 * [safe] true to use safe mode. (default: false)\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 * [safe] true to use safe mode. (default: false)\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/* Events API and handlers */\njsonld.logEventHandler = _logEventHandler;\njsonld.logWarningEventHandler = _logWarningEventHandler;\njsonld.safeEventHandler = _safeEventHandler;\njsonld.setDefaultEventHandler = _setDefaultEventHandler;\njsonld.strictEventHandler = _strictEventHandler;\njsonld.unhandledEventHandler = _unhandledEventHandler;\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 // fail if obsolete options present\n if(options && 'compactionMap' in options) {\n throw new JsonLdError(\n '\"compactionMap\" not supported.',\n 'jsonld.OptionsError');\n }\n if(options && 'expansionMap' in options) {\n throw new JsonLdError(\n '\"expansionMap\" not supported.',\n 'jsonld.OptionsError');\n }\n return Object.assign(\n {},\n {documentLoader},\n defaults,\n options,\n {eventHandler: _setupEventHandler({options})}\n );\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","/*\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","/*\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-2023 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 JsonLdError = require('./JsonLdError');\nconst types = require('./types');\nconst util = require('./util');\n\nconst {\n handleEvent: _handleEvent\n} = require('./events');\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 if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative graph reference',\n level: 'warning',\n message: 'Relative graph reference found.',\n details: {\n graph: graphName\n }\n },\n options\n });\n }\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 if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative subject reference',\n level: 'warning',\n message: 'Relative subject reference found.',\n details: {\n subject: id\n }\n },\n options\n });\n }\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 if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative predicate reference',\n level: 'warning',\n message: 'Relative predicate reference found.',\n details: {\n predicate: property\n }\n },\n options\n });\n }\n continue;\n }\n\n // skip blank node predicates unless producing generalized RDF\n if(predicate.termType === 'BlankNode' &&\n !options.produceGeneralizedRdf) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'blank node predicate',\n level: 'warning',\n message: 'Dropping blank node predicate.',\n details: {\n // FIXME: add better issuer API to get reverse mapping\n property: issuer.getOldIds()\n .find(key => issuer.getId(key) === property)\n }\n },\n options\n });\n }\n continue;\n }\n\n // convert list, value or node object to triple\n const object = _objectToRDF(\n item, issuer, dataset, graphTerm, options.rdfDirection, options);\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 * @param options the RDF serialization options.\n *\n * @return the head of the list.\n */\nfunction _listToRDF(list, issuer, dataset, graphTerm, rdfDirection, options) {\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(\n item, issuer, dataset, graphTerm, rdfDirection, options);\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(\n last, issuer, dataset, graphTerm, rdfDirection, options);\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 * @param options the RDF serialization options.\n *\n * @return the RDF literal or RDF resource.\n */\nfunction _objectToRDF(\n item, issuer, dataset, graphTerm, rdfDirection, options\n) {\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('@direction' in item && rdfDirection === 'i18n-datatype') {\n const language = (item['@language'] || '').toLowerCase();\n const direction = item['@direction'];\n const datatype = `https://www.w3.org/ns/i18n#${language}_${direction}`;\n object.datatype.value = datatype;\n object.value = value;\n } else if('@direction' in item && rdfDirection === 'compound-literal') {\n throw new JsonLdError(\n 'Unsupported rdfDirection value.',\n 'jsonld.InvalidRdfDirection',\n {value: rdfDirection});\n } else if('@direction' in item && rdfDirection) {\n throw new JsonLdError(\n 'Unknown rdfDirection value.',\n 'jsonld.InvalidRdfDirection',\n {value: rdfDirection});\n } else if('@language' in item) {\n if('@direction' in item && !rdfDirection) {\n if(options.eventHandler) {\n // FIXME: only emit once?\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'rdfDirection not set',\n level: 'warning',\n message: 'rdfDirection not set for @direction.',\n details: {\n object: object.value\n }\n },\n options\n });\n }\n }\n object.value = value;\n object.datatype.value = datatype || RDF_LANGSTRING;\n object.language = item['@language'];\n } else {\n if('@direction' in item && !rdfDirection) {\n if(options.eventHandler) {\n // FIXME: only emit once?\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'rdfDirection not set',\n level: 'warning',\n message: 'rdfDirection not set for @direction.',\n details: {\n object: object.value\n }\n },\n options\n });\n }\n }\n object.value = value;\n object.datatype.value = datatype || XSD_STRING;\n }\n } else if(graphTypes.isList(item)) {\n const _list = _listToRDF(\n item['@list'], issuer, dataset, graphTerm, rdfDirection, options);\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 if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative object reference',\n level: 'warning',\n message: 'Relative object reference found.',\n details: {\n object: object.value\n }\n },\n options\n });\n }\n return null;\n }\n\n return object;\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","/*\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 \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: /^(([a-zA-Z][a-zA-Z0-9+-.]*):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\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 * 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_BCP47 = /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/;\nconst REGEX_LINK_HEADERS = /(?:<[^>]*?>|\"[^\"]*?\"|[^,])+/g;\nconst REGEX_LINK_HEADER = /\\s*<([^>]*?)>\\s*(?:;\\s*(.*))?/;\nconst REGEX_LINK_HEADER_PARAMS =\n /(.*?)=(?:(?:\"([^\"]*?)\")|([^\"]*?))\\s*(?:(?:;\\s*)|$)/g;\nconst REGEX_KEYWORD = /^@[a-zA-Z]+$/;\n\nconst DEFAULTS = {\n headers: {\n accept: 'application/ld+json, application/json'\n }\n};\n\nconst api = {};\nmodule.exports = api;\napi.IdentifierIssuer = IdentifierIssuer;\napi.REGEX_BCP47 = REGEX_BCP47;\napi.REGEX_KEYWORD = REGEX_KEYWORD;\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: ;\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","'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","'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","'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","/**\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 ('').\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-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nrequire('setimmediate');\n\nconst crypto = self.crypto || self.msCrypto;\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(`Unsupported 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-2022 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 RDF quad components to an N-Quad string (a single quad).\n *\n * @param {Object} s - N-Quad subject component.\n * @param {Object} p - N-Quad predicate component.\n * @param {Object} o - N-Quad object component.\n * @param {Object} g - N-Quad graph component.\n *\n * @return {string} the N-Quad.\n */\n static serializeQuadComponents(s, p, o, g) {\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 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 return NQuads.serializeQuadComponents(\n quad.subject, quad.predicate, quad.object, quad.graph);\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) 2016-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\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-2022 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 createMessageDigest = () => new MessageDigest('sha256'),\n canonicalIdMap = new Map(),\n maxDeepIterations = Infinity\n } = {}) {\n this.name = 'URDNA2015';\n this.blankNodeInfo = new Map();\n this.canonicalIssuer = new IdentifierIssuer('_:c14n', canonicalIdMap);\n this.createMessageDigest = createMessageDigest;\n this.maxDeepIterations = maxDeepIterations;\n this.quads = null;\n this.deepIterations = null;\n }\n\n // 4.4) Normalization Algorithm\n async main(dataset) {\n this.deepIterations = new Map();\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 away the copy here.\n const nQuad = NQuads.serializeQuadComponents(\n this._componentWithCanonicalId(quad.subject),\n quad.predicate,\n this._componentWithCanonicalId(quad.object),\n this._componentWithCanonicalId(quad.graph)\n );\n // 7.2) Add quad copy to the normalized dataset.\n normalized.push(nQuad);\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 = this.createMessageDigest();\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 = this.createMessageDigest();\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 const deepIterations = this.deepIterations.get(id) || 0;\n if(deepIterations > this.maxDeepIterations) {\n throw new Error(\n `Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);\n }\n this.deepIterations.set(id, deepIterations + 1);\n\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 = this.createMessageDigest();\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 // canonical ids for 7.1\n _componentWithCanonicalId(component) {\n if(component.termType === 'BlankNode' &&\n !component.value.startsWith(this.canonicalIssuer.prefix)) {\n // create new BlankNode\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","/*!\n * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst IdentifierIssuer = require('./IdentifierIssuer');\n// FIXME: do not import; convert to requiring a\n// hash factory\nconst MessageDigest = require('./MessageDigest');\nconst Permuter = require('./Permuter');\nconst NQuads = require('./NQuads');\n\nmodule.exports = class URDNA2015Sync {\n constructor({\n createMessageDigest = () => new MessageDigest('sha256'),\n canonicalIdMap = new Map(),\n maxDeepIterations = Infinity\n } = {}) {\n this.name = 'URDNA2015';\n this.blankNodeInfo = new Map();\n this.canonicalIssuer = new IdentifierIssuer('_:c14n', canonicalIdMap);\n this.createMessageDigest = createMessageDigest;\n this.maxDeepIterations = maxDeepIterations;\n this.quads = null;\n this.deepIterations = null;\n }\n\n // 4.4) Normalization Algorithm\n main(dataset) {\n this.deepIterations = new Map();\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 away the copy here.\n const nQuad = NQuads.serializeQuadComponents(\n this._componentWithCanonicalId({component: quad.subject}),\n quad.predicate,\n this._componentWithCanonicalId({component: quad.object}),\n this._componentWithCanonicalId({component: quad.graph})\n );\n // 7.2) Add quad copy to the normalized dataset.\n normalized.push(nQuad);\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 = this.createMessageDigest();\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 = this.createMessageDigest();\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 const deepIterations = this.deepIterations.get(id) || 0;\n if(deepIterations > this.maxDeepIterations) {\n throw new Error(\n `Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);\n }\n this.deepIterations.set(id, deepIterations + 1);\n\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 = this.createMessageDigest();\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 // canonical ids for 7.1\n _componentWithCanonicalId({component}) {\n if(component.termType === 'BlankNode' &&\n !component.value.startsWith(this.canonicalIssuer.prefix)) {\n // create new BlankNode\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) 2016-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst MessageDigest = require('./MessageDigest');\nconst URDNA2015 = require('./URDNA2015');\n\nmodule.exports = class URDNA2012 extends URDNA2015 {\n constructor() {\n super();\n this.name = 'URGNA2012';\n this.createMessageDigest = () => new MessageDigest('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 MessageDigest = require('./MessageDigest');\nconst URDNA2015Sync = require('./URDNA2015Sync');\n\nmodule.exports = class URDNA2012Sync extends URDNA2015Sync {\n constructor() {\n super();\n this.name = 'URGNA2012';\n this.createMessageDigest = () => new MessageDigest('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 * 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-2023 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\n// return a dataset from input dataset or legacy dataset\nfunction _inputToDataset(input/*, options*/) {\n // back-compat with legacy dataset\n if(!Array.isArray(input)) {\n return exports.NQuads.legacyDatasetToQuads(input);\n }\n return input;\n}\n\n// expose helpers\nexports.NQuads = require('./NQuads');\nexports.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 */\nexports._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 {Array|object|string} input - The input to canonize given as a\n * dataset or legacy dataset.\n * @param {object} options - The options to use:\n * {string} algorithm - The canonicalization algorithm to use, `URDNA2015` or\n * `URGNA2012`.\n * {Function} [createMessageDigest] - A factory function for creating a\n * `MessageDigest` interface that overrides the built-in message digest\n * implementation used by the canonize algorithm; note that using a hash\n * algorithm (or HMAC algorithm) that differs from the one specified by\n * the canonize algorithm will result in different output.\n * {Map} [canonicalIdMap] - An optional Map to be populated by the canonical\n * identifier issuer with the bnode identifier mapping generated by the\n * canonicalization algorithm.\n * {boolean} [useNative=false] - Use native implementation.\n * {number} [maxDeepIterations=Infinity] - The maximum number of times to run\n * deep comparison algorithms (such as the N-Degree Hash Quads algorithm\n * used in URDNA2015) before bailing out and throwing an error; this is a\n * useful setting for preventing wasted CPU cycles or DoS when canonizing\n * meaningless or potentially malicious datasets, a recommended value is\n * `1`.\n *\n * @return a Promise that resolves to the canonicalized RDF Dataset.\n */\nexports.canonize = async function(input, options) {\n const dataset = _inputToDataset(input, options);\n\n if(options.useNative) {\n if(!rdfCanonizeNative) {\n throw new Error('rdf-canonize-native not available');\n }\n if(options.createMessageDigest) {\n throw new Error(\n '\"createMessageDigest\" cannot be used with \"useNative\".');\n }\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 if(options.createMessageDigest) {\n throw new Error(\n '\"createMessageDigest\" cannot be used with \"URGNA2012\".');\n }\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 {Array|object|string} input - The input to canonize given as a\n * dataset or legacy dataset.\n * @param {object} options - The options to use:\n * {string} algorithm - The canonicalization algorithm to use, `URDNA2015` or\n * `URGNA2012`.\n * {Function} [createMessageDigest] - A factory function for creating a\n * `MessageDigest` interface that overrides the built-in message digest\n * implementation used by the canonize algorithm; note that using a hash\n * algorithm (or HMAC algorithm) that differs from the one specified by\n * the canonize algorithm will result in different output.\n * {boolean} [useNative=false] - Use native implementation.\n * {number} [maxDeepIterations=Infinity] - The maximum number of times to run\n * deep comparison algorithms (such as the N-Degree Hash Quads algorithm\n * used in URDNA2015) before bailing out and throwing an error; this is a\n * useful setting for preventing wasted CPU cycles or DoS when canonizing\n * meaningless or potentially malicious datasets, a recommended value is\n * `1`.\n *\n * @return the RDF dataset in canonical form.\n */\nexports._canonizeSync = function(input, options) {\n const dataset = _inputToDataset(input, options);\n\n if(options.useNative) {\n if(!rdfCanonizeNative) {\n throw new Error('rdf-canonize-native not available');\n }\n if(options.createMessageDigest) {\n throw new Error(\n '\"createMessageDigest\" cannot be used with \"useNative\".');\n }\n return rdfCanonizeNative.canonizeSync(dataset, options);\n }\n if(options.algorithm === 'URDNA2015') {\n return new URDNA2015Sync(options).main(dataset);\n }\n if(options.algorithm === 'URGNA2012') {\n if(options.createMessageDigest) {\n throw new Error(\n '\"createMessageDigest\" cannot be used with \"URGNA2012\".');\n }\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","(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